diff --git a/README.md b/README.md index fefff6da4..941fceae5 100644 --- a/README.md +++ b/README.md @@ -6,11 +6,14 @@

- - Gitbook - - Scc Count Badge + Scc Count Badge + + + Ask DeepWiki + + + Gitbook

diff --git a/bukkit/build.gradle.kts b/bukkit/build.gradle.kts index 607fff3b3..8e5ae6b27 100644 --- a/bukkit/build.gradle.kts +++ b/bukkit/build.gradle.kts @@ -1,5 +1,5 @@ plugins { - id("com.gradleup.shadow") version "9.0.0-beta11" + id("com.gradleup.shadow") version "9.0.0-beta13" id("maven-publish") } diff --git a/bukkit/legacy/build.gradle.kts b/bukkit/legacy/build.gradle.kts index ae80f6f46..da89d9df8 100644 --- a/bukkit/legacy/build.gradle.kts +++ b/bukkit/legacy/build.gradle.kts @@ -1,5 +1,5 @@ plugins { - id("com.gradleup.shadow") version "9.0.0-beta11" + id("com.gradleup.shadow") version "9.0.0-beta13" } repositories { diff --git a/bukkit/loader/build.gradle.kts b/bukkit/loader/build.gradle.kts index dae694cd2..6be000e1a 100644 --- a/bukkit/loader/build.gradle.kts +++ b/bukkit/loader/build.gradle.kts @@ -1,6 +1,6 @@ plugins { - id("com.gradleup.shadow") version "9.0.0-beta11" - id("net.minecrell.plugin-yml.bukkit") version "0.6.0" + id("com.gradleup.shadow") version "9.0.0-beta13" + id("de.eldoria.plugin-yml.bukkit") version "0.7.1" } repositories { @@ -60,7 +60,7 @@ artifacts { tasks { shadowJar { - archiveFileName = "${rootProject.name}-plugin-${rootProject.properties["project_version"]}.jar" + archiveFileName = "${rootProject.name}-bukkit-plugin-${rootProject.properties["project_version"]}.jar" destinationDirectory.set(file("$rootDir/target")) relocate("net.kyori", "net.momirealms.craftengine.libraries") relocate("net.momirealms.sparrow.nbt", "net.momirealms.craftengine.libraries.nbt") diff --git a/bukkit/loader/src/main/resources/resources/default/configuration/fix_client_visual.yml b/bukkit/loader/src/main/resources/resources/default/configuration/fix_client_visual.yml index f9d659368..9e18aabaf 100644 --- a/bukkit/loader/src/main/resources/resources/default/configuration/fix_client_visual.yml +++ b/bukkit/loader/src/main/resources/resources/default/configuration/fix_client_visual.yml @@ -23,4 +23,5 @@ blocks: minecraft:note_block: settings: client-bound-tags: - - minecraft:beacon_base_blocks \ No newline at end of file + - minecraft:beacon_base_blocks + - minecraft:mineable/axe \ No newline at end of file diff --git a/bukkit/loader/src/main/resources/translations/en.yml b/bukkit/loader/src/main/resources/translations/en.yml index 4c2938cb0..456d2405d 100644 --- a/bukkit/loader/src/main/resources/translations/en.yml +++ b/bukkit/loader/src/main/resources/translations/en.yml @@ -90,6 +90,7 @@ warning.config.condition.match_block_property.missing_properties: "Issue warning.config.condition.match_item.missing_id: "Issue found in file - The config '' is missing the required 'id' argument for 'match_item' condition." warning.config.condition.table_bonus.missing_enchantment: "Issue found in file - The config '' is missing the required 'enchantment' argument for 'table_bonus' condition." warning.config.condition.table_bonus.missing_chances: "Issue found in file - The config '' is missing the required 'chances' argument for 'table_bonus' condition." +warning.config.condition.click_type.missing_click_type: "Issue found in file - The config '' is missing the required 'click-type' argument for 'click_type' condition." warning.config.structure.not_section: "Issue found in file - The config '' is expected to be a config section while it's actually a(n) ''." warning.config.image.duplicate: "Issue found in file - Duplicated image ''. Please check if there is the same configuration in other files." warning.config.image.missing_height: "Issue found in file - The image '' is missing the required 'height' argument." @@ -298,4 +299,5 @@ warning.config.conflict_matcher.any_of.missing_terms: "Issue found in co warning.config.conflict_resolution.missing_type: "Issue found in config.yml at 'resource-pack.duplicated-files-handler' - Missing required 'type' argument for one of the resolutions." warning.config.conflict_resolution.invalid_type: "Issue found in config.yml at 'resource-pack.duplicated-files-handler' - One of the resolutions is using the invalid type ''." warning.config.function.command.missing_command: "Issue found in file - The config '' is missing the required 'command' argument for 'command' function." +warning.config.event.missing_trigger: "Issue found in file - The config '' is missing the required 'on' argument for event triggers." warning.config.event.invalid_trigger: "Issue found in file - The config '' is using an invalid event trigger ''." \ No newline at end of file diff --git a/bukkit/src/main/java/net/momirealms/craftengine/bukkit/block/BukkitBlockManager.java b/bukkit/src/main/java/net/momirealms/craftengine/bukkit/block/BukkitBlockManager.java index 5e8d9a78a..84f1098d6 100644 --- a/bukkit/src/main/java/net/momirealms/craftengine/bukkit/block/BukkitBlockManager.java +++ b/bukkit/src/main/java/net/momirealms/craftengine/bukkit/block/BukkitBlockManager.java @@ -31,7 +31,6 @@ import net.momirealms.craftengine.core.plugin.locale.LocalizedResourceConfigExce import net.momirealms.craftengine.core.plugin.locale.TranslationManager; import net.momirealms.craftengine.core.registry.BuiltInRegistries; import net.momirealms.craftengine.core.registry.Holder; -import net.momirealms.craftengine.core.registry.Registries; import net.momirealms.craftengine.core.registry.WritableRegistry; import net.momirealms.craftengine.core.util.*; import org.bukkit.Bukkit; @@ -49,7 +48,6 @@ import java.io.File; import java.lang.reflect.Field; import java.nio.file.Path; import java.util.*; -import java.util.stream.Collectors; public class BukkitBlockManager extends AbstractBlockManager { private static BukkitBlockManager instance; @@ -252,7 +250,7 @@ public class BukkitBlockManager extends AbstractBlockManager { for (int i = 0; i < size; i++) { states[i] = new PackedBlockState(BlockStateUtils.idToBlockState(i), i); } - BlockRegistryMirror.init(states); + BlockRegistryMirror.init(states, new PackedBlockState(Reflections.instance$Blocks$STONE$defaultState, BlockStateUtils.blockStateToId(Reflections.instance$Blocks$STONE$defaultState))); } private void registerEmptyBlock() { @@ -460,36 +458,8 @@ public class BukkitBlockManager extends AbstractBlockManager { } } - Object eventsObj = ResourceConfigUtils.get(section, "events"); - EnumMap>> events = new EnumMap<>(EventTrigger.class); - if (eventsObj instanceof Map eventsSection) { - Map eventsSectionMap = MiscUtils.castToMap(eventsSection, false); - for (Map.Entry eventEntry : eventsSectionMap.entrySet()) { - try { - EventTrigger eventTrigger = EventTrigger.valueOf(eventEntry.getKey().toUpperCase(Locale.ENGLISH)); - if (eventEntry.getValue() instanceof List list) { - if (list.size() == 1) { - events.put(eventTrigger, List.of(BlockEventFunctions.fromMap(MiscUtils.castToMap(list.get(0), false)))); - } else if (list.size() == 2) { - events.put(eventTrigger, List.of( - BlockEventFunctions.fromMap(MiscUtils.castToMap(list.get(0), false)), - BlockEventFunctions.fromMap(MiscUtils.castToMap(list.get(1), false)) - )); - } else { - List> eventsList = new ArrayList<>(); - for (Object event : list) { - eventsList.add(BlockEventFunctions.fromMap(MiscUtils.castToMap(event, false))); - } - events.put(eventTrigger, eventsList); - } - } else if (eventEntry.getValue() instanceof Map eventSection) { - events.put(eventTrigger, List.of(BlockEventFunctions.fromMap(MiscUtils.castToMap(eventSection, false)))); - } - } catch (IllegalArgumentException e) { - throw new LocalizedResourceConfigException("warning.config.event.invalid_trigger", eventEntry.getKey()); - } - } - } + Object eventsObj = ResourceConfigUtils.get(section, "events", "event"); + EnumMap>> events = parseEvents(eventsObj); Map behaviors = MiscUtils.castToMap(section.getOrDefault("behavior", Map.of()), false); CustomBlock block = BukkitCustomBlock.builder(id) @@ -543,6 +513,55 @@ public class BukkitBlockManager extends AbstractBlockManager { } } + private EnumMap>> parseEvents(Object eventsObj) { + EnumMap>> events = new EnumMap<>(EventTrigger.class); + if (eventsObj instanceof Map eventsSection) { + Map eventsSectionMap = MiscUtils.castToMap(eventsSection, false); + for (Map.Entry eventEntry : eventsSectionMap.entrySet()) { + try { + EventTrigger eventTrigger = EventTrigger.byName(eventEntry.getKey()); + if (eventEntry.getValue() instanceof List list) { + if (list.size() == 1) { + events.put(eventTrigger, List.of(BlockEventFunctions.fromMap(MiscUtils.castToMap(list.get(0), false)))); + } else if (list.size() == 2) { + events.put(eventTrigger, List.of( + BlockEventFunctions.fromMap(MiscUtils.castToMap(list.get(0), false)), + BlockEventFunctions.fromMap(MiscUtils.castToMap(list.get(1), false)) + )); + } else { + List> eventsList = new ArrayList<>(); + for (Object event : list) { + eventsList.add(BlockEventFunctions.fromMap(MiscUtils.castToMap(event, false))); + } + events.put(eventTrigger, eventsList); + } + } else if (eventEntry.getValue() instanceof Map eventSection) { + events.put(eventTrigger, List.of(BlockEventFunctions.fromMap(MiscUtils.castToMap(eventSection, false)))); + } + } catch (IllegalArgumentException e) { + throw new LocalizedResourceConfigException("warning.config.event.invalid_trigger", eventEntry.getKey()); + } + } + } else if (eventsObj instanceof List list) { + @SuppressWarnings("unchecked") + List> eventsList = (List>) list; + for (Map eventSection : eventsList) { + Object onObj = eventSection.get("on"); + if (onObj == null) { + throw new LocalizedResourceConfigException("warning.config.event.missing_trigger"); + } + try { + EventTrigger eventTrigger = EventTrigger.byName(onObj.toString()); + Function function = BlockEventFunctions.fromMap(eventSection); + events.computeIfAbsent(eventTrigger, k -> new ArrayList<>(4)).add(function); + } catch (IllegalArgumentException e) { + throw new LocalizedResourceConfigException("warning.config.event.invalid_trigger", onObj.toString()); + } + } + } + return events; + } + private Map> parseProperties(Map propertiesSection) { Map> properties = new HashMap<>(); for (Map.Entry entry : propertiesSection.entrySet()) { diff --git a/bukkit/src/main/java/net/momirealms/craftengine/bukkit/item/behavior/AxeItemBehavior.java b/bukkit/src/main/java/net/momirealms/craftengine/bukkit/item/behavior/AxeItemBehavior.java index 732978b30..d1e6b038e 100644 --- a/bukkit/src/main/java/net/momirealms/craftengine/bukkit/item/behavior/AxeItemBehavior.java +++ b/bukkit/src/main/java/net/momirealms/craftengine/bukkit/item/behavior/AxeItemBehavior.java @@ -89,7 +89,7 @@ public class AxeItemBehavior extends ItemBehavior { bukkitPlayer.setStatistic(Statistic.USE_ITEM, material, bukkitPlayer.getStatistic(Statistic.USE_ITEM, material) + 1); // resend swing if it's not interactable on client side - if (!InteractUtils.isInteractable(BlockStateUtils.getBlockOwnerIdFromState(state.vanillaBlockState().handle()), + if (!InteractUtils.isInteractable( bukkitPlayer, BlockStateUtils.fromBlockData(state.vanillaBlockState().handle()), context.getHitResult(), item ) || player.isSecondaryUseActive()) { diff --git a/bukkit/src/main/java/net/momirealms/craftengine/bukkit/item/behavior/BlockItemBehavior.java b/bukkit/src/main/java/net/momirealms/craftengine/bukkit/item/behavior/BlockItemBehavior.java index 847935ca0..39d62f1e4 100644 --- a/bukkit/src/main/java/net/momirealms/craftengine/bukkit/item/behavior/BlockItemBehavior.java +++ b/bukkit/src/main/java/net/momirealms/craftengine/bukkit/item/behavior/BlockItemBehavior.java @@ -1,5 +1,7 @@ package net.momirealms.craftengine.bukkit.item.behavior; +import net.kyori.adventure.text.Component; +import net.kyori.adventure.text.format.NamedTextColor; import net.momirealms.craftengine.bukkit.api.CraftEngineBlocks; import net.momirealms.craftengine.bukkit.api.event.CustomBlockAttemptPlaceEvent; import net.momirealms.craftengine.bukkit.api.event.CustomBlockPlaceEvent; @@ -21,6 +23,7 @@ import net.momirealms.craftengine.core.pack.Pack; import net.momirealms.craftengine.core.plugin.CraftEngine; import net.momirealms.craftengine.core.plugin.config.Config; import net.momirealms.craftengine.core.plugin.locale.LocalizedResourceConfigException; +import net.momirealms.craftengine.core.util.Direction; import net.momirealms.craftengine.core.util.Key; import net.momirealms.craftengine.core.util.MiscUtils; import net.momirealms.craftengine.core.world.BlockPos; @@ -38,7 +41,6 @@ import org.bukkit.inventory.EquipmentSlot; import org.bukkit.inventory.ItemStack; import org.bukkit.util.Vector; -import javax.annotation.Nullable; import java.nio.file.Path; import java.util.Map; import java.util.Optional; @@ -57,34 +59,32 @@ public class BlockItemBehavior extends ItemBehavior { } public InteractionResult place(BlockPlaceContext context) { - if (!context.canPlace()) { - return InteractionResult.FAIL; - } Optional optionalBlock = BukkitBlockManager.instance().blockById(this.blockId); if (optionalBlock.isEmpty()) { CraftEngine.instance().logger().warn("Failed to place unknown block " + this.blockId); return InteractionResult.FAIL; } - CustomBlock block = optionalBlock.get(); - BlockPlaceContext placeContext = updatePlacementContext(context); - if (placeContext == null) { + if (!context.canPlace()) { return InteractionResult.FAIL; } - ImmutableBlockState blockStateToPlace = getPlacementState(placeContext, block); + + CustomBlock block = optionalBlock.get(); + BlockPos pos = context.getClickedPos(); + int maxY = context.getLevel().worldHeight().getMaxBuildHeight() - 1; + if (context.getClickedFace() == Direction.UP && pos.y() >= maxY) { + context.getPlayer().sendActionBar(Component.translatable("build.tooHigh").arguments(Component.text(maxY)).color(NamedTextColor.RED)); + return InteractionResult.FAIL; + } + + ImmutableBlockState blockStateToPlace = getPlacementState(context, block); if (blockStateToPlace == null) { return InteractionResult.FAIL; } - Player player = placeContext.getPlayer(); - BlockPos pos = placeContext.getClickedPos(); - BlockPos againstPos = placeContext.getAgainstPos(); - World world = (World) placeContext.getLevel().platformWorld(); + + Player player = context.getPlayer(); + BlockPos againstPos = context.getAgainstPos(); + World world = (World) context.getLevel().platformWorld(); Location placeLocation = new Location(world, pos.x(), pos.y(), pos.z()); - - int gameTicks = player.gameTicks(); - if (!player.updateLastSuccessfulInteractionTick(gameTicks)) { - return InteractionResult.FAIL; - } - Block bukkitBlock = world.getBlockAt(placeLocation); Block againstBlock = world.getBlockAt(againstPos.x(), againstPos.y(), againstPos.z()); org.bukkit.entity.Player bukkitPlayer = (org.bukkit.entity.Player) player.platformPlayer(); @@ -105,6 +105,11 @@ public class BlockItemBehavior extends ItemBehavior { } } + int gameTicks = player.gameTicks(); + if (!player.updateLastSuccessfulInteractionTick(gameTicks)) { + return InteractionResult.FAIL; + } + // trigger event CustomBlockAttemptPlaceEvent attemptPlaceEvent = new CustomBlockAttemptPlaceEvent(bukkitPlayer, placeLocation.clone(), blockStateToPlace, DirectionUtils.toBlockFace(context.getClickedFace()), bukkitBlock, context.getHand()); @@ -117,7 +122,7 @@ public class BlockItemBehavior extends ItemBehavior { // place custom block CraftEngineBlocks.place(placeLocation, blockStateToPlace, UpdateOption.UPDATE_ALL_IMMEDIATE, false); // call bukkit event - BlockPlaceEvent bukkitPlaceEvent = new BlockPlaceEvent(bukkitBlock, previousState, againstBlock, (ItemStack) placeContext.getItem().getItem(), bukkitPlayer, true, context.getHand() == InteractionHand.MAIN_HAND ? EquipmentSlot.HAND : EquipmentSlot.OFF_HAND); + BlockPlaceEvent bukkitPlaceEvent = new BlockPlaceEvent(bukkitBlock, previousState, againstBlock, (ItemStack) context.getItem().getItem(), bukkitPlayer, true, context.getHand() == InteractionHand.MAIN_HAND ? EquipmentSlot.HAND : EquipmentSlot.OFF_HAND); if (EventUtils.fireAndCheckCancel(bukkitPlaceEvent)) { // revert changes previousState.update(true, false); @@ -133,23 +138,17 @@ public class BlockItemBehavior extends ItemBehavior { } if (!player.isCreativeMode()) { - Item item = placeContext.getItem(); + Item item = context.getItem(); item.count(item.count() - 1); item.load(); } - player.swingHand(placeContext.getHand()); - placeContext.getLevel().playBlockSound(new Vec3d(pos.x() + 0.5, pos.y() + 0.5, pos.z() + 0.5), blockStateToPlace.sounds().placeSound()); + player.swingHand(context.getHand()); + context.getLevel().playBlockSound(new Vec3d(pos.x() + 0.5, pos.y() + 0.5, pos.z() + 0.5), blockStateToPlace.sounds().placeSound()); world.sendGameEvent(bukkitPlayer, GameEvent.BLOCK_PLACE, new Vector(pos.x(), pos.y(), pos.z())); return InteractionResult.SUCCESS; } - // for child class to override - @Nullable - public BlockPlaceContext updatePlacementContext(BlockPlaceContext context) { - return context; - } - protected ImmutableBlockState getPlacementState(BlockPlaceContext context, CustomBlock block) { ImmutableBlockState state = block.getStateForPlacement(context); return state != null && this.canPlace(context, state) ? state : null; diff --git a/bukkit/src/main/java/net/momirealms/craftengine/bukkit/item/factory/BukkitItemFactory.java b/bukkit/src/main/java/net/momirealms/craftengine/bukkit/item/factory/BukkitItemFactory.java index 0dd515534..8606b48a6 100644 --- a/bukkit/src/main/java/net/momirealms/craftengine/bukkit/item/factory/BukkitItemFactory.java +++ b/bukkit/src/main/java/net/momirealms/craftengine/bukkit/item/factory/BukkitItemFactory.java @@ -54,6 +54,7 @@ public abstract class BukkitItemFactory> extend @Override protected boolean isBlockItem(W item) { + // todo 这个 isBlockItem 他考虑组件了吗??? return item.getItem().getType().isBlock(); } diff --git a/bukkit/src/main/java/net/momirealms/craftengine/bukkit/item/listener/ItemEventListener.java b/bukkit/src/main/java/net/momirealms/craftengine/bukkit/item/listener/ItemEventListener.java index 18d04e54c..9c1d62e4c 100644 --- a/bukkit/src/main/java/net/momirealms/craftengine/bukkit/item/listener/ItemEventListener.java +++ b/bukkit/src/main/java/net/momirealms/craftengine/bukkit/item/listener/ItemEventListener.java @@ -1,13 +1,12 @@ package net.momirealms.craftengine.bukkit.item.listener; -import net.kyori.adventure.text.Component; -import net.kyori.adventure.text.format.NamedTextColor; import net.momirealms.craftengine.bukkit.api.event.CustomBlockInteractEvent; import net.momirealms.craftengine.bukkit.block.BukkitBlockManager; -import net.momirealms.craftengine.bukkit.item.behavior.BlockItemBehavior; import net.momirealms.craftengine.bukkit.plugin.BukkitCraftEngine; import net.momirealms.craftengine.bukkit.plugin.user.BukkitServerPlayer; import net.momirealms.craftengine.bukkit.util.*; +import net.momirealms.craftengine.bukkit.world.BukkitBlockInWorld; +import net.momirealms.craftengine.core.block.CustomBlock; import net.momirealms.craftengine.core.block.ImmutableBlockState; import net.momirealms.craftengine.core.entity.player.InteractionHand; import net.momirealms.craftengine.core.entity.player.InteractionResult; @@ -15,6 +14,11 @@ import net.momirealms.craftengine.core.item.CustomItem; import net.momirealms.craftengine.core.item.Item; import net.momirealms.craftengine.core.item.behavior.ItemBehavior; import net.momirealms.craftengine.core.item.context.UseOnContext; +import net.momirealms.craftengine.core.plugin.context.ContextHolder; +import net.momirealms.craftengine.core.plugin.context.PlayerBlockActionContext; +import net.momirealms.craftengine.core.plugin.context.parameter.CommonParameters; +import net.momirealms.craftengine.core.plugin.event.EventTrigger; +import net.momirealms.craftengine.core.util.ClickType; import net.momirealms.craftengine.core.util.Direction; import net.momirealms.craftengine.core.world.BlockHitResult; import net.momirealms.craftengine.core.world.BlockPos; @@ -24,7 +28,6 @@ import org.bukkit.Location; import org.bukkit.block.Block; import org.bukkit.block.data.BlockData; import org.bukkit.entity.Player; -import org.bukkit.event.Event; import org.bukkit.event.EventHandler; import org.bukkit.event.EventPriority; import org.bukkit.event.Listener; @@ -44,37 +47,140 @@ public class ItemEventListener implements Listener { this.plugin = plugin; } - @EventHandler(ignoreCancelled = true, priority = EventPriority.HIGH) + @EventHandler(ignoreCancelled = true, priority = EventPriority.HIGHEST) public void onInteractBlock(PlayerInteractEvent event) { Action action = event.getAction(); - if (action != Action.LEFT_CLICK_BLOCK && action != Action.RIGHT_CLICK_BLOCK) { + Player player = event.getPlayer(); + if ( + (action != Action.LEFT_CLICK_BLOCK && action != Action.RIGHT_CLICK_BLOCK) || /* block is required */ + (player.getGameMode() == GameMode.SPECTATOR) || /* no spectator interactions */ + (action == Action.LEFT_CLICK_BLOCK && player.getGameMode() == GameMode.CREATIVE) /* it's breaking the block */ + ) { return; } + + BukkitServerPlayer serverPlayer = this.plugin.adapt(player); + InteractionHand hand = event.getHand() == EquipmentSlot.HAND ? InteractionHand.MAIN_HAND : InteractionHand.OFF_HAND; + // 如果本tick内主手已被处理,则不处理副手 + // 这是因为客户端可能会同时发主副手交互包,但实际上只能处理其中一个 + if (this.cancelEventIfHasInteraction(event, serverPlayer, hand)) { + return; + } + + // some common data Block block = Objects.requireNonNull(event.getClickedBlock()); - Object blockState = BlockStateUtils.blockDataToBlockState(block.getBlockData()); + BlockData blockData = block.getBlockData(); + Object blockState = BlockStateUtils.blockDataToBlockState(blockData); + ImmutableBlockState immutableBlockState = null; int stateId = BlockStateUtils.blockStateToId(blockState); - if (BlockStateUtils.isVanillaBlock(stateId)) { - return; + + // 处理自定义方块 + if (!BlockStateUtils.isVanillaBlock(stateId)) { + immutableBlockState = BukkitBlockManager.instance().getImmutableBlockStateUnsafe(stateId); + // call the event if it's custom + CustomBlockInteractEvent interactEvent = new CustomBlockInteractEvent( + player, + block.getLocation(), + event.getInteractionPoint(), + immutableBlockState, + block, + event.getBlockFace(), + hand, + action.isRightClick() ? CustomBlockInteractEvent.Action.RIGHT_CLICK : CustomBlockInteractEvent.Action.LEFT_CLICK, + event.getItem() + ); + if (EventUtils.fireAndCheckCancel(interactEvent)) { + event.setCancelled(true); + return; + } + + // run custom functions + CustomBlock customBlock = immutableBlockState.owner().value(); + PlayerBlockActionContext context = PlayerBlockActionContext.of(serverPlayer, new BukkitBlockInWorld(block), ContextHolder.builder() + .withParameter(CommonParameters.BLOCK_STATE, immutableBlockState) + .withParameter(CommonParameters.PLAYER, serverPlayer) + .withParameter(CommonParameters.WORLD, serverPlayer.world()) + .withParameter(CommonParameters.LOCATION, new Vec3d(block.getX(), block.getY(), block.getZ())) + .withParameter(CommonParameters.CLICK_TYPE, action.isRightClick() ? ClickType.RIGHT : ClickType.LEFT) + .build()); + customBlock.execute(context, EventTrigger.CLICK); + if (action.isRightClick()) customBlock.execute(context, EventTrigger.RIGHT_CLICK); + else customBlock.execute(context, EventTrigger.LEFT_CLICK); } - // it's breaking the block - if (action == Action.LEFT_CLICK_BLOCK && event.getPlayer().getGameMode() == GameMode.CREATIVE) { - return; - } + Item itemInHand = serverPlayer.getItemInHand(hand); + Optional> optionalCustomItem = itemInHand == null ? Optional.empty() : itemInHand.getCustomItem(); + boolean hasItem = itemInHand != null; + boolean hasCustomItem = optionalCustomItem.isPresent(); - CustomBlockInteractEvent interactEvent = new CustomBlockInteractEvent( - event.getPlayer(), - block.getLocation(), - event.getInteractionPoint(), - BukkitBlockManager.instance().getImmutableBlockStateUnsafe(stateId), - block, - event.getBlockFace(), - event.getHand() == EquipmentSlot.HAND ? InteractionHand.MAIN_HAND : InteractionHand.OFF_HAND, - action.isRightClick() ? CustomBlockInteractEvent.Action.RIGHT_CLICK : CustomBlockInteractEvent.Action.LEFT_CLICK, - event.getItem() - ); - if (EventUtils.fireAndCheckCancel(interactEvent)) { - event.setCancelled(true); + // interact block with items + if (hasItem && action == Action.RIGHT_CLICK_BLOCK) { + Location interactionPoint = Objects.requireNonNull(event.getInteractionPoint(), "interaction point should not be null"); + Direction direction = DirectionUtils.toDirection(event.getBlockFace()); + BlockPos pos = LocationUtils.toBlockPos(block.getLocation()); + Vec3d vec3d = new Vec3d(interactionPoint.getX(), interactionPoint.getY(), interactionPoint.getZ()); + BlockHitResult hitResult = new BlockHitResult(vec3d, direction, pos, false); + + // handle block item + if (itemInHand.isBlockItem()) { + // vanilla item + if (!hasCustomItem) { + // interact a custom block + if (immutableBlockState != null) { + // client won't have sounds if the clientside block is interactable + // so we should check and resend sounds on BlockPlaceEvent + BlockData craftBlockData = BlockStateUtils.fromBlockData(immutableBlockState.vanillaBlockState().handle()); + if (InteractUtils.isInteractable(player, craftBlockData, hitResult, itemInHand)) { + if (!serverPlayer.isSecondaryUseActive()) { + serverPlayer.setResendSound(); + } + } else { + if (BlockStateUtils.isReplaceable(immutableBlockState.customBlockState().handle()) && !BlockStateUtils.isReplaceable(immutableBlockState.vanillaBlockState().handle())) { + serverPlayer.setResendSwing(); + } + } + } + } + // custom item + else { + if (optionalCustomItem.get().settings().canPlaceRelatedVanillaBlock()) { + // 如果用户设置了允许放置对应的原版方块,那么直接返回。 + // 这种情况下最好是return,以避免同时触发多个behavior发生冲突 + // 当用户选择其作为原版方块放下时,自定义行为可能已经不重要了? + return; + } else { + // todo 实际上这里的处理并不正确,因为判断玩家是否能够放置那个方块需要更加细节的判断。比如玩家无法对着树叶放置火把,但是交互事件依然触发,此情况下不可丢弃自定义行为。 + if (serverPlayer.isSecondaryUseActive() || !InteractUtils.isInteractable(player, blockData, hitResult, itemInHand)) { + event.setCancelled(true); + } + } + } + } + + // 检查其他的物品行为,物品行为理论只在交互时处理 + Optional> optionalItemBehaviors = itemInHand.getItemBehavior(); + // 物品类型是否包含自定义物品行为,行为不一定来自于自定义物品,部分原版物品也包含了新的行为 + if (optionalItemBehaviors.isPresent()) { + // 检测是否可交互应当只判断原版方块,因为自定义方块早就判断过了,如果可交互不可能到这一步 + boolean interactable = immutableBlockState == null && InteractUtils.isInteractable(player, blockData, hitResult, itemInHand); + // 如果方块可交互但是玩家没shift,那么原版的方块交互优先,取消自定义物品的behavior + // todo 如果我的物品行为允许某些交互呢?是否值得进一步处理? + if (!serverPlayer.isSecondaryUseActive() && interactable) { + return; + } + // 依次执行物品行为 + for (ItemBehavior itemBehavior : optionalItemBehaviors.get()) { + InteractionResult result = itemBehavior.useOnBlock(new UseOnContext(serverPlayer, hand, hitResult)); + if (result == InteractionResult.SUCCESS_AND_CANCEL) { + event.setCancelled(true); + return; + } + // 非pass的情况直接结束 + if (result != InteractionResult.PASS) { + return; + } + } + } } } @@ -112,109 +218,6 @@ public class ItemEventListener implements Listener { } } - @EventHandler(priority = EventPriority.HIGHEST) - public void onInteractAtBlock(PlayerInteractEvent event) { - if (event.getAction() != Action.RIGHT_CLICK_BLOCK) return; - if (event.useItemInHand() == Event.Result.DENY || event.useInteractedBlock() == Event.Result.DENY) return; - Location interactionPoint = event.getInteractionPoint(); - if (interactionPoint == null) return; - Player bukkitPlayer = event.getPlayer(); - Block clickedBlock = Objects.requireNonNull(event.getClickedBlock()); - BukkitServerPlayer player = this.plugin.adapt(bukkitPlayer); - InteractionHand hand = event.getHand() == EquipmentSlot.HAND ? InteractionHand.MAIN_HAND : InteractionHand.OFF_HAND; - if (cancelEventIfHasInteraction(event, player, hand)) { - return; - } - - // Gets the item in hand - Item itemInHand = player.getItemInHand(hand); - if (itemInHand == null) return; - Optional> optionalItemBehaviors = itemInHand.getItemBehavior(); - - // has custom item behavior - if (optionalItemBehaviors.isPresent()) { - BlockPos pos = LocationUtils.toBlockPos(clickedBlock.getLocation()); - Vec3d vec3d = new Vec3d(interactionPoint.getX(), interactionPoint.getY(), interactionPoint.getZ()); - Direction direction = DirectionUtils.toDirection(event.getBlockFace()); - BlockHitResult hitResult = new BlockHitResult(vec3d, direction, pos, false); - boolean interactable = InteractUtils.isInteractable(BlockStateUtils.getBlockOwnerId(clickedBlock), bukkitPlayer, clickedBlock.getBlockData(), hitResult, itemInHand); - - // do not allow to place block if it's a vanilla block - Optional> optionalCustomItem = itemInHand.getCustomItem(); - if (itemInHand.isBlockItem() && optionalCustomItem.isPresent()) { - // it's a custom item, but now it's ignored - if (optionalCustomItem.get().settings().canPlaceRelatedVanillaBlock()) { - return; - } - if (!interactable || player.isSecondaryUseActive()) { - event.setCancelled(true); - } - } - - if (!player.isSecondaryUseActive() && interactable) { - // if it's interactable on server, cancel the custom behaviors - return; - } - - // no spectator interactions - if (player.isSpectatorMode()) { - return; - } - - for (ItemBehavior itemBehavior : optionalItemBehaviors.get()) { - InteractionResult result = itemBehavior.useOnBlock(new UseOnContext(player, hand, hitResult)); - if (result == InteractionResult.SUCCESS_AND_CANCEL) { - event.setCancelled(true); - return; - } - int maxY = player.world().worldHeight().getMaxBuildHeight() - 1; - if (direction == Direction.UP - && result != InteractionResult.SUCCESS - && pos.y() >= maxY - && itemBehavior instanceof BlockItemBehavior - ) { - player.sendActionBar(Component.translatable("build.tooHigh").arguments(Component.text(maxY)).color(NamedTextColor.RED)); - return; - } - if (result != InteractionResult.PASS) { - return; - } - } - return; - } - - // it's a vanilla block - if (itemInHand.isBlockItem() && !itemInHand.isCustomItem()) { - // client won't have sounds if the fake block is interactable - // so we should check and resend sounds on interact - Object blockState = BlockStateUtils.blockDataToBlockState(clickedBlock.getBlockData()); - int stateId = BlockStateUtils.blockStateToId(blockState); - ImmutableBlockState againstCustomBlock = BukkitBlockManager.instance().getImmutableBlockState(stateId); - if (againstCustomBlock == null || againstCustomBlock.isEmpty()) { - return; - } - - BlockPos pos = LocationUtils.toBlockPos(clickedBlock.getLocation()); - Vec3d vec3d = new Vec3d(interactionPoint.getX(), interactionPoint.getY(), interactionPoint.getZ()); - Direction direction = DirectionUtils.toDirection(event.getBlockFace()); - BlockHitResult hitResult = new BlockHitResult(vec3d, direction, pos, false); - try { - BlockData craftBlockData = BlockStateUtils.fromBlockData(againstCustomBlock.vanillaBlockState().handle()); - if (InteractUtils.isInteractable(KeyUtils.namespacedKey2Key(craftBlockData.getMaterial().getKey()), bukkitPlayer, craftBlockData, hitResult, itemInHand)) { - if (!player.isSecondaryUseActive()) { - player.setResendSound(); - } - } else { - if (BlockStateUtils.isReplaceable(againstCustomBlock.customBlockState().handle()) && !BlockStateUtils.isReplaceable(againstCustomBlock.vanillaBlockState().handle())) { - player.setResendSwing(); - } - } - } catch (ReflectiveOperationException e) { - plugin.logger().warn("Failed to get CraftBlockData", e); - } - } - } - private boolean cancelEventIfHasInteraction(PlayerInteractEvent event, BukkitServerPlayer player, InteractionHand hand) { if (hand == InteractionHand.OFF_HAND) { int currentTicks = player.gameTicks(); diff --git a/bukkit/src/main/java/net/momirealms/craftengine/bukkit/plugin/classpath/BukkitClassPathAppender.java b/bukkit/src/main/java/net/momirealms/craftengine/bukkit/plugin/classpath/BukkitClassPathAppender.java new file mode 100644 index 000000000..ddb3b04da --- /dev/null +++ b/bukkit/src/main/java/net/momirealms/craftengine/bukkit/plugin/classpath/BukkitClassPathAppender.java @@ -0,0 +1,38 @@ +package net.momirealms.craftengine.bukkit.plugin.classpath; + +import net.momirealms.craftengine.bukkit.util.Reflections; +import net.momirealms.craftengine.core.plugin.Plugin; +import net.momirealms.craftengine.core.plugin.classpath.ClassPathAppender; +import net.momirealms.craftengine.core.plugin.classpath.URLClassLoaderAccess; + +import java.net.MalformedURLException; +import java.net.URLClassLoader; +import java.nio.file.Path; + +public class BukkitClassPathAppender implements ClassPathAppender { + private final URLClassLoaderAccess classLoaderAccess; + + public BukkitClassPathAppender(ClassLoader classLoader) throws IllegalAccessException { + if (Reflections.clazz$PaperPluginClassLoader != null && Reflections.clazz$PaperPluginClassLoader.isInstance(classLoader)) { + URLClassLoader libraryClassLoader = (URLClassLoader) Reflections.field$PaperPluginClassLoader$libraryLoader.get(classLoader); + this.classLoaderAccess = URLClassLoaderAccess.create(libraryClassLoader); + } else if (classLoader instanceof URLClassLoader) { + this.classLoaderAccess = URLClassLoaderAccess.create((URLClassLoader) classLoader); + } else { + throw new IllegalStateException("ClassLoader is not instance of URLClassLoader"); + } + } + + public BukkitClassPathAppender(Plugin plugin) throws IllegalAccessException { + this(plugin.getClass().getClassLoader()); + } + + @Override + public void addJarToClasspath(Path file) { + try { + this.classLoaderAccess.addURL(file.toUri().toURL()); + } catch (MalformedURLException e) { + throw new RuntimeException(e); + } + } +} diff --git a/bukkit/src/main/java/net/momirealms/craftengine/bukkit/plugin/command/feature/TestCommand.java b/bukkit/src/main/java/net/momirealms/craftengine/bukkit/plugin/command/feature/TestCommand.java index 69bcf57e2..ab1b59966 100644 --- a/bukkit/src/main/java/net/momirealms/craftengine/bukkit/plugin/command/feature/TestCommand.java +++ b/bukkit/src/main/java/net/momirealms/craftengine/bukkit/plugin/command/feature/TestCommand.java @@ -1,7 +1,6 @@ package net.momirealms.craftengine.bukkit.plugin.command.feature; import net.momirealms.craftengine.bukkit.plugin.command.BukkitCommandFeature; -import net.momirealms.craftengine.bukkit.util.BlockTags; import net.momirealms.craftengine.core.plugin.CraftEngine; import net.momirealms.craftengine.core.plugin.command.CraftEngineCommandManager; import org.bukkit.Material; diff --git a/bukkit/src/main/java/net/momirealms/craftengine/bukkit/plugin/user/BukkitServerPlayer.java b/bukkit/src/main/java/net/momirealms/craftengine/bukkit/plugin/user/BukkitServerPlayer.java index b1f33c52d..590515847 100644 --- a/bukkit/src/main/java/net/momirealms/craftengine/bukkit/plugin/user/BukkitServerPlayer.java +++ b/bukkit/src/main/java/net/momirealms/craftengine/bukkit/plugin/user/BukkitServerPlayer.java @@ -317,7 +317,6 @@ public class BukkitServerPlayer extends Player { public void tick() { // not fully online if (serverPlayer() == null) return; - if (VersionHelper.isFolia()) { try { Object serverPlayer = serverPlayer(); @@ -329,7 +328,7 @@ public class BukkitServerPlayer extends Player { } else { this.gameTicks = FastNMS.INSTANCE.field$MinecraftServer$currentTick(); } - if (this.gameTicks % 15 == 0) { + if (this.gameTicks % 30 == 0) { this.updateGUI(); } if (this.isDestroyingBlock) { diff --git a/bukkit/src/main/java/net/momirealms/craftengine/bukkit/util/BlockStateUtils.java b/bukkit/src/main/java/net/momirealms/craftengine/bukkit/util/BlockStateUtils.java index 515fdfc63..81163c601 100644 --- a/bukkit/src/main/java/net/momirealms/craftengine/bukkit/util/BlockStateUtils.java +++ b/bukkit/src/main/java/net/momirealms/craftengine/bukkit/util/BlockStateUtils.java @@ -101,8 +101,11 @@ public class BlockStateUtils { } public static Key getBlockOwnerId(Block block) { - BlockData data = block.getBlockData(); - Object blockState = blockDataToBlockState(data); + return getBlockOwnerId(block.getBlockData()); + } + + public static Key getBlockOwnerId(BlockData block) { + Object blockState = blockDataToBlockState(block); return getBlockOwnerIdFromState(blockState); } @@ -188,8 +191,12 @@ public class BlockStateUtils { Reflections.field$BlockStateBase$replaceable.set(state, replaceable); } - public static boolean isReplaceable(Object state) throws ReflectiveOperationException { - return (boolean) Reflections.field$BlockStateBase$replaceable.get(state); + public static boolean isReplaceable(Object state) { + try { + return (boolean) Reflections.field$BlockStateBase$replaceable.get(state); + } catch (ReflectiveOperationException e) { + throw new RuntimeException("Failed to get replaceable property", e); + } } public static void setCanOcclude(Object state, boolean canOcclude) throws ReflectiveOperationException { diff --git a/bukkit/src/main/java/net/momirealms/craftengine/bukkit/util/InteractUtils.java b/bukkit/src/main/java/net/momirealms/craftengine/bukkit/util/InteractUtils.java index ac0bf989c..7152b3f98 100644 --- a/bukkit/src/main/java/net/momirealms/craftengine/bukkit/util/InteractUtils.java +++ b/bukkit/src/main/java/net/momirealms/craftengine/bukkit/util/InteractUtils.java @@ -273,9 +273,10 @@ public class InteractUtils { } } - public static boolean isInteractable(Key block, org.bukkit.entity.Player player, BlockData state, BlockHitResult hit, Item item) { - if (INTERACTIONS.containsKey(block)) { - return INTERACTIONS.get(block).apply(player, item, state, hit); + public static boolean isInteractable(Player player, BlockData state, BlockHitResult hit, Item item) { + Key blockType = BlockStateUtils.getBlockOwnerId(state); + if (INTERACTIONS.containsKey(blockType)) { + return INTERACTIONS.get(blockType).apply(player, item, state, hit); } else { return false; } diff --git a/bukkit/src/main/java/net/momirealms/craftengine/bukkit/util/Reflections.java b/bukkit/src/main/java/net/momirealms/craftengine/bukkit/util/Reflections.java index 345e6a05c..a8a39911e 100644 --- a/bukkit/src/main/java/net/momirealms/craftengine/bukkit/util/Reflections.java +++ b/bukkit/src/main/java/net/momirealms/craftengine/bukkit/util/Reflections.java @@ -27,6 +27,7 @@ import sun.misc.Unsafe; import java.io.BufferedReader; import java.lang.invoke.VarHandle; import java.lang.reflect.*; +import java.net.URLClassLoader; import java.time.Instant; import java.util.*; import java.util.concurrent.CompletableFuture; @@ -6688,6 +6689,14 @@ public class Reflections { .map(clazz -> ReflectionUtils.getTheOnlyConstructor(clazz)) .orElse(null); + public static final Class clazz$PaperPluginClassLoader = ReflectionUtils.getClazz( + "io.papermc.paper.plugin.entrypoint.classloader.PaperPluginClassLoader" + ); + + public static final Field field$PaperPluginClassLoader$libraryLoader = Optional.ofNullable(clazz$PaperPluginClassLoader) + .map(it -> ReflectionUtils.getDeclaredField(it, URLClassLoader.class, 0)) + .orElse(null); + public static final Method method$SoundSource$values = requireNonNull( ReflectionUtils.getStaticMethod( clazz$SoundSource, clazz$SoundSource.arrayType() diff --git a/bukkit/src/main/java/net/momirealms/craftengine/bukkit/util/TagUtils.java b/bukkit/src/main/java/net/momirealms/craftengine/bukkit/util/TagUtils.java index e54f30677..28e6e971e 100644 --- a/bukkit/src/main/java/net/momirealms/craftengine/bukkit/util/TagUtils.java +++ b/bukkit/src/main/java/net/momirealms/craftengine/bukkit/util/TagUtils.java @@ -5,7 +5,6 @@ import it.unimi.dsi.fastutil.ints.IntArrayList; import it.unimi.dsi.fastutil.ints.IntList; import net.momirealms.craftengine.bukkit.nms.FastNMS; import net.momirealms.craftengine.core.util.FriendlyByteBuf; -import net.momirealms.craftengine.core.util.Key; import java.util.ArrayList; import java.util.HashMap; diff --git a/client-mod/build.gradle.kts b/client-mod/build.gradle.kts index df2efc2e3..083cc7ad4 100644 --- a/client-mod/build.gradle.kts +++ b/client-mod/build.gradle.kts @@ -1,6 +1,6 @@ plugins { id("fabric-loom") version "1.10-SNAPSHOT" - id("com.gradleup.shadow") version "9.0.0-beta11" + id("com.gradleup.shadow") version "9.0.0-beta13" } version = property("project_version")!! diff --git a/core/build.gradle.kts b/core/build.gradle.kts index 83e995a17..8b6a644d8 100644 --- a/core/build.gradle.kts +++ b/core/build.gradle.kts @@ -1,5 +1,5 @@ plugins { - id("com.gradleup.shadow") version "9.0.0-beta11" + id("com.gradleup.shadow") version "9.0.0-beta13" id("maven-publish") } @@ -52,9 +52,7 @@ dependencies { // Aho-Corasick java implementation compileOnly("org.ahocorasick:ahocorasick:${rootProject.properties["ahocorasick_version"]}") // Amazon S3 - compileOnly("software.amazon.awssdk:s3:${rootProject.properties["amazon_awssdk_version"]}") { - - } + compileOnly("software.amazon.awssdk:s3:${rootProject.properties["amazon_awssdk_version"]}") compileOnly("software.amazon.awssdk:netty-nio-client:${rootProject.properties["amazon_awssdk_version"]}") // EvalEx compileOnly("com.ezylang:EvalEx:${rootProject.properties["evalex_version"]}") diff --git a/core/src/main/java/net/momirealms/craftengine/core/block/BlockRegistryMirror.java b/core/src/main/java/net/momirealms/craftengine/core/block/BlockRegistryMirror.java index 77645ffa1..f93bf3a57 100644 --- a/core/src/main/java/net/momirealms/craftengine/core/block/BlockRegistryMirror.java +++ b/core/src/main/java/net/momirealms/craftengine/core/block/BlockRegistryMirror.java @@ -2,13 +2,15 @@ package net.momirealms.craftengine.core.block; public class BlockRegistryMirror { private static PackedBlockState[] customBlockStates; + private static PackedBlockState stoneState; - public static void init(PackedBlockState[] states) { + public static void init(PackedBlockState[] states, PackedBlockState state) { customBlockStates = states; + stoneState = state; } public static PackedBlockState stateByRegistryId(int vanillaId) { - if (vanillaId < 0) return null; + if (vanillaId < 0) return stoneState; return customBlockStates[vanillaId]; } diff --git a/core/src/main/java/net/momirealms/craftengine/core/block/CustomBlock.java b/core/src/main/java/net/momirealms/craftengine/core/block/CustomBlock.java index b30236ae6..6ce564f82 100644 --- a/core/src/main/java/net/momirealms/craftengine/core/block/CustomBlock.java +++ b/core/src/main/java/net/momirealms/craftengine/core/block/CustomBlock.java @@ -93,6 +93,12 @@ public abstract class CustomBlock { return lootTable; } + public void execute(PlayerBlockActionContext context, EventTrigger trigger) { + for (Function function : Optional.ofNullable(this.events.get(trigger)).orElse(Collections.emptyList())) { + function.run(context); + } + } + @NotNull public BlockStateVariantProvider variantProvider() { return variantProvider; diff --git a/core/src/main/java/net/momirealms/craftengine/core/block/ImmutableBlockState.java b/core/src/main/java/net/momirealms/craftengine/core/block/ImmutableBlockState.java index 7e53699aa..30be17f0c 100644 --- a/core/src/main/java/net/momirealms/craftengine/core/block/ImmutableBlockState.java +++ b/core/src/main/java/net/momirealms/craftengine/core/block/ImmutableBlockState.java @@ -20,9 +20,7 @@ import java.util.List; public class ImmutableBlockState extends BlockStateHolder { private CompoundTag tag; - @Nullable private PackedBlockState customBlockState; - @Nullable private PackedBlockState vanillaBlockState; private BlockBehavior behavior; @@ -84,18 +82,18 @@ public class ImmutableBlockState extends BlockStateHolder { } public PackedBlockState customBlockState() { - return customBlockState; + return this.customBlockState; } public PackedBlockState vanillaBlockState() { - return vanillaBlockState; + return this.vanillaBlockState; } - public void setCustomBlockState(@Nullable PackedBlockState customBlockState) { + public void setCustomBlockState(@NotNull PackedBlockState customBlockState) { this.customBlockState = customBlockState; } - public void setVanillaBlockState(@Nullable PackedBlockState vanillaBlockState) { + public void setVanillaBlockState(@NotNull PackedBlockState vanillaBlockState) { this.vanillaBlockState = vanillaBlockState; } diff --git a/core/src/main/java/net/momirealms/craftengine/core/loot/LootContext.java b/core/src/main/java/net/momirealms/craftengine/core/loot/LootContext.java index c7251cd9e..5e3c9092d 100644 --- a/core/src/main/java/net/momirealms/craftengine/core/loot/LootContext.java +++ b/core/src/main/java/net/momirealms/craftengine/core/loot/LootContext.java @@ -1,7 +1,6 @@ package net.momirealms.craftengine.core.loot; import net.momirealms.craftengine.core.entity.player.Player; -import net.momirealms.craftengine.core.item.Item; import net.momirealms.craftengine.core.plugin.context.ContextHolder; import net.momirealms.craftengine.core.plugin.context.PlayerOptionalContext; import net.momirealms.craftengine.core.world.World; @@ -12,7 +11,6 @@ import javax.annotation.Nullable; public class LootContext extends PlayerOptionalContext { private final World world; private final float luck; - private Item tempLoot; public LootContext(@NotNull World world, @Nullable Player player, float luck, @NotNull ContextHolder contexts) { super(player, contexts); @@ -27,12 +25,4 @@ public class LootContext extends PlayerOptionalContext { public World world() { return this.world; } - - public Item tempLoot() { - return this.tempLoot; - } - - public void setTempLoot(Item tempLoot) { - this.tempLoot = tempLoot; - } } diff --git a/core/src/main/java/net/momirealms/craftengine/core/plugin/context/condition/AllOfCondition.java b/core/src/main/java/net/momirealms/craftengine/core/plugin/context/condition/AllOfCondition.java index c89b52606..a1776b43d 100644 --- a/core/src/main/java/net/momirealms/craftengine/core/plugin/context/condition/AllOfCondition.java +++ b/core/src/main/java/net/momirealms/craftengine/core/plugin/context/condition/AllOfCondition.java @@ -4,6 +4,7 @@ import net.momirealms.craftengine.core.plugin.context.Condition; import net.momirealms.craftengine.core.plugin.context.Context; import net.momirealms.craftengine.core.plugin.locale.LocalizedResourceConfigException; import net.momirealms.craftengine.core.util.Key; +import net.momirealms.craftengine.core.util.MCUtils; import net.momirealms.craftengine.core.util.MiscUtils; import net.momirealms.craftengine.core.util.ResourceConfigUtils; @@ -11,22 +12,18 @@ import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.function.Function; +import java.util.function.Predicate; public class AllOfCondition implements Condition { - protected final List> conditions; + protected final Predicate condition; public AllOfCondition(List> conditions) { - this.conditions = conditions; + this.condition = MCUtils.allOf(conditions); } @Override public boolean test(CTX ctx) { - for (Condition condition : conditions) { - if (!condition.test(ctx)) { - return false; - } - } - return true; + return this.condition.test(ctx); } @Override diff --git a/core/src/main/java/net/momirealms/craftengine/core/plugin/context/condition/AnyOfCondition.java b/core/src/main/java/net/momirealms/craftengine/core/plugin/context/condition/AnyOfCondition.java index 4151e9870..e01568f5b 100644 --- a/core/src/main/java/net/momirealms/craftengine/core/plugin/context/condition/AnyOfCondition.java +++ b/core/src/main/java/net/momirealms/craftengine/core/plugin/context/condition/AnyOfCondition.java @@ -4,6 +4,7 @@ import net.momirealms.craftengine.core.plugin.context.Condition; import net.momirealms.craftengine.core.plugin.context.Context; import net.momirealms.craftengine.core.plugin.locale.LocalizedResourceConfigException; import net.momirealms.craftengine.core.util.Key; +import net.momirealms.craftengine.core.util.MCUtils; import net.momirealms.craftengine.core.util.MiscUtils; import net.momirealms.craftengine.core.util.ResourceConfigUtils; @@ -11,22 +12,18 @@ import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.function.Function; +import java.util.function.Predicate; public class AnyOfCondition implements Condition { - protected final List> conditions; + protected final Predicate condition; public AnyOfCondition(List> conditions) { - this.conditions = conditions; + this.condition = MCUtils.anyOf(conditions); } @Override public boolean test(CTX ctx) { - for (Condition condition : conditions) { - if (condition.test(ctx)) { - return true; - } - } - return false; + return this.condition.test(ctx); } @Override diff --git a/core/src/main/java/net/momirealms/craftengine/core/plugin/context/condition/ClickTypeCondition.java b/core/src/main/java/net/momirealms/craftengine/core/plugin/context/condition/ClickTypeCondition.java new file mode 100644 index 000000000..ce9d60570 --- /dev/null +++ b/core/src/main/java/net/momirealms/craftengine/core/plugin/context/condition/ClickTypeCondition.java @@ -0,0 +1,44 @@ +package net.momirealms.craftengine.core.plugin.context.condition; + +import net.momirealms.craftengine.core.plugin.context.Condition; +import net.momirealms.craftengine.core.plugin.context.Context; +import net.momirealms.craftengine.core.plugin.context.parameter.CommonParameters; +import net.momirealms.craftengine.core.util.ClickType; +import net.momirealms.craftengine.core.util.Key; +import net.momirealms.craftengine.core.util.ResourceConfigUtils; + +import java.util.Locale; +import java.util.Map; +import java.util.Optional; + +public class ClickTypeCondition implements Condition { + private final ClickType clickType; + + public ClickTypeCondition(ClickType clickType) { + this.clickType = clickType; + } + + @Override + public Key type() { + return CommonConditions.CLICK_TYPE; + } + + @Override + public boolean test(CTX ctx) { + Optional clickTypeOptional = ctx.getOptionalParameter(CommonParameters.CLICK_TYPE); + if (clickTypeOptional.isPresent()) { + ClickType clickType = clickTypeOptional.get(); + return clickType.equals(this.clickType); + } + return false; + } + + public static class FactoryImpl implements ConditionFactory { + + @Override + public Condition create(Map arguments) { + ClickType clickType = ClickType.valueOf(ResourceConfigUtils.requireNonEmptyStringOrThrow(arguments.get("click-type"), "warning.config.condition.click_type.missing_click_type").toUpperCase(Locale.ENGLISH)); + return new ClickTypeCondition<>(clickType); + } + } +} diff --git a/core/src/main/java/net/momirealms/craftengine/core/plugin/context/condition/CommonConditions.java b/core/src/main/java/net/momirealms/craftengine/core/plugin/context/condition/CommonConditions.java index 1607f8013..59cc4895d 100644 --- a/core/src/main/java/net/momirealms/craftengine/core/plugin/context/condition/CommonConditions.java +++ b/core/src/main/java/net/momirealms/craftengine/core/plugin/context/condition/CommonConditions.java @@ -10,6 +10,7 @@ public final class CommonConditions { public static final Key ANY_OF = Key.of("craftengine:any_of"); public static final Key INVERTED = Key.of("craftengine:inverted"); public static final Key MATCH_ITEM = Key.of("craftengine:match_item"); + public static final Key CLICK_TYPE = Key.of("craftengine:click_type"); public static final Key MATCH_BLOCK_PROPERTY = Key.from("craftengine:match_block_property"); public static final Key TABLE_BONUS = Key.from("craftengine:table_bonus"); public static final Key SURVIVES_EXPLOSION = Key.from("craftengine:survives_explosion"); diff --git a/core/src/main/java/net/momirealms/craftengine/core/plugin/context/function/AbstractConditionalFunction.java b/core/src/main/java/net/momirealms/craftengine/core/plugin/context/function/AbstractConditionalFunction.java index 25d56a813..394552424 100644 --- a/core/src/main/java/net/momirealms/craftengine/core/plugin/context/function/AbstractConditionalFunction.java +++ b/core/src/main/java/net/momirealms/craftengine/core/plugin/context/function/AbstractConditionalFunction.java @@ -2,7 +2,6 @@ package net.momirealms.craftengine.core.plugin.context.function; import net.momirealms.craftengine.core.plugin.context.Condition; import net.momirealms.craftengine.core.plugin.context.Context; -import net.momirealms.craftengine.core.util.Factory; import net.momirealms.craftengine.core.util.MCUtils; import net.momirealms.craftengine.core.util.MiscUtils; @@ -11,7 +10,6 @@ import java.util.List; import java.util.Map; import java.util.function.Predicate; -// TODO 将loot functions迁移过来 public abstract class AbstractConditionalFunction implements Function { protected final List> predicates; private final Predicate compositePredicates; @@ -30,13 +28,17 @@ public abstract class AbstractConditionalFunction implement protected abstract void runInternal(CTX ctx); - public static abstract class AbstractFactory implements Factory> { + public static abstract class AbstractFactory implements FunctionFactory { private final java.util.function.Function, Condition> factory; public AbstractFactory(java.util.function.Function, Condition> factory) { this.factory = factory; } + public java.util.function.Function, Condition> conditionFactory() { + return factory; + } + protected List> getPredicates(Map arguments) { Object predicates = arguments.get("conditions"); if (predicates == null) return List.of(); diff --git a/core/src/main/java/net/momirealms/craftengine/core/plugin/context/function/CommandFunction.java b/core/src/main/java/net/momirealms/craftengine/core/plugin/context/function/CommandFunction.java index a6dd5254d..1dc91d843 100644 --- a/core/src/main/java/net/momirealms/craftengine/core/plugin/context/function/CommandFunction.java +++ b/core/src/main/java/net/momirealms/craftengine/core/plugin/context/function/CommandFunction.java @@ -72,7 +72,7 @@ public class CommandFunction extends AbstractConditionalFun Object command = ResourceConfigUtils.requireNonNullOrThrow(ResourceConfigUtils.get(arguments, "command", "commands"), "warning.config.function.command.missing_command"); List commands = MiscUtils.getAsStringList(command).stream().map(TextProviders::fromString).toList(); boolean asPlayer = (boolean) arguments.getOrDefault("as-player", false); - return new CommandFunction<>(getPredicates(arguments), commands, asPlayer, PlayerSelectors.fromObject(arguments.get("target"))); + return new CommandFunction<>(getPredicates(arguments), commands, asPlayer, PlayerSelectors.fromObject(arguments.get("target"), conditionFactory())); } } } diff --git a/core/src/main/java/net/momirealms/craftengine/core/plugin/context/function/FunctionFactory.java b/core/src/main/java/net/momirealms/craftengine/core/plugin/context/function/FunctionFactory.java new file mode 100644 index 000000000..f4e52f07c --- /dev/null +++ b/core/src/main/java/net/momirealms/craftengine/core/plugin/context/function/FunctionFactory.java @@ -0,0 +1,10 @@ +package net.momirealms.craftengine.core.plugin.context.function; + +import net.momirealms.craftengine.core.plugin.context.Context; + +import java.util.Map; + +public interface FunctionFactory { + + Function create(Map args); +} diff --git a/core/src/main/java/net/momirealms/craftengine/core/plugin/context/number/ExpressionNumberProvider.java b/core/src/main/java/net/momirealms/craftengine/core/plugin/context/number/ExpressionNumberProvider.java index 21c2ccabf..6428df308 100644 --- a/core/src/main/java/net/momirealms/craftengine/core/plugin/context/number/ExpressionNumberProvider.java +++ b/core/src/main/java/net/momirealms/craftengine/core/plugin/context/number/ExpressionNumberProvider.java @@ -6,7 +6,6 @@ import com.ezylang.evalex.parser.ParseException; import net.kyori.adventure.text.Component; import net.momirealms.craftengine.core.plugin.context.Context; import net.momirealms.craftengine.core.util.AdventureHelper; -import net.momirealms.craftengine.core.util.Factory; import net.momirealms.craftengine.core.util.Key; import net.momirealms.craftengine.core.util.ResourceConfigUtils; @@ -41,7 +40,7 @@ public class ExpressionNumberProvider implements NumberProvider { return this.expr; } - public static class FactoryImpl implements Factory { + public static class FactoryImpl implements NumberProviderFactory { @Override public NumberProvider create(Map arguments) { diff --git a/core/src/main/java/net/momirealms/craftengine/core/plugin/context/number/FixedNumberProvider.java b/core/src/main/java/net/momirealms/craftengine/core/plugin/context/number/FixedNumberProvider.java index cfbd165f9..3bbf7729f 100644 --- a/core/src/main/java/net/momirealms/craftengine/core/plugin/context/number/FixedNumberProvider.java +++ b/core/src/main/java/net/momirealms/craftengine/core/plugin/context/number/FixedNumberProvider.java @@ -3,7 +3,6 @@ package net.momirealms.craftengine.core.plugin.context.number; import com.ezylang.evalex.Expression; import net.momirealms.craftengine.core.plugin.context.Context; import net.momirealms.craftengine.core.plugin.locale.LocalizedResourceConfigException; -import net.momirealms.craftengine.core.util.Factory; import net.momirealms.craftengine.core.util.Key; import net.momirealms.craftengine.core.util.ResourceConfigUtils; @@ -27,7 +26,7 @@ public class FixedNumberProvider implements NumberProvider { return NumberProviders.FIXED; } - public static class FactoryImpl implements Factory { + public static class FactoryImpl implements NumberProviderFactory { @Override public NumberProvider create(Map arguments) { diff --git a/core/src/main/java/net/momirealms/craftengine/core/plugin/context/number/NumberProviderFactory.java b/core/src/main/java/net/momirealms/craftengine/core/plugin/context/number/NumberProviderFactory.java new file mode 100644 index 000000000..3d557362a --- /dev/null +++ b/core/src/main/java/net/momirealms/craftengine/core/plugin/context/number/NumberProviderFactory.java @@ -0,0 +1,8 @@ +package net.momirealms.craftengine.core.plugin.context.number; + +import java.util.Map; + +public interface NumberProviderFactory { + + NumberProvider create(Map args); +} diff --git a/core/src/main/java/net/momirealms/craftengine/core/plugin/context/number/NumberProviders.java b/core/src/main/java/net/momirealms/craftengine/core/plugin/context/number/NumberProviders.java index 5d5d609a4..8baef2d0b 100644 --- a/core/src/main/java/net/momirealms/craftengine/core/plugin/context/number/NumberProviders.java +++ b/core/src/main/java/net/momirealms/craftengine/core/plugin/context/number/NumberProviders.java @@ -5,7 +5,6 @@ import net.momirealms.craftengine.core.registry.BuiltInRegistries; import net.momirealms.craftengine.core.registry.Holder; import net.momirealms.craftengine.core.registry.Registries; import net.momirealms.craftengine.core.registry.WritableRegistry; -import net.momirealms.craftengine.core.util.Factory; import net.momirealms.craftengine.core.util.Key; import net.momirealms.craftengine.core.util.ResourceConfigUtils; import net.momirealms.craftengine.core.util.ResourceKey; @@ -27,8 +26,8 @@ public class NumberProviders { register(EXPRESSION, ExpressionNumberProvider.FACTORY); } - public static void register(Key key, Factory factory) { - Holder.Reference> holder = ((WritableRegistry>) BuiltInRegistries.NUMBER_PROVIDER_FACTORY) + public static void register(Key key, NumberProviderFactory factory) { + Holder.Reference holder = ((WritableRegistry) BuiltInRegistries.NUMBER_PROVIDER_FACTORY) .registerForHolder(new ResourceKey<>(Registries.NUMBER_PROVIDER_FACTORY.location(), key)); holder.bindValue(factory); } @@ -45,7 +44,7 @@ public class NumberProviders { public static NumberProvider fromMap(Map map) { String type = ResourceConfigUtils.requireNonEmptyStringOrThrow(map.get("type"), "warning.config.number.missing_type"); Key key = Key.withDefaultNamespace(type, Key.DEFAULT_NAMESPACE); - Factory factory = BuiltInRegistries.NUMBER_PROVIDER_FACTORY.getValue(key); + NumberProviderFactory factory = BuiltInRegistries.NUMBER_PROVIDER_FACTORY.getValue(key); if (factory == null) { throw new LocalizedResourceConfigException("warning.config.number.invalid_type", type); } diff --git a/core/src/main/java/net/momirealms/craftengine/core/plugin/context/number/UniformNumberProvider.java b/core/src/main/java/net/momirealms/craftengine/core/plugin/context/number/UniformNumberProvider.java index 38cbf80ae..62d7c4ddc 100644 --- a/core/src/main/java/net/momirealms/craftengine/core/plugin/context/number/UniformNumberProvider.java +++ b/core/src/main/java/net/momirealms/craftengine/core/plugin/context/number/UniformNumberProvider.java @@ -1,7 +1,6 @@ package net.momirealms.craftengine.core.plugin.context.number; import net.momirealms.craftengine.core.plugin.context.Context; -import net.momirealms.craftengine.core.util.Factory; import net.momirealms.craftengine.core.util.Key; import net.momirealms.craftengine.core.util.RandomUtils; import net.momirealms.craftengine.core.util.ResourceConfigUtils; @@ -41,7 +40,7 @@ public class UniformNumberProvider implements NumberProvider { return NumberProviders.UNIFORM; } - public static class FactoryImpl implements Factory { + public static class FactoryImpl implements NumberProviderFactory { @Override public NumberProvider create(Map arguments) { diff --git a/core/src/main/java/net/momirealms/craftengine/core/plugin/context/parameter/CommonParameters.java b/core/src/main/java/net/momirealms/craftengine/core/plugin/context/parameter/CommonParameters.java index 615aa93bb..2b2ad13c9 100644 --- a/core/src/main/java/net/momirealms/craftengine/core/plugin/context/parameter/CommonParameters.java +++ b/core/src/main/java/net/momirealms/craftengine/core/plugin/context/parameter/CommonParameters.java @@ -4,6 +4,7 @@ import net.momirealms.craftengine.core.block.ImmutableBlockState; import net.momirealms.craftengine.core.entity.player.Player; import net.momirealms.craftengine.core.item.Item; import net.momirealms.craftengine.core.plugin.context.ContextKey; +import net.momirealms.craftengine.core.util.ClickType; import net.momirealms.craftengine.core.world.Vec3d; import net.momirealms.craftengine.core.world.World; @@ -18,5 +19,6 @@ public final class CommonParameters { public static final ContextKey FALLING_BLOCK = ContextKey.of("falling_block"); public static final ContextKey EXPLOSION_RADIUS = ContextKey.of("explosion_radius"); public static final ContextKey PLAYER = ContextKey.of("player"); + public static final ContextKey CLICK_TYPE = ContextKey.of("click_type"); public static final ContextKey BLOCK_STATE = ContextKey.of("block_state"); } diff --git a/core/src/main/java/net/momirealms/craftengine/core/plugin/context/selector/AllPlayerSelector.java b/core/src/main/java/net/momirealms/craftengine/core/plugin/context/selector/AllPlayerSelector.java index 77e431e1a..19330e03e 100644 --- a/core/src/main/java/net/momirealms/craftengine/core/plugin/context/selector/AllPlayerSelector.java +++ b/core/src/main/java/net/momirealms/craftengine/core/plugin/context/selector/AllPlayerSelector.java @@ -8,42 +8,38 @@ import net.momirealms.craftengine.core.plugin.context.ContextHolder; import net.momirealms.craftengine.core.plugin.context.PlayerOptionalContext; import net.momirealms.craftengine.core.plugin.context.parameter.CommonParameters; import net.momirealms.craftengine.core.util.Key; +import net.momirealms.craftengine.core.util.MCUtils; import java.util.ArrayList; import java.util.Arrays; import java.util.List; +import java.util.function.Predicate; public class AllPlayerSelector implements PlayerSelector { - private final List> predicates; + private final Predicate predicate; public AllPlayerSelector(List> predicates) { - this.predicates = predicates; + this.predicate = MCUtils.allOf(predicates); } public AllPlayerSelector() { - this.predicates = List.of(); - } - - public List> predicates() { - return predicates; + this.predicate = null; } @SuppressWarnings("unchecked") @Override public List get(CTX context) { - if (this.predicates.isEmpty()) { + if (this.predicate == null) { return Arrays.asList(CraftEngine.instance().networkManager().onlineUsers()); } else { List players = new ArrayList<>(); - outer: for (Player player : CraftEngine.instance().networkManager().onlineUsers()) { + for (Player player : CraftEngine.instance().networkManager().onlineUsers()) { PlayerOptionalContext newContext = PlayerOptionalContext.of(player, ContextHolder.builder() .withOptionalParameter(CommonParameters.WORLD, context.getOptionalParameter(CommonParameters.WORLD).orElse(null)) .withOptionalParameter(CommonParameters.LOCATION, context.getOptionalParameter(CommonParameters.LOCATION).orElse(null)) ); - for (Condition predicate : this.predicates) { - if (!predicate.test((CTX) newContext)) { - continue outer; - } + if (!this.predicate.test((CTX) newContext)) { + continue; } players.add(player); } diff --git a/core/src/main/java/net/momirealms/craftengine/core/plugin/context/selector/PlayerSelectors.java b/core/src/main/java/net/momirealms/craftengine/core/plugin/context/selector/PlayerSelectors.java index ae5010c81..2887faa49 100644 --- a/core/src/main/java/net/momirealms/craftengine/core/plugin/context/selector/PlayerSelectors.java +++ b/core/src/main/java/net/momirealms/craftengine/core/plugin/context/selector/PlayerSelectors.java @@ -1,13 +1,21 @@ package net.momirealms.craftengine.core.plugin.context.selector; +import net.momirealms.craftengine.core.plugin.context.Condition; import net.momirealms.craftengine.core.plugin.context.Context; import net.momirealms.craftengine.core.util.Key; +import net.momirealms.craftengine.core.util.MiscUtils; +import net.momirealms.craftengine.core.util.ResourceConfigUtils; + +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.function.Function; public class PlayerSelectors { public static final Key ALL = Key.of("craftengine:all"); public static final Key SELF = Key.of("craftengine:self"); - public static PlayerSelector fromObject(Object object) { + public static PlayerSelector fromObject(Object object, Function, Condition> conditionFactory) { if (object == null) return null; if (object instanceof String string) { if (string.equals("self") || string.equals("@self") || string.equals("@s")) { @@ -15,6 +23,28 @@ public class PlayerSelectors { } else if (string.equals("all") || string.equals("@all") || string.equals("@a")) { return new AllPlayerSelector<>(); } + } else if (object instanceof Map map) { + Map selectorMap = MiscUtils.castToMap(map, false); + Object typeObj = selectorMap.get("type"); + Object conditionObj = ResourceConfigUtils.get(selectorMap, "conditions"); + if (!(typeObj instanceof String typeString)) { + throw new UnsupportedOperationException("Not supported yet."); + } + if (typeString.equals("all") || typeString.equals("@all") || typeString.equals("@a")) { + List> conditions = new ArrayList<>(); + if (conditionObj instanceof List list) { + @SuppressWarnings("unchecked") + List> conditionList = (List>) list; + for (Map condition : conditionList) { + conditions.add(conditionFactory.apply(condition)); + } + } else if (conditionObj instanceof Map) { + conditions.add(conditionFactory.apply(MiscUtils.castToMap(conditionObj, false))); + } else { + return new AllPlayerSelector<>(); + } + return new AllPlayerSelector<>(conditions); + } } throw new UnsupportedOperationException("Not supported yet."); } diff --git a/core/src/main/java/net/momirealms/craftengine/core/plugin/event/BlockEventConditions.java b/core/src/main/java/net/momirealms/craftengine/core/plugin/event/BlockEventConditions.java index 5cb58ed8a..6acee5ff4 100644 --- a/core/src/main/java/net/momirealms/craftengine/core/plugin/event/BlockEventConditions.java +++ b/core/src/main/java/net/momirealms/craftengine/core/plugin/event/BlockEventConditions.java @@ -2,28 +2,52 @@ package net.momirealms.craftengine.core.plugin.event; import net.momirealms.craftengine.core.plugin.context.Condition; import net.momirealms.craftengine.core.plugin.context.PlayerBlockActionContext; -import net.momirealms.craftengine.core.plugin.context.condition.InvertedCondition; +import net.momirealms.craftengine.core.plugin.context.condition.*; import net.momirealms.craftengine.core.plugin.locale.LocalizedResourceConfigException; import net.momirealms.craftengine.core.registry.BuiltInRegistries; -import net.momirealms.craftengine.core.util.Factory; +import net.momirealms.craftengine.core.registry.Holder; +import net.momirealms.craftengine.core.registry.Registries; +import net.momirealms.craftengine.core.registry.WritableRegistry; import net.momirealms.craftengine.core.util.Key; import net.momirealms.craftengine.core.util.ResourceConfigUtils; +import net.momirealms.craftengine.core.util.ResourceKey; import java.util.Map; public class BlockEventConditions { + static { + register(CommonConditions.MATCH_ITEM, new MatchItemCondition.FactoryImpl<>()); + register(CommonConditions.MATCH_BLOCK_PROPERTY, new MatchBlockPropertyCondition.FactoryImpl<>()); + register(CommonConditions.TABLE_BONUS, new TableBonusCondition.FactoryImpl<>()); + register(CommonConditions.SURVIVES_EXPLOSION, new SurvivesExplosionCondition.FactoryImpl<>()); + register(CommonConditions.ANY_OF, new AnyOfCondition.FactoryImpl<>(BlockEventConditions::fromMap)); + register(CommonConditions.ALL_OF, new AllOfCondition.FactoryImpl<>(BlockEventConditions::fromMap)); + register(CommonConditions.ENCHANTMENT, new EnchantmentCondition.FactoryImpl<>()); + register(CommonConditions.INVERTED, new InvertedCondition.FactoryImpl<>(BlockEventConditions::fromMap)); + register(CommonConditions.FALLING_BLOCK, new FallingBlockCondition.FactoryImpl<>()); + register(CommonConditions.RANDOM, new RandomCondition.FactoryImpl<>()); + register(CommonConditions.DISTANCE, new DistanceCondition.FactoryImpl<>()); + register(CommonConditions.CLICK_TYPE, new ClickTypeCondition.FactoryImpl<>()); + } + + public static void register(Key key, ConditionFactory factory) { + Holder.Reference> holder = ((WritableRegistry>) BuiltInRegistries.PLAYER_BLOCK_CONDITION_FACTORY) + .registerForHolder(new ResourceKey<>(Registries.PLAYER_BLOCK_CONDITION_FACTORY.location(), key)); + holder.bindValue(factory); + } + public static Condition fromMap(Map map) { String type = ResourceConfigUtils.requireNonEmptyStringOrThrow(map.get("type"), "warning.config.block.event.condition.missing_type"); Key key = Key.withDefaultNamespace(type, Key.DEFAULT_NAMESPACE); if (key.value().charAt(0) == '!') { - Factory> factory = BuiltInRegistries.PLAYER_BLOCK_CONDITION_FACTORY.getValue(new Key(key.namespace(), key.value().substring(1))); + ConditionFactory factory = BuiltInRegistries.PLAYER_BLOCK_CONDITION_FACTORY.getValue(new Key(key.namespace(), key.value().substring(1))); if (factory == null) { throw new LocalizedResourceConfigException("warning.config.block.event.condition.invalid_type", type); } return new InvertedCondition<>(factory.create(map)); } else { - Factory> factory = BuiltInRegistries.PLAYER_BLOCK_CONDITION_FACTORY.getValue(key); + ConditionFactory factory = BuiltInRegistries.PLAYER_BLOCK_CONDITION_FACTORY.getValue(key); if (factory == null) { throw new LocalizedResourceConfigException("warning.config.block.event.condition.invalid_type", type); } diff --git a/core/src/main/java/net/momirealms/craftengine/core/plugin/event/BlockEventFunctions.java b/core/src/main/java/net/momirealms/craftengine/core/plugin/event/BlockEventFunctions.java index 885e7fec2..0cce7cdf1 100644 --- a/core/src/main/java/net/momirealms/craftengine/core/plugin/event/BlockEventFunctions.java +++ b/core/src/main/java/net/momirealms/craftengine/core/plugin/event/BlockEventFunctions.java @@ -4,12 +4,12 @@ import net.momirealms.craftengine.core.plugin.context.PlayerBlockActionContext; import net.momirealms.craftengine.core.plugin.context.function.CommandFunction; import net.momirealms.craftengine.core.plugin.context.function.CommonFunctions; import net.momirealms.craftengine.core.plugin.context.function.Function; +import net.momirealms.craftengine.core.plugin.context.function.FunctionFactory; import net.momirealms.craftengine.core.plugin.locale.LocalizedResourceConfigException; import net.momirealms.craftengine.core.registry.BuiltInRegistries; import net.momirealms.craftengine.core.registry.Holder; import net.momirealms.craftengine.core.registry.Registries; import net.momirealms.craftengine.core.registry.WritableRegistry; -import net.momirealms.craftengine.core.util.Factory; import net.momirealms.craftengine.core.util.Key; import net.momirealms.craftengine.core.util.ResourceConfigUtils; import net.momirealms.craftengine.core.util.ResourceKey; @@ -22,8 +22,8 @@ public class BlockEventFunctions { register(CommonFunctions.COMMAND, new CommandFunction.FactoryImpl<>(BlockEventConditions::fromMap)); } - public static void register(Key key, Factory> factory) { - Holder.Reference>> holder = ((WritableRegistry>>) BuiltInRegistries.PLAYER_BLOCK_FUNCTION_FACTORY) + public static void register(Key key, FunctionFactory factory) { + Holder.Reference> holder = ((WritableRegistry>) BuiltInRegistries.PLAYER_BLOCK_FUNCTION_FACTORY) .registerForHolder(new ResourceKey<>(Registries.PLAYER_BLOCK_FUNCTION_FACTORY.location(), key)); holder.bindValue(factory); } @@ -31,7 +31,7 @@ public class BlockEventFunctions { public static Function fromMap(Map map) { String type = ResourceConfigUtils.requireNonEmptyStringOrThrow(map.get("type"), "TODO I18N"); Key key = Key.withDefaultNamespace(type, Key.DEFAULT_NAMESPACE); - Factory> factory = BuiltInRegistries.PLAYER_BLOCK_FUNCTION_FACTORY.getValue(key); + FunctionFactory factory = BuiltInRegistries.PLAYER_BLOCK_FUNCTION_FACTORY.getValue(key); if (factory == null) { throw new LocalizedResourceConfigException("TODO I18N", type); } diff --git a/core/src/main/java/net/momirealms/craftengine/core/plugin/event/EventTrigger.java b/core/src/main/java/net/momirealms/craftengine/core/plugin/event/EventTrigger.java index 5d26f6c1f..7e9ef2820 100644 --- a/core/src/main/java/net/momirealms/craftengine/core/plugin/event/EventTrigger.java +++ b/core/src/main/java/net/momirealms/craftengine/core/plugin/event/EventTrigger.java @@ -1,8 +1,36 @@ package net.momirealms.craftengine.core.plugin.event; +import java.util.HashMap; +import java.util.Map; +import java.util.Optional; + public enum EventTrigger { - USE_ITEM, - USE_ITEM_ON, - CONSUME, - BREAK + CLICK("click", "interact"), + LEFT_CLICK("attack", "left_click"), + RIGHT_CLICK("right_click", "use_on", "use", "use_item_on"), + CONSUME("eat", "consume", "drink"), + BREAK("break", "dig"),; + + public static final Map BY_NAME = new HashMap<>(); + private final String[] names; + + EventTrigger(String... names) { + this.names = names; + } + + public String[] names() { + return names; + } + + static { + for (EventTrigger trigger : EventTrigger.values()) { + for (String name : trigger.names()) { + BY_NAME.put(name, trigger); + } + } + } + + public static EventTrigger byName(String name) { + return Optional.ofNullable(BY_NAME.get(name)).orElseThrow(() -> new IllegalArgumentException("Unknown event trigger: " + name)); + } } diff --git a/core/src/main/java/net/momirealms/craftengine/core/registry/BuiltInRegistries.java b/core/src/main/java/net/momirealms/craftengine/core/registry/BuiltInRegistries.java index a92d3db1d..63e13ac40 100644 --- a/core/src/main/java/net/momirealms/craftengine/core/registry/BuiltInRegistries.java +++ b/core/src/main/java/net/momirealms/craftengine/core/registry/BuiltInRegistries.java @@ -21,12 +21,10 @@ import net.momirealms.craftengine.core.pack.model.select.SelectPropertyFactory; import net.momirealms.craftengine.core.pack.model.special.SpecialModelFactory; import net.momirealms.craftengine.core.pack.model.tint.TintFactory; import net.momirealms.craftengine.core.plugin.config.template.TemplateArgumentFactory; -import net.momirealms.craftengine.core.plugin.context.Condition; import net.momirealms.craftengine.core.plugin.context.PlayerBlockActionContext; import net.momirealms.craftengine.core.plugin.context.condition.ConditionFactory; -import net.momirealms.craftengine.core.plugin.context.function.Function; -import net.momirealms.craftengine.core.plugin.context.number.NumberProvider; -import net.momirealms.craftengine.core.util.Factory; +import net.momirealms.craftengine.core.plugin.context.function.FunctionFactory; +import net.momirealms.craftengine.core.plugin.context.number.NumberProviderFactory; import net.momirealms.craftengine.core.util.Key; import net.momirealms.craftengine.core.util.ResourceKey; @@ -39,7 +37,7 @@ public class BuiltInRegistries { public static final Registry> LOOT_FUNCTION_FACTORY = createRegistry(Registries.LOOT_FUNCTION_FACTORY); public static final Registry> LOOT_CONDITION_FACTORY = createRegistry(Registries.LOOT_CONDITION_FACTORY); public static final Registry> LOOT_ENTRY_CONTAINER_FACTORY = createRegistry(Registries.LOOT_ENTRY_CONTAINER_FACTORY); - public static final Registry> NUMBER_PROVIDER_FACTORY = createRegistry(Registries.NUMBER_PROVIDER_FACTORY); + public static final Registry NUMBER_PROVIDER_FACTORY = createRegistry(Registries.NUMBER_PROVIDER_FACTORY); public static final Registry TEMPLATE_ARGUMENT_FACTORY = createRegistry(Registries.TEMPLATE_ARGUMENT_FACTORY); public static final Registry ITEM_MODEL_FACTORY = createRegistry(Registries.ITEM_MODEL_FACTORY); public static final Registry TINT_FACTORY = createRegistry(Registries.TINT_FACTORY); @@ -54,8 +52,8 @@ public class BuiltInRegistries { public static final Registry SMITHING_RESULT_PROCESSOR_FACTORY = createRegistry(Registries.SMITHING_RESULT_PROCESSOR_FACTORY); public static final Registry HITBOX_FACTORY = createRegistry(Registries.HITBOX_FACTORY); public static final Registry RESOURCE_PACK_HOST_FACTORY = createRegistry(Registries.RESOURCE_PACK_HOST_FACTORY); - public static final Registry>> PLAYER_BLOCK_FUNCTION_FACTORY = createRegistry(Registries.PLAYER_BLOCK_FUNCTION_FACTORY); - public static final Registry>> PLAYER_BLOCK_CONDITION_FACTORY = createRegistry(Registries.PLAYER_BLOCK_CONDITION_FACTORY); + public static final Registry> PLAYER_BLOCK_FUNCTION_FACTORY = createRegistry(Registries.PLAYER_BLOCK_FUNCTION_FACTORY); + public static final Registry> PLAYER_BLOCK_CONDITION_FACTORY = createRegistry(Registries.PLAYER_BLOCK_CONDITION_FACTORY); private static Registry createRegistry(ResourceKey> key) { return new MappedRegistry<>(key); diff --git a/core/src/main/java/net/momirealms/craftengine/core/registry/Registries.java b/core/src/main/java/net/momirealms/craftengine/core/registry/Registries.java index 434302ba9..a5bd19c5d 100644 --- a/core/src/main/java/net/momirealms/craftengine/core/registry/Registries.java +++ b/core/src/main/java/net/momirealms/craftengine/core/registry/Registries.java @@ -21,12 +21,10 @@ import net.momirealms.craftengine.core.pack.model.select.SelectPropertyFactory; import net.momirealms.craftengine.core.pack.model.special.SpecialModelFactory; import net.momirealms.craftengine.core.pack.model.tint.TintFactory; import net.momirealms.craftengine.core.plugin.config.template.TemplateArgumentFactory; -import net.momirealms.craftengine.core.plugin.context.Condition; import net.momirealms.craftengine.core.plugin.context.PlayerBlockActionContext; import net.momirealms.craftengine.core.plugin.context.condition.ConditionFactory; -import net.momirealms.craftengine.core.plugin.context.function.Function; -import net.momirealms.craftengine.core.plugin.context.number.NumberProvider; -import net.momirealms.craftengine.core.util.Factory; +import net.momirealms.craftengine.core.plugin.context.function.FunctionFactory; +import net.momirealms.craftengine.core.plugin.context.number.NumberProviderFactory; import net.momirealms.craftengine.core.util.Key; import net.momirealms.craftengine.core.util.ResourceKey; @@ -40,7 +38,7 @@ public class Registries { public static final ResourceKey>> LOOT_FUNCTION_FACTORY = new ResourceKey<>(ROOT_REGISTRY, Key.withDefaultNamespace("loot_function_factory")); public static final ResourceKey>> LOOT_ENTRY_CONTAINER_FACTORY = new ResourceKey<>(ROOT_REGISTRY, Key.withDefaultNamespace("loot_entry_container_factory")); public static final ResourceKey>> LOOT_CONDITION_FACTORY = new ResourceKey<>(ROOT_REGISTRY, Key.withDefaultNamespace("loot_condition_factory")); - public static final ResourceKey>> NUMBER_PROVIDER_FACTORY = new ResourceKey<>(ROOT_REGISTRY, Key.withDefaultNamespace("number_provider_factory")); + public static final ResourceKey> NUMBER_PROVIDER_FACTORY = new ResourceKey<>(ROOT_REGISTRY, Key.withDefaultNamespace("number_provider_factory")); public static final ResourceKey> TEMPLATE_ARGUMENT_FACTORY = new ResourceKey<>(ROOT_REGISTRY, Key.withDefaultNamespace("template_argument_factory")); public static final ResourceKey> ITEM_MODEL_FACTORY = new ResourceKey<>(ROOT_REGISTRY, Key.withDefaultNamespace("item_model_factory")); public static final ResourceKey> TINT_FACTORY = new ResourceKey<>(ROOT_REGISTRY, Key.withDefaultNamespace("tint_factory")); @@ -55,6 +53,6 @@ public class Registries { public static final ResourceKey> SMITHING_RESULT_PROCESSOR_FACTORY = new ResourceKey<>(ROOT_REGISTRY, Key.withDefaultNamespace("smithing_result_processor_factory")); public static final ResourceKey> HITBOX_FACTORY = new ResourceKey<>(ROOT_REGISTRY, Key.withDefaultNamespace("hitbox_factory")); public static final ResourceKey> RESOURCE_PACK_HOST_FACTORY = new ResourceKey<>(ROOT_REGISTRY, Key.withDefaultNamespace("resource_pack_host_factory")); - public static final ResourceKey>>> PLAYER_BLOCK_FUNCTION_FACTORY = new ResourceKey<>(ROOT_REGISTRY, Key.withDefaultNamespace("player_block_function_factory")); - public static final ResourceKey>>> PLAYER_BLOCK_CONDITION_FACTORY = new ResourceKey<>(ROOT_REGISTRY, Key.withDefaultNamespace("player_block_condition_factory")); + public static final ResourceKey>> PLAYER_BLOCK_FUNCTION_FACTORY = new ResourceKey<>(ROOT_REGISTRY, Key.withDefaultNamespace("player_block_function_factory")); + public static final ResourceKey>> PLAYER_BLOCK_CONDITION_FACTORY = new ResourceKey<>(ROOT_REGISTRY, Key.withDefaultNamespace("player_block_condition_factory")); } diff --git a/core/src/main/java/net/momirealms/craftengine/core/util/ClickType.java b/core/src/main/java/net/momirealms/craftengine/core/util/ClickType.java new file mode 100644 index 000000000..1489885b7 --- /dev/null +++ b/core/src/main/java/net/momirealms/craftengine/core/util/ClickType.java @@ -0,0 +1,5 @@ +package net.momirealms.craftengine.core.util; + +public enum ClickType { + LEFT, RIGHT, MIDDLE +} diff --git a/core/src/main/java/net/momirealms/craftengine/core/util/Factory.java b/core/src/main/java/net/momirealms/craftengine/core/util/Factory.java deleted file mode 100644 index ec3e37b2f..000000000 --- a/core/src/main/java/net/momirealms/craftengine/core/util/Factory.java +++ /dev/null @@ -1,8 +0,0 @@ -package net.momirealms.craftengine.core.util; - -import java.util.Map; - -public interface Factory { - - T create(Map args); -} diff --git a/core/src/main/java/net/momirealms/craftengine/core/util/MCUtils.java b/core/src/main/java/net/momirealms/craftengine/core/util/MCUtils.java index 5ead78a3d..7886f0e0f 100644 --- a/core/src/main/java/net/momirealms/craftengine/core/util/MCUtils.java +++ b/core/src/main/java/net/momirealms/craftengine/core/util/MCUtils.java @@ -118,7 +118,6 @@ public class MCUtils { return false; } } - return true; }; } @@ -150,6 +149,70 @@ public class MCUtils { }; } + public static Predicate anyOf() { + return o -> false; + } + + @SuppressWarnings("unchecked") + public static Predicate anyOf(Predicate a) { + return (Predicate) a; + } + + public static Predicate anyOf(Predicate a, Predicate b) { + return o -> a.test(o) || b.test(o); + } + + public static Predicate anyOf(Predicate a, Predicate b, Predicate c) { + return o -> a.test(o) || b.test(o) || c.test(o); + } + + public static Predicate anyOf(Predicate a, Predicate b, Predicate c, Predicate d) { + return o -> a.test(o) || b.test(o) || c.test(o) || d.test(o); + } + + public static Predicate anyOf(Predicate a, Predicate b, Predicate c, Predicate d, Predicate e) { + return o -> a.test(o) || b.test(o) || c.test(o) || d.test(o) || e.test(o); + } + + @SafeVarargs + public static Predicate anyOf(Predicate... predicates) { + return o -> { + for (Predicate predicate : predicates) { + if (predicate.test(o)) { + return true; + } + } + return false; + }; + } + + public static Predicate anyOf(List> predicates) { + return switch (predicates.size()) { + case 0 -> anyOf(); + case 1 -> anyOf((Predicate) predicates.get(0)); + case 2 -> anyOf((Predicate) predicates.get(0), (Predicate) predicates.get(1)); + case 3 -> anyOf((Predicate) predicates.get(0), (Predicate) predicates.get(1), (Predicate) predicates.get(2)); + case 4 -> anyOf( + (Predicate) predicates.get(0), + (Predicate) predicates.get(1), + (Predicate) predicates.get(2), + (Predicate) predicates.get(3) + ); + case 5 -> anyOf( + (Predicate) predicates.get(0), + (Predicate) predicates.get(1), + (Predicate) predicates.get(2), + (Predicate) predicates.get(3), + (Predicate) predicates.get(4) + ); + default -> { + @SuppressWarnings("unchecked") + Predicate[] predicates2 = predicates.toArray(Predicate[]::new); + yield anyOf(predicates2); + } + }; + } + public static T findPreviousInIterable(Iterable iterable, @Nullable T object) { Iterator iterator = iterable.iterator(); T previous = null; diff --git a/server-mod/v1_20_1/build.gradle.kts b/server-mod/v1_20_1/build.gradle.kts index 8589cbe10..0266dd510 100644 --- a/server-mod/v1_20_1/build.gradle.kts +++ b/server-mod/v1_20_1/build.gradle.kts @@ -1,6 +1,6 @@ plugins { id("java-library") - id("com.gradleup.shadow") version "9.0.0-beta11" + id("com.gradleup.shadow") version "9.0.0-beta13" id("io.papermc.paperweight.userdev") version "2.0.0-beta.16" } diff --git a/server-mod/v1_20_1/src/main/java/net/momirealms/craftengine/mod/block/CraftEngineBlock.java b/server-mod/v1_20_1/src/main/java/net/momirealms/craftengine/mod/block/CraftEngineBlock.java index 09f390769..52214c52a 100644 --- a/server-mod/v1_20_1/src/main/java/net/momirealms/craftengine/mod/block/CraftEngineBlock.java +++ b/server-mod/v1_20_1/src/main/java/net/momirealms/craftengine/mod/block/CraftEngineBlock.java @@ -18,15 +18,15 @@ import net.momirealms.craftengine.mod.CraftEnginePlugin; import net.momirealms.craftengine.mod.util.NoteBlockUtils; import net.momirealms.craftengine.shared.ObjectHolder; import net.momirealms.craftengine.shared.block.*; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; import org.jetbrains.annotations.NotNull; @SuppressWarnings("deprecation") -public class CraftEngineBlock - extends Block - implements BehaviorHolder, ShapeHolder, NoteBlockIndicator, Fallable, BonemealableBlock - //TODO , SimpleWaterloggedBlock -{ +public class CraftEngineBlock extends Block + implements BehaviorHolder, ShapeHolder, NoteBlockIndicator, Fallable, BonemealableBlock { private static final StoneBlockShape STONE = new StoneBlockShape(Blocks.STONE.defaultBlockState()); + private static final Logger LOGGER = LogManager.getLogger(CraftEngineBlock.class); private boolean isNoteBlock; public ObjectHolder behaviorHolder; public ObjectHolder shapeHolder; @@ -39,30 +39,30 @@ public class CraftEngineBlock } public void setNoteBlock(boolean noteBlock) { - isNoteBlock = noteBlock; + this.isNoteBlock = noteBlock; } @Override public ObjectHolder getBehaviorHolder() { - return behaviorHolder; + return this.behaviorHolder; } @Override public ObjectHolder getShapeHolder() { - return shapeHolder; + return this.shapeHolder; } @Override public boolean isNoteBlock() { - return isClientSideNoteBlock; + return this.isClientSideNoteBlock; } @Override public @NotNull VoxelShape getShape(@NotNull BlockState state, @NotNull BlockGetter level, @NotNull BlockPos pos, @NotNull CollisionContext context) { try { - return (VoxelShape) shapeHolder.value().getShape(this, new Object[]{state, level, pos, context}); + return (VoxelShape) this.shapeHolder.value().getShape(this, new Object[]{state, level, pos, context}); } catch (Exception e) { - e.printStackTrace(); + LOGGER.error(e); return super.getShape(state, level, pos, context); } } @@ -72,7 +72,7 @@ public class CraftEngineBlock try { return (BlockState) this.behaviorHolder.value().rotate(this, new Object[]{state, rotation}, () -> super.rotate(state, rotation)); } catch (Exception e) { - e.printStackTrace(); + LOGGER.error(e); return super.rotate(state, rotation); } } @@ -82,7 +82,7 @@ public class CraftEngineBlock try { return (BlockState) this.behaviorHolder.value().mirror(this, new Object[]{state, mirror}, () -> super.mirror(state, mirror)); } catch (Exception e) { - e.printStackTrace(); + LOGGER.error(e); return super.mirror(state, mirror); } } @@ -95,7 +95,7 @@ public class CraftEngineBlock return null; }); } catch (Exception e) { - e.printStackTrace(); + LOGGER.error(e); super.tick(state, level, pos, random); } } @@ -103,12 +103,12 @@ public class CraftEngineBlock @Override public void randomTick(@NotNull BlockState state, @NotNull ServerLevel level, @NotNull BlockPos pos, @NotNull RandomSource random) { try { - behaviorHolder.value().randomTick(this, new Object[]{state, level, pos, random}, () -> { + this.behaviorHolder.value().randomTick(this, new Object[]{state, level, pos, random}, () -> { super.randomTick(state, level, pos, random); return null; }); } catch (Exception e) { - e.printStackTrace(); + LOGGER.error(e); super.randomTick(state, level, pos, random); } } @@ -116,12 +116,12 @@ public class CraftEngineBlock @Override public void onPlace(@NotNull BlockState state, @NotNull Level level, @NotNull BlockPos pos, @NotNull BlockState oldState, boolean movedByPiston) { try { - behaviorHolder.value().onPlace(this, new Object[]{state, level, pos, oldState, movedByPiston}, () -> { + this.behaviorHolder.value().onPlace(this, new Object[]{state, level, pos, oldState, movedByPiston}, () -> { super.onPlace(state, level, pos, oldState, movedByPiston); return null; }); } catch (Exception e) { - e.printStackTrace(); + LOGGER.error(e); super.onPlace(state, level, pos, oldState, movedByPiston); } } @@ -129,9 +129,9 @@ public class CraftEngineBlock @Override public void onBrokenAfterFall(@NotNull Level level, @NotNull BlockPos pos, @NotNull FallingBlockEntity fallingBlock) { try { - behaviorHolder.value().onBrokenAfterFall(this, new Object[]{level, pos, fallingBlock}); + this.behaviorHolder.value().onBrokenAfterFall(this, new Object[]{level, pos, fallingBlock}); } catch (Exception e) { - e.printStackTrace(); + LOGGER.error(e); Fallable.super.onBrokenAfterFall(level, pos, fallingBlock); } } @@ -139,27 +139,27 @@ public class CraftEngineBlock @Override public boolean canSurvive(@NotNull BlockState state, @NotNull LevelReader level, @NotNull BlockPos pos) { try { - return behaviorHolder.value().canSurvive(this, new Object[]{state, level, pos}, () -> super.canSurvive(state, level, pos)); + return this.behaviorHolder.value().canSurvive(this, new Object[]{state, level, pos}, () -> super.canSurvive(state, level, pos)); } catch (Exception e) { - e.printStackTrace(); + LOGGER.error(e); return super.canSurvive(state, level, pos); } } @Override - public BlockState updateShape(@NotNull BlockState state, - @NotNull Direction direction, - @NotNull BlockState neighborState, - @NotNull LevelAccessor world, - @NotNull BlockPos pos, - @NotNull BlockPos neighborPos) { + public @NotNull BlockState updateShape(@NotNull BlockState state, + @NotNull Direction direction, + @NotNull BlockState neighborState, + @NotNull LevelAccessor world, + @NotNull BlockPos pos, + @NotNull BlockPos neighborPos) { try { - if (isNoteBlock && world instanceof ServerLevel serverLevel) { + if (this.isNoteBlock && world instanceof ServerLevel serverLevel) { startNoteBlockChain(direction, serverLevel, pos); } - return (BlockState) behaviorHolder.value().updateShape(this, new Object[]{state, direction, neighborState, world, pos, neighborPos}, () -> super.updateShape(state, direction, neighborState, world, pos, neighborPos)); + return (BlockState) this.behaviorHolder.value().updateShape(this, new Object[]{state, direction, neighborState, world, pos, neighborPos}, () -> super.updateShape(state, direction, neighborState, world, pos, neighborPos)); } catch (Exception e) { - e.printStackTrace(); + LOGGER.error(e); return super.updateShape(state, direction, neighborState, world, pos, neighborPos); } } @@ -191,9 +191,9 @@ public class CraftEngineBlock @Override public boolean isValidBonemealTarget(@NotNull LevelReader world, @NotNull BlockPos pos, @NotNull BlockState state, boolean isClient) { try { - return behaviorHolder.value().isValidBoneMealTarget(this, new Object[]{world, pos, state, isClient}); + return this.behaviorHolder.value().isValidBoneMealTarget(this, new Object[]{world, pos, state, isClient}); } catch (Exception e) { - e.printStackTrace(); + LOGGER.error(e); return false; } } @@ -203,7 +203,7 @@ public class CraftEngineBlock try { return behaviorHolder.value().isBoneMealSuccess(this, new Object[]{level, randomSource, blockPos, blockState}); } catch (Exception e) { - e.printStackTrace(); + LOGGER.error(e); return false; } } @@ -211,49 +211,18 @@ public class CraftEngineBlock @Override public void performBonemeal(@NotNull ServerLevel serverLevel, @NotNull RandomSource randomSource, @NotNull BlockPos blockPos, @NotNull BlockState blockState) { try { - behaviorHolder.value().performBoneMeal(this, new Object[]{serverLevel, randomSource, blockPos, blockState}); + this.behaviorHolder.value().performBoneMeal(this, new Object[]{serverLevel, randomSource, blockPos, blockState}); } catch (Exception e) { - e.printStackTrace(); + LOGGER.error(e); } } @Override public void onLand(@NotNull Level level, @NotNull BlockPos pos, @NotNull BlockState state, @NotNull BlockState replaceableState, @NotNull FallingBlockEntity fallingBlock) { try { - behaviorHolder.value().onLand(this, new Object[]{level, pos, state, replaceableState, fallingBlock}); + this.behaviorHolder.value().onLand(this, new Object[]{level, pos, state, replaceableState, fallingBlock}); } catch (Exception e) { - e.printStackTrace(); + LOGGER.error(e); } } - -// @Override -// public boolean canPlaceLiquid(@Nullable Player player, @NotNull BlockGetter level, @NotNull BlockPos pos, @NotNull BlockState state, @NotNull Fluid fluid) { -// try { -// return behaviorHolder.value().canPlaceLiquid(this, new Object[]{player, level, pos, state, fluid}, () -> SimpleWaterloggedBlock.super.canPlaceLiquid(player, level, pos, state, fluid)); -// } catch (Exception e) { -// e.printStackTrace(); -// return SimpleWaterloggedBlock.super.canPlaceLiquid(player, level, pos, state, fluid); -// } -// } -// -// @Override -// public boolean placeLiquid(@NotNull LevelAccessor level, @NotNull BlockPos pos, @NotNull BlockState state, @NotNull FluidState fluidState) { -// try { -// return behaviorHolder.value().placeLiquid(this, new Object[]{level, pos, state, fluidState}, () -> SimpleWaterloggedBlock.super.placeLiquid(level, pos, state, fluidState)); -// } catch (Exception e) { -// e.printStackTrace(); -// return SimpleWaterloggedBlock.super.placeLiquid(level, pos, state, fluidState); -// } -// } -// -// @NotNull -// @Override -// public ItemStack pickupBlock(@Nullable Player player, @NotNull LevelAccessor level, @NotNull BlockPos pos, @NotNull BlockState state) { -// try { -// return (ItemStack) behaviorHolder.value().pickupBlock(this, new Object[]{player, level, pos, state}, () -> SimpleWaterloggedBlock.super.pickupBlock(player, level, pos, state)); -// } catch (Exception e) { -// e.printStackTrace(); -// return SimpleWaterloggedBlock.super.pickupBlock(player, level, pos, state); -// } -// } } diff --git a/server-mod/v1_20_5/build.gradle.kts b/server-mod/v1_20_5/build.gradle.kts index 272257de9..db31453d2 100644 --- a/server-mod/v1_20_5/build.gradle.kts +++ b/server-mod/v1_20_5/build.gradle.kts @@ -1,6 +1,6 @@ plugins { id("java-library") - id("com.gradleup.shadow") version "9.0.0-beta11" + id("com.gradleup.shadow") version "9.0.0-beta13" id("io.papermc.paperweight.userdev") version "2.0.0-beta.16" } diff --git a/server-mod/v1_20_5/src/main/java/net/momirealms/craftengine/mod/block/CraftEngineBlock.java b/server-mod/v1_20_5/src/main/java/net/momirealms/craftengine/mod/block/CraftEngineBlock.java index 8b3039c7b..4e37a60ef 100644 --- a/server-mod/v1_20_5/src/main/java/net/momirealms/craftengine/mod/block/CraftEngineBlock.java +++ b/server-mod/v1_20_5/src/main/java/net/momirealms/craftengine/mod/block/CraftEngineBlock.java @@ -18,14 +18,14 @@ import net.momirealms.craftengine.mod.CraftEnginePlugin; import net.momirealms.craftengine.mod.util.NoteBlockUtils; import net.momirealms.craftengine.shared.ObjectHolder; import net.momirealms.craftengine.shared.block.*; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; import org.jetbrains.annotations.NotNull; -public class CraftEngineBlock - extends Block - implements BehaviorHolder, ShapeHolder, NoteBlockIndicator, Fallable, BonemealableBlock - //TODO , SimpleWaterloggedBlock -{ +public class CraftEngineBlock extends Block + implements BehaviorHolder, ShapeHolder, NoteBlockIndicator, Fallable, BonemealableBlock { private static final StoneBlockShape STONE = new StoneBlockShape(Blocks.STONE.defaultBlockState()); + private static final Logger LOGGER = LogManager.getLogger(CraftEngineBlock.class); private boolean isNoteBlock; public ObjectHolder behaviorHolder; public ObjectHolder shapeHolder; @@ -38,30 +38,30 @@ public class CraftEngineBlock } public void setNoteBlock(boolean noteBlock) { - isNoteBlock = noteBlock; + this.isNoteBlock = noteBlock; } @Override public ObjectHolder getBehaviorHolder() { - return behaviorHolder; + return this.behaviorHolder; } @Override public ObjectHolder getShapeHolder() { - return shapeHolder; + return this.shapeHolder; } @Override public boolean isNoteBlock() { - return isClientSideNoteBlock; + return this.isClientSideNoteBlock; } @Override protected @NotNull VoxelShape getShape(@NotNull BlockState state, @NotNull BlockGetter level, @NotNull BlockPos pos, @NotNull CollisionContext context) { try { - return (VoxelShape) shapeHolder.value().getShape(this, new Object[]{state, level, pos, context}); + return (VoxelShape) this.shapeHolder.value().getShape(this, new Object[]{state, level, pos, context}); } catch (Exception e) { - e.printStackTrace(); + LOGGER.error(e); return super.getShape(state, level, pos, context); } } @@ -71,7 +71,7 @@ public class CraftEngineBlock try { return (BlockState) this.behaviorHolder.value().rotate(this, new Object[]{state, rotation}, () -> super.rotate(state, rotation)); } catch (Exception e) { - e.printStackTrace(); + LOGGER.error(e); return super.rotate(state, rotation); } } @@ -81,7 +81,7 @@ public class CraftEngineBlock try { return (BlockState) this.behaviorHolder.value().mirror(this, new Object[]{state, mirror}, () -> super.mirror(state, mirror)); } catch (Exception e) { - e.printStackTrace(); + LOGGER.error(e); return super.mirror(state, mirror); } } @@ -94,7 +94,7 @@ public class CraftEngineBlock return null; }); } catch (Exception e) { - e.printStackTrace(); + LOGGER.error(e); super.tick(state, level, pos, random); } } @@ -102,12 +102,12 @@ public class CraftEngineBlock @Override protected void randomTick(@NotNull BlockState state, @NotNull ServerLevel level, @NotNull BlockPos pos, @NotNull RandomSource random) { try { - behaviorHolder.value().randomTick(this, new Object[]{state, level, pos, random}, () -> { + this.behaviorHolder.value().randomTick(this, new Object[]{state, level, pos, random}, () -> { super.randomTick(state, level, pos, random); return null; }); } catch (Exception e) { - e.printStackTrace(); + LOGGER.error(e); super.randomTick(state, level, pos, random); } } @@ -115,12 +115,12 @@ public class CraftEngineBlock @Override protected void onPlace(@NotNull BlockState state, @NotNull Level level, @NotNull BlockPos pos, @NotNull BlockState oldState, boolean movedByPiston) { try { - behaviorHolder.value().onPlace(this, new Object[]{state, level, pos, oldState, movedByPiston}, () -> { + this.behaviorHolder.value().onPlace(this, new Object[]{state, level, pos, oldState, movedByPiston}, () -> { super.onPlace(state, level, pos, oldState, movedByPiston); return null; }); } catch (Exception e) { - e.printStackTrace(); + LOGGER.error(e); super.onPlace(state, level, pos, oldState, movedByPiston); } } @@ -128,9 +128,9 @@ public class CraftEngineBlock @Override public void onBrokenAfterFall(@NotNull Level level, @NotNull BlockPos pos, @NotNull FallingBlockEntity fallingBlock) { try { - behaviorHolder.value().onBrokenAfterFall(this, new Object[]{level, pos, fallingBlock}); + this.behaviorHolder.value().onBrokenAfterFall(this, new Object[]{level, pos, fallingBlock}); } catch (Exception e) { - e.printStackTrace(); + LOGGER.error(e); Fallable.super.onBrokenAfterFall(level, pos, fallingBlock); } } @@ -138,29 +138,29 @@ public class CraftEngineBlock @Override protected boolean canSurvive(@NotNull BlockState state, @NotNull LevelReader level, @NotNull BlockPos pos) { try { - return behaviorHolder.value().canSurvive(this, new Object[]{state, level, pos}, () -> super.canSurvive(state, level, pos)); + return this.behaviorHolder.value().canSurvive(this, new Object[]{state, level, pos}, () -> super.canSurvive(state, level, pos)); } catch (Exception e) { - e.printStackTrace(); + LOGGER.error(e); return super.canSurvive(state, level, pos); } } @Override - protected BlockState updateShape(@NotNull BlockState state, - @NotNull LevelReader level, - @NotNull ScheduledTickAccess scheduledTickAccess, - @NotNull BlockPos pos, - @NotNull Direction direction, - @NotNull BlockPos neighborPos, - @NotNull BlockState neighborState, - @NotNull RandomSource random) { + protected @NotNull BlockState updateShape(@NotNull BlockState state, + @NotNull LevelReader level, + @NotNull ScheduledTickAccess scheduledTickAccess, + @NotNull BlockPos pos, + @NotNull Direction direction, + @NotNull BlockPos neighborPos, + @NotNull BlockState neighborState, + @NotNull RandomSource random) { try { - if (isNoteBlock && level instanceof ServerLevel serverLevel) { + if (this.isNoteBlock && level instanceof ServerLevel serverLevel) { startNoteBlockChain(direction, serverLevel, pos); } - return (BlockState) behaviorHolder.value().updateShape(this, new Object[]{state, level, scheduledTickAccess, pos, direction, neighborPos, neighborState, random}, () -> super.updateShape(state, level, scheduledTickAccess, pos, direction, neighborPos, neighborState, random)); + return (BlockState) this.behaviorHolder.value().updateShape(this, new Object[]{state, level, scheduledTickAccess, pos, direction, neighborPos, neighborState, random}, () -> super.updateShape(state, level, scheduledTickAccess, pos, direction, neighborPos, neighborState, random)); } catch (Exception e) { - e.printStackTrace(); + LOGGER.error(e); return super.updateShape(state, level, scheduledTickAccess, pos, direction, neighborPos, neighborState, random); } } @@ -189,22 +189,12 @@ public class CraftEngineBlock } } -// @Override -// protected @NotNull FluidState getFluidState(@NotNull BlockState state) { -// try { -// return (FluidState) behaviorHolder.value().getFluidState(this, new Object[]{state}, () -> super.getFluidState(state)); -// } catch (Exception e) { -// e.printStackTrace(); -// return super.getFluidState(state); -// } -// } - @Override public boolean isValidBonemealTarget(@NotNull LevelReader levelReader, @NotNull BlockPos blockPos, @NotNull BlockState blockState) { try { - return behaviorHolder.value().isValidBoneMealTarget(this, new Object[]{levelReader, blockPos, blockState}); + return this.behaviorHolder.value().isValidBoneMealTarget(this, new Object[]{levelReader, blockPos, blockState}); } catch (Exception e) { - e.printStackTrace(); + LOGGER.error(e); return false; } } @@ -212,9 +202,9 @@ public class CraftEngineBlock @Override public boolean isBonemealSuccess(@NotNull Level level, @NotNull RandomSource randomSource, @NotNull BlockPos blockPos, @NotNull BlockState blockState) { try { - return behaviorHolder.value().isBoneMealSuccess(this, new Object[]{level, randomSource, blockPos, blockState}); + return this.behaviorHolder.value().isBoneMealSuccess(this, new Object[]{level, randomSource, blockPos, blockState}); } catch (Exception e) { - e.printStackTrace(); + LOGGER.error(e); return false; } } @@ -222,49 +212,18 @@ public class CraftEngineBlock @Override public void performBonemeal(@NotNull ServerLevel serverLevel, @NotNull RandomSource randomSource, @NotNull BlockPos blockPos, @NotNull BlockState blockState) { try { - behaviorHolder.value().performBoneMeal(this, new Object[]{serverLevel, randomSource, blockPos, blockState}); + this.behaviorHolder.value().performBoneMeal(this, new Object[]{serverLevel, randomSource, blockPos, blockState}); } catch (Exception e) { - e.printStackTrace(); + LOGGER.error(e); } } @Override public void onLand(@NotNull Level level, @NotNull BlockPos pos, @NotNull BlockState state, @NotNull BlockState replaceableState, @NotNull FallingBlockEntity fallingBlock) { try { - behaviorHolder.value().onLand(this, new Object[]{level, pos, state, replaceableState, fallingBlock}); + this.behaviorHolder.value().onLand(this, new Object[]{level, pos, state, replaceableState, fallingBlock}); } catch (Exception e) { - e.printStackTrace(); + LOGGER.error(e); } } - -// @Override -// public boolean canPlaceLiquid(@Nullable Player player, @NotNull BlockGetter level, @NotNull BlockPos pos, @NotNull BlockState state, @NotNull Fluid fluid) { -// try { -// return behaviorHolder.value().canPlaceLiquid(this, new Object[]{player, level, pos, state, fluid}, () -> SimpleWaterloggedBlock.super.canPlaceLiquid(player, level, pos, state, fluid)); -// } catch (Exception e) { -// e.printStackTrace(); -// return SimpleWaterloggedBlock.super.canPlaceLiquid(player, level, pos, state, fluid); -// } -// } -// -// @Override -// public boolean placeLiquid(@NotNull LevelAccessor level, @NotNull BlockPos pos, @NotNull BlockState state, @NotNull FluidState fluidState) { -// try { -// return behaviorHolder.value().placeLiquid(this, new Object[]{level, pos, state, fluidState}, () -> SimpleWaterloggedBlock.super.placeLiquid(level, pos, state, fluidState)); -// } catch (Exception e) { -// e.printStackTrace(); -// return SimpleWaterloggedBlock.super.placeLiquid(level, pos, state, fluidState); -// } -// } -// -// @NotNull -// @Override -// public ItemStack pickupBlock(@Nullable Player player, @NotNull LevelAccessor level, @NotNull BlockPos pos, @NotNull BlockState state) { -// try { -// return (ItemStack) behaviorHolder.value().pickupBlock(this, new Object[]{player, level, pos, state}, () -> SimpleWaterloggedBlock.super.pickupBlock(player, level, pos, state)); -// } catch (Exception e) { -// e.printStackTrace(); -// return SimpleWaterloggedBlock.super.pickupBlock(player, level, pos, state); -// } -// } } diff --git a/server-mod/v1_21_5/build.gradle.kts b/server-mod/v1_21_5/build.gradle.kts index 0be3a008a..617f52ce2 100644 --- a/server-mod/v1_21_5/build.gradle.kts +++ b/server-mod/v1_21_5/build.gradle.kts @@ -1,6 +1,6 @@ plugins { id("java-library") - id("com.gradleup.shadow") version "9.0.0-beta11" + id("com.gradleup.shadow") version "9.0.0-beta13" id("io.papermc.paperweight.userdev") version "2.0.0-beta.16" } diff --git a/server-mod/v1_21_5/src/main/java/net/momirealms/craftengine/mod/block/CraftEngineBlock.java b/server-mod/v1_21_5/src/main/java/net/momirealms/craftengine/mod/block/CraftEngineBlock.java index 8b3039c7b..212e34087 100644 --- a/server-mod/v1_21_5/src/main/java/net/momirealms/craftengine/mod/block/CraftEngineBlock.java +++ b/server-mod/v1_21_5/src/main/java/net/momirealms/craftengine/mod/block/CraftEngineBlock.java @@ -18,14 +18,14 @@ import net.momirealms.craftengine.mod.CraftEnginePlugin; import net.momirealms.craftengine.mod.util.NoteBlockUtils; import net.momirealms.craftengine.shared.ObjectHolder; import net.momirealms.craftengine.shared.block.*; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; import org.jetbrains.annotations.NotNull; -public class CraftEngineBlock - extends Block - implements BehaviorHolder, ShapeHolder, NoteBlockIndicator, Fallable, BonemealableBlock - //TODO , SimpleWaterloggedBlock -{ +public class CraftEngineBlock extends Block + implements BehaviorHolder, ShapeHolder, NoteBlockIndicator, Fallable, BonemealableBlock { private static final StoneBlockShape STONE = new StoneBlockShape(Blocks.STONE.defaultBlockState()); + private static final Logger LOGGER = LogManager.getLogger(CraftEngineBlock.class); private boolean isNoteBlock; public ObjectHolder behaviorHolder; public ObjectHolder shapeHolder; @@ -38,30 +38,30 @@ public class CraftEngineBlock } public void setNoteBlock(boolean noteBlock) { - isNoteBlock = noteBlock; + this.isNoteBlock = noteBlock; } @Override public ObjectHolder getBehaviorHolder() { - return behaviorHolder; + return this.behaviorHolder; } @Override public ObjectHolder getShapeHolder() { - return shapeHolder; + return this.shapeHolder; } @Override public boolean isNoteBlock() { - return isClientSideNoteBlock; + return this.isClientSideNoteBlock; } @Override protected @NotNull VoxelShape getShape(@NotNull BlockState state, @NotNull BlockGetter level, @NotNull BlockPos pos, @NotNull CollisionContext context) { try { - return (VoxelShape) shapeHolder.value().getShape(this, new Object[]{state, level, pos, context}); + return (VoxelShape) this.shapeHolder.value().getShape(this, new Object[]{state, level, pos, context}); } catch (Exception e) { - e.printStackTrace(); + LOGGER.error(e); return super.getShape(state, level, pos, context); } } @@ -71,7 +71,7 @@ public class CraftEngineBlock try { return (BlockState) this.behaviorHolder.value().rotate(this, new Object[]{state, rotation}, () -> super.rotate(state, rotation)); } catch (Exception e) { - e.printStackTrace(); + LOGGER.error(e); return super.rotate(state, rotation); } } @@ -81,7 +81,7 @@ public class CraftEngineBlock try { return (BlockState) this.behaviorHolder.value().mirror(this, new Object[]{state, mirror}, () -> super.mirror(state, mirror)); } catch (Exception e) { - e.printStackTrace(); + LOGGER.error(e); return super.mirror(state, mirror); } } @@ -94,7 +94,7 @@ public class CraftEngineBlock return null; }); } catch (Exception e) { - e.printStackTrace(); + LOGGER.error(e); super.tick(state, level, pos, random); } } @@ -107,7 +107,7 @@ public class CraftEngineBlock return null; }); } catch (Exception e) { - e.printStackTrace(); + LOGGER.error(e); super.randomTick(state, level, pos, random); } } @@ -120,7 +120,7 @@ public class CraftEngineBlock return null; }); } catch (Exception e) { - e.printStackTrace(); + LOGGER.error(e); super.onPlace(state, level, pos, oldState, movedByPiston); } } @@ -128,9 +128,9 @@ public class CraftEngineBlock @Override public void onBrokenAfterFall(@NotNull Level level, @NotNull BlockPos pos, @NotNull FallingBlockEntity fallingBlock) { try { - behaviorHolder.value().onBrokenAfterFall(this, new Object[]{level, pos, fallingBlock}); + this.behaviorHolder.value().onBrokenAfterFall(this, new Object[]{level, pos, fallingBlock}); } catch (Exception e) { - e.printStackTrace(); + LOGGER.error(e); Fallable.super.onBrokenAfterFall(level, pos, fallingBlock); } } @@ -138,29 +138,29 @@ public class CraftEngineBlock @Override protected boolean canSurvive(@NotNull BlockState state, @NotNull LevelReader level, @NotNull BlockPos pos) { try { - return behaviorHolder.value().canSurvive(this, new Object[]{state, level, pos}, () -> super.canSurvive(state, level, pos)); + return this.behaviorHolder.value().canSurvive(this, new Object[]{state, level, pos}, () -> super.canSurvive(state, level, pos)); } catch (Exception e) { - e.printStackTrace(); + LOGGER.error(e); return super.canSurvive(state, level, pos); } } @Override - protected BlockState updateShape(@NotNull BlockState state, - @NotNull LevelReader level, - @NotNull ScheduledTickAccess scheduledTickAccess, - @NotNull BlockPos pos, - @NotNull Direction direction, - @NotNull BlockPos neighborPos, - @NotNull BlockState neighborState, - @NotNull RandomSource random) { + protected @NotNull BlockState updateShape(@NotNull BlockState state, + @NotNull LevelReader level, + @NotNull ScheduledTickAccess scheduledTickAccess, + @NotNull BlockPos pos, + @NotNull Direction direction, + @NotNull BlockPos neighborPos, + @NotNull BlockState neighborState, + @NotNull RandomSource random) { try { - if (isNoteBlock && level instanceof ServerLevel serverLevel) { + if (this.isNoteBlock && level instanceof ServerLevel serverLevel) { startNoteBlockChain(direction, serverLevel, pos); } - return (BlockState) behaviorHolder.value().updateShape(this, new Object[]{state, level, scheduledTickAccess, pos, direction, neighborPos, neighborState, random}, () -> super.updateShape(state, level, scheduledTickAccess, pos, direction, neighborPos, neighborState, random)); + return (BlockState) this.behaviorHolder.value().updateShape(this, new Object[]{state, level, scheduledTickAccess, pos, direction, neighborPos, neighborState, random}, () -> super.updateShape(state, level, scheduledTickAccess, pos, direction, neighborPos, neighborState, random)); } catch (Exception e) { - e.printStackTrace(); + LOGGER.error(e); return super.updateShape(state, level, scheduledTickAccess, pos, direction, neighborPos, neighborState, random); } } @@ -189,22 +189,12 @@ public class CraftEngineBlock } } -// @Override -// protected @NotNull FluidState getFluidState(@NotNull BlockState state) { -// try { -// return (FluidState) behaviorHolder.value().getFluidState(this, new Object[]{state}, () -> super.getFluidState(state)); -// } catch (Exception e) { -// e.printStackTrace(); -// return super.getFluidState(state); -// } -// } - @Override public boolean isValidBonemealTarget(@NotNull LevelReader levelReader, @NotNull BlockPos blockPos, @NotNull BlockState blockState) { try { - return behaviorHolder.value().isValidBoneMealTarget(this, new Object[]{levelReader, blockPos, blockState}); + return this.behaviorHolder.value().isValidBoneMealTarget(this, new Object[]{levelReader, blockPos, blockState}); } catch (Exception e) { - e.printStackTrace(); + LOGGER.error(e); return false; } } @@ -212,9 +202,9 @@ public class CraftEngineBlock @Override public boolean isBonemealSuccess(@NotNull Level level, @NotNull RandomSource randomSource, @NotNull BlockPos blockPos, @NotNull BlockState blockState) { try { - return behaviorHolder.value().isBoneMealSuccess(this, new Object[]{level, randomSource, blockPos, blockState}); + return this.behaviorHolder.value().isBoneMealSuccess(this, new Object[]{level, randomSource, blockPos, blockState}); } catch (Exception e) { - e.printStackTrace(); + LOGGER.error(e); return false; } } @@ -222,49 +212,18 @@ public class CraftEngineBlock @Override public void performBonemeal(@NotNull ServerLevel serverLevel, @NotNull RandomSource randomSource, @NotNull BlockPos blockPos, @NotNull BlockState blockState) { try { - behaviorHolder.value().performBoneMeal(this, new Object[]{serverLevel, randomSource, blockPos, blockState}); + this.behaviorHolder.value().performBoneMeal(this, new Object[]{serverLevel, randomSource, blockPos, blockState}); } catch (Exception e) { - e.printStackTrace(); + LOGGER.error(e); } } @Override public void onLand(@NotNull Level level, @NotNull BlockPos pos, @NotNull BlockState state, @NotNull BlockState replaceableState, @NotNull FallingBlockEntity fallingBlock) { try { - behaviorHolder.value().onLand(this, new Object[]{level, pos, state, replaceableState, fallingBlock}); + this.behaviorHolder.value().onLand(this, new Object[]{level, pos, state, replaceableState, fallingBlock}); } catch (Exception e) { - e.printStackTrace(); + LOGGER.error(e); } } - -// @Override -// public boolean canPlaceLiquid(@Nullable Player player, @NotNull BlockGetter level, @NotNull BlockPos pos, @NotNull BlockState state, @NotNull Fluid fluid) { -// try { -// return behaviorHolder.value().canPlaceLiquid(this, new Object[]{player, level, pos, state, fluid}, () -> SimpleWaterloggedBlock.super.canPlaceLiquid(player, level, pos, state, fluid)); -// } catch (Exception e) { -// e.printStackTrace(); -// return SimpleWaterloggedBlock.super.canPlaceLiquid(player, level, pos, state, fluid); -// } -// } -// -// @Override -// public boolean placeLiquid(@NotNull LevelAccessor level, @NotNull BlockPos pos, @NotNull BlockState state, @NotNull FluidState fluidState) { -// try { -// return behaviorHolder.value().placeLiquid(this, new Object[]{level, pos, state, fluidState}, () -> SimpleWaterloggedBlock.super.placeLiquid(level, pos, state, fluidState)); -// } catch (Exception e) { -// e.printStackTrace(); -// return SimpleWaterloggedBlock.super.placeLiquid(level, pos, state, fluidState); -// } -// } -// -// @NotNull -// @Override -// public ItemStack pickupBlock(@Nullable Player player, @NotNull LevelAccessor level, @NotNull BlockPos pos, @NotNull BlockState state) { -// try { -// return (ItemStack) behaviorHolder.value().pickupBlock(this, new Object[]{player, level, pos, state}, () -> SimpleWaterloggedBlock.super.pickupBlock(player, level, pos, state)); -// } catch (Exception e) { -// e.printStackTrace(); -// return SimpleWaterloggedBlock.super.pickupBlock(player, level, pos, state); -// } -// } } diff --git a/shared/src/main/java/net/momirealms/craftengine/shared/block/BlockBehavior.java b/shared/src/main/java/net/momirealms/craftengine/shared/block/BlockBehavior.java index 67c22fbd8..24e08c8b3 100644 --- a/shared/src/main/java/net/momirealms/craftengine/shared/block/BlockBehavior.java +++ b/shared/src/main/java/net/momirealms/craftengine/shared/block/BlockBehavior.java @@ -48,20 +48,4 @@ public abstract class BlockBehavior { public void performBoneMeal(Object thisBlock, Object[] args) throws Exception { } - -// -// public Object getFluidState(Object thisBlock, Object[] args, Callable superMethod) throws Exception { -// return superMethod.call(); -// } -// public boolean canPlaceLiquid(Object thisBlock, Object[] args, Callable superMethod) throws Exception { -// return (boolean) superMethod.call(); -// } -// -// public boolean placeLiquid(Object thisBlock, Object[] args, Callable superMethod) throws Exception { -// return (boolean) superMethod.call(); -// } -// -// public Object pickupBlock(Object thisBlock, Object[] args, Callable superMethod) throws Exception { -// return superMethod.call(); -// } }