From ff15f45ea0ea26428952bf5ccc31cd3e120fdfe7 Mon Sep 17 00:00:00 2001 From: Tschipp Date: Tue, 21 Dec 2021 11:00:11 +0100 Subject: [PATCH] cleaned up some code --- src/main/java/tschipp/carryon/CarryOn.java | 4 +- .../client/event/RenderEntityEvents.java | 53 +-- .../carryon/client/event/RenderEvents.java | 67 ++- .../client/helper/CarryRenderHelper.java | 12 +- .../client/keybinds/CarryOnKeybinds.java | 14 +- .../common/capabilities/IPosition.java | 12 +- .../common/capabilities/PositionProvider.java | 30 +- .../common/capabilities/TEPosition.java | 15 +- .../event/PositionClientEvents.java | 45 +- .../event/PositionCommonEvents.java | 21 +- .../common/command/CommandCarryOn.java | 15 +- .../carryon/common/config/CarryOnConfig.java | 1 - .../carryon/common/config/Configs.java | 436 +++++------------ .../carryon/common/event/IMCEvents.java | 10 +- .../common/event/ItemEntityEvents.java | 69 ++- .../carryon/common/event/ItemEvents.java | 154 +++--- .../handler/CustomPickupOverrideHandler.java | 23 +- .../carryon/common/handler/ListHandler.java | 88 ++-- .../common/handler/ModelOverridesHandler.java | 16 +- .../carryon/common/handler/PickupHandler.java | 130 ++--- .../common/handler/RegistrationHandler.java | 24 +- .../common/helper/CarryonGamestageHelper.java | 2 +- .../common/helper/InvalidConfigException.java | 10 +- .../helper/KeyboardCallbackWrapper.java | 12 +- .../common/helper/ReflectionHelper.java | 395 ++++++++-------- .../common/helper/ScriptParseHelper.java | 143 ++++-- .../common/helper/ScrollCallbackWrapper.java | 8 +- .../carryon/common/helper/StringParser.java | 39 +- .../carryon/common/item/ItemCarryonBlock.java | 155 +++--- .../common/item/ItemCarryonEntity.java | 123 +++-- .../common/scripting/CarryOnOverride.java | 444 +++++++----------- .../common/scripting/ScriptChecker.java | 72 ++- .../common/scripting/ScriptReader.java | 354 +++++++------- .../scripting/ScriptReloadListener.java | 6 +- .../compat/obfuscate/ObfuscateEvents.java | 207 ++++---- .../network/client/CarrySlotPacket.java | 20 +- .../network/client/ScriptReloadPacket.java | 20 +- .../network/server/SyncKeybindPacket.java | 4 +- .../tschipp/carryon/proxy/ClientProxy.java | 12 +- .../java/tschipp/carryon/proxy/IProxy.java | 6 +- 40 files changed, 1477 insertions(+), 1794 deletions(-) diff --git a/src/main/java/tschipp/carryon/CarryOn.java b/src/main/java/tschipp/carryon/CarryOn.java index 1d47646..7dfcfaa 100644 --- a/src/main/java/tschipp/carryon/CarryOn.java +++ b/src/main/java/tschipp/carryon/CarryOn.java @@ -66,10 +66,10 @@ public class CarryOn // CLIENT PACKETS CarryOn.network.registerMessage(0, CarrySlotPacket.class, CarrySlotPacket::toBytes, CarrySlotPacket::new, CarrySlotPacket::handle, Optional.of(NetworkDirection.PLAY_TO_CLIENT)); - CarryOn.network.registerMessage(1, ScriptReloadPacket.class, ScriptReloadPacket::toBytes, ScriptReloadPacket::new, ScriptReloadPacket::handle, Optional.of(NetworkDirection.PLAY_TO_CLIENT)); + CarryOn.network.registerMessage(1, ScriptReloadPacket.class, ScriptReloadPacket::toBytes, ScriptReloadPacket::new, ScriptReloadPacket::handle, Optional.of(NetworkDirection.PLAY_TO_CLIENT)); // SERVER PACKETS - CarryOn.network.registerMessage(2, SyncKeybindPacket.class, SyncKeybindPacket::toBytes, SyncKeybindPacket::new, SyncKeybindPacket::handle, Optional.of(NetworkDirection.PLAY_TO_SERVER)); + CarryOn.network.registerMessage(2, SyncKeybindPacket.class, SyncKeybindPacket::toBytes, SyncKeybindPacket::new, SyncKeybindPacket::handle, Optional.of(NetworkDirection.PLAY_TO_SERVER)); RegistrationHandler.regCommonEvents(); diff --git a/src/main/java/tschipp/carryon/client/event/RenderEntityEvents.java b/src/main/java/tschipp/carryon/client/event/RenderEntityEvents.java index 75a6d40..f789e1e 100644 --- a/src/main/java/tschipp/carryon/client/event/RenderEntityEvents.java +++ b/src/main/java/tschipp/carryon/client/event/RenderEntityEvents.java @@ -4,8 +4,6 @@ import java.util.HashMap; import java.util.Map; import java.util.Optional; -import com.mojang.blaze3d.platform.Lighting; -import com.mojang.blaze3d.systems.RenderSystem; import com.mojang.blaze3d.vertex.PoseStack; import com.mojang.math.Vector3f; @@ -34,31 +32,30 @@ import tschipp.carryon.common.scripting.ScriptChecker; public class RenderEntityEvents { - + public static final Map nbtEntityMap = new HashMap<>(); - + public static Entity getEntity(ItemStack carried, Level world) { String nbt = ItemCarryonEntity.getPersistentData(carried).toString(); - if(nbtEntityMap.containsKey(nbt)) + if (nbtEntityMap.containsKey(nbt)) { return nbtEntityMap.get(nbt); } - + Entity entity = ItemCarryonEntity.getEntity(carried, world); nbtEntityMap.put(nbt, entity); - + return entity; } - + @OnlyIn(Dist.CLIENT) @SubscribeEvent public void onWorldUnload(WorldEvent.Unload event) { nbtEntityMap.clear(); } - - + /* * Renders the Entity in First Person */ @@ -75,52 +72,52 @@ public class RenderEntityEvents int light = event.getLight(); MultiBufferSource buffer = event.getBuffers(); EntityRenderDispatcher manager = Minecraft.getInstance().getEntityRenderDispatcher(); - + if (!stack.isEmpty() && stack.getItem() == RegistrationHandler.itemEntity && ItemCarryonEntity.hasEntityData(stack)) { - if(ModList.get().isLoaded("realrender") || ModList.get().isLoaded("rfpr")) + if (ModList.get().isLoaded("realrender") || ModList.get().isLoaded("rfpr")) return; - + Entity entity = getEntity(stack, world); if (entity != null) { Vec3 playerpos = CarryRenderHelper.getExactPos(player, partialticks); - + entity.setPos(playerpos.x, playerpos.y, playerpos.z); entity.xRotO = 0.0f; entity.yRotO = 0.0f; entity.setYHeadRot(0.0f); - + float height = entity.getBbHeight(); float width = entity.getBbWidth(); - + matrix.pushPose(); matrix.scale(0.8f, 0.8f, 0.8f); matrix.mulPose(Vector3f.YP.rotationDegrees(180)); matrix.translate(0.0, -height - .1, width + 0.1); - -// RenderSystem.enableAlphaTest(); + + // RenderSystem.enableAlphaTest(); if (perspective == 0) { -// Lighting.en + // Lighting.en manager.setRenderShadow(false); CarryOnOverride carryOverride = ScriptChecker.getOverride(player); if (carryOverride != null) { CarryRenderHelper.performOverrideTransformation(matrix, carryOverride); - + String entityname = carryOverride.getRenderNameEntity(); if (entityname != null) { Entity newEntity = null; Optional> type = EntityType.byString(entityname); - if(type.isPresent()) + if (type.isPresent()) newEntity = type.get().create(world); - + if (newEntity != null) { CompoundTag nbttag = carryOverride.getRenderNBT(); @@ -135,19 +132,19 @@ public class RenderEntityEvents } } - if(entity instanceof LivingEntity) + if (entity instanceof LivingEntity) ((LivingEntity) entity).hurtTime = 0; - + manager.render(entity, 0, 0, 0, 0f, 0, matrix, buffer, light); manager.setRenderShadow(true); } -// RenderSystem.disableAlphaTest(); + // RenderSystem.disableAlphaTest(); matrix.popPose(); -// Lighting.turnOff(); -// TODO -// RenderSystem.disableRescaleNormal(); + // Lighting.turnOff(); + // TODO + // RenderSystem.disableRescaleNormal(); if (perspective == 0) { diff --git a/src/main/java/tschipp/carryon/client/event/RenderEvents.java b/src/main/java/tschipp/carryon/client/event/RenderEvents.java index e6f7549..da0beb8 100644 --- a/src/main/java/tschipp/carryon/client/event/RenderEvents.java +++ b/src/main/java/tschipp/carryon/client/event/RenderEvents.java @@ -3,7 +3,6 @@ package tschipp.carryon.client.event; import java.lang.reflect.InvocationTargetException; import java.util.Optional; -import com.mojang.blaze3d.platform.Lighting; import com.mojang.blaze3d.systems.RenderSystem; import com.mojang.blaze3d.vertex.PoseStack; import com.mojang.blaze3d.vertex.Tesselator; @@ -164,7 +163,7 @@ public class RenderEvents { ItemStack stack = player.getItemInHand(InteractionHand.MAIN_HAND); - if (!stack.isEmpty() && ((stack.getItem() == RegistrationHandler.itemTile && ItemCarryonBlock.hasTileData(stack)) || (stack.getItem() == RegistrationHandler.itemEntity && ItemCarryonEntity.hasEntityData(stack)))) + if (!stack.isEmpty() && (stack.getItem() == RegistrationHandler.itemTile && ItemCarryonBlock.hasTileData(stack) || stack.getItem() == RegistrationHandler.itemEntity && ItemCarryonEntity.hasEntityData(stack))) { Minecraft.getInstance().player.closeContainer(); Minecraft.getInstance().screen = null; @@ -193,7 +192,7 @@ public class RenderEvents { ItemStack stack = Minecraft.getInstance().player.getMainHandItem(); - if (!stack.isEmpty() && ((stack.getItem() == RegistrationHandler.itemTile && ItemCarryonBlock.hasTileData(stack)) || (stack.getItem() == RegistrationHandler.itemEntity && ItemCarryonEntity.hasEntityData(stack)))) + if (!stack.isEmpty() && (stack.getItem() == RegistrationHandler.itemTile && ItemCarryonBlock.hasTileData(stack) || stack.getItem() == RegistrationHandler.itemEntity && ItemCarryonEntity.hasEntityData(stack))) { if (settings.keyDrop.matches(key, scancode)) { @@ -268,7 +267,7 @@ public class RenderEvents matrix.mulPose(Vector3f.XP.rotationDegrees(8)); } - BakedModel model = ModelOverridesHandler.hasCustomOverrideModel(state, tag) ? ModelOverridesHandler.getCustomOverrideModel(state, tag, world, player) : (tileStack.isEmpty() ? Minecraft.getInstance().getBlockRenderer().getBlockModel(state) : Minecraft.getInstance().getItemRenderer().getModel(tileStack, world, player, 0)); + BakedModel model = ModelOverridesHandler.hasCustomOverrideModel(state, tag) ? ModelOverridesHandler.getCustomOverrideModel(state, tag, world, player) : tileStack.isEmpty() ? Minecraft.getInstance().getBlockRenderer().getBlockModel(state) : Minecraft.getInstance().getItemRenderer().getModel(tileStack, world, player, 0); CarryOnOverride carryOverride = ScriptChecker.getOverride(player); if (carryOverride != null) @@ -333,7 +332,7 @@ public class RenderEvents if (perspective == 0 && player == Minecraft.getInstance().player) continue; - light = Minecraft.getInstance().getEntityRenderDispatcher().getPackedLightCoords(player, partialticks); + light = manager.getPackedLightCoords(player, partialticks); ItemStack stack = player.getMainHandItem(); if (!stack.isEmpty() && stack.getItem() == RegistrationHandler.itemTile && ItemCarryonBlock.hasTileData(stack)) @@ -345,7 +344,7 @@ public class RenderEvents applyBlockTransformations(player, partialticks, matrix, block); - BakedModel model = ModelOverridesHandler.hasCustomOverrideModel(state, tag) ? ModelOverridesHandler.getCustomOverrideModel(state, tag, world, player) : (tileItem.isEmpty() ? Minecraft.getInstance().getBlockRenderer().getBlockModel(state) : Minecraft.getInstance().getItemRenderer().getModel(tileItem, world, player, 0)); + BakedModel model = ModelOverridesHandler.hasCustomOverrideModel(state, tag) ? ModelOverridesHandler.getCustomOverrideModel(state, tag, world, player) : tileItem.isEmpty() ? Minecraft.getInstance().getBlockRenderer().getBlockModel(state) : Minecraft.getInstance().getItemRenderer().getModel(tileItem, world, player, 0); CarryOnOverride carryOverride = ScriptChecker.getOverride(player); if (carryOverride != null) @@ -365,7 +364,7 @@ public class RenderEvents } RenderSystem.setShaderTexture(0, TextureAtlas.LOCATION_BLOCKS); - //TODO: Fix block light + // TODO: Fix block light RenderSystem.enableCull(); PoseStack.Pose p = matrix.last(); @@ -375,10 +374,10 @@ public class RenderEvents drawArms(player, partialticks, matrix, buffer, light); RenderSystem.setShaderColor(1.0F, 1.0F, 1.0F, 1.0F); - + CarryRenderHelper.renderItem(state, tag, stack, tileItem, copy, buffer, light, model); buffer.endBatch(); - + matrix.popPose(); } else if (!stack.isEmpty() && stack.getItem() == RegistrationHandler.itemEntity && ItemCarryonEntity.hasEntityData(stack)) @@ -420,8 +419,8 @@ public class RenderEvents } } - if (entity instanceof LivingEntity) - ((LivingEntity) entity).hurtTime = 0; + if (entity instanceof LivingEntity le) + le.hurtTime = 0; RenderSystem.setShaderColor(1.0F, 1.0F, 1.0F, 1.0F); @@ -492,7 +491,7 @@ public class RenderEvents if (pose == Pose.FALL_FLYING) { - float f1 = (float) player.getFallFlyingTicks() + partialticks; + float f1 = player.getFallFlyingTicks() + partialticks; float f2 = Mth.clamp(f1 * f1 / 100.0F, 0.0F, 1.0F); if (!player.isAutoSpinAttack()) { @@ -537,11 +536,8 @@ public class RenderEvents matrix.translate(0, 0, -0.4); matrix.mulPose(Vector3f.YP.rotationDegrees(180)); } - else - { - if ((ModList.get().isLoaded("realrender") || ModList.get().isLoaded("rfpr")) && perspective == 0) - matrix.translate(0, 0, 0.4); - } + else if ((ModList.get().isLoaded("realrender") || ModList.get().isLoaded("rfpr")) && perspective == 0) + matrix.translate(0, 0, 0.4); } private void applyEntityTransformations(Player player, float partialticks, PoseStack matrix, Entity entity) @@ -592,10 +588,7 @@ public class RenderEvents int perspective = CarryRenderHelper.getPerspective(); Pose pose = player.getPose(); - if (!Settings.renderArms.get()) - return; - - if (pose == Pose.SWIMMING || pose == Pose.FALL_FLYING) + if (!Settings.renderArms.get() || pose == Pose.SWIMMING || pose == Pose.FALL_FLYING) return; if (handleMobends() && !ModList.get().isLoaded("obfuscate")) @@ -631,32 +624,32 @@ public class RenderEvents if (renderLeft && rotLeft != null) { - renderArmPost(model.leftArm, (float) rotLeft[0], (float) rotLeft[2], false, doSneakCheck(player), light, matrix, builder); - renderArmPost(model.leftSleeve, (float) rotLeft[0], (float) rotLeft[2], false, doSneakCheck(player), light, matrix, builder); + renderArmPost(model.leftArm, rotLeft[0], rotLeft[2], false, doSneakCheck(player), light, matrix, builder); + renderArmPost(model.leftSleeve, rotLeft[0], rotLeft[2], false, doSneakCheck(player), light, matrix, builder); } else if (renderLeft) { - renderArmPost(model.leftArm, 2.0F + (doSneakCheck(player) ? 0f : 0.2f) - (stack.getItem() == RegistrationHandler.itemEntity ? 0.3f : 0), (stack.getItem() == RegistrationHandler.itemEntity ? 0.15f : 0), false, doSneakCheck(player), light, matrix, builder); - renderArmPost(model.leftSleeve, 2.0F + (doSneakCheck(player) ? 0f : 0.2f) - (stack.getItem() == RegistrationHandler.itemEntity ? 0.3f : 0), (stack.getItem() == RegistrationHandler.itemEntity ? 0.15f : 0), false, doSneakCheck(player), light, matrix, builder); + renderArmPost(model.leftArm, 2.0F + (doSneakCheck(player) ? 0f : 0.2f) - (stack.getItem() == RegistrationHandler.itemEntity ? 0.3f : 0), stack.getItem() == RegistrationHandler.itemEntity ? 0.15f : 0, false, doSneakCheck(player), light, matrix, builder); + renderArmPost(model.leftSleeve, 2.0F + (doSneakCheck(player) ? 0f : 0.2f) - (stack.getItem() == RegistrationHandler.itemEntity ? 0.3f : 0), stack.getItem() == RegistrationHandler.itemEntity ? 0.15f : 0, false, doSneakCheck(player), light, matrix, builder); } if (renderRight && rotRight != null) { - renderArmPost(model.rightArm, (float) rotRight[0], (float) rotRight[2], true, doSneakCheck(player), light, matrix, builder); - renderArmPost(model.rightSleeve, (float) rotRight[0], (float) rotRight[2], true, doSneakCheck(player), light, matrix, builder); + renderArmPost(model.rightArm, rotRight[0], rotRight[2], true, doSneakCheck(player), light, matrix, builder); + renderArmPost(model.rightSleeve, rotRight[0], rotRight[2], true, doSneakCheck(player), light, matrix, builder); } else if (renderRight) { - renderArmPost(model.rightArm, 2.0F + (doSneakCheck(player) ? 0f : 0.2f) - (stack.getItem() == RegistrationHandler.itemEntity ? 0.3f : 0), (stack.getItem() == RegistrationHandler.itemEntity ? -0.15f : 0), true, doSneakCheck(player), light, matrix, builder); - renderArmPost(model.rightSleeve, 2.0F + (doSneakCheck(player) ? 0f : 0.2f) - (stack.getItem() == RegistrationHandler.itemEntity ? 0.3f : 0), (stack.getItem() == RegistrationHandler.itemEntity ? -0.15f : 0), true, doSneakCheck(player), light, matrix, builder); + renderArmPost(model.rightArm, 2.0F + (doSneakCheck(player) ? 0f : 0.2f) - (stack.getItem() == RegistrationHandler.itemEntity ? 0.3f : 0), stack.getItem() == RegistrationHandler.itemEntity ? -0.15f : 0, true, doSneakCheck(player), light, matrix, builder); + renderArmPost(model.rightSleeve, 2.0F + (doSneakCheck(player) ? 0f : 0.2f) - (stack.getItem() == RegistrationHandler.itemEntity ? 0.3f : 0), stack.getItem() == RegistrationHandler.itemEntity ? -0.15f : 0, true, doSneakCheck(player), light, matrix, builder); } } else { - renderArmPost(model.rightArm, 2.0F + (doSneakCheck(player) ? 0f : 0.2f) - (stack.getItem() == RegistrationHandler.itemEntity ? 0.3f : 0), (stack.getItem() == RegistrationHandler.itemEntity ? -0.15f : 0), true, doSneakCheck(player), light, matrix, builder); - renderArmPost(model.leftArm, 2.0F + (doSneakCheck(player) ? 0f : 0.2f) - (stack.getItem() == RegistrationHandler.itemEntity ? 0.3f : 0), (stack.getItem() == RegistrationHandler.itemEntity ? 0.15f : 0), false, doSneakCheck(player), light, matrix, builder); - renderArmPost(model.leftSleeve, 2.0F + (doSneakCheck(player) ? 0f : 0.2f) - (stack.getItem() == RegistrationHandler.itemEntity ? 0.3f : 0), (stack.getItem() == RegistrationHandler.itemEntity ? 0.15f : 0), false, doSneakCheck(player), light, matrix, builder); - renderArmPost(model.rightSleeve, 2.0F + (doSneakCheck(player) ? 0f : 0.2f) - (stack.getItem() == RegistrationHandler.itemEntity ? 0.3f : 0), (stack.getItem() == RegistrationHandler.itemEntity ? -0.15f : 0), true, doSneakCheck(player), light, matrix, builder); + renderArmPost(model.rightArm, 2.0F + (doSneakCheck(player) ? 0f : 0.2f) - (stack.getItem() == RegistrationHandler.itemEntity ? 0.3f : 0), stack.getItem() == RegistrationHandler.itemEntity ? -0.15f : 0, true, doSneakCheck(player), light, matrix, builder); + renderArmPost(model.leftArm, 2.0F + (doSneakCheck(player) ? 0f : 0.2f) - (stack.getItem() == RegistrationHandler.itemEntity ? 0.3f : 0), stack.getItem() == RegistrationHandler.itemEntity ? 0.15f : 0, false, doSneakCheck(player), light, matrix, builder); + renderArmPost(model.leftSleeve, 2.0F + (doSneakCheck(player) ? 0f : 0.2f) - (stack.getItem() == RegistrationHandler.itemEntity ? 0.3f : 0), stack.getItem() == RegistrationHandler.itemEntity ? 0.15f : 0, false, doSneakCheck(player), light, matrix, builder); + renderArmPost(model.rightSleeve, 2.0F + (doSneakCheck(player) ? 0f : 0.2f) - (stack.getItem() == RegistrationHandler.itemEntity ? 0.3f : 0), stack.getItem() == RegistrationHandler.itemEntity ? -0.15f : 0, true, doSneakCheck(player), light, matrix, builder); } if (buffer instanceof BufferSource) @@ -731,9 +724,9 @@ public class RenderEvents else arm.y = 15; - arm.xRot = (float) x; - arm.yRot = (float) 0; - arm.zRot = (float) -z; + arm.xRot = x; + arm.yRot = 0; + arm.zRot = -z; arm.render(matrix, builder, light, 655360); arm.y = 2; matrix.popPose(); @@ -766,7 +759,7 @@ public class RenderEvents if (player.getAbilities().flying) return false; - return (player.isShiftKeyDown() || player.isCrouching()); + return player.isShiftKeyDown() || player.isCrouching(); } public static boolean isChest(Block block) diff --git a/src/main/java/tschipp/carryon/client/helper/CarryRenderHelper.java b/src/main/java/tschipp/carryon/client/helper/CarryRenderHelper.java index ab89d5b..ab12db0 100644 --- a/src/main/java/tschipp/carryon/client/helper/CarryRenderHelper.java +++ b/src/main/java/tschipp/carryon/client/helper/CarryRenderHelper.java @@ -45,13 +45,13 @@ public class CarryRenderHelper float[] translation = ScriptParseHelper.getXYZArray(override.getRenderTranslation()); float[] rotation = ScriptParseHelper.getXYZArray(override.getRenderRotation()); float[] scaled = ScriptParseHelper.getScaled(override.getRenderScaled()); - + Quaternion rot = Vector3f.XP.rotationDegrees(rotation[0]); - rot.mul(Vector3f.YP.rotationDegrees(rotation[1])); + rot.mul(Vector3f.YP.rotationDegrees(rotation[1])); rot.mul(Vector3f.ZP.rotationDegrees(rotation[2])); matrix.mulPose(rot); - - matrix.translate(translation[0], translation[1], perspective == 1 && override.isBlock() ? -translation[2] : translation[2]); + + matrix.translate(translation[0], translation[1], perspective == 1 && override.isBlock() ? -translation[2] : translation[2]); matrix.scale(scaled[0], scaled[1], scaled[2]); } @@ -64,7 +64,7 @@ public class CarryRenderHelper if (override instanceof ItemStack) { - Minecraft.getInstance().getItemRenderer().render((ItemStack) override, TransformType.NONE, false, matrix, buffer, light, 0xFFFFFF, model); + Minecraft.getInstance().getItemRenderer().render((ItemStack) override, TransformType.NONE, false, matrix, buffer, light, 0xFFFFFF, model); return; } } @@ -75,7 +75,7 @@ public class CarryRenderHelper @SuppressWarnings("resource") public static int getPerspective() { - boolean isThirdPerson = !Minecraft.getInstance().options.getCameraType().isFirstPerson(); //isThirdPerson + boolean isThirdPerson = !Minecraft.getInstance().options.getCameraType().isFirstPerson(); // isThirdPerson boolean isThirdPersonReverse = Minecraft.getInstance().options.getCameraType().isMirrored(); if (!isThirdPerson && !isThirdPersonReverse) diff --git a/src/main/java/tschipp/carryon/client/keybinds/CarryOnKeybinds.java b/src/main/java/tschipp/carryon/client/keybinds/CarryOnKeybinds.java index a62a1b1..99eaf27 100644 --- a/src/main/java/tschipp/carryon/client/keybinds/CarryOnKeybinds.java +++ b/src/main/java/tschipp/carryon/client/keybinds/CarryOnKeybinds.java @@ -12,31 +12,29 @@ public class CarryOnKeybinds public static final String KEYBIND_KEY = "carryOnKeyPressed"; public static KeyMapping carryKey; - + @OnlyIn(Dist.CLIENT) public static void init() { carryKey = new KeyMapping("key.carry.desc", 340, "key.carry.category"); - + ClientRegistry.registerKeyBinding(carryKey); } - + public static boolean isKeyPressed(Player player) { CompoundTag tag = player.getPersistentData(); - if(tag != null && tag.contains(KEYBIND_KEY)) + if (tag != null && tag.contains(KEYBIND_KEY)) { return tag.getBoolean(KEYBIND_KEY); } return false; } - + public static void setKeyPressed(Player player, boolean pressed) { CompoundTag tag = player.getPersistentData(); tag.putBoolean(KEYBIND_KEY, pressed); } - - - + } diff --git a/src/main/java/tschipp/carryon/common/capabilities/IPosition.java b/src/main/java/tschipp/carryon/common/capabilities/IPosition.java index ca450d0..1bc0afe 100644 --- a/src/main/java/tschipp/carryon/common/capabilities/IPosition.java +++ b/src/main/java/tschipp/carryon/common/capabilities/IPosition.java @@ -2,15 +2,15 @@ package tschipp.carryon.common.capabilities; import net.minecraft.core.BlockPos; -public interface IPosition { +public interface IPosition +{ public BlockPos getPos(); - + public void setPos(BlockPos pos); - + public boolean isBlockActivated(); - + public void setBlockActivated(boolean b); - - + } diff --git a/src/main/java/tschipp/carryon/common/capabilities/PositionProvider.java b/src/main/java/tschipp/carryon/common/capabilities/PositionProvider.java index 46614d9..7026d9b 100644 --- a/src/main/java/tschipp/carryon/common/capabilities/PositionProvider.java +++ b/src/main/java/tschipp/carryon/common/capabilities/PositionProvider.java @@ -14,17 +14,15 @@ public class PositionProvider implements ICapabilitySerializable @CapabilityInject(IPosition.class) public static final Capability POSITION_CAPABILITY = null; - private IPosition instance = new TEPosition();//POSITION_CAPABILITY.getDefaultInstance(); + private IPosition instance = new TEPosition();// POSITION_CAPABILITY.getDefaultInstance(); @SuppressWarnings("unchecked") @Override public LazyOptional getCapability(Capability cap, Direction side) { if (cap == POSITION_CAPABILITY) - return (LazyOptional) LazyOptional.of(() -> { - return new TEPosition(); - }); - + return (LazyOptional) LazyOptional.of(TEPosition::new); + return LazyOptional.empty(); } @@ -33,27 +31,27 @@ public class PositionProvider implements ICapabilitySerializable { CompoundTag tag = new CompoundTag(); - tag.putBoolean("blockActivated", instance.isBlockActivated()); - tag.putInt("x", instance.getPos().getX()); - tag.putInt("y", instance.getPos().getY()); - tag.putInt("z", instance.getPos().getZ()); - + tag.putBoolean("blockActivated", this.instance.isBlockActivated()); + tag.putInt("x", this.instance.getPos().getX()); + tag.putInt("y", this.instance.getPos().getY()); + tag.putInt("z", this.instance.getPos().getZ()); + return tag; } @Override public void deserializeNBT(CompoundTag nbt) { - CompoundTag tag = (CompoundTag) nbt; + CompoundTag tag = nbt; int x = tag.getInt("x"); int y = tag.getInt("y"); int z = tag.getInt("z"); - - BlockPos pos = new BlockPos(x,y,z); - - instance.setPos(pos); - instance.setBlockActivated(tag.getBoolean("blockActivated")); + + BlockPos pos = new BlockPos(x, y, z); + + this.instance.setPos(pos); + this.instance.setBlockActivated(tag.getBoolean("blockActivated")); } } diff --git a/src/main/java/tschipp/carryon/common/capabilities/TEPosition.java b/src/main/java/tschipp/carryon/common/capabilities/TEPosition.java index 0194a2e..aca1862 100644 --- a/src/main/java/tschipp/carryon/common/capabilities/TEPosition.java +++ b/src/main/java/tschipp/carryon/common/capabilities/TEPosition.java @@ -2,31 +2,34 @@ package tschipp.carryon.common.capabilities; import net.minecraft.core.BlockPos; -public class TEPosition implements IPosition { - +public class TEPosition implements IPosition +{ + private BlockPos pos = new BlockPos(0, 0, 0); private boolean blockActivated = false; - + @Override public BlockPos getPos() { - return pos; + return this.pos; } + @Override public void setPos(BlockPos pos) { this.pos = pos; } + @Override public boolean isBlockActivated() { - return blockActivated; + return this.blockActivated; } + @Override public void setBlockActivated(boolean b) { this.blockActivated = b; } - } diff --git a/src/main/java/tschipp/carryon/common/capabilities/event/PositionClientEvents.java b/src/main/java/tschipp/carryon/common/capabilities/event/PositionClientEvents.java index 5021db9..71e267f 100644 --- a/src/main/java/tschipp/carryon/common/capabilities/event/PositionClientEvents.java +++ b/src/main/java/tschipp/carryon/common/capabilities/event/PositionClientEvents.java @@ -28,48 +28,44 @@ public class PositionClientEvents { Player player = Minecraft.getInstance().player; boolean inventory = event.getGui() instanceof AbstractContainerScreen; - - if (player != null && inventory) + + if (player != null && inventory && player.getCapability(PositionProvider.POSITION_CAPABILITY).isPresent()) { - if(player.getCapability(PositionProvider.POSITION_CAPABILITY).isPresent()) + IPosition cap = player.getCapability(PositionProvider.POSITION_CAPABILITY).orElse(new TEPosition()); + if (cap.isBlockActivated()) { - IPosition cap = player.getCapability(PositionProvider.POSITION_CAPABILITY).orElse(new TEPosition()); - if(cap.isBlockActivated()) + Level world = player.level; + BlockPos pos = cap.getPos(); + if (world != null) { - Level world = player.level; - BlockPos pos = cap.getPos(); - if(world != null) + BlockEntity te = world.getBlockEntity(pos); + if (te == null) { - BlockEntity te = world.getBlockEntity(pos); - if(te == null) - { -// player.openContainer = null; - Minecraft.getInstance().screen = null; -// Minecraft.getInstance().fo; - cap.setBlockActivated(false); - cap.setPos(new BlockPos(0,0,0)); - } + // player.openContainer = null; + Minecraft.getInstance().screen = null; + // Minecraft.getInstance().fo; + cap.setBlockActivated(false); + cap.setPos(new BlockPos(0, 0, 0)); } } } } } } - + @OnlyIn(Dist.CLIENT) @SubscribeEvent public void onGuiClose(PlayerContainerEvent.Close event) { Player player = event.getPlayer(); - if(player.getCapability(PositionProvider.POSITION_CAPABILITY).isPresent()) + if (player.getCapability(PositionProvider.POSITION_CAPABILITY).isPresent()) { IPosition cap = player.getCapability(PositionProvider.POSITION_CAPABILITY).orElse(new TEPosition()); cap.setBlockActivated(false); - cap.setPos(new BlockPos(0,0,0)); + cap.setPos(new BlockPos(0, 0, 0)); } } - - + @OnlyIn(Dist.CLIENT) @SubscribeEvent public void onPlayerTick(PlayerTickEvent event) @@ -77,7 +73,7 @@ public class PositionClientEvents if (event.side == LogicalSide.CLIENT) { Player player = event.player; - if(player.getCapability(PositionProvider.POSITION_CAPABILITY).isPresent()) + if (player.getCapability(PositionProvider.POSITION_CAPABILITY).isPresent()) { IPosition cap = player.getCapability(PositionProvider.POSITION_CAPABILITY).orElse(new TEPosition()); if (cap.isBlockActivated() && Minecraft.getInstance().screen == null) @@ -88,6 +84,5 @@ public class PositionClientEvents } } } - - + } diff --git a/src/main/java/tschipp/carryon/common/capabilities/event/PositionCommonEvents.java b/src/main/java/tschipp/carryon/common/capabilities/event/PositionCommonEvents.java index c977a6c..0d26efc 100644 --- a/src/main/java/tschipp/carryon/common/capabilities/event/PositionCommonEvents.java +++ b/src/main/java/tschipp/carryon/common/capabilities/event/PositionCommonEvents.java @@ -35,27 +35,16 @@ public class PositionCommonEvents Level world = event.getWorld(); Player player = event.getPlayer(); - if (event.isCanceled()) - return; - - if (player == null) - return; - - if (player instanceof FakePlayer) + if (event.isCanceled() || player == null || player instanceof FakePlayer) return; BlockEntity te = world.getBlockEntity(pos); - if (te != null) + if (te != null && player.getCapability(PositionProvider.POSITION_CAPABILITY).isPresent()) { - if(player.getCapability(PositionProvider.POSITION_CAPABILITY).isPresent()) - { - IPosition cap = player.getCapability(PositionProvider.POSITION_CAPABILITY).orElse(new TEPosition()); - cap.setBlockActivated(true); - cap.setPos(pos); - } + IPosition cap = player.getCapability(PositionProvider.POSITION_CAPABILITY).orElse(new TEPosition()); + cap.setBlockActivated(true); + cap.setPos(pos); } } - - } diff --git a/src/main/java/tschipp/carryon/common/command/CommandCarryOn.java b/src/main/java/tschipp/carryon/common/command/CommandCarryOn.java index a8fc547..85aa432 100644 --- a/src/main/java/tschipp/carryon/common/command/CommandCarryOn.java +++ b/src/main/java/tschipp/carryon/common/command/CommandCarryOn.java @@ -28,17 +28,11 @@ public class CommandCarryOn { LiteralArgumentBuilder builder = Commands.literal("carryon") - .then(Commands.literal("debug").executes((cmd) -> { - return handleDebug(cmd.getSource()); - })) + .then(Commands.literal("debug").executes(cmd -> handleDebug(cmd.getSource()))) - .then(Commands.literal("clear").executes((cmd) -> { - return handleClear(cmd.getSource(), Collections.singleton(cmd.getSource().getPlayerOrException())); - })) + .then(Commands.literal("clear").executes(cmd -> handleClear(cmd.getSource(), Collections.singleton(cmd.getSource().getPlayerOrException())))) - .then(Commands.literal("clear").then(Commands.argument("target", EntityArgument.players()).requires(src -> src.hasPermission(2)).executes((cmd) -> { - return handleClear(cmd.getSource(), EntityArgument.getPlayers(cmd, "target")); - }))) + .then(Commands.literal("clear").then(Commands.argument("target", EntityArgument.players()).requires(src -> src.hasPermission(2)).executes(cmd -> handleClear(cmd.getSource(), EntityArgument.getPlayers(cmd, "target"))))) ; @@ -100,7 +94,6 @@ public class CommandCarryOn } catch (CommandSyntaxException e) { - return 0; } return 0; @@ -114,7 +107,7 @@ public class CommandCarryOn cleared += player.getInventory().clearOrCountMatchingItems(stack -> !stack.isEmpty() && stack.getItem() == RegistrationHandler.itemTile, 64, player.inventoryMenu.getCraftSlots()); // TODO cleared += player.getInventory().clearOrCountMatchingItems(stack -> !stack.isEmpty() && stack.getItem() == RegistrationHandler.itemEntity, 64, player.inventoryMenu.getCraftSlots()); - CarryOn.network.send(PacketDistributor.PLAYER.with(() -> (ServerPlayer) player), new CarrySlotPacket(9, player.getId())); + CarryOn.network.send(PacketDistributor.PLAYER.with(() -> player), new CarrySlotPacket(9, player.getId())); if (cleared != 1) source.sendSuccess(new TextComponent("Cleared " + cleared + " Items!"), true); diff --git a/src/main/java/tschipp/carryon/common/config/CarryOnConfig.java b/src/main/java/tschipp/carryon/common/config/CarryOnConfig.java index d23f9ae..15151e0 100644 --- a/src/main/java/tschipp/carryon/common/config/CarryOnConfig.java +++ b/src/main/java/tschipp/carryon/common/config/CarryOnConfig.java @@ -13,5 +13,4 @@ public class CarryOnConfig public static Configs.CustomPickupConditions customPickupConditions = new Configs.CustomPickupConditions(); - } diff --git a/src/main/java/tschipp/carryon/common/config/Configs.java b/src/main/java/tschipp/carryon/common/config/Configs.java index 237f4ec..1bbf1cc 100644 --- a/src/main/java/tschipp/carryon/common/config/Configs.java +++ b/src/main/java/tschipp/carryon/common/config/Configs.java @@ -19,26 +19,28 @@ import tschipp.carryon.CarryOn; import tschipp.carryon.common.handler.ListHandler; @Mod.EventBusSubscriber(modid = CarryOn.MODID, bus = Bus.MOD) -public class Configs { - +public class Configs +{ + private static final ForgeConfigSpec.Builder SERVER_BUILDER = new ForgeConfigSpec.Builder(); private static final ForgeConfigSpec.Builder CLIENT_BUILDER = new ForgeConfigSpec.Builder(); public static final ForgeConfigSpec SERVER_CONFIG; public static final ForgeConfigSpec CLIENT_CONFIG; - static { - + static + { + Settings.init(SERVER_BUILDER, CLIENT_BUILDER); Blacklist.init(SERVER_BUILDER, CLIENT_BUILDER); WhiteList.init(SERVER_BUILDER, CLIENT_BUILDER); ModelOverrides.init(SERVER_BUILDER, CLIENT_BUILDER); CustomPickupConditions.init(SERVER_BUILDER, CLIENT_BUILDER); - + SERVER_CONFIG = SERVER_BUILDER.build(); CLIENT_CONFIG = CLIENT_BUILDER.build(); } - + @SubscribeEvent public static void onLoad(final ModConfigEvent.Loading event) { @@ -47,12 +49,12 @@ public class Configs { ListHandler.initConfigLists(); CommentedConfig cfg = event.getConfig().getConfigData(); - - if(cfg instanceof CommentedFileConfig) + + if (cfg instanceof CommentedFileConfig) ((CommentedFileConfig) cfg).load(); } } - + @SubscribeEvent public static void onConfigChanged(ModConfigEvent.Reloading event) { @@ -61,59 +63,58 @@ public class Configs { ListHandler.initConfigLists(); CommentedConfig cfg = event.getConfig().getConfigData(); - - if(cfg instanceof CommentedFileConfig) + + if (cfg instanceof CommentedFileConfig) ((CommentedFileConfig) cfg).load(); } } - - + public static class Settings { public static BooleanValue facePlayer; - + public static BooleanValue heavyTiles; - + public static BooleanValue pickupAllBlocks; - + public static BooleanValue slownessInCreative; - + public static DoubleValue maxDistance; - + public static DoubleValue maxEntityWidth; - + public static DoubleValue maxEntityHeight; - + public static BooleanValue pickupHostileMobs; - + public static BooleanValue heavyEntities; - + public static DoubleValue blockSlownessMultiplier; - + public static DoubleValue entitySlownessMultiplier; - + public static BooleanValue renderArms; - + public static BooleanValue allowBabies; - + public static BooleanValue useWhitelistBlocks; - + public static BooleanValue useWhitelistEntities; - + public static BooleanValue useWhitelistStacking; - + public static BooleanValue hitWhileCarrying; - + public static BooleanValue dropCarriedWhenHit; - + public static BooleanValue useScripts; - + public static BooleanValue stackableEntities; - + public static IntValue maxEntityStackLimit; - + public static BooleanValue entitySizeMattersStacking; - + public static void init(ForgeConfigSpec.Builder s, ForgeConfigSpec.Builder c) { c.comment("Settings"); @@ -121,336 +122,127 @@ public class Configs { s.push("settings"); c.push("settings"); - - maxDistance = s - .comment("Maximum distance from where Blocks and Entities can be picked up") - .defineInRange("maxDistance", 2.5, 0, Double.MAX_VALUE); - - maxEntityWidth = s - .comment("Max width of entities that can be picked up in survival mode") - .defineInRange("maxEntityWidth", 1.5, 0, 10); - - maxEntityHeight = s - .comment("Max height of entities that can be picked up in survival mode") - .defineInRange("maxEntityHeight", 1.5, 0, 10); - - maxEntityWidth = s - .comment("Max width of entities that can be picked up in survival mode") - .defineInRange("maxEntityWidth", 1.5, 0, 10); - - blockSlownessMultiplier = s - .comment("Slowness multiplier for blocks") - .defineInRange("blockSlownessMultiplier", 1, 0, Double.MAX_VALUE); - - entitySlownessMultiplier = s - .comment("Slowness multiplier for entities") - .defineInRange("entitySlownessMultiplier", 1, 0, Double.MAX_VALUE); - - maxEntityStackLimit = s - .comment("Maximum stack limit for entities") - .defineInRange("maxEntityStackLimit", 10, 1, Integer.MAX_VALUE); - - facePlayer = c - .comment("If the front of the Tile Entities should face the player or should face outward") - .define("facePlayer", false); - - heavyTiles = s - .comment("More complex Tile Entities slow down the player more") - .define("heavyTiles", true); - - pickupAllBlocks = s - .comment("Allow all blocks to be picked up, not just Tile Entites") - .define("pickupAllBlocks", false); - - slownessInCreative = s - .comment("Whether Blocks and Entities slow the creative player down when carried") - .define("slownessInCreative", true); - - pickupHostileMobs = s - .comment("Whether hostile mobs should be able to picked up in survival mode") - .define("pickupHostileMobs", false); - - heavyEntities = s - .comment("Larger Entities slow down the player more") - .define("heavyEntities", true); - - renderArms = c - .comment("Arms should render on sides when carrying") - .define("renderArms", true); - - allowBabies = s - .comment("Allow babies to be carried even when adult mob is blacklisted (or not whitelisted)") - .define("allowBabies", false); - - useWhitelistBlocks = s - .comment("Use Whitelist instead of Blacklist for Blocks") - .define("useWhitelistBlocks", false); - - useWhitelistEntities = s - .comment("Use Whitelist instead of Blacklist for Entities") - .define("useWhitelistEntities", false); - - useWhitelistStacking = s - .comment("Use Whitelist instead of Blacklist for Stacking") - .define("useWhitelistStacking", false); - - hitWhileCarrying = s - .comment("Whether the player can hit blocks and entities while carrying or not") - .define("hitWhileCarrying", false); - - dropCarriedWhenHit = s - .comment("Whether the player drops the carried object when hit or not") - .define("dropCarriedWhenHit", false); - - useScripts = s - .comment("Use custom Pickup Scripts. Having this set to false, will not allow you to run scripts, but will increase your performance") - .worldRestart() - .define("useScripts", false); - - stackableEntities = s - .comment("Allows entities to be stacked using Carry On") - .define("stackableEntities", true); - - entitySizeMattersStacking = s - .comment("Whether entities' size matters when stacking or not") - .define("stackableEntities", true); - + + maxDistance = s.comment("Maximum distance from where Blocks and Entities can be picked up").defineInRange("maxDistance", 2.5, 0, Double.MAX_VALUE); + + maxEntityWidth = s.comment("Max width of entities that can be picked up in survival mode").defineInRange("maxEntityWidth", 1.5, 0, 10); + + maxEntityHeight = s.comment("Max height of entities that can be picked up in survival mode").defineInRange("maxEntityHeight", 1.5, 0, 10); + + maxEntityWidth = s.comment("Max width of entities that can be picked up in survival mode").defineInRange("maxEntityWidth", 1.5, 0, 10); + + blockSlownessMultiplier = s.comment("Slowness multiplier for blocks").defineInRange("blockSlownessMultiplier", 1, 0, Double.MAX_VALUE); + + entitySlownessMultiplier = s.comment("Slowness multiplier for entities").defineInRange("entitySlownessMultiplier", 1, 0, Double.MAX_VALUE); + + maxEntityStackLimit = s.comment("Maximum stack limit for entities").defineInRange("maxEntityStackLimit", 10, 1, Integer.MAX_VALUE); + + facePlayer = c.comment("If the front of the Tile Entities should face the player or should face outward").define("facePlayer", false); + + heavyTiles = s.comment("More complex Tile Entities slow down the player more").define("heavyTiles", true); + + pickupAllBlocks = s.comment("Allow all blocks to be picked up, not just Tile Entites").define("pickupAllBlocks", false); + + slownessInCreative = s.comment("Whether Blocks and Entities slow the creative player down when carried").define("slownessInCreative", true); + + pickupHostileMobs = s.comment("Whether hostile mobs should be able to picked up in survival mode").define("pickupHostileMobs", false); + + heavyEntities = s.comment("Larger Entities slow down the player more").define("heavyEntities", true); + + renderArms = c.comment("Arms should render on sides when carrying").define("renderArms", true); + + allowBabies = s.comment("Allow babies to be carried even when adult mob is blacklisted (or not whitelisted)").define("allowBabies", false); + + useWhitelistBlocks = s.comment("Use Whitelist instead of Blacklist for Blocks").define("useWhitelistBlocks", false); + + useWhitelistEntities = s.comment("Use Whitelist instead of Blacklist for Entities").define("useWhitelistEntities", false); + + useWhitelistStacking = s.comment("Use Whitelist instead of Blacklist for Stacking").define("useWhitelistStacking", false); + + hitWhileCarrying = s.comment("Whether the player can hit blocks and entities while carrying or not").define("hitWhileCarrying", false); + + dropCarriedWhenHit = s.comment("Whether the player drops the carried object when hit or not").define("dropCarriedWhenHit", false); + + useScripts = s.comment("Use custom Pickup Scripts. Having this set to false, will not allow you to run scripts, but will increase your performance").worldRestart().define("useScripts", false); + + stackableEntities = s.comment("Allows entities to be stacked using Carry On").define("stackableEntities", true); + + entitySizeMattersStacking = s.comment("Whether entities' size matters when stacking or not").define("stackableEntities", true); + s.pop(); c.pop(); - + } - + } - + public static class WhiteList { public static ConfigValue> allowedEntities; - + public static ConfigValue> allowedBlocks; - + public static ConfigValue> allowedStacking; - + public static void init(ForgeConfigSpec.Builder s, ForgeConfigSpec.Builder c) { s.comment("Whitelist. Read about the format here: https://github.com/Tschipp/CarryOn/wiki/Black---and-Whitelist-Config"); - - allowedEntities = s - .comment("Entities that CAN be picked up (useWhitelistEntities must be true)") - .defineList("whitelist.allowedEntities", Arrays.asList(new String[]{}), (obj) -> obj instanceof String ? true : false); - - allowedBlocks = s - .comment("Blocks that CAN be picked up (useWhitelistBlocks must be true)") - .defineList("whitelist.allowedBlocks", Arrays.asList(new String[]{}), (obj) -> obj instanceof String ? true : false); - - allowedStacking = s - .comment("Entities that CAN have other entities stacked on top of them (useWhitelistStacking must be true)") - .defineList("whitelist.allowedStacking", Arrays.asList(new String[]{}), (obj) -> obj instanceof String ? true : false); + + allowedEntities = s.comment("Entities that CAN be picked up (useWhitelistEntities must be true)").defineList("whitelist.allowedEntities", Arrays.asList(), obj -> obj instanceof String ? true : false); + + allowedBlocks = s.comment("Blocks that CAN be picked up (useWhitelistBlocks must be true)").defineList("whitelist.allowedBlocks", Arrays.asList(), obj -> obj instanceof String ? true : false); + + allowedStacking = s.comment("Entities that CAN have other entities stacked on top of them (useWhitelistStacking must be true)").defineList("whitelist.allowedStacking", Arrays.asList(), obj -> obj instanceof String ? true : false); } } - + public static class Blacklist { public static ConfigValue> forbiddenTiles; - + public static ConfigValue> forbiddenEntities; - + public static ConfigValue> forbiddenStacking; - + public static void init(ForgeConfigSpec.Builder s, ForgeConfigSpec.Builder c) { s.comment("Blacklist. Read about the format here: https://github.com/Tschipp/CarryOn/wiki/Black---and-Whitelist-Config"); - - forbiddenTiles = s - .comment("Blocks that cannot be picked up") - .defineList("blacklist.forbiddenTiles", Arrays.asList(new String[] - { - "#forge:immovable", - "#forge:relocation_not_supported", - "minecraft:end_portal", - "minecraft:end_gateway", - "minecraft:tall_grass", - "minecraft:large_fern", - "minecraft:peony", - "minecraft:rose_bush", - "minecraft:lilac", - "minecraft:sunflower", - "minecraft:*_bed", - "minecraft:oak_door", - "minecraft:iron_door", - "minecraft:spruce_door", - "minecraft:birch_door", - "minecraft:jungle_door", - "minecraft:acacia_door", - "minecraft:dark_oak_door", - "minecraft:waterlily", - "minecraft:cake", - "minecraft:nether_portal", - "minecraft:tall_seagrass", - "animania:block_trough", - "animania:block_invisiblock", - "colossalchests:*", - "ic2:*", - "bigreactors:*", - "forestry:*", - "tconstruct:*", - "rustic:*", - "botania:*", - "astralsorcery:*", - "quark:colored_bed_*", - "immersiveengineering:*", - "embers:block_furnace", - "embers:ember_bore", - "embers:ember_activator", - "embers:mixer", - "embers:heat_coil", - "embers:large_tank", - "embers:crystal_cell", - "embers:alchemy_pedestal", - "embers:boiler", - "embers:combustor", - "embers:catalzyer", - "embers:field_chart", - "embers:inferno_forge", - "storagedrawers:framingtable", - "skyresources:*", - "lootbags:*", - "exsartagine:*", - "aquamunda:tank", - "opencomputers:*", - "malisisdoors:*", - "industrialforegoing:*", - "minecolonies:*", - "thaumcraft:pillar*", - "thaumcraft:infernal_furnace", - "thaumcraft:placeholder*", - "thaumcraft:infusion_matrix", - "thaumcraft:golem_builder", - "thaumcraft:thaumatorium*", - "magneticraft:oil_heater", - "magneticraft:solar_panel", - "magneticraft:steam_engine", - "magneticraft:shelving_unit", - "magneticraft:grinder", - "magneticraft:sieve", - "magneticraft:solar_tower", - "magneticraft:solar_mirror", - "magneticraft:container", - "magneticraft:pumpjack", - "magneticraft:solar_panel", - "magneticraft:refinery", - "magneticraft:oil_heater", - "magneticraft:hydraulic_press", - "magneticraft:multiblock_gap", - "refinedstorage:*", - "mcmultipart:*", - "enderstorage:*", - "betterstorage:*", - "practicallogistics2:*", - "wearablebackpacks:*", - "rftools:screen", - "rftools:creative_screen", - "create:*", - "magic_doorknob:*", - "iceandfire:*", - "ftbquests:*", - "waystones:*" - - }), (obj) -> obj instanceof String); - - forbiddenEntities = s - .comment("Entities that cannot be picked up") - .defineList("blacklist.forbiddenEntities", Arrays.asList(new String[] - { - "minecraft:end_crystal", - "minecraft:ender_dragon", - "minecraft:ghast", - "minecraft:shulker", - "minecraft:leash_knot", - "minecraft:armor_stand", - "minecraft:item_frame", - "minecraft:painting", - "minecraft:shulker_bullet", - "animania:hamster", - "animania:ferret*", - "animania:hedgehog*", - "animania:cart", - "animania:wagon", - "mynko:*", - "pixelmon:*", - "mocreatures:*", - "quark:totem", - "vehicle:*" - }), (obj) -> obj instanceof String ? true : false); - - forbiddenStacking = s - .comment("Entities that cannot have other entities stacked on top of them") - .defineList("blacklist.forbiddenStacking", Arrays.asList(new String[] - { - "minecraft:horse" - }), (obj) -> obj instanceof String ? true : false); + forbiddenTiles = s.comment("Blocks that cannot be picked up").defineList("blacklist.forbiddenTiles", Arrays.asList("#forge:immovable", "#forge:relocation_not_supported", "minecraft:end_portal", "minecraft:end_gateway", "minecraft:tall_grass", "minecraft:large_fern", "minecraft:peony", "minecraft:rose_bush", "minecraft:lilac", "minecraft:sunflower", "minecraft:*_bed", "minecraft:oak_door", "minecraft:iron_door", "minecraft:spruce_door", "minecraft:birch_door", "minecraft:jungle_door", "minecraft:acacia_door", "minecraft:dark_oak_door", "minecraft:waterlily", "minecraft:cake", "minecraft:nether_portal", "minecraft:tall_seagrass", "animania:block_trough", "animania:block_invisiblock", "colossalchests:*", "ic2:*", "bigreactors:*", "forestry:*", "tconstruct:*", "rustic:*", "botania:*", "astralsorcery:*", "quark:colored_bed_*", "immersiveengineering:*", "embers:block_furnace", "embers:ember_bore", "embers:ember_activator", "embers:mixer", "embers:heat_coil", "embers:large_tank", "embers:crystal_cell", "embers:alchemy_pedestal", "embers:boiler", "embers:combustor", "embers:catalzyer", "embers:field_chart", "embers:inferno_forge", "storagedrawers:framingtable", "skyresources:*", "lootbags:*", "exsartagine:*", "aquamunda:tank", "opencomputers:*", "malisisdoors:*", "industrialforegoing:*", "minecolonies:*", "thaumcraft:pillar*", "thaumcraft:infernal_furnace", "thaumcraft:placeholder*", "thaumcraft:infusion_matrix", "thaumcraft:golem_builder", "thaumcraft:thaumatorium*", "magneticraft:oil_heater", "magneticraft:solar_panel", "magneticraft:steam_engine", "magneticraft:shelving_unit", "magneticraft:grinder", "magneticraft:sieve", "magneticraft:solar_tower", "magneticraft:solar_mirror", "magneticraft:container", "magneticraft:pumpjack", "magneticraft:solar_panel", "magneticraft:refinery", "magneticraft:oil_heater", "magneticraft:hydraulic_press", "magneticraft:multiblock_gap", "refinedstorage:*", "mcmultipart:*", "enderstorage:*", "betterstorage:*", "practicallogistics2:*", "wearablebackpacks:*", "rftools:screen", "rftools:creative_screen", "create:*", "magic_doorknob:*", "iceandfire:*", "ftbquests:*", "waystones:*"), obj -> obj instanceof String); + + forbiddenEntities = s.comment("Entities that cannot be picked up").defineList("blacklist.forbiddenEntities", Arrays.asList("minecraft:end_crystal", "minecraft:ender_dragon", "minecraft:ghast", "minecraft:shulker", "minecraft:leash_knot", "minecraft:armor_stand", "minecraft:item_frame", "minecraft:painting", "minecraft:shulker_bullet", "animania:hamster", "animania:ferret*", "animania:hedgehog*", "animania:cart", "animania:wagon", "mynko:*", "pixelmon:*", "mocreatures:*", "quark:totem", "vehicle:*"), obj -> obj instanceof String ? true : false); + + forbiddenStacking = s.comment("Entities that cannot have other entities stacked on top of them").defineList("blacklist.forbiddenStacking", Arrays.asList("minecraft:horse"), obj -> obj instanceof String ? true : false); } - + } - + public static class ModelOverrides { public static ConfigValue> modelOverrides; - + public static void init(ForgeConfigSpec.Builder s, ForgeConfigSpec.Builder c) { c.comment("Model Overrides. Read about the format here: https://github.com/Tschipp/CarryOn/wiki/Model-Override-Config"); - - modelOverrides = c - .comment("Model Overrides based on NBT or on Meta. Advanced Users Only!") - .defineList("modeloverrides.overrides", Arrays.asList(new String[] - { - "minecraft:hopper->(block)minecraft:hopper", - "minecraft:comparator->(block)minecraft:comparator", - "minecraft:repeater->(block)minecraft:repeater", - "minecraft:cauldron->(block)minecraft:cauldron", - "minecraft:brewing_stand->(item)minecraft:brewing_stand", - "minecraft:flower_pot->(block)minecraft:flower_pot", - "minecraft:sugar_cane->(block)minecraft:sugar_cane", - "minecraft:redstone_wire->(item)minecraft:redstone", - "animania:block_nest->(block)animania:block_nest", - "animania:cheese_mold;0->(block)animania:cheese_mold;0", - "animania:cheese_mold;1->(block)animania:cheese_mold;1", - "animania:cheese_mold;2->(block)animania:cheese_mold;2", - "animania:cheese_mold;3->(block)animania:cheese_mold;3", - "animania:cheese_mold;4->(block)animania:cheese_mold;4", - "animania:cheese_mold;5->(block)animania:cheese_mold;5", - "animania:cheese_mold;6->(block)animania:cheese_mold;6", - "animania:cheese_mold;7->(block)animania:cheese_mold;7", - "animania:cheese_mold;8->(block)animania:cheese_mold;8", - "animania:cheese_mold;9->(block)animania:cheese_mold;9", - "animania:cheese_mold;10->(block)animania:cheese_mold;10", - }), (obj) -> obj instanceof String ? true : false); + modelOverrides = c.comment("Model Overrides based on NBT or on Meta. Advanced Users Only!").defineList("modeloverrides.overrides", Arrays.asList("minecraft:hopper->(block)minecraft:hopper", "minecraft:comparator->(block)minecraft:comparator", "minecraft:repeater->(block)minecraft:repeater", "minecraft:cauldron->(block)minecraft:cauldron", "minecraft:brewing_stand->(item)minecraft:brewing_stand", "minecraft:flower_pot->(block)minecraft:flower_pot", "minecraft:sugar_cane->(block)minecraft:sugar_cane", "minecraft:redstone_wire->(item)minecraft:redstone", "animania:block_nest->(block)animania:block_nest", "animania:cheese_mold;0->(block)animania:cheese_mold;0", "animania:cheese_mold;1->(block)animania:cheese_mold;1", "animania:cheese_mold;2->(block)animania:cheese_mold;2", "animania:cheese_mold;3->(block)animania:cheese_mold;3", "animania:cheese_mold;4->(block)animania:cheese_mold;4", "animania:cheese_mold;5->(block)animania:cheese_mold;5", "animania:cheese_mold;6->(block)animania:cheese_mold;6", "animania:cheese_mold;7->(block)animania:cheese_mold;7", "animania:cheese_mold;8->(block)animania:cheese_mold;8", "animania:cheese_mold;9->(block)animania:cheese_mold;9", "animania:cheese_mold;10->(block)animania:cheese_mold;10"), obj -> obj instanceof String ? true : false); } } - - - + public static class CustomPickupConditions { public static ConfigValue> customPickupConditionsBlocks; - + public static ConfigValue> customPickupConditionsEntities; - + public static void init(ForgeConfigSpec.Builder s, ForgeConfigSpec.Builder c) { s.comment("Custom Pickup Conditions. Read about the format here: https://github.com/Tschipp/CarryOn/wiki/Custom-Pickup-Condition-Config"); - - customPickupConditionsBlocks = s - .comment("Custom Pickup Conditions for Blocks") - .defineList("custom_pickup_conditions.customPickupConditionsBlocks", Arrays.asList(new String[]{}), (obj) -> obj instanceof String ? true : false); - - customPickupConditionsEntities = s - .comment("Custom Pickup Conditions for Entities") - .defineList("custom_pickup_conditions.customPickupConditionsEntities", Arrays.asList(new String[]{}), (obj) -> obj instanceof String ? true : false); + customPickupConditionsBlocks = s.comment("Custom Pickup Conditions for Blocks").defineList("custom_pickup_conditions.customPickupConditionsBlocks", Arrays.asList(), obj -> obj instanceof String ? true : false); + + customPickupConditionsEntities = s.comment("Custom Pickup Conditions for Entities").defineList("custom_pickup_conditions.customPickupConditionsEntities", Arrays.asList(), obj -> obj instanceof String ? true : false); } } diff --git a/src/main/java/tschipp/carryon/common/event/IMCEvents.java b/src/main/java/tschipp/carryon/common/event/IMCEvents.java index f9edbea..f7bc876 100644 --- a/src/main/java/tschipp/carryon/common/event/IMCEvents.java +++ b/src/main/java/tschipp/carryon/common/event/IMCEvents.java @@ -19,16 +19,14 @@ public class IMCEvents { Stream messages = InterModComms.getMessages(CarryOn.MODID); - messages.forEach((msg) -> { + messages.forEach(msg -> { String method = msg.method(); Object obj = msg.messageSupplier().get(); - if(!(obj instanceof String)) + if (!(obj instanceof String str)) return; - - String str = (String)obj; - + switch (method) { case "blacklistBlock": @@ -57,5 +55,5 @@ public class IMCEvents }); } - + } diff --git a/src/main/java/tschipp/carryon/common/event/ItemEntityEvents.java b/src/main/java/tschipp/carryon/common/event/ItemEntityEvents.java index 4191294..8c88506 100644 --- a/src/main/java/tschipp/carryon/common/event/ItemEntityEvents.java +++ b/src/main/java/tschipp/carryon/common/event/ItemEntityEvents.java @@ -55,7 +55,7 @@ public class ItemEntityEvents if (override != null) { String command = override.getCommandPlace(); - + if (command != null) player.getServer().getCommands().performCommand(player.getServer().createCommandSourceStack(), "/execute as " + player.getGameProfile().getName() + " run " + command); } @@ -69,9 +69,8 @@ public class ItemEntityEvents { Entity e = event.getEntity(); Level world = event.getWorld(); - if (e instanceof net.minecraft.world.entity.item.ItemEntity) + if (e instanceof net.minecraft.world.entity.item.ItemEntity eitem) { - net.minecraft.world.entity.item.ItemEntity eitem = (net.minecraft.world.entity.item.ItemEntity) e; ItemStack stack = eitem.getItem(); Item item = stack.getItem(); if (item == RegistrationHandler.itemEntity && ItemCarryonEntity.hasEntityData(stack)) @@ -109,40 +108,38 @@ public class ItemEntityEvents if (entity instanceof Animal) ((Animal) entity).dropLeash(true, true); - if (PickupHandler.canPlayerPickUpEntity((ServerPlayer) player, entity)) + if (PickupHandler.canPlayerPickUpEntity((ServerPlayer) player, entity) && ItemCarryonEntity.storeEntityData(entity, world, stack)) { - if (ItemCarryonEntity.storeEntityData(entity, world, stack)) - { - LazyOptional handler = entity.getCapability(CapabilityItemHandler.ITEM_HANDLER_CAPABILITY); + LazyOptional handler = entity.getCapability(CapabilityItemHandler.ITEM_HANDLER_CAPABILITY); - handler.ifPresent((hand) -> { - for (int i = 0; i < hand.getSlots(); i++) - { - hand.extractItem(i, 64, false); - } - }); + handler.ifPresent(hand -> { + for (int i = 0; i < hand.getSlots(); i++) + { + hand.extractItem(i, 64, false); + } + }); - CarryOnOverride override = ScriptChecker.inspectEntity(entity); - int overrideHash = 0; - if (override != null) - overrideHash = override.hashCode(); + CarryOnOverride override = ScriptChecker.inspectEntity(entity); + int overrideHash = 0; + if (override != null) + overrideHash = override.hashCode(); - ItemEvents.sendPacket(player, player.getInventory().selected, overrideHash); + ItemEvents.sendPacket(player, player.getInventory().selected, overrideHash); - if (entity instanceof LivingEntity) - ((LivingEntity) entity).setHealth(0); + if (entity instanceof LivingEntity) + ((LivingEntity) entity).setHealth(0); - entity.ejectPassengers(); - entity.setPos(entity.getX(), 0, entity.getZ()); - entity.discard(); - player.setItemInHand(InteractionHand.MAIN_HAND, stack); - event.setCanceled(true); - event.setCancellationResult(InteractionResult.FAIL); - } + entity.ejectPassengers(); + entity.setPos(entity.getX(), 0, entity.getZ()); + entity.discard(); + player.setItemInHand(InteractionHand.MAIN_HAND, stack); + event.setCanceled(true); + event.setCancellationResult(InteractionResult.FAIL); } } - } else if (!main.isEmpty() && main.getItem() == RegistrationHandler.itemEntity && ItemCarryonEntity.hasEntityData(main) && !CarryOnKeybinds.isKeyPressed(player) && Settings.stackableEntities.get()) + } + else if (!main.isEmpty() && main.getItem() == RegistrationHandler.itemEntity && ItemCarryonEntity.hasEntityData(main) && !CarryOnKeybinds.isKeyPressed(player) && Settings.stackableEntities.get()) { Entity entityHeld = ItemCarryonEntity.getEntity(main, world); @@ -163,11 +160,10 @@ public class ItemEntityEvents if (Settings.useWhitelistStacking.get() ? ListHandler.isStackingAllowed(topEntity) : !ListHandler.isStackingForbidden(topEntity)) { double sizeEntity = topEntity.getBbHeight() * topEntity.getBbWidth(); - if ((Settings.entitySizeMattersStacking.get() && sizeHeldEntity <= sizeEntity) || !Settings.entitySizeMattersStacking.get()) + if (Settings.entitySizeMattersStacking.get() && sizeHeldEntity <= sizeEntity || !Settings.entitySizeMattersStacking.get()) { - if (topEntity instanceof Horse) + if (topEntity instanceof Horse horse) { - Horse horse = (Horse) topEntity; horse.setTamed(true); } @@ -180,7 +176,8 @@ public class ItemEntityEvents world.addFreshEntity(entityHeld); entityHeld.startRiding(topEntity, false); entityHeld.teleportTo(tempX, tempY, tempZ); - } else + } + else { entityHeld.setPos(entity.getX(), entity.getY(), entity.getZ()); world.addFreshEntity(entityHeld); @@ -193,16 +190,16 @@ public class ItemEntityEvents event.setCanceled(true); event.setCancellationResult(InteractionResult.FAIL); world.playSound(null, player.getX(), player.getY(), player.getZ(), SoundEvents.HORSE_SADDLE, SoundSource.PLAYERS, 0.5F, 1.5F); - } else + } + else { world.playSound(null, player.getX(), player.getY(), player.getZ(), SoundEvents.NOTE_BLOCK_BASS, SoundSource.PLAYERS, 0.5F, 1.5F); - return; } } - } else + } + else { world.playSound(null, player.getX(), player.getY(), player.getZ(), SoundEvents.NOTE_BLOCK_BASS, SoundSource.PLAYERS, 0.5F, 1.5F); - return; } } diff --git a/src/main/java/tschipp/carryon/common/event/ItemEvents.java b/src/main/java/tschipp/carryon/common/event/ItemEvents.java index 39674b5..52b245f 100644 --- a/src/main/java/tschipp/carryon/common/event/ItemEvents.java +++ b/src/main/java/tschipp/carryon/common/event/ItemEvents.java @@ -77,7 +77,7 @@ public class ItemEvents { player.getPersistentData().remove("carrySlot"); event.setUseBlock(Result.DENY); - + if (!player.level.isClientSide) { CarryOnOverride override = ScriptChecker.getOverride(player); @@ -92,15 +92,14 @@ public class ItemEvents } } - + @SubscribeEvent(priority = EventPriority.HIGH) public void onItemDropped(EntityJoinWorldEvent event) { Entity e = event.getEntity(); Level world = event.getWorld(); - if (e instanceof net.minecraft.world.entity.item.ItemEntity) + if (e instanceof net.minecraft.world.entity.item.ItemEntity eitem) { - net.minecraft.world.entity.item.ItemEntity eitem = (net.minecraft.world.entity.item.ItemEntity) e; ItemStack stack = eitem.getItem(); Item item = stack.getItem(); if (item == RegistrationHandler.itemTile && ItemCarryonBlock.hasTileData(stack)) @@ -134,21 +133,22 @@ public class ItemEvents eitem.setItem(ItemStack.EMPTY); } -// BlockPos pos = new BlockPos(Math.floor(eitem.getPosX()), Math.floor(eitem.getPosY()), Math.floor(eitem.getPosZ())); -// if (positions.containsKey(pos)) -// { -// event.setCanceled(true); -// } + // BlockPos pos = new BlockPos(Math.floor(eitem.getPosX()), + // Math.floor(eitem.getPosY()), Math.floor(eitem.getPosZ())); + // if (positions.containsKey(pos)) + // { + // event.setCanceled(true); + // } } } - + @SubscribeEvent public void onPlayerLogin(PlayerLoggedInEvent event) { if (event.getPlayer() instanceof Player) { - Player player = (Player) event.getPlayer(); + Player player = event.getPlayer(); Level world = player.getCommandSenderWorld(); ItemStack carried = player.getMainHandItem(); @@ -161,7 +161,8 @@ public class ItemEvents CarryOn.network.send(PacketDistributor.PLAYER.with(() -> (ServerPlayer) player), new CarrySlotPacket(player.getInventory().selected, player.getId(), override.hashCode())); else CarryOn.network.send(PacketDistributor.PLAYER.with(() -> (ServerPlayer) player), new CarrySlotPacket(player.getInventory().selected, player.getId())); - } else + } + else { CarryOnOverride override = ScriptChecker.inspectEntity(ItemCarryonEntity.getEntity(carried, world)); if (override != null) @@ -173,25 +174,24 @@ public class ItemEvents } } - if(event.getPlayer() instanceof ServerPlayer) + if (event.getPlayer() instanceof ServerPlayer) { - CarryOn.network.send(PacketDistributor.PLAYER.with(() -> (ServerPlayer)event.getPlayer()), new ScriptReloadPacket(ScriptReader.OVERRIDES.values())); + CarryOn.network.send(PacketDistributor.PLAYER.with(() -> (ServerPlayer) event.getPlayer()), new ScriptReloadPacket(ScriptReader.OVERRIDES.values())); } } - @SubscribeEvent public void serverLoad(RegisterCommandsEvent event) { CommandCarryOn.register(event.getDispatcher()); } - + @SubscribeEvent public void serverLoad(FMLServerStartingEvent event) { CustomPickupOverrideHandler.initPickupOverrides(); } - + @SubscribeEvent public void reloadTags(TagsUpdatedEvent event) { @@ -204,9 +204,8 @@ public class ItemEvents Entity e = event.getTarget(); Player tracker = event.getPlayer(); - if (e instanceof Player && tracker instanceof ServerPlayer) + if (e instanceof Player player && tracker instanceof ServerPlayer) { - Player player = (Player) e; Level world = player.getCommandSenderWorld(); ItemStack carried = player.getMainHandItem(); @@ -219,7 +218,8 @@ public class ItemEvents CarryOn.network.send(PacketDistributor.PLAYER.with(() -> (ServerPlayer) tracker), new CarrySlotPacket(player.getInventory().selected, player.getId(), override.hashCode())); else CarryOn.network.send(PacketDistributor.PLAYER.with(() -> (ServerPlayer) tracker), new CarrySlotPacket(player.getInventory().selected, player.getId())); - } else + } + else { CarryOnOverride override = ScriptChecker.inspectEntity(ItemCarryonEntity.getEntity(carried, world)); if (override != null) @@ -271,19 +271,15 @@ public class ItemEvents public void playerAttack(LivingAttackEvent event) { LivingEntity eliving = event.getEntityLiving(); - if (eliving instanceof Player && Settings.dropCarriedWhenHit.get()) + if (eliving instanceof Player player && Settings.dropCarriedWhenHit.get()) { - Player player = (Player) eliving; ItemStack stack = player.getMainHandItem(); - if (!stack.isEmpty() && (stack.getItem() == RegistrationHandler.itemTile || stack.getItem() == RegistrationHandler.itemEntity)) + if (!stack.isEmpty() && (stack.getItem() == RegistrationHandler.itemTile || stack.getItem() == RegistrationHandler.itemEntity) && !player.level.isClientSide) { - if (!player.level.isClientSide) - { - player.setItemInHand(InteractionHand.MAIN_HAND, ItemStack.EMPTY); - ItemEntity item = new ItemEntity(player.level, player.getX(), player.getY(), player.getZ(), stack); - sendPacket(player, 9, 0); - player.level.addFreshEntity(item); - } + player.setItemInHand(InteractionHand.MAIN_HAND, ItemStack.EMPTY); + ItemEntity item = new ItemEntity(player.level, player.getX(), player.getY(), player.getZ(), stack); + sendPacket(player, 9, 0); + player.level.addFreshEntity(item); } } @@ -293,8 +289,8 @@ public class ItemEvents public static void onBlockRightClick(PlayerInteractEvent.RightClickBlock event) { Player player = event.getPlayer(); - - if(event.isCanceled()) + + if (event.isCanceled()) return; if (!player.level.isClientSide) @@ -315,8 +311,7 @@ public class ItemEvents if (PickupHandler.canPlayerPickUpBlock((ServerPlayer) player, te, world, pos)) { player.closeContainer(); - world.levelEvent(1010, pos, 0); - + world.levelEvent(1010, pos, 0); if (ItemCarryonBlock.storeTileData(te, world, pos, state, stack)) { @@ -342,19 +337,21 @@ public class ItemEvents event.setUseItem(Result.DENY); event.setCanceled(true); success = true; - } catch (Exception e) + } + catch (Exception e) { try { sendPacket(player, player.getInventory().selected, overrideHash); emptyTileEntity(te); - world.removeBlock(pos,false); + world.removeBlock(pos, false); player.setItemInHand(InteractionHand.MAIN_HAND, stack); event.setUseBlock(Result.DENY); event.setUseItem(Result.DENY); event.setCanceled(true); success = true; - } catch (Exception ex) + } + catch (Exception ex) { sendPacket(player, 9, 0); world.setBlockAndUpdate(pos, statee); @@ -393,7 +390,7 @@ public class ItemEvents { LazyOptional itemHandler = te.getCapability(CapabilityItemHandler.ITEM_HANDLER_CAPABILITY, facing); - itemHandler.ifPresent((handler) -> { + itemHandler.ifPresent(handler -> { for (int i = 0; i < handler.getSlots(); i++) { @@ -406,7 +403,7 @@ public class ItemEvents LazyOptional itemHandler = te.getCapability(CapabilityItemHandler.ITEM_HANDLER_CAPABILITY, null); - itemHandler.ifPresent((handler) -> { + itemHandler.ifPresent(handler -> { for (int i = 0; i < handler.getSlots(); i++) { @@ -415,15 +412,13 @@ public class ItemEvents }); - if (te instanceof Container) + if (te instanceof Container inv) { - Container inv = (Container) te; inv.clearContent(); } - if (te instanceof IItemHandler) + if (te instanceof IItemHandler itemHandler1) { - IItemHandler itemHandler1 = (IItemHandler) te; for (int i = 0; i < itemHandler1.getSlots(); i++) { itemHandler1.extractItem(i, 64, false); @@ -454,7 +449,7 @@ public class ItemEvents ItemEntity item = new ItemEntity(world, 0, 0, 0, stack); BlockPos pos = null; Optional bedpos = original.getSleepingPos(); - if(bedpos.isPresent()) + if (bedpos.isPresent()) pos = bedpos.get(); if (pos == null) pos = player.blockPosition(); @@ -468,54 +463,44 @@ public class ItemEvents public void dropNonHotbarItems(LivingUpdateEvent event) { LivingEntity entity = event.getEntityLiving(); - if (entity instanceof Player) + if (entity instanceof Player player && !entity.level.isClientSide) { - Player player = (Player) entity; + boolean hasCarried = player.getInventory().contains(new ItemStack(RegistrationHandler.itemTile)) || player.getInventory().contains(new ItemStack(RegistrationHandler.itemEntity)); + ItemStack inHand = player.getMainHandItem(); - if (!entity.level.isClientSide) + if (hasCarried && inHand.getItem() != RegistrationHandler.itemTile && inHand.getItem() != RegistrationHandler.itemEntity && player.getDimensionChangingDelay() == 0) { - boolean hasCarried = player.getInventory().contains(new ItemStack(RegistrationHandler.itemTile)) || player.getInventory().contains(new ItemStack(RegistrationHandler.itemEntity)); - ItemStack inHand = player.getMainHandItem(); + int slotBlock = this.getSlot(player, RegistrationHandler.itemTile); + int slotEntity = this.getSlot(player, RegistrationHandler.itemEntity); - if (hasCarried) + ItemEntity item = null; + if (slotBlock != -1) { - if ((inHand.getItem() != RegistrationHandler.itemTile && inHand.getItem() != RegistrationHandler.itemEntity) && player.getDimensionChangingDelay() == 0) - { - int slotBlock = getSlot(player, RegistrationHandler.itemTile); - int slotEntity = getSlot(player, RegistrationHandler.itemEntity); - - - - ItemEntity item = null; - if (slotBlock != -1) - { - ItemStack dropped = player.getInventory().removeItemNoUpdate(slotBlock); - item = new ItemEntity(player.level, player.getX(), player.getY(), player.getZ(), dropped); - } - if (slotEntity != -1) - { - ItemStack dropped = player.getInventory().removeItemNoUpdate(slotEntity); - item = new ItemEntity(player.level, player.getX(), player.getY(), player.getZ(), dropped); - } - if (item != null) - { - player.level.addFreshEntity(item); - sendPacket(player, 9, 0); - } - } + ItemStack dropped = player.getInventory().removeItemNoUpdate(slotBlock); + item = new ItemEntity(player.level, player.getX(), player.getY(), player.getZ(), dropped); } - - CarryOnOverride override = ScriptChecker.getOverride(player); - - if (override != null) + if (slotEntity != -1) { - String command = override.getCommandLoop(); - - if (command != null) - player.getServer().getCommands().performCommand(player.getServer().createCommandSourceStack(), "/execute as " + player.getGameProfile().getName() + " run " + command); + ItemStack dropped = player.getInventory().removeItemNoUpdate(slotEntity); + item = new ItemEntity(player.level, player.getX(), player.getY(), player.getZ(), dropped); + } + if (item != null) + { + player.level.addFreshEntity(item); + sendPacket(player, 9, 0); } - } + + CarryOnOverride override = ScriptChecker.getOverride(player); + + if (override != null) + { + String command = override.getCommandLoop(); + + if (command != null) + player.getServer().getCommands().performCommand(player.getServer().createCommandSourceStack(), "/execute as " + player.getGameProfile().getName() + " run " + command); + } + } } @@ -541,7 +526,8 @@ public class ItemEvents { player.getPersistentData().remove("carrySlot"); player.getPersistentData().remove("overrideKey"); - } else + } + else { player.getPersistentData().putInt("carrySlot", currentItem); if (hash != 0) diff --git a/src/main/java/tschipp/carryon/common/handler/CustomPickupOverrideHandler.java b/src/main/java/tschipp/carryon/common/handler/CustomPickupOverrideHandler.java index dae3169..edff1cb 100644 --- a/src/main/java/tschipp/carryon/common/handler/CustomPickupOverrideHandler.java +++ b/src/main/java/tschipp/carryon/common/handler/CustomPickupOverrideHandler.java @@ -17,8 +17,8 @@ import tschipp.carryon.common.helper.InvalidConfigException; public class CustomPickupOverrideHandler { - public static HashMap PICKUP_CONDITIONS = new HashMap(); - public static HashMap PICKUP_CONDITIONS_ENTITIES = new HashMap(); + public static HashMap PICKUP_CONDITIONS = new HashMap<>(); + public static HashMap PICKUP_CONDITIONS_ENTITIES = new HashMap<>(); @SuppressWarnings("unchecked") public static void initPickupOverrides() @@ -78,13 +78,12 @@ public class CustomPickupOverrideHandler } } - public static boolean hasSpecialPickupConditions(BlockState state) { if (!ModList.get().isLoaded("gamestages")) return false; - for(String cond : PICKUP_CONDITIONS.keySet()) + for (String cond : PICKUP_CONDITIONS.keySet()) { BlockStateParser parser = new BlockStateParser(new StringReader(cond), false); try @@ -94,16 +93,16 @@ public class CustomPickupOverrideHandler catch (CommandSyntaxException e) { } - if(parser.getState() == state) + if (parser.getState() == state) return true; } - + return false; } public static String getPickupCondition(BlockState state) { - for(String cond : PICKUP_CONDITIONS.keySet()) + for (String cond : PICKUP_CONDITIONS.keySet()) { BlockStateParser parser = new BlockStateParser(new StringReader(cond), false); try @@ -113,7 +112,7 @@ public class CustomPickupOverrideHandler catch (CommandSyntaxException e) { } - if(parser.getState() == state) + if (parser.getState() == state) return PICKUP_CONDITIONS.get(cond); } return null; @@ -125,17 +124,13 @@ public class CustomPickupOverrideHandler return false; String name = entity.getType().getRegistryName().toString(); - boolean condition = PICKUP_CONDITIONS_ENTITIES.containsKey(name); - - return condition; + return PICKUP_CONDITIONS_ENTITIES.containsKey(name); } public static String getPickupCondition(Entity entity) { String name = entity.getType().getRegistryName().toString(); - String condition = PICKUP_CONDITIONS_ENTITIES.get(name); - - return condition; + return PICKUP_CONDITIONS_ENTITIES.get(name); } } diff --git a/src/main/java/tschipp/carryon/common/handler/ListHandler.java b/src/main/java/tschipp/carryon/common/handler/ListHandler.java index 0867f6c..48c3192 100644 --- a/src/main/java/tschipp/carryon/common/handler/ListHandler.java +++ b/src/main/java/tschipp/carryon/common/handler/ListHandler.java @@ -22,11 +22,11 @@ public class ListHandler public static List ALLOWED_ENTITIES = new ArrayList<>(); public static List ALLOWED_TILES = new ArrayList<>(); public static List FORBIDDEN_STACKING = new ArrayList<>(); - public static List ALLOWED_STACKING = new ArrayList<>(); + public static List ALLOWED_STACKING = new ArrayList<>(); public static List> FORBIDDEN_TILES_TAGS = new ArrayList<>(); public static List>> FORBIDDEN_ENTITIES_TAGS = new ArrayList<>(); - public static List>> ALLOWED_ENTITIES_TAGS = new ArrayList<>(); + public static List>> ALLOWED_ENTITIES_TAGS = new ArrayList<>(); public static List> ALLOWED_TILES_TAGS = new ArrayList<>(); public static List>> FORBIDDEN_STACKING_TAGS = new ArrayList<>(); public static List>> ALLOWED_STACKING_TAGS = new ArrayList<>(); @@ -48,10 +48,10 @@ public class ListHandler contains = true; } } - - for(Tag tag : FORBIDDEN_TILES_TAGS) + + for (Tag tag : FORBIDDEN_TILES_TAGS) { - if(tag.contains(block)) + if (tag.contains(block)) return true; } @@ -63,13 +63,13 @@ public class ListHandler { String name = entity.getType().getRegistryName().toString(); boolean contains = FORBIDDEN_ENTITIES.contains(name); - - for(Tag> tag : FORBIDDEN_ENTITIES_TAGS) + + for (Tag> tag : FORBIDDEN_ENTITIES_TAGS) { - if(tag.contains(entity.getType())) + if (tag.contains(entity.getType())) return true; } - + return contains; } @@ -77,13 +77,13 @@ public class ListHandler { String name = entity.getType().getRegistryName().toString(); boolean contains = ALLOWED_ENTITIES.contains(name); - - for(Tag> tag : ALLOWED_ENTITIES_TAGS) + + for (Tag> tag : ALLOWED_ENTITIES_TAGS) { - if(tag.contains(entity.getType())) + if (tag.contains(entity.getType())) return true; } - + return contains; } @@ -91,13 +91,13 @@ public class ListHandler { String name = entity.getType().getRegistryName().toString(); boolean contains = FORBIDDEN_STACKING.contains(name); - - for(Tag> tag : FORBIDDEN_STACKING_TAGS) + + for (Tag> tag : FORBIDDEN_STACKING_TAGS) { - if(tag.contains(entity.getType())) + if (tag.contains(entity.getType())) return true; } - + return contains; } @@ -105,13 +105,13 @@ public class ListHandler { String name = entity.getType().getRegistryName().toString(); boolean contains = ALLOWED_STACKING.contains(name); - - for(Tag> tag : ALLOWED_STACKING_TAGS) + + for (Tag> tag : ALLOWED_STACKING_TAGS) { - if(tag.contains(entity.getType())) + if (tag.contains(entity.getType())) return true; } - + return contains; } @@ -132,10 +132,10 @@ public class ListHandler contains = true; } } - - for(Tag tag : ALLOWED_TILES_TAGS) + + for (Tag tag : ALLOWED_TILES_TAGS) { - if(tag.contains(block)) + if (tag.contains(block)) return true; } @@ -145,7 +145,7 @@ public class ListHandler } public static void initConfigLists() - { + { FORBIDDEN_ENTITIES.clear(); FORBIDDEN_ENTITIES_TAGS.clear(); FORBIDDEN_STACKING.clear(); @@ -158,10 +158,10 @@ public class ListHandler ALLOWED_STACKING_TAGS.clear(); ALLOWED_TILES.clear(); ALLOWED_TILES_TAGS.clear(); - + List forbidden = new ArrayList<>(Blacklist.forbiddenTiles.get()); forbidden.add("#carryon:block_blacklist"); - FORBIDDEN_TILES = new ArrayList(); + FORBIDDEN_TILES = new ArrayList<>(); for (int i = 0; i < forbidden.size(); i++) { @@ -171,7 +171,7 @@ public class ListHandler List forbiddenEntity = new ArrayList<>(Blacklist.forbiddenEntities.get()); forbiddenEntity.add("#carryon:entity_blacklist"); - FORBIDDEN_ENTITIES = new ArrayList(); + FORBIDDEN_ENTITIES = new ArrayList<>(); for (int i = 0; i < forbiddenEntity.size(); i++) { @@ -196,7 +196,7 @@ public class ListHandler List allowedEntities = new ArrayList<>(WhiteList.allowedEntities.get()); allowedEntities.add("#carryon:entity_whitelist"); - ALLOWED_ENTITIES = new ArrayList(); + ALLOWED_ENTITIES = new ArrayList<>(); for (int i = 0; i < allowedEntities.size(); i++) { if (!allowedEntities.get(i).startsWith("#")) @@ -220,7 +220,7 @@ public class ListHandler List allowedBlocks = new ArrayList<>(WhiteList.allowedBlocks.get()); allowedBlocks.add("#carryon:block_whitelist"); - ALLOWED_TILES = new ArrayList(); + ALLOWED_TILES = new ArrayList<>(); for (int i = 0; i < allowedBlocks.size(); i++) { if (!allowedBlocks.get(i).startsWith("#")) @@ -229,7 +229,7 @@ public class ListHandler List forbiddenStacking = new ArrayList<>(Blacklist.forbiddenStacking.get()); forbiddenStacking.add("#carryon:stacking_blacklist"); - FORBIDDEN_STACKING = new ArrayList(); + FORBIDDEN_STACKING = new ArrayList<>(); for (int i = 0; i < forbiddenStacking.size(); i++) { @@ -254,7 +254,7 @@ public class ListHandler List allowedStacking = new ArrayList<>(WhiteList.allowedStacking.get()); allowedStacking.add("#carryon:stacking_whitelist"); - ALLOWED_STACKING = new ArrayList(); + ALLOWED_STACKING = new ArrayList<>(); for (int i = 0; i < allowedStacking.size(); i++) { if (!allowedStacking.get(i).startsWith("#")) @@ -280,63 +280,63 @@ public class ListHandler TagCollection> entitytags = EntityTypeTags.getAllTags(); System.out.println(blocktags.getAvailableTags()); - + for (String s : forbidden) { if (s.startsWith("#")) { - String sub = s.substring(1, s.length()); + String sub = s.substring(1); Tag tag = blocktags.getTag(new ResourceLocation(sub)); if (tag != null) FORBIDDEN_TILES_TAGS.add(tag); } } - + for (String s : allowedBlocks) { if (s.startsWith("#")) { - Tag tag = blocktags.getTag(new ResourceLocation(s.substring(1, s.length()))); + Tag tag = blocktags.getTag(new ResourceLocation(s.substring(1))); if (tag != null) ALLOWED_TILES_TAGS.add(tag); } } - + for (String s : forbiddenEntity) { if (s.startsWith("#")) { - Tag> tag = entitytags.getTag(new ResourceLocation(s.substring(1, s.length()))); + Tag> tag = entitytags.getTag(new ResourceLocation(s.substring(1))); if (tag != null) FORBIDDEN_ENTITIES_TAGS.add(tag); } } - + for (String s : allowedEntities) { if (s.startsWith("#")) { - Tag> tag = entitytags.getTag(new ResourceLocation(s.substring(1, s.length()))); + Tag> tag = entitytags.getTag(new ResourceLocation(s.substring(1))); if (tag != null) ALLOWED_ENTITIES_TAGS.add(tag); } } - + for (String s : forbiddenStacking) { if (s.startsWith("#")) { - Tag> tag = entitytags.getTag(new ResourceLocation(s.substring(1, s.length()))); + Tag> tag = entitytags.getTag(new ResourceLocation(s.substring(1))); if (tag != null) FORBIDDEN_STACKING_TAGS.add(tag); } } - + for (String s : allowedStacking) { if (s.startsWith("#")) { - Tag> tag = entitytags.getTag(new ResourceLocation(s.substring(1, s.length()))); + Tag> tag = entitytags.getTag(new ResourceLocation(s.substring(1))); if (tag != null) ALLOWED_STACKING_TAGS.add(tag); } diff --git a/src/main/java/tschipp/carryon/common/handler/ModelOverridesHandler.java b/src/main/java/tschipp/carryon/common/handler/ModelOverridesHandler.java index 2db7492..ce4641a 100644 --- a/src/main/java/tschipp/carryon/common/handler/ModelOverridesHandler.java +++ b/src/main/java/tschipp/carryon/common/handler/ModelOverridesHandler.java @@ -25,12 +25,12 @@ import tschipp.carryon.common.helper.StringParser; public class ModelOverridesHandler { - public static HashMap OVERRIDE_OBJECTS = new HashMap(); + public static HashMap OVERRIDE_OBJECTS = new HashMap<>(); /* * This class is really ugly, will probably be replaced by something else - * Tschipp - */ + */ public static void parseOverride(String overrideString, int i) { boolean errored = false; @@ -94,7 +94,7 @@ public class ModelOverridesHandler } overridetype = override.substring(0, override.indexOf(")") + 1); - override =override.replace(overridetype, ""); + override = override.replace(overridetype, ""); overridetype = overridetype.replace("(", ""); overridetype = overridetype.replace(")", ""); @@ -116,7 +116,7 @@ public class ModelOverridesHandler if ((ModList.get().isLoaded(modidOverride) || modidOverride.equals("minecraft")) && (ModList.get().isLoaded(modidToOverride) || modidToOverride.equals("minecraft")) && !errored) { - toOverrideObject = StringParser.getBlockState(toOverride); + toOverrideObject = StringParser.getBlockState(toOverride); if (toOverrideObject != null) { @@ -143,8 +143,7 @@ public class ModelOverridesHandler } } } - - + public static void initOverrides() { @SuppressWarnings("unchecked") @@ -233,7 +232,7 @@ public class ModelOverridesHandler return null; } - + public static Object getOverrideObject(BlockState state, CompoundTag tag) { int stateid = Block.getId(state); @@ -259,8 +258,7 @@ public class ModelOverridesHandler } if (flag) { - Object override = OVERRIDE_OBJECTS.get(key); - return override; + return OVERRIDE_OBJECTS.get(key); } } } diff --git a/src/main/java/tschipp/carryon/common/handler/PickupHandler.java b/src/main/java/tschipp/carryon/common/handler/PickupHandler.java index ce71f13..4164f76 100644 --- a/src/main/java/tschipp/carryon/common/handler/PickupHandler.java +++ b/src/main/java/tschipp/carryon/common/handler/PickupHandler.java @@ -30,20 +30,19 @@ public class PickupHandler { public static boolean canPlayerPickUpBlock(ServerPlayer player, @Nullable BlockEntity tile, Level world, BlockPos pos) - { - if(player.gameMode.getGameModeForPlayer() == GameType.SPECTATOR || player.gameMode.getGameModeForPlayer() == GameType.ADVENTURE) + { + if (player.gameMode.getGameModeForPlayer() == GameType.SPECTATOR || player.gameMode.getGameModeForPlayer() == GameType.ADVENTURE) return false; - - + BlockState state = world.getBlockState(pos); CompoundTag tag = new CompoundTag(); if (tile != null) tile.save(tag); - + CarryOnOverride override = ScriptChecker.inspectBlock(world.getBlockState(pos), world, pos, tag); if (override != null) { - return (ScriptChecker.fulfillsConditions(override, player)) && handleProtections((ServerPlayer) player, world, pos, state); + return ScriptChecker.fulfillsConditions(override, player) && handleProtections(player, world, pos, state); } else { @@ -54,35 +53,28 @@ public class PickupHandler return false; } } - else + else if (ListHandler.isForbidden(world.getBlockState(pos).getBlock())) { - if (ListHandler.isForbidden(world.getBlockState(pos).getBlock())) - { - return false; - } + return false; } - if ((state.getDestroySpeed(world, pos) != -1 || player.isCreative())) + if (state.getDestroySpeed(world, pos) != -1 || player.isCreative()) { double distance = Vec3.atLowerCornerOf(pos).distanceTo(player.position()); double maxDist = Settings.maxDistance.get(); - - if (distance < maxDist) + + if (distance < maxDist && !ItemCarryonBlock.isLocked(pos, world)) { - if (!ItemCarryonBlock.isLocked(pos, world)) + if (CustomPickupOverrideHandler.hasSpecialPickupConditions(state)) { - - if (CustomPickupOverrideHandler.hasSpecialPickupConditions(state)) - { - return CarryonGamestageHelper.hasGamestage(CustomPickupOverrideHandler.getPickupCondition(state), player) && handleProtections((ServerPlayer) player, world, pos, state); - } - else if (Settings.pickupAllBlocks.get() ? true : tile != null) - { - return handleProtections(player, world, pos, state); - } - + return CarryonGamestageHelper.hasGamestage(CustomPickupOverrideHandler.getPickupCondition(state), player) && handleProtections(player, world, pos, state); } + else if (Settings.pickupAllBlocks.get() ? true : tile != null) + { + return handleProtections(player, world, pos, state); + } + } } } @@ -92,9 +84,9 @@ public class PickupHandler public static boolean canPlayerPickUpEntity(ServerPlayer player, Entity toPickUp) { - if(player.gameMode.getGameModeForPlayer() == GameType.SPECTATOR || player.gameMode.getGameModeForPlayer() == GameType.ADVENTURE) + if (player.gameMode.getGameModeForPlayer() == GameType.SPECTATOR || player.gameMode.getGameModeForPlayer() == GameType.ADVENTURE) return false; - + Vec3 pos = toPickUp.position(); if (toPickUp instanceof Player) @@ -103,34 +95,23 @@ public class PickupHandler CarryOnOverride override = ScriptChecker.inspectEntity(toPickUp); if (override != null) { - return (ScriptChecker.fulfillsConditions(override, player)) && handleProtections(player, toPickUp); + return ScriptChecker.fulfillsConditions(override, player) && handleProtections(player, toPickUp); } else { - if (toPickUp instanceof AgeableMob && Settings.allowBabies.get()) + if (toPickUp instanceof AgeableMob living && Settings.allowBabies.get() && (living.getAge() < 0 || living.isBaby())) { - AgeableMob living = (AgeableMob) toPickUp; - if (living.getAge() < 0 || living.isBaby()) + + double distance = pos.distanceToSqr(player.position()); + if (distance <= Math.pow(Settings.maxDistance.get(), 2) && toPickUp instanceof TamableAnimal tame && tame.getOwnerUUID() != null && tame.getOwnerUUID() != Player.createPlayerUUID(player.getGameProfile())) + return false; + + if (CustomPickupOverrideHandler.hasSpecialPickupConditions(toPickUp)) { - - double distance = pos.distanceToSqr(player.position()); - if (distance <= Math.pow(Settings.maxDistance.get(), 2)) - { - if (toPickUp instanceof TamableAnimal) - { - TamableAnimal tame = (TamableAnimal) toPickUp; - if (tame.getOwnerUUID() != null && tame.getOwnerUUID() != Player.createPlayerUUID(player.getGameProfile())) - return false; - } - } - - if (CustomPickupOverrideHandler.hasSpecialPickupConditions(toPickUp)) - { - return CarryonGamestageHelper.hasGamestage(CustomPickupOverrideHandler.getPickupCondition(toPickUp), player) && handleProtections((ServerPlayer) player, toPickUp); - } - else - return handleProtections((ServerPlayer) player, toPickUp); + return CarryonGamestageHelper.hasGamestage(CustomPickupOverrideHandler.getPickupCondition(toPickUp), player) && handleProtections(player, toPickUp); } + else + return handleProtections(player, toPickUp); } if (Settings.useWhitelistEntities.get()) @@ -140,44 +121,35 @@ public class PickupHandler return false; } } - else + else if (ListHandler.isForbidden(toPickUp)) { - if (ListHandler.isForbidden(toPickUp)) - { - return false; - } + return false; } - if ((Settings.pickupHostileMobs.get() ? true : toPickUp.getType().getCategory() != MobCategory.MONSTER || player.isCreative())) + if ((Settings.pickupHostileMobs.get() ? true : toPickUp.getType().getCategory() != MobCategory.MONSTER || player.isCreative()) && (Settings.pickupHostileMobs.get() ? true : toPickUp.getType().getCategory() != MobCategory.MONSTER || player.isCreative())) { - if ((Settings.pickupHostileMobs.get() ? true : toPickUp.getType().getCategory() != MobCategory.MONSTER || player.isCreative())) + if (toPickUp.getBbHeight() <= Settings.maxEntityHeight.get() && toPickUp.getBbWidth() <= Settings.maxEntityWidth.get() || player.isCreative()) { - if ((toPickUp.getBbHeight() <= Settings.maxEntityHeight.get() && toPickUp.getBbWidth() <= Settings.maxEntityWidth.get() || player.isCreative())) + double distance = pos.distanceToSqr(player.position()); + if (distance < Math.pow(Settings.maxDistance.get(), 2)) { - double distance = pos.distanceToSqr(player.position()); - if (distance < Math.pow(Settings.maxDistance.get(), 2)) + if (toPickUp instanceof TamableAnimal tame) { - if (toPickUp instanceof TamableAnimal) - { - TamableAnimal tame = (TamableAnimal) toPickUp; - UUID owner = tame.getOwnerUUID(); - UUID playerID = Player.createPlayerUUID(player.getGameProfile()); - if (owner != null && !owner.equals(playerID)) - return false; - } - - if (CustomPickupOverrideHandler.hasSpecialPickupConditions(toPickUp)) - { - return CarryonGamestageHelper.hasGamestage(CustomPickupOverrideHandler.getPickupCondition(toPickUp), player) && handleProtections((ServerPlayer) player, toPickUp); - } - else - return handleProtections((ServerPlayer) player, toPickUp); + UUID owner = tame.getOwnerUUID(); + UUID playerID = Player.createPlayerUUID(player.getGameProfile()); + if (owner != null && !owner.equals(playerID)) + return false; } - + if (CustomPickupOverrideHandler.hasSpecialPickupConditions(toPickUp)) + { + return CarryonGamestageHelper.hasGamestage(CustomPickupOverrideHandler.getPickupCondition(toPickUp), player) && handleProtections(player, toPickUp); + } + else + return handleProtections(player, toPickUp); } - } + } } } @@ -189,9 +161,9 @@ public class PickupHandler public PickUpBlockEvent(Level world, BlockPos pos, BlockState state, Player player) { super(world, pos, state, player); - } + } } - + public static class PickUpEntityEvent extends AttackEntityEvent { public PickUpEntityEvent(Player player, Entity target) @@ -199,7 +171,7 @@ public class PickupHandler super(player, target); } } - + private static boolean handleProtections(ServerPlayer player, Level world, BlockPos pos, BlockState state) { boolean breakable = true; diff --git a/src/main/java/tschipp/carryon/common/handler/RegistrationHandler.java b/src/main/java/tschipp/carryon/common/handler/RegistrationHandler.java index fd68bef..b1b5237 100644 --- a/src/main/java/tschipp/carryon/common/handler/RegistrationHandler.java +++ b/src/main/java/tschipp/carryon/common/handler/RegistrationHandler.java @@ -19,10 +19,10 @@ import tschipp.carryon.common.item.ItemCarryonEntity; @EventBusSubscriber(modid = CarryOn.MODID) public class RegistrationHandler -{ +{ @ObjectHolder("carryon:tile_item") public static Item itemTile; - + @ObjectHolder("carryon:entity_item") public static Item itemEntity; @@ -31,7 +31,7 @@ public class RegistrationHandler itemTile = new ItemCarryonBlock(); itemEntity = new ItemCarryonEntity(); } - + public static void regCommonEvents() { MinecraftForge.EVENT_BUS.register(new ItemEvents()); @@ -39,32 +39,28 @@ public class RegistrationHandler MinecraftForge.EVENT_BUS.register(new PositionCommonEvents()); MinecraftForge.EVENT_BUS.register(new IMCEvents()); } - + public static void regClientEvents() { MinecraftForge.EVENT_BUS.register(new RenderEvents()); MinecraftForge.EVENT_BUS.register(new RenderEntityEvents()); MinecraftForge.EVENT_BUS.register(new PositionClientEvents()); - - -// if(ModList.get().isLoaded("obfuscate")) -// MinecraftForge.EVENT_BUS.register(new ObfuscateEvents()); + + // if(ModList.get().isLoaded("obfuscate")) + // MinecraftForge.EVENT_BUS.register(new ObfuscateEvents()); } - + public static void regOverrideList() { ModelOverridesHandler.initOverrides(); CustomPickupOverrideHandler.initPickupOverrides(); -// ListHandler.initConfigLists(); + // ListHandler.initConfigLists(); } - + public static void regCaps() { CapabilityManager.INSTANCE.register(IPosition.class); } - - - } diff --git a/src/main/java/tschipp/carryon/common/helper/CarryonGamestageHelper.java b/src/main/java/tschipp/carryon/common/helper/CarryonGamestageHelper.java index 9af70c7..be0c725 100644 --- a/src/main/java/tschipp/carryon/common/helper/CarryonGamestageHelper.java +++ b/src/main/java/tschipp/carryon/common/helper/CarryonGamestageHelper.java @@ -7,7 +7,7 @@ public class CarryonGamestageHelper { public static boolean hasGamestage(String stage, Player player) { -// return GameStageHelper.hasStage(player, stage); + // return GameStageHelper.hasStage(player, stage); return true; } } diff --git a/src/main/java/tschipp/carryon/common/helper/InvalidConfigException.java b/src/main/java/tschipp/carryon/common/helper/InvalidConfigException.java index ebd4438..67cca97 100644 --- a/src/main/java/tschipp/carryon/common/helper/InvalidConfigException.java +++ b/src/main/java/tschipp/carryon/common/helper/InvalidConfigException.java @@ -19,15 +19,15 @@ public class InvalidConfigException extends Exception { StackTraceElement element = this.getStackTrace()[i]; CarryOn.LOGGER.error(element.toString()); - - if(i >= 10) + + if (i >= 10) { - CarryOn.LOGGER.error((this.getStackTrace().length - 10) + " more..."); + CarryOn.LOGGER.error(this.getStackTrace().length - 10 + " more..."); break; } } - + CarryOn.LOGGER.info(""); } - + } diff --git a/src/main/java/tschipp/carryon/common/helper/KeyboardCallbackWrapper.java b/src/main/java/tschipp/carryon/common/helper/KeyboardCallbackWrapper.java index 3f7e462..854a50a 100644 --- a/src/main/java/tschipp/carryon/common/helper/KeyboardCallbackWrapper.java +++ b/src/main/java/tschipp/carryon/common/helper/KeyboardCallbackWrapper.java @@ -14,7 +14,7 @@ public class KeyboardCallbackWrapper public void setup(Minecraft mc) { - oldCallback = GLFW.glfwSetKeyCallback(mc.getWindow().getWindow(), this::keyCallback); + this.oldCallback = GLFW.glfwSetKeyCallback(mc.getWindow().getWindow(), this::keyCallback); } private void keyCallback(long window, int key, int scancode, int action, int mods) @@ -25,21 +25,21 @@ public class KeyboardCallbackWrapper if (event.isCanceled()) return; - if (oldCallback != null) - oldCallback.invoke(window, key, scancode, action, mods); + if (this.oldCallback != null) + this.oldCallback.invoke(window, key, scancode, action, mods); } - + @Cancelable public static class KeyPressedEvent extends Event { public int key; public int scancode; - + public KeyPressedEvent(int key, int scancode) { this.key = key; this.scancode = scancode; } - + } } \ No newline at end of file diff --git a/src/main/java/tschipp/carryon/common/helper/ReflectionHelper.java b/src/main/java/tschipp/carryon/common/helper/ReflectionHelper.java index 35131a3..885f06e 100644 --- a/src/main/java/tschipp/carryon/common/helper/ReflectionHelper.java +++ b/src/main/java/tschipp/carryon/common/helper/ReflectionHelper.java @@ -25,6 +25,7 @@ import javax.annotation.Nonnull; import javax.annotation.Nullable; import com.google.common.base.Preconditions; + /** * Some reflection helper code. * @@ -33,214 +34,230 @@ import com.google.common.base.Preconditions; */ public class ReflectionHelper { - public static class UnableToFindMethodException extends RuntimeException - { - private static final long serialVersionUID = 1L; - //private String[] methodNames; + public static class UnableToFindMethodException extends RuntimeException + { + private static final long serialVersionUID = 1L; + // private String[] methodNames; - public UnableToFindMethodException(String[] methodNames, Exception failed) - { - super(failed); - //this.methodNames = methodNames; - } + public UnableToFindMethodException(String[] methodNames, Exception failed) + { + super(failed); + // this.methodNames = methodNames; + } - public UnableToFindMethodException(Throwable failed) - { - super(failed); - } + public UnableToFindMethodException(Throwable failed) + { + super(failed); + } - } + } - public static class UnableToFindClassException extends RuntimeException - { - private static final long serialVersionUID = 1L; - //private String[] classNames; + public static class UnableToFindClassException extends RuntimeException + { + private static final long serialVersionUID = 1L; + // private String[] classNames; - public UnableToFindClassException(String[] classNames, @Nullable Exception err) - { - super(err); - //this.classNames = classNames; - } + public UnableToFindClassException(String[] classNames, @Nullable Exception err) + { + super(err); + // this.classNames = classNames; + } - } + } - public static class UnableToAccessFieldException extends RuntimeException - { - private static final long serialVersionUID = 1L; - //private String[] fieldNameList; + public static class UnableToAccessFieldException extends RuntimeException + { + private static final long serialVersionUID = 1L; + // private String[] fieldNameList; - public UnableToAccessFieldException(String[] fieldNames, Exception e) - { - super(e); - //this.fieldNameList = fieldNames; - } - } + public UnableToAccessFieldException(String[] fieldNames, Exception e) + { + super(e); + // this.fieldNameList = fieldNames; + } + } - public static class UnableToFindFieldException extends RuntimeException - { - private static final long serialVersionUID = 1L; - //private String[] fieldNameList; - public UnableToFindFieldException(String[] fieldNameList, Exception e) - { - super(e); - //this.fieldNameList = fieldNameList; - } - } + public static class UnableToFindFieldException extends RuntimeException + { + private static final long serialVersionUID = 1L; - @SuppressWarnings("serial") + // private String[] fieldNameList; + public UnableToFindFieldException(String[] fieldNameList, Exception e) + { + super(e); + // this.fieldNameList = fieldNameList; + } + } + + @SuppressWarnings("serial") public static class UnknownConstructorException extends RuntimeException - { - public UnknownConstructorException(final String message) - { - super(message); - } - } + { + public UnknownConstructorException(final String message) + { + super(message); + } + } - public static Field findField(Class clazz, String... fieldNames) - { - Exception failed = null; - for (String fieldName : fieldNames) - { - try - { - Field f = clazz.getDeclaredField(fieldName); - f.setAccessible(true); - return f; - } - catch (Exception e) - { - failed = e; - } - } - throw new UnableToFindFieldException(fieldNames, failed); - } + public static Field findField(Class clazz, String... fieldNames) + { + Exception failed = null; + for (String fieldName : fieldNames) + { + try + { + Field f = clazz.getDeclaredField(fieldName); + f.setAccessible(true); + return f; + } + catch (Exception e) + { + failed = e; + } + } + throw new UnableToFindFieldException(fieldNames, failed); + } - @SuppressWarnings("unchecked") - public static T getPrivateValue(Class classToAccess, @Nullable E instance, int fieldIndex) - { - try - { - Field f = classToAccess.getDeclaredFields()[fieldIndex]; - f.setAccessible(true); - return (T) f.get(instance); - } - catch (Exception e) - { - throw new UnableToAccessFieldException(new String[0], e); - } - } + @SuppressWarnings("unchecked") + public static T getPrivateValue(Class classToAccess, @Nullable E instance, int fieldIndex) + { + try + { + Field f = classToAccess.getDeclaredFields()[fieldIndex]; + f.setAccessible(true); + return (T) f.get(instance); + } + catch (Exception e) + { + throw new UnableToAccessFieldException(new String[0], e); + } + } - @SuppressWarnings("unchecked") - public static T getPrivateValue(Class classToAccess, E instance, String... fieldNames) - { - try - { - return (T) findField(classToAccess, fieldNames).get(instance); - } - catch (Exception e) - { - throw new UnableToAccessFieldException(fieldNames, e); - } - } + @SuppressWarnings("unchecked") + public static T getPrivateValue(Class classToAccess, E instance, String... fieldNames) + { + try + { + return (T) findField(classToAccess, fieldNames).get(instance); + } + catch (Exception e) + { + throw new UnableToAccessFieldException(fieldNames, e); + } + } - public static void setPrivateValue(Class classToAccess, T instance, E value, int fieldIndex) - { - try - { - Field f = classToAccess.getDeclaredFields()[fieldIndex]; - f.setAccessible(true); - f.set(instance, value); - } - catch (Exception e) - { - throw new UnableToAccessFieldException(new String[0] , e); - } - } + public static void setPrivateValue(Class classToAccess, T instance, E value, int fieldIndex) + { + try + { + Field f = classToAccess.getDeclaredFields()[fieldIndex]; + f.setAccessible(true); + f.set(instance, value); + } + catch (Exception e) + { + throw new UnableToAccessFieldException(new String[0], e); + } + } - public static void setPrivateValue(Class classToAccess, T instance, E value, String... fieldNames) - { - try - { - findField(classToAccess, fieldNames).set(instance, value); - } - catch (Exception e) - { - throw new UnableToAccessFieldException(fieldNames, e); - } - } + public static void setPrivateValue(Class classToAccess, T instance, E value, String... fieldNames) + { + try + { + findField(classToAccess, fieldNames).set(instance, value); + } + catch (Exception e) + { + throw new UnableToAccessFieldException(fieldNames, e); + } + } - @SuppressWarnings("unchecked") - public static Class getClass(ClassLoader loader, String... classNames) - { - Exception err = null; - for (String className : classNames) - { - try - { - return (Class) Class.forName(className, false, loader); - } - catch (Exception e) - { - err = e; - } - } + @SuppressWarnings("unchecked") + public static Class getClass(ClassLoader loader, String... classNames) + { + Exception err = null; + for (String className : classNames) + { + try + { + return (Class) Class.forName(className, false, loader); + } + catch (Exception e) + { + err = e; + } + } - throw new UnableToFindClassException(classNames, err); - } + throw new UnableToFindClassException(classNames, err); + } - /** - * Finds a method with the specified name and parameters in the given class and makes it accessible. - * Note: for performance, store the returned value and avoid calling this repeatedly. - *

- * Throws an exception if the method is not found. - * - * @param clazz The class to find the method on. - * @param methodName The name of the method to find (used in developer environments, i.e. "getWorldTime"). - * @param methodObfName The obfuscated name of the method to find (used in obfuscated environments, i.e. "getWorldTime"). - * If the name you are looking for is on a class that is never obfuscated, this should be null. - * @param parameterTypes The parameter types of the method to find. - * @return The method with the specified name and parameters in the given class. - */ - + /** + * Finds a method with the specified name and parameters in the given class + * and makes it accessible. Note: for performance, store the returned value + * and avoid calling this repeatedly. + *

+ * Throws an exception if the method is not found. + * + * @param clazz + * The class to find the method on. + * @param methodName + * The name of the method to find (used in developer + * environments, i.e. "getWorldTime"). + * @param methodObfName + * The obfuscated name of the method to find (used in obfuscated + * environments, i.e. "getWorldTime"). If the name you are + * looking for is on a class that is never obfuscated, this + * should be null. + * @param parameterTypes + * The parameter types of the method to find. + * @return The method with the specified name and parameters in the given + * class. + */ - /** - * Finds a constructor in the specified class that has matching parameter types. - * - * @param klass The class to find the constructor in - * @param parameterTypes The parameter types of the constructor. - * @param The type - * @return The constructor - * @throws NullPointerException if {@code klass} is null - * @throws NullPointerException if {@code parameterTypes} is null - * @throws UnknownConstructorException if the constructor could not be found - */ - @Nonnull - public static Constructor findConstructor(@Nonnull final Class klass, @Nonnull final Class... parameterTypes) - { - Preconditions.checkNotNull(klass, "class"); - Preconditions.checkNotNull(parameterTypes, "parameter types"); + /** + * Finds a constructor in the specified class that has matching parameter + * types. + * + * @param klass + * The class to find the constructor in + * @param parameterTypes + * The parameter types of the constructor. + * @param + * The type + * @return The constructor + * @throws NullPointerException + * if {@code klass} is null + * @throws NullPointerException + * if {@code parameterTypes} is null + * @throws UnknownConstructorException + * if the constructor could not be found + */ + @Nonnull + public static Constructor findConstructor(@Nonnull final Class klass, @Nonnull final Class... parameterTypes) + { + Preconditions.checkNotNull(klass, "class"); + Preconditions.checkNotNull(parameterTypes, "parameter types"); - final Constructor constructor; - try - { - constructor = klass.getDeclaredConstructor(parameterTypes); - constructor.setAccessible(true); - } - catch (final NoSuchMethodException e) - { - final StringBuilder desc = new StringBuilder(); - desc.append(klass.getSimpleName()).append('('); - for (int i = 0, length = parameterTypes.length; i < length; i++) - { - desc.append(parameterTypes[i].getName()); - if (i > length) - { - desc.append(',').append(' '); - } - } - desc.append(')'); - throw new UnknownConstructorException("Could not find constructor '" + desc.toString() + "' in " + klass); - } - return constructor; - } + final Constructor constructor; + try + { + constructor = klass.getDeclaredConstructor(parameterTypes); + constructor.setAccessible(true); + } + catch (final NoSuchMethodException e) + { + final StringBuilder desc = new StringBuilder(); + desc.append(klass.getSimpleName()).append('('); + for (int i = 0, length = parameterTypes.length; i < length; i++) + { + desc.append(parameterTypes[i].getName()); + if (i > length) + { + desc.append(',').append(' '); + } + } + desc.append(')'); + throw new UnknownConstructorException("Could not find constructor '" + desc.toString() + "' in " + klass); + } + return constructor; + } } \ No newline at end of file diff --git a/src/main/java/tschipp/carryon/common/helper/ScriptParseHelper.java b/src/main/java/tschipp/carryon/common/helper/ScriptParseHelper.java index 9ffe3cb..2996f47 100644 --- a/src/main/java/tschipp/carryon/common/helper/ScriptParseHelper.java +++ b/src/main/java/tschipp/carryon/common/helper/ScriptParseHelper.java @@ -16,38 +16,50 @@ import net.minecraft.world.scores.Objective; import net.minecraft.world.scores.Score; import net.minecraft.world.scores.Scoreboard; -public class ScriptParseHelper { +public class ScriptParseHelper +{ - public static boolean matches(double number, String cond) { + public static boolean matches(double number, String cond) + { if (cond == null || cond.isEmpty()) return true; - try { - if (cond.contains("<=")) { + try + { + if (cond.contains("<=")) + { return number <= Double.parseDouble(cond.replace("<=", "")); } - if (cond.contains(">=")) { + if (cond.contains(">=")) + { return number >= Double.parseDouble(cond.replace(">=", "")); } - if (cond.contains("<")) { + if (cond.contains("<")) + { return number < Double.parseDouble(cond.replace("<", "")); } - if (cond.contains(">")) { + if (cond.contains(">")) + { return number > Double.parseDouble(cond.replace(">", "")); } - if (cond.contains("=")) { + if (cond.contains("=")) + { return number == Double.parseDouble(cond.replace("=", "")); - } else + } + else return number == Double.parseDouble(cond); - } catch (Exception e) { + } + catch (Exception e) + { new InvalidConfigException(e.getMessage()).printException(); } return false; } - public static boolean matches(Block block, String cond) { + public static boolean matches(Block block, String cond) + { if (cond == null || cond.isEmpty()) return true; @@ -58,12 +70,14 @@ public class ScriptParseHelper { return false; } - public static boolean matches(CompoundTag toCheck, CompoundTag toMatch) { + public static boolean matches(CompoundTag toCheck, CompoundTag toMatch) + { if (toCheck == null || toMatch == null || toMatch.isEmpty()) return true; boolean matching = true; - for (String key : toMatch.getAllKeys()) { + for (String key : toMatch.getAllKeys()) + { Tag tag = toMatch.get(key); key = key.replace("\"", ""); Tag tagToCheck = toCheck.get(key); @@ -74,7 +88,8 @@ public class ScriptParseHelper { return matching; } - public static float[] getXYZArray(String s) { + public static float[] getXYZArray(String s) + { float[] d = new float[3]; d[0] = getValueFromString(s, "x"); d[1] = getValueFromString(s, "y"); @@ -83,7 +98,8 @@ public class ScriptParseHelper { return d; } - public static float[] getScaled(String s) { + public static float[] getScaled(String s) + { float[] d = new float[3]; d[0] = getScaledValueFromString(s, "x"); d[1] = getScaledValueFromString(s, "y"); @@ -92,19 +108,25 @@ public class ScriptParseHelper { return d; } - public static float getScaledValueFromString(String toGetFrom, String key) { + public static float getScaledValueFromString(String toGetFrom, String key) + { if (toGetFrom == null || toGetFrom.isEmpty()) return 1; String[] s = toGetFrom.split(","); - for (String string : s) { - if (string.contains(key) && string.contains("=")) { + for (String string : s) + { + if (string.contains(key) && string.contains("=")) + { float numb = 1; string = string.replace(key + "=", ""); - try { + try + { numb = Float.parseFloat(string); - } catch (Exception e) { + } + catch (Exception e) + { } return numb; @@ -114,7 +136,8 @@ public class ScriptParseHelper { return 1; } - public static boolean matchesScore(Player player, String cond) { + public static boolean matchesScore(Player player, String cond) + { if (cond == null || cond.isEmpty()) return true; @@ -134,9 +157,11 @@ public class ScriptParseHelper { scorename = cond.replace(numb, ""); Map o = score.getPlayerScores(player.getGameProfile().getName()); - if (o != null) { + if (o != null) + { Score sc = o.get(score.getObjective(scorename)); - if (sc != null) { + if (sc != null) + { int points = sc.getScore(); return matches(points, numb); @@ -146,36 +171,41 @@ public class ScriptParseHelper { return false; } - public static boolean matches(BlockPos pos, String cond) { + public static boolean matches(BlockPos pos, String cond) + { if (cond == null || cond.isEmpty()) return true; - BlockPos blockpos = new BlockPos(getValueFromString(cond, "x"), getValueFromString(cond, "y"), - getValueFromString(cond, "z")); - BlockPos expand = new BlockPos(getValueFromString(cond, "dx"), getValueFromString(cond, "dy"), - getValueFromString(cond, "dz")); + BlockPos blockpos = new BlockPos(getValueFromString(cond, "x"), getValueFromString(cond, "y"), getValueFromString(cond, "z")); + BlockPos expand = new BlockPos(getValueFromString(cond, "dx"), getValueFromString(cond, "dy"), getValueFromString(cond, "dz")); BlockPos expanded = blockpos.offset(expand); - boolean x = (pos.getX() >= blockpos.getX() && pos.getX() <= expanded.getX()) || blockpos.getX() == 0; - boolean y = (pos.getY() >= blockpos.getY() && pos.getY() <= expanded.getY()) || blockpos.getY() == 0; - boolean z = (pos.getZ() >= blockpos.getZ() && pos.getZ() <= expanded.getZ()) || blockpos.getZ() == 0; + boolean x = pos.getX() >= blockpos.getX() && pos.getX() <= expanded.getX() || blockpos.getX() == 0; + boolean y = pos.getY() >= blockpos.getY() && pos.getY() <= expanded.getY() || blockpos.getY() == 0; + boolean z = pos.getZ() >= blockpos.getZ() && pos.getZ() <= expanded.getZ() || blockpos.getZ() == 0; return x && y && z; } - public static float getValueFromString(String toGetFrom, String key) { + public static float getValueFromString(String toGetFrom, String key) + { if (toGetFrom == null || toGetFrom.isEmpty()) return 0; String[] s = toGetFrom.split(","); - for (String string : s) { - if (string.contains(key) && string.contains("=")) { + for (String string : s) + { + if (string.contains(key) && string.contains("=")) + { float numb = 0; string = string.replace(key + "=", ""); - try { + try + { numb = Float.parseFloat(string); - } catch (Exception e) { + } + catch (Exception e) + { } return numb; @@ -185,42 +215,51 @@ public class ScriptParseHelper { return 0; } - public static boolean hasEffects(Player player, String cond) { + public static boolean hasEffects(Player player, String cond) + { if (cond == null || cond.isEmpty()) return true; Collection effects = player.getActiveEffects(); String[] potions = cond.split(","); - List names = new ArrayList(); - List levels = new ArrayList(); + List names = new ArrayList<>(); + List levels = new ArrayList<>(); - for (int i = 0; i < potions.length; i++) { - String pot = potions[i]; - if (pot.contains("#")) { + for (String pot : potions) + { + if (pot.contains("#")) + { String level = pot.substring(pot.indexOf("#")); String name = pot.substring(0, pot.indexOf("#")); level = level.replace("#", ""); int lev = 0; - try { + try + { lev = Integer.parseInt(level); - } catch (Exception e) { + } + catch (Exception e) + { } levels.add(lev); names.add(name); - } else { + } + else + { levels.add(0); names.add(pot); } } int matches = 0; - for (MobEffectInstance effect : effects) { + for (MobEffectInstance effect : effects) + { int amp = effect.getAmplifier(); String name = effect.getEffect().getRegistryName().toString(); - if (names.contains(name)) { + if (names.contains(name)) + { int idx = names.indexOf(name); int lev = levels.get(idx); @@ -232,11 +271,13 @@ public class ScriptParseHelper { return matches == potions.length; } - public static boolean matches(Material material, String cond) { + public static boolean matches(Material material, String cond) + { if (cond == null || cond.isEmpty()) return true; - - switch (cond) { + + switch (cond) + { case "air": return material == Material.AIR; case "anvil": @@ -306,6 +347,6 @@ public class ScriptParseHelper { default: return false; } - + } } diff --git a/src/main/java/tschipp/carryon/common/helper/ScrollCallbackWrapper.java b/src/main/java/tschipp/carryon/common/helper/ScrollCallbackWrapper.java index 8f5bfa8..b71e8e9 100644 --- a/src/main/java/tschipp/carryon/common/helper/ScrollCallbackWrapper.java +++ b/src/main/java/tschipp/carryon/common/helper/ScrollCallbackWrapper.java @@ -15,7 +15,7 @@ public class ScrollCallbackWrapper public void setup(Minecraft mc) { - oldCallback = GLFW.glfwSetScrollCallback(mc.getWindow().getWindow(), this::scrollCallback); + this.oldCallback = GLFW.glfwSetScrollCallback(mc.getWindow().getWindow(), this::scrollCallback); } private void scrollCallback(long window, double xoffset, double yoffset) @@ -26,10 +26,10 @@ public class ScrollCallbackWrapper if (event.isCanceled()) return; - if (oldCallback != null) - oldCallback.invoke(window, xoffset, yoffset); + if (this.oldCallback != null) + this.oldCallback.invoke(window, xoffset, yoffset); } - + @Cancelable public static class MouseScrolledEvent extends Event { diff --git a/src/main/java/tschipp/carryon/common/helper/StringParser.java b/src/main/java/tschipp/carryon/common/helper/StringParser.java index d38ee2e..1a4ba08 100644 --- a/src/main/java/tschipp/carryon/common/helper/StringParser.java +++ b/src/main/java/tschipp/carryon/common/helper/StringParser.java @@ -20,19 +20,18 @@ public class StringParser public static Block getBlock(String string) { BlockState state = getBlockState(string); - if(state != null) + if (state != null) return state.getBlock(); - + return null; } - @Nullable public static BlockState getBlockState(String string) { - if(string == null) + if (string == null) return null; - + BlockStateParser parser = new BlockStateParser(new StringReader(string), false); try @@ -50,11 +49,11 @@ public class StringParser @Nullable public static Item getItem(String string) { - if(string == null) + if (string == null) return null; - + ItemParser parser = new ItemParser(new StringReader(string), false); - + try { parser.parse(); @@ -69,32 +68,32 @@ public class StringParser public static ItemStack getItemStack(String string) { - if(string == null) + if (string == null) return null; - + ItemParser parser = new ItemParser(new StringReader(string), false); - + try { parser.parse(); - Item item = parser.getItem(); + Item item = parser.getItem(); CompoundTag nbt = parser.getNbt(); - + ItemStack stack = new ItemStack(item, 1); - - if(nbt != null) + + if (nbt != null) { stack.setTag(nbt); } - + return stack; } catch (Exception e) { new InvalidConfigException("Item parsing Exception at: " + string + " : " + e.getMessage()).printException(); return ItemStack.EMPTY; - - } + + } } @@ -102,9 +101,9 @@ public class StringParser public static CompoundTag getTagCompound(String string) { CompoundTag tag = null; - if(string == null) + if (string == null) return null; - + if (string.contains("{")) { if (!string.contains("}")) diff --git a/src/main/java/tschipp/carryon/common/item/ItemCarryonBlock.java b/src/main/java/tschipp/carryon/common/item/ItemCarryonBlock.java index fc91974..e0c3d45 100644 --- a/src/main/java/tschipp/carryon/common/item/ItemCarryonBlock.java +++ b/src/main/java/tschipp/carryon/common/item/ItemCarryonBlock.java @@ -46,7 +46,7 @@ public class ItemCarryonBlock extends Item { public static final String TILE_DATA_KEY = "tileData"; - public static final String[] FACING_KEYS = new String[] { "rotation", "rot", "facing", "face", "direction", "dir", "front", "forward" }; + public static final String[] FACING_KEYS = { "rotation", "rot", "facing", "face", "direction", "dir", "front", "forward" }; public ItemCarryonBlock() { @@ -89,11 +89,8 @@ public class ItemCarryonBlock extends Item BlockPos pos = context.getClickedPos(); ItemStack stack = context.getItemInHand(); - if (ModList.get().isLoaded("betterplacement")) - { - if (CarryOnKeybinds.isKeyPressed(player)) - return InteractionResult.FAIL; - } + if (ModList.get().isLoaded("betterplacement") && CarryOnKeybinds.isKeyPressed(player)) + return InteractionResult.FAIL; if (hasTileData(stack)) { @@ -113,92 +110,92 @@ public class ItemCarryonBlock extends Item { boolean canPlace = containedstate.canSurvive(world, pos2); - if (canPlace) + if (canPlace && player.mayUseItemAt(pos, facing, stack) && world.mayInteract(player, pos2)) { - if (player.mayUseItemAt(pos, facing, stack) && world.mayInteract(player, pos2)) + + BlockState placementState = containedblock.getStateForPlacement(new BlockPlaceContext(context)); + + BlockState actualState = placementState == null ? containedstate : placementState; + + // Attempted fix for #287 + // for (IProperty prop : + // placementState.getValues().keySet()) + // { + // if (prop instanceof DirectionProperty) + // actualState = actualState.with((DirectionProperty) + // prop, placementState.get((DirectionProperty) prop)); + // else if (prop == BlockStateProperties.WATERLOGGED) + // actualState = actualState.with((BooleanProperty) + // prop, placementState.get((BooleanProperty) prop)); + // else if(prop instanceof EnumProperty) + // { + // Object value = placementState.get(prop); + // if(value instanceof Direction.Axis) + // { + // actualState = actualState.with((EnumProperty)prop, + // (Direction.Axis)value); + // } + // } + // } + + BlockSnapshot snapshot = BlockSnapshot.create(world.dimension(), world, pos2); + EntityPlaceEvent event = new EntityPlaceEvent(snapshot, world.getBlockState(pos), player); + MinecraftForge.EVENT_BUS.post(event); + + if (!event.isCanceled()) { + world.setBlockAndUpdate(pos2, actualState); - BlockState placementState = containedblock.getStateForPlacement(new BlockPlaceContext(context)); - - BlockState actualState = placementState == null ? containedstate : placementState; - - //Attempted fix for #287 -// for (IProperty prop : placementState.getValues().keySet()) -// { -// if (prop instanceof DirectionProperty) -// actualState = actualState.with((DirectionProperty) prop, placementState.get((DirectionProperty) prop)); -// else if (prop == BlockStateProperties.WATERLOGGED) -// actualState = actualState.with((BooleanProperty) prop, placementState.get((BooleanProperty) prop)); -// else if(prop instanceof EnumProperty) -// { -// Object value = placementState.get(prop); -// if(value instanceof Direction.Axis) -// { -// actualState = actualState.with((EnumProperty)prop, (Direction.Axis)value); -// } -// } -// } - - BlockSnapshot snapshot = BlockSnapshot.create(world.dimension(), world, pos2); - EntityPlaceEvent event = new EntityPlaceEvent(snapshot, world.getBlockState(pos), player); - MinecraftForge.EVENT_BUS.post(event); - - if (!event.isCanceled()) + // If the blockstate doesn't handle rotation, + // try to + // change rotation via NBT + if (!getTileData(stack).isEmpty()) { - world.setBlockAndUpdate(pos2, actualState); - - // If the blockstate doesn't handle rotation, - // try to - // change rotation via NBT - if (!getTileData(stack).isEmpty()) + CompoundTag tag = getTileData(stack); + Set keys = tag.getAllKeys(); + keytester: for (String key : keys) { - CompoundTag tag = getTileData(stack); - Set keys = tag.getAllKeys(); - keytester: for (String key : keys) + for (String facingKey : FACING_KEYS) { - for (String facingKey : FACING_KEYS) + if (key.toLowerCase().equals(facingKey)) { - if (key.toLowerCase().equals(facingKey)) + byte type = tag.getTagType(key); + switch (type) { - byte type = tag.getTagType(key); - switch (type) - { - case 8: - tag.putString(key, CharMatcher.javaUpperCase().matchesAllOf(tag.getString(key)) ? facing2.getOpposite().getName().toUpperCase() : facing2.getOpposite().getName()); - break; - case 3: - tag.putInt(key, facing2.getOpposite().get3DDataValue()); - break; - case 1: - tag.putByte(key, (byte) facing2.getOpposite().get3DDataValue()); - break; - default: - break; - } - - break keytester; + case 8: + tag.putString(key, CharMatcher.javaUpperCase().matchesAllOf(tag.getString(key)) ? facing2.getOpposite().getName().toUpperCase() : facing2.getOpposite().getName()); + break; + case 3: + tag.putInt(key, facing2.getOpposite().get3DDataValue()); + break; + case 1: + tag.putByte(key, (byte) facing2.getOpposite().get3DDataValue()); + break; + default: + break; } + + break keytester; } } } - - BlockEntity tile = world.getBlockEntity(pos2); - if (tile != null) - { - CompoundTag data = getTileData(stack); - updateTileLocation(data, pos2); - tile.load(data); - } - clearTileData(stack); - player.playSound(actualState.getSoundType(world, pos2, player).getPlaceSound(), 1.0f, 0.5f); - player.setItemInHand(InteractionHand.MAIN_HAND, ItemStack.EMPTY); - player.getPersistentData().remove("overrideKey"); - ItemEvents.sendPacket(player, 9, 0); - return InteractionResult.SUCCESS; - } - } + BlockEntity tile = world.getBlockEntity(pos2); + if (tile != null) + { + CompoundTag data = getTileData(stack); + updateTileLocation(data, pos2); + tile.load(data); + } + clearTileData(stack); + player.playSound(actualState.getSoundType(world, pos2, player).getPlaceSound(), 1.0f, 0.5f); + player.setItemInHand(InteractionHand.MAIN_HAND, ItemStack.EMPTY); + player.getPersistentData().remove("overrideKey"); + ItemEvents.sendPacket(player, 9, 0); + return InteractionResult.SUCCESS; + + } } } } @@ -286,7 +283,7 @@ public class ItemCarryonBlock extends Item stack.setTag(tag); return true; } - + public static void updateTileLocation(CompoundTag tag, BlockPos pos) { tag.putInt("x", pos.getX()); diff --git a/src/main/java/tschipp/carryon/common/item/ItemCarryonEntity.java b/src/main/java/tschipp/carryon/common/item/ItemCarryonEntity.java index a177ac1..7168213 100644 --- a/src/main/java/tschipp/carryon/common/item/ItemCarryonEntity.java +++ b/src/main/java/tschipp/carryon/common/item/ItemCarryonEntity.java @@ -33,19 +33,21 @@ import tschipp.carryon.client.keybinds.CarryOnKeybinds; import tschipp.carryon.common.config.Configs.Settings; import tschipp.carryon.common.event.ItemEvents; -public class ItemCarryonEntity extends Item { +public class ItemCarryonEntity extends Item +{ private static final Method initGoals; - + static { - initGoals = ObfuscationReflectionHelper.findMethod(Mob.class, "m_8099_"); + initGoals = ObfuscationReflectionHelper.findMethod(Mob.class, "m_8099_"); initGoals.setAccessible(true); } - + public static final String ENTITY_DATA_KEY = "entityData"; - public ItemCarryonEntity() { + public ItemCarryonEntity() + { super(new Item.Properties().stacksTo(1)); this.setRegistryName(CarryOn.MODID, "entity_item"); } @@ -53,27 +55,28 @@ public class ItemCarryonEntity extends Item { @Override public Component getName(ItemStack stack) { - if (hasEntityData(stack)) { - + if (hasEntityData(stack)) + { + return new TranslatableComponent(getEntityType(stack).getDescriptionId()); } return new TextComponent(""); } - public static boolean hasEntityData(ItemStack stack) { - if (stack.hasTag()) { + public static boolean hasEntityData(ItemStack stack) + { + if (stack.hasTag()) + { CompoundTag tag = stack.getTag(); return tag.contains(ENTITY_DATA_KEY) && tag.contains("entity"); } return false; } - public static boolean storeEntityData(@Nonnull Entity entity, Level world, ItemStack stack) { - if (entity == null) - return false; - - if (stack.isEmpty()) + public static boolean storeEntityData(@Nonnull Entity entity, Level world, ItemStack stack) + { + if (entity == null || stack.isEmpty()) return false; CompoundTag entityData = new CompoundTag(); @@ -92,7 +95,8 @@ public class ItemCarryonEntity extends Item { } @Override - public InteractionResult useOn(UseOnContext context) { + public InteractionResult useOn(UseOnContext context) + { Player player = context.getPlayer(); Level world = context.getLevel(); BlockPos pos = context.getClickedPos(); @@ -102,25 +106,27 @@ public class ItemCarryonEntity extends Item { BlockState state = world.getBlockState(pos); - if (ModList.get().isLoaded("betterplacement")) { - if (CarryOnKeybinds.isKeyPressed(player)) - return InteractionResult.FAIL; - } + if (ModList.get().isLoaded("betterplacement") && CarryOnKeybinds.isKeyPressed(player)) + return InteractionResult.FAIL; - if (hasEntityData(stack)) { + if (hasEntityData(stack)) + { BlockPos finalPos = pos; - if (!state.canBeReplaced(new BlockPlaceContext(context))) { + if (!state.canBeReplaced(new BlockPlaceContext(context))) + { finalPos = pos.relative(facing); } Entity entity = getEntity(stack, world); - if (entity != null) { - if (!world.isClientSide) { - entity.absMoveTo(finalPos.getX() + 0.5, finalPos.getY(), finalPos.getZ() + 0.5, - 180 + player.yHeadRot, 0.0f); + if (entity != null) + { + if (!world.isClientSide) + { + entity.absMoveTo(finalPos.getX() + 0.5, finalPos.getY(), finalPos.getZ() + 0.5, 180 + player.yHeadRot, 0.0f); world.addFreshEntity(entity); - if (entity instanceof Mob) { + if (entity instanceof Mob) + { ((Mob) entity).playAmbientSound(); } clearEntityData(stack); @@ -137,42 +143,50 @@ public class ItemCarryonEntity extends Item { } @Override - public void inventoryTick(ItemStack stack, Level world, Entity entity, int itemSlot, boolean isSelected) { - if (hasEntityData(stack)) { + public void inventoryTick(ItemStack stack, Level world, Entity entity, int itemSlot, boolean isSelected) + { + if (hasEntityData(stack)) + { if (getEntity(stack, world) == null) stack = ItemStack.EMPTY; - if (entity instanceof LivingEntity) { - if (entity instanceof Player && Settings.slownessInCreative.get() ? false - : ((Player) entity).isCreative()) + if (entity instanceof LivingEntity) + { + if (entity instanceof Player && Settings.slownessInCreative.get() ? false : ((Player) entity).isCreative()) return; - ((LivingEntity) entity).addEffect( - new MobEffectInstance(MobEffects.MOVEMENT_SLOWDOWN, 1, potionLevel(stack, world), false, false)); + ((LivingEntity) entity).addEffect(new MobEffectInstance(MobEffects.MOVEMENT_SLOWDOWN, 1, this.potionLevel(stack, world), false, false)); } - } else { + } + else + { stack = ItemStack.EMPTY; } } - public static void clearEntityData(ItemStack stack) { - if (stack.hasTag()) { + public static void clearEntityData(ItemStack stack) + { + if (stack.hasTag()) + { CompoundTag tag = stack.getTag(); tag.remove(ENTITY_DATA_KEY); tag.remove("entity"); } } - public static CompoundTag getPersistentData(ItemStack stack) { - if (stack.hasTag()) { + public static CompoundTag getPersistentData(ItemStack stack) + { + if (stack.hasTag()) + { CompoundTag tag = stack.getTag(); return tag.getCompound(ENTITY_DATA_KEY); } return null; } - public static Entity getEntity(ItemStack stack, Level world) { + public static Entity getEntity(ItemStack stack, Level world) + { if (world == null) return null; @@ -182,7 +196,8 @@ public class ItemCarryonEntity extends Item { Optional> type = EntityType.byString(name); Entity entity = null; - if (type.isPresent()) { + if (type.isPresent()) + { entity = type.get().create(world); } @@ -201,28 +216,37 @@ public class ItemCarryonEntity extends Item { return entity; } - public static String getEntityName(ItemStack stack) { - if (stack.hasTag()) { + public static String getEntityName(ItemStack stack) + { + if (stack.hasTag()) + { CompoundTag tag = stack.getTag(); return tag.getString("entity"); } return null; } - public static String getCustomName(ItemStack stack) { - if (stack.hasTag()) { + public static String getCustomName(ItemStack stack) + { + if (stack.hasTag()) + { CompoundTag tag = stack.getTag(); - if (tag.contains("CustomName") && !tag.getString("CustomName").isEmpty()) { + if (tag.contains("CustomName") && !tag.getString("CustomName").isEmpty()) + { return tag.toString(); - } else { + } + else + { return tag.toString(); } } return null; } - public static EntityType getEntityType(ItemStack stack) { - if (stack.hasTag()) { + public static EntityType getEntityType(ItemStack stack) + { + if (stack.hasTag()) + { CompoundTag tag = stack.getTag(); String name = tag.getString("entity"); Optional> type = EntityType.byString(name); @@ -232,7 +256,8 @@ public class ItemCarryonEntity extends Item { return null; } - private int potionLevel(ItemStack stack, Level world) { + private int potionLevel(ItemStack stack, Level world) + { Entity e = getEntity(stack, world); if (e == null) return 1; diff --git a/src/main/java/tschipp/carryon/common/scripting/CarryOnOverride.java b/src/main/java/tschipp/carryon/common/scripting/CarryOnOverride.java index e34645f..511119b 100644 --- a/src/main/java/tschipp/carryon/common/scripting/CarryOnOverride.java +++ b/src/main/java/tschipp/carryon/common/scripting/CarryOnOverride.java @@ -1,5 +1,7 @@ package tschipp.carryon.common.scripting; +import java.util.Objects; + import com.google.gson.JsonElement; import com.google.gson.JsonObject; @@ -64,7 +66,7 @@ public class CarryOnOverride public CarryOnOverride(JsonElement jsonElem, ResourceLocation loc) { boolean errored = false; - resourceLocation = loc.toString(); + this.resourceLocation = loc.toString(); if (jsonElem != null && jsonElem.isJsonObject()) { @@ -76,19 +78,19 @@ public class CarryOnOverride JsonObject render = (JsonObject) json.get("render"); JsonObject effects = (JsonObject) json.get("effects"); - if ((object != null && conditions != null) || (object != null && render != null) || (object != null && effects != null)) + if (object != null && (conditions != null || render != null || effects != null)) { JsonObject block = (JsonObject) object.get("block"); JsonObject entity = (JsonObject) object.get("entity"); - if ((block == null && entity == null) || (block != null && entity != null)) + if (block == null && entity == null || block != null && entity != null) errored = true; if (!errored) { if (block != null) { - setBlock(true); + this.setBlock(true); JsonElement name = block.get("name"); JsonElement material = block.get("material"); JsonElement hardness = block.get("hardness"); @@ -96,19 +98,19 @@ public class CarryOnOverride JsonObject nbt = (JsonObject) block.get("nbt"); if (name != null) - setTypeNameBlock(name.getAsString()); + this.setTypeNameBlock(name.getAsString()); if (material != null) - setTypeMaterial(material.getAsString()); + this.setTypeMaterial(material.getAsString()); if (hardness != null) - setTypeHardness(hardness.getAsString()); + this.setTypeHardness(hardness.getAsString()); if (resistance != null) - setTypeResistance(resistance.getAsString()); + this.setTypeResistance(resistance.getAsString()); if (nbt != null) - setTypeBlockTag(TagParser.parseTag(nbt.toString())); + this.setTypeBlockTag(TagParser.parseTag(nbt.toString())); } else { - setEntity(true); + this.setEntity(true); JsonElement name = entity.get("name"); JsonElement health = entity.get("health"); JsonElement height = entity.get("height"); @@ -116,15 +118,15 @@ public class CarryOnOverride JsonObject nbt = (JsonObject) entity.get("nbt"); if (name != null) - setTypeNameEntity(name.getAsString()); + this.setTypeNameEntity(name.getAsString()); if (health != null) - setTypeHealth(health.getAsString()); + this.setTypeHealth(health.getAsString()); if (height != null) - setTypeHeight(height.getAsString()); + this.setTypeHeight(height.getAsString()); if (width != null) - setTypeWidth(width.getAsString()); + this.setTypeWidth(width.getAsString()); if (nbt != null) - setTypeEntityTag(TagParser.parseTag(nbt.toString())); + this.setTypeEntityTag(TagParser.parseTag(nbt.toString())); } if (conditions != null) @@ -138,19 +140,19 @@ public class CarryOnOverride JsonElement potionEffects = conditions.get("effects"); if (gamestage != null) - setConditionGamestage(gamestage.getAsString()); + this.setConditionGamestage(gamestage.getAsString()); if (achievement != null) - setConditionAchievement(achievement.getAsString()); + this.setConditionAchievement(achievement.getAsString()); if (xp != null) - setConditionXp(xp.getAsString()); + this.setConditionXp(xp.getAsString()); if (gamemode != null) - setConditionGamemode(gamemode.getAsString()); + this.setConditionGamemode(gamemode.getAsString()); if (scoreboard != null) - setConditionScoreboard(scoreboard.getAsString()); + this.setConditionScoreboard(scoreboard.getAsString()); if (position != null) - setConditionPosition(position.getAsString()); + this.setConditionPosition(position.getAsString()); if (potionEffects != null) - setConditionEffects(potionEffects.getAsString()); + this.setConditionEffects(potionEffects.getAsString()); } if (render != null) @@ -167,25 +169,25 @@ public class CarryOnOverride JsonElement renderRightArm = render.get("render_right_arm"); if (name_block != null) - setRenderNameBlock(name_block.getAsString()); + this.setRenderNameBlock(name_block.getAsString()); if (name_entity != null) - setRenderNameEntity(name_entity.getAsString()); + this.setRenderNameEntity(name_entity.getAsString()); if (translation != null) - setRenderTranslation(translation.getAsString()); + this.setRenderTranslation(translation.getAsString()); if (rotation != null) - setRenderRotation(rotation.getAsString()); + this.setRenderRotation(rotation.getAsString()); if (scaled != null) - setRenderscaled(scaled.getAsString()); + this.setRenderscaled(scaled.getAsString()); if (nbt != null) - setRenderNBT(TagParser.parseTag(nbt.toString())); + this.setRenderNBT(TagParser.parseTag(nbt.toString())); if (rotationLeftArm != null) - setRenderRotationLeftArm(rotationLeftArm.getAsString()); + this.setRenderRotationLeftArm(rotationLeftArm.getAsString()); if (rotationRightArm != null) - setRenderRotationRightArm(rotationRightArm.getAsString()); + this.setRenderRotationRightArm(rotationRightArm.getAsString()); if (renderLeftArm != null) - setRenderLeftArm(renderLeftArm.getAsBoolean()); + this.setRenderLeftArm(renderLeftArm.getAsBoolean()); if (renderRightArm != null) - setRenderRightArm(renderRightArm.getAsBoolean()); + this.setRenderRightArm(renderRightArm.getAsBoolean()); } if (effects != null) @@ -195,35 +197,35 @@ public class CarryOnOverride JsonElement commandPlace = effects.get("commandPlace"); if (commandInit != null) - setCommandInit(commandInit.getAsString()); + this.setCommandInit(commandInit.getAsString()); if (commandLoop != null) - setCommandLoop(commandLoop.getAsString()); + this.setCommandLoop(commandLoop.getAsString()); if (commandPlace != null) - setCommandPlace(commandPlace.getAsString()); + this.setCommandPlace(commandPlace.getAsString()); } } else - isInvalid = true; + this.isInvalid = true; } } catch (Exception e) { - isInvalid = true; + this.isInvalid = true; } } else - isInvalid = true; - - if(!isBlock && !isEntity) - isInvalid = true; - - if(isInvalid) - new InvalidConfigException("The script parsing for " + resourceLocation + " has failed! Please double check!").printException(); + this.isInvalid = true; + + if (!this.isBlock && !this.isEntity) + this.isInvalid = true; + + if (this.isInvalid) + new InvalidConfigException("The script parsing for " + this.resourceLocation + " has failed! Please double check!").printException(); } public String getCommandInit() { - return commandInit; + return this.commandInit; } public void setCommandInit(String commandInit) @@ -233,7 +235,7 @@ public class CarryOnOverride public String getCommandLoop() { - return commandLoop; + return this.commandLoop; } public void setCommandLoop(String commandLoop) @@ -243,7 +245,7 @@ public class CarryOnOverride public String getConditionEffects() { - return conditionEffects; + return this.conditionEffects; } public void setConditionEffects(String conditionEffects) @@ -253,7 +255,7 @@ public class CarryOnOverride public String getRenderRotationLeftArm() { - return renderRotationLeftArm; + return this.renderRotationLeftArm; } public void setRenderRotationLeftArm(String renderRotationLeftArm) @@ -263,7 +265,7 @@ public class CarryOnOverride public String getRenderRotationRightArm() { - return renderRotationRightArm; + return this.renderRotationRightArm; } public void setRenderRotationRightArm(String renderRotationRightArm) @@ -273,7 +275,7 @@ public class CarryOnOverride public boolean isRenderLeftArm() { - return renderLeftArm; + return this.renderLeftArm; } public void setRenderLeftArm(boolean renderLeftArm) @@ -283,7 +285,7 @@ public class CarryOnOverride public boolean isRenderRightArm() { - return renderRightArm; + return this.renderRightArm; } public void setRenderRightArm(boolean renderRightArm) @@ -296,8 +298,7 @@ public class CarryOnOverride { final int prime = 31; int result = 1; - result = prime * result + ((resourceLocation == null) ? 0 : resourceLocation.hashCode()); - return result; + return prime * result + (this.resourceLocation == null ? 0 : this.resourceLocation.hashCode()); } @Override @@ -311,228 +312,115 @@ public class CarryOnOverride { if (this == obj) return true; - if (obj == null) - return false; - if (getClass() != obj.getClass()) + if (obj == null || this.getClass() != obj.getClass()) return false; CarryOnOverride other = (CarryOnOverride) obj; - if (commandInit == null) + if (!Objects.equals(this.commandInit, other.commandInit) || !Objects.equals(this.commandLoop, other.commandLoop) || !Objects.equals(this.commandPlace, other.commandPlace) || !Objects.equals(this.conditionAchievement, other.conditionAchievement)) { - if (other.commandInit != null) - return false; - } - else if (!commandInit.equals(other.commandInit)) return false; - if (commandLoop == null) + } + if (!Objects.equals(this.conditionEffects, other.conditionEffects) || !Objects.equals(this.conditionGamemode, other.conditionGamemode) || !Objects.equals(this.conditionGamestage, other.conditionGamestage) || !Objects.equals(this.conditionPosition, other.conditionPosition)) { - if (other.commandLoop != null) - return false; - } - else if (!commandLoop.equals(other.commandLoop)) return false; - if (commandPlace == null) + } + if (!Objects.equals(this.conditionScoreboard, other.conditionScoreboard)) { - if (other.commandPlace != null) - return false; - } - else if (!commandPlace.equals(other.commandPlace)) return false; - if (conditionAchievement == null) + } + if (!Objects.equals(this.conditionXp, other.conditionXp)) { - if (other.conditionAchievement != null) - return false; - } - else if (!conditionAchievement.equals(other.conditionAchievement)) return false; - if (conditionEffects == null) + } + if (this.isBlock != other.isBlock) + return false; + if (this.isEntity != other.isEntity) + return false; + if (!Objects.equals(this.resourceLocation, other.resourceLocation)) { - if (other.conditionEffects != null) - return false; - } - else if (!conditionEffects.equals(other.conditionEffects)) return false; - if (conditionGamemode == null) + } + if (this.renderLeftArm != other.renderLeftArm) + return false; + if (!Objects.equals(this.renderNBT, other.renderNBT)) { - if (other.conditionGamemode != null) - return false; - } - else if (!conditionGamemode.equals(other.conditionGamemode)) return false; - if (conditionGamestage == null) + } + if (!Objects.equals(this.renderNameBlock, other.renderNameBlock)) { - if (other.conditionGamestage != null) - return false; - } - else if (!conditionGamestage.equals(other.conditionGamestage)) return false; - if (conditionPosition == null) + } + if (!Objects.equals(this.renderNameEntity, other.renderNameEntity)) { - if (other.conditionPosition != null) - return false; - } - else if (!conditionPosition.equals(other.conditionPosition)) return false; - if (conditionScoreboard == null) + } + if (this.renderRightArm != other.renderRightArm) + return false; + if (!Objects.equals(this.renderRotation, other.renderRotation)) { - if (other.conditionScoreboard != null) - return false; - } - else if (!conditionScoreboard.equals(other.conditionScoreboard)) return false; - if (conditionXp == null) + } + if (!Objects.equals(this.renderRotationLeftArm, other.renderRotationLeftArm)) { - if (other.conditionXp != null) - return false; + return false; } - else if (!conditionXp.equals(other.conditionXp)) - return false; - if (isBlock != other.isBlock) - return false; - if (isEntity != other.isEntity) - return false; - if (resourceLocation == null) + if (!Objects.equals(this.renderRotationRightArm, other.renderRotationRightArm)) { - if (other.resourceLocation != null) - return false; + return false; } - else if (!resourceLocation.equals(other.resourceLocation)) - return false; - if (renderLeftArm != other.renderLeftArm) - return false; - if (renderNBT == null) + if (!Objects.equals(this.renderscaled, other.renderscaled)) { - if (other.renderNBT != null) - return false; - } - else if (!renderNBT.equals(other.renderNBT)) return false; - if (renderNameBlock == null) + } + if (!Objects.equals(this.renderTranslation, other.renderTranslation)) { - if (other.renderNameBlock != null) - return false; - } - else if (!renderNameBlock.equals(other.renderNameBlock)) return false; - if (renderNameEntity == null) + } + if (!Objects.equals(this.typeBlockTag, other.typeBlockTag)) { - if (other.renderNameEntity != null) - return false; + return false; } - else if (!renderNameEntity.equals(other.renderNameEntity)) - return false; - if (renderRightArm != other.renderRightArm) - return false; - if (renderRotation == null) + if (!Objects.equals(this.typeEntityTag, other.typeEntityTag)) { - if (other.renderRotation != null) - return false; - } - else if (!renderRotation.equals(other.renderRotation)) return false; - if (renderRotationLeftArm == null) + } + if (!Objects.equals(this.typeHardness, other.typeHardness)) { - if (other.renderRotationLeftArm != null) - return false; - } - else if (!renderRotationLeftArm.equals(other.renderRotationLeftArm)) return false; - if (renderRotationRightArm == null) + } + if (!Objects.equals(this.typeHealth, other.typeHealth)) { - if (other.renderRotationRightArm != null) - return false; - } - else if (!renderRotationRightArm.equals(other.renderRotationRightArm)) return false; - if (renderscaled == null) + } + if (!Objects.equals(this.typeHeight, other.typeHeight)) { - if (other.renderscaled != null) - return false; - } - else if (!renderscaled.equals(other.renderscaled)) return false; - if (renderTranslation == null) + } + if (!Objects.equals(this.typeMaterial, other.typeMaterial)) { - if (other.renderTranslation != null) - return false; - } - else if (!renderTranslation.equals(other.renderTranslation)) return false; - if (typeBlockTag == null) + } + if (!Objects.equals(this.typeNameBlock, other.typeNameBlock)) { - if (other.typeBlockTag != null) - return false; - } - else if (!typeBlockTag.equals(other.typeBlockTag)) return false; - if (typeEntityTag == null) + } + if (!Objects.equals(this.typeNameEntity, other.typeNameEntity)) { - if (other.typeEntityTag != null) - return false; - } - else if (!typeEntityTag.equals(other.typeEntityTag)) return false; - if (typeHardness == null) + } + if (!Objects.equals(this.typeResistance, other.typeResistance)) { - if (other.typeHardness != null) - return false; - } - else if (!typeHardness.equals(other.typeHardness)) return false; - if (typeHealth == null) + } + if (!Objects.equals(this.typeWidth, other.typeWidth)) { - if (other.typeHealth != null) - return false; - } - else if (!typeHealth.equals(other.typeHealth)) return false; - if (typeHeight == null) - { - if (other.typeHeight != null) - return false; } - else if (!typeHeight.equals(other.typeHeight)) - return false; - if (typeMaterial == null) - { - if (other.typeMaterial != null) - return false; - } - else if (!typeMaterial.equals(other.typeMaterial)) - return false; - if (typeNameBlock == null) - { - if (other.typeNameBlock != null) - return false; - } - else if (!typeNameBlock.equals(other.typeNameBlock)) - return false; - if (typeNameEntity == null) - { - if (other.typeNameEntity != null) - return false; - } - else if (!typeNameEntity.equals(other.typeNameEntity)) - return false; - if (typeResistance == null) - { - if (other.typeResistance != null) - return false; - } - else if (!typeResistance.equals(other.typeResistance)) - return false; - if (typeWidth == null) - { - if (other.typeWidth != null) - return false; - } - else if (!typeWidth.equals(other.typeWidth)) - return false; return true; } public boolean isBlock() { - return isBlock; + return this.isBlock; } public void setBlock(boolean isBlock) @@ -542,7 +430,7 @@ public class CarryOnOverride public boolean isEntity() { - return isEntity; + return this.isEntity; } public void setEntity(boolean isEntity) @@ -552,112 +440,112 @@ public class CarryOnOverride public CompoundTag getTypeBlockTag() { - return typeBlockTag; + return this.typeBlockTag; } public String getTypeNameBlock() { - return typeNameBlock; + return this.typeNameBlock; } public String getTypeMaterial() { - return typeMaterial; + return this.typeMaterial; } public String getTypeHardness() { - return typeHardness; + return this.typeHardness; } public String getTypeResistance() { - return typeResistance; + return this.typeResistance; } public CompoundTag getTypeEntityTag() { - return typeEntityTag; + return this.typeEntityTag; } public String getTypeNameEntity() { - return typeNameEntity; + return this.typeNameEntity; } public String getTypeHeight() { - return typeHeight; + return this.typeHeight; } public String getTypeWidth() { - return typeWidth; + return this.typeWidth; } public String getTypeHealth() { - return typeHealth; + return this.typeHealth; } public String getConditionGamestage() { - return conditionGamestage; + return this.conditionGamestage; } public String getConditionAchievement() { - return conditionAchievement; + return this.conditionAchievement; } public String getConditionXp() { - return conditionXp; + return this.conditionXp; } public String getConditionGamemode() { - return conditionGamemode; + return this.conditionGamemode; } public String getConditionScoreboard() { - return conditionScoreboard; + return this.conditionScoreboard; } public String getConditionPosition() { - return conditionPosition; + return this.conditionPosition; } public String getRenderNameBlock() { - return renderNameBlock; + return this.renderNameBlock; } public String getRenderNameEntity() { - return renderNameEntity; + return this.renderNameEntity; } public CompoundTag getRenderNBT() { - return renderNBT; + return this.renderNBT; } public String getRenderTranslation() { - return renderTranslation; + return this.renderTranslation; } public String getRenderRotation() { - return renderRotation; + return this.renderRotation; } public String getRenderScaled() { - return renderscaled; + return this.renderscaled; } public void setTypeBlockTag(CompoundTag typeBlockTag) @@ -772,7 +660,7 @@ public class CarryOnOverride public String getCommandPlace() { - return commandPlace; + return this.commandPlace; } public void setCommandPlace(String commandPlace) @@ -783,48 +671,48 @@ public class CarryOnOverride public void serialize(FriendlyByteBuf buf) { // BLOCKS - buf.writeNbt(typeBlockTag); - buf.writeUtf(typeNameBlock); - buf.writeUtf(typeMaterial); - buf.writeUtf(typeHardness); - buf.writeUtf(typeResistance); + buf.writeNbt(this.typeBlockTag); + buf.writeUtf(this.typeNameBlock); + buf.writeUtf(this.typeMaterial); + buf.writeUtf(this.typeHardness); + buf.writeUtf(this.typeResistance); // ENTITIES - buf.writeNbt(typeEntityTag); - buf.writeUtf(typeNameEntity); - buf.writeUtf(typeHeight); - buf.writeUtf(typeWidth); - buf.writeUtf(typeHealth); + buf.writeNbt(this.typeEntityTag); + buf.writeUtf(this.typeNameEntity); + buf.writeUtf(this.typeHeight); + buf.writeUtf(this.typeWidth); + buf.writeUtf(this.typeHealth); // CONDITIONS - buf.writeUtf(conditionGamestage); - buf.writeUtf(conditionAchievement); - buf.writeUtf(conditionXp); - buf.writeUtf(conditionGamemode); - buf.writeUtf(conditionScoreboard); - buf.writeUtf(conditionPosition); - buf.writeUtf(conditionEffects); + buf.writeUtf(this.conditionGamestage); + buf.writeUtf(this.conditionAchievement); + buf.writeUtf(this.conditionXp); + buf.writeUtf(this.conditionGamemode); + buf.writeUtf(this.conditionScoreboard); + buf.writeUtf(this.conditionPosition); + buf.writeUtf(this.conditionEffects); // RENDER - buf.writeUtf(renderNameBlock); - buf.writeUtf(renderNameEntity); - buf.writeNbt(renderNBT); - buf.writeUtf(renderTranslation); - buf.writeUtf(renderRotation); - buf.writeUtf(renderscaled); - buf.writeUtf(renderRotationLeftArm); - buf.writeUtf(renderRotationRightArm); - buf.writeBoolean(renderLeftArm); - buf.writeBoolean(renderRightArm); + buf.writeUtf(this.renderNameBlock); + buf.writeUtf(this.renderNameEntity); + buf.writeNbt(this.renderNBT); + buf.writeUtf(this.renderTranslation); + buf.writeUtf(this.renderRotation); + buf.writeUtf(this.renderscaled); + buf.writeUtf(this.renderRotationLeftArm); + buf.writeUtf(this.renderRotationRightArm); + buf.writeBoolean(this.renderLeftArm); + buf.writeBoolean(this.renderRightArm); // EFFECTS - buf.writeUtf(commandInit); - buf.writeUtf(commandLoop); - buf.writeUtf(commandPlace); + buf.writeUtf(this.commandInit); + buf.writeUtf(this.commandLoop); + buf.writeUtf(this.commandPlace); - buf.writeBoolean(isBlock); - buf.writeBoolean(isEntity); - buf.writeUtf(resourceLocation); + buf.writeBoolean(this.isBlock); + buf.writeBoolean(this.isEntity); + buf.writeUtf(this.resourceLocation); } public static CarryOnOverride deserialize(FriendlyByteBuf buf) diff --git a/src/main/java/tschipp/carryon/common/scripting/ScriptChecker.java b/src/main/java/tschipp/carryon/common/scripting/ScriptChecker.java index 817d1aa..aa8f362 100644 --- a/src/main/java/tschipp/carryon/common/scripting/ScriptChecker.java +++ b/src/main/java/tschipp/carryon/common/scripting/ScriptChecker.java @@ -44,11 +44,8 @@ public class ScriptChecker { for (CarryOnOverride override : ScriptReader.OVERRIDES.values()) { - if (override.isBlock()) - { - if (matchesAll(override, block, material, hardness, resistance, nbt)) - return override; - } + if (override.isBlock() && matchesAll(override, block, material, hardness, resistance, nbt)) + return override; } } @@ -66,7 +63,6 @@ public class ScriptChecker float width = entity.getBbWidth(); float health = entity instanceof LivingEntity ? ((LivingEntity) entity).getHealth() : 0.0f; CompoundTag tag = entity.serializeNBT(); - boolean isAllowed = Settings.useWhitelistEntities.get() ? ListHandler.isAllowed(entity) : !ListHandler.isForbidden(entity); @@ -74,11 +70,8 @@ public class ScriptChecker { for (CarryOnOverride override : ScriptReader.OVERRIDES.values()) { - if (override.isEntity()) - { - if (matchesAll(override, name, height, width, health, tag)) - return override; - } + if (override.isEntity() && matchesAll(override, name, height, width, health, tag)) + return override; } } @@ -93,7 +86,7 @@ public class ScriptChecker boolean matchhealth = ScriptParseHelper.matches(health, override.getTypeHealth()); boolean matchnbt = ScriptParseHelper.matches(tag, override.getTypeEntityTag()); - return (matchname && matchheight && matchwidth && matchhealth && matchnbt); + return matchname && matchheight && matchwidth && matchhealth && matchnbt; } public static boolean matchesAll(CarryOnOverride override, Block block, Material material, float hardness, float resistance, CompoundTag nbt) @@ -104,54 +97,51 @@ public class ScriptChecker boolean matchhardness = ScriptParseHelper.matches(hardness, override.getTypeHardness()); boolean matchresistance = ScriptParseHelper.matches(resistance, override.getTypeResistance()); - return (matchnbt && matchblock && matchmaterial && matchhardness && matchresistance); + return matchnbt && matchblock && matchmaterial && matchhardness && matchresistance; } public static boolean fulfillsConditions(CarryOnOverride override, Player player) { ServerAdvancementManager manager = ((ServerPlayer) player).server.getAdvancements(); - Advancement adv = manager.getAdvancement(new ResourceLocation((override.getConditionAchievement()).isEmpty() ? "" : override.getConditionAchievement())); + Advancement adv = manager.getAdvancement(new ResourceLocation(override.getConditionAchievement().isEmpty() ? "" : override.getConditionAchievement())); boolean achievement = adv == null ? true : ((ServerPlayer) player).getAdvancements().getOrStartProgress(adv).isDone(); boolean gamemode = ScriptParseHelper.matches(((ServerPlayer) player).gameMode.getGameModeForPlayer().getId(), override.getConditionGamemode()); boolean gamestage = true; - if (ModList.get().isLoaded("gamestages")) + if (ModList.get().isLoaded("gamestages") && !override.getConditionGamestage().isEmpty()) { - if (!override.getConditionGamestage().isEmpty()) + try + { + Class gameStageHelper = Class.forName("net.darkhax.gamestages.GameStageHelper"); + Class iStageData = Class.forName("net.darkhax.gamestages.data.IStageData"); + + Method getPlayerData = ObfuscationReflectionHelper.findMethod(gameStageHelper, "getPlayerData", Player.class); + Method hasStage = ObfuscationReflectionHelper.findMethod(iStageData, "hasStage", String.class); + + Object stageData = getPlayerData.invoke(null, player); + String condition = override.getConditionGamestage(); + gamestage = (boolean) hasStage.invoke(stageData, condition); + } + catch (Exception e) { try { - Class gameStageHelper = Class.forName("net.darkhax.gamestages.GameStageHelper"); - Class iStageData = Class.forName("net.darkhax.gamestages.data.IStageData"); + Class playerDataHandler = Class.forName("net.darkhax.gamestages.capabilities.PlayerDataHandler"); + Class iStageData = Class.forName("net.darkhax.gamestages.capabilities.PlayerDataHandler$IStageData"); - Method getPlayerData = ObfuscationReflectionHelper.findMethod(gameStageHelper, "getPlayerData", Player.class); - Method hasStage = ObfuscationReflectionHelper.findMethod(iStageData, "hasStage", String.class); + Method getStageData = ObfuscationReflectionHelper.findMethod(playerDataHandler, "getStageData", Player.class); + Method hasUnlockedStage = ObfuscationReflectionHelper.findMethod(iStageData, "hasUnlockedStage", String.class); - Object stageData = getPlayerData.invoke(null, player); + Object stageData = getStageData.invoke(null, player); String condition = override.getConditionGamestage(); - gamestage = (boolean) hasStage.invoke(stageData, condition); + gamestage = (boolean) hasUnlockedStage.invoke(stageData, condition); + } - catch (Exception e) + catch (Exception ex) { - try - { - Class playerDataHandler = Class.forName("net.darkhax.gamestages.capabilities.PlayerDataHandler"); - Class iStageData = Class.forName("net.darkhax.gamestages.capabilities.PlayerDataHandler$IStageData"); - - Method getStageData = ObfuscationReflectionHelper.findMethod(playerDataHandler, "getStageData", Player.class); - Method hasUnlockedStage = ObfuscationReflectionHelper.findMethod(iStageData, "hasUnlockedStage", String.class); - - Object stageData = getStageData.invoke(null, player); - String condition = override.getConditionGamestage(); - gamestage = (boolean) hasUnlockedStage.invoke(stageData, condition); - - } - catch (Exception ex) - { - } } - } + } boolean position = ScriptParseHelper.matches(player.blockPosition(), override.getConditionPosition()); @@ -159,7 +149,7 @@ public class ScriptChecker boolean scoreboard = ScriptParseHelper.matchesScore(player, override.getConditionScoreboard()); boolean effects = ScriptParseHelper.hasEffects(player, override.getConditionEffects()); - return (achievement && gamemode && gamestage && position && xp && scoreboard && effects); + return achievement && gamemode && gamestage && position && xp && scoreboard && effects; } @Nullable diff --git a/src/main/java/tschipp/carryon/common/scripting/ScriptReader.java b/src/main/java/tschipp/carryon/common/scripting/ScriptReader.java index a9ce59c..9d68dbd 100644 --- a/src/main/java/tschipp/carryon/common/scripting/ScriptReader.java +++ b/src/main/java/tschipp/carryon/common/scripting/ScriptReader.java @@ -4,184 +4,188 @@ import java.util.HashMap; public class ScriptReader { - public static HashMap OVERRIDES = new HashMap(); + public static HashMap OVERRIDES = new HashMap<>(); // public static HashSet OVERRIDES = new // HashSet(); -// public static void preInit() -// { -// scripts.clear(); -// -// CarryOn.CONFIGURATION_FILE = new File(FMLPaths.CONFIGDIR.get().toString(), "/carryon-scripts/"); -// -// if (!CarryOn.CONFIGURATION_FILE.exists()) -// CarryOn.CONFIGURATION_FILE.mkdir(); -// -// for (File file : CarryOn.CONFIGURATION_FILE.listFiles()) -// { -// if (file.getName().endsWith(".json")) -// scripts.add(file); -// } -// -// } + // public static void preInit() + // { + // scripts.clear(); + // + // CarryOn.CONFIGURATION_FILE = new + // File(FMLPaths.CONFIGDIR.get().toString(), "/carryon-scripts/"); + // + // if (!CarryOn.CONFIGURATION_FILE.exists()) + // CarryOn.CONFIGURATION_FILE.mkdir(); + // + // for (File file : CarryOn.CONFIGURATION_FILE.listFiles()) + // { + // if (file.getName().endsWith(".json")) + // scripts.add(file); + // } + // + // } -// public static void parseScripts() -// { -// OVERRIDES.clear(); -// -// try -// { -// if (!Settings.useScripts.get()) -// return; -// -// for (File file : scripts) -// { -// boolean errored = false; -// JsonParser parser = new JsonParser(); -// JsonObject json = (JsonObject) parser.parse(new FileReader(file.getAbsolutePath())); -// -// JsonObject object = (JsonObject) json.get("object"); -// JsonObject conditions = (JsonObject) json.get("conditions"); -// JsonObject render = (JsonObject) json.get("render"); -// JsonObject effects = (JsonObject) json.get("effects"); -// -// if ((object != null && conditions != null) || (object != null && render != null) || (object != null && effects != null)) -// { -// JsonObject block = (JsonObject) object.get("block"); -// JsonObject entity = (JsonObject) object.get("entity"); -// -// if ((block == null && entity == null) || (block != null && entity != null)) -// errored = true; -// -// if (!errored) -// { -// CarryOnOverride override = new CarryOnOverride(file.getAbsolutePath()); -// -// if (block != null) -// { -// override.setBlock(true); -// JsonElement name = block.get("name"); -// JsonElement material = block.get("material"); -// JsonElement hardness = block.get("hardness"); -// JsonElement resistance = block.get("resistance"); -// JsonObject nbt = (JsonObject) block.get("nbt"); -// -// if (name != null) -// override.setTypeNameBlock(name.getAsString()); -// if (material != null) -// override.setTypeMaterial(material.getAsString()); -// if (hardness != null) -// override.setTypeHardness(hardness.getAsString()); -// if (resistance != null) -// override.setTypeResistance(resistance.getAsString()); -// if (nbt != null) -// override.setTypeBlockTag(JsonToNBT.getTagFromJson(nbt.toString())); -// } else -// { -// override.setEntity(true); -// JsonElement name = entity.get("name"); -// JsonElement health = entity.get("health"); -// JsonElement height = entity.get("height"); -// JsonElement width = entity.get("width"); -// JsonObject nbt = (JsonObject) entity.get("nbt"); -// -// if (name != null) -// override.setTypeNameEntity(name.getAsString()); -// if (health != null) -// override.setTypeHealth(health.getAsString()); -// if (height != null) -// override.setTypeHeight(height.getAsString()); -// if (width != null) -// override.setTypeWidth(width.getAsString()); -// if (nbt != null) -// override.setTypeEntityTag(JsonToNBT.getTagFromJson(nbt.toString())); -// } -// -// if (conditions != null) -// { -// JsonElement gamestage = conditions.get("gamestage"); -// JsonElement achievement = conditions.get("advancement"); -// JsonElement xp = conditions.get("xp"); -// JsonElement gamemode = conditions.get("gamemode"); -// JsonElement scoreboard = conditions.get("scoreboard"); -// JsonElement position = conditions.get("position"); -// JsonElement potionEffects = conditions.get("effects"); -// -// if (gamestage != null) -// override.setConditionGamestage(gamestage.getAsString()); -// if (achievement != null) -// override.setConditionAchievement(achievement.getAsString()); -// if (xp != null) -// override.setConditionXp(xp.getAsString()); -// if (gamemode != null) -// override.setConditionGamemode(gamemode.getAsString()); -// if (scoreboard != null) -// override.setConditionScoreboard(scoreboard.getAsString()); -// if (position != null) -// override.setConditionPosition(position.getAsString()); -// if (potionEffects != null) -// override.setConditionEffects(potionEffects.getAsString()); -// } -// -// if (render != null) -// { -// JsonElement name_block = render.get("name_block"); -// JsonElement name_entity = render.get("name_entity"); -// JsonObject nbt = (JsonObject) render.get("nbt"); -// JsonElement translation = render.get("translation"); -// JsonElement rotation = render.get("rotation"); -// JsonElement scaled = render.get("scale"); -// JsonElement rotationLeftArm = render.get("rotation_left_arm"); -// JsonElement rotationRightArm = render.get("rotation_right_arm"); -// JsonElement renderLeftArm = render.get("render_left_arm"); -// JsonElement renderRightArm = render.get("render_right_arm"); -// -// if (name_block != null) -// override.setRenderNameBlock(name_block.getAsString()); -// if (name_entity != null) -// override.setRenderNameEntity(name_entity.getAsString()); -// if (translation != null) -// override.setRenderTranslation(translation.getAsString()); -// if (rotation != null) -// override.setRenderRotation(rotation.getAsString()); -// if (scaled != null) -// override.setRenderscaled(scaled.getAsString()); -// if (nbt != null) -// override.setRenderNBT(JsonToNBT.getTagFromJson(nbt.toString())); -// if (rotationLeftArm != null) -// override.setRenderRotationLeftArm(rotationLeftArm.getAsString()); -// if (rotationRightArm != null) -// override.setRenderRotationRightArm(rotationRightArm.getAsString()); -// if (renderLeftArm != null) -// override.setRenderLeftArm(renderLeftArm.getAsBoolean()); -// if (renderRightArm != null) -// override.setRenderRightArm(renderRightArm.getAsBoolean()); -// } -// -// if (effects != null) -// { -// JsonElement commandInit = effects.get("commandPickup"); -// JsonElement commandLoop = effects.get("commandLoop"); -// JsonElement commandPlace = effects.get("commandPlace"); -// -// if (commandInit != null) -// override.setCommandInit(commandInit.getAsString()); -// if (commandLoop != null) -// override.setCommandLoop(commandLoop.getAsString()); -// if (commandPlace != null) -// override.setCommandPlace(commandPlace.getAsString()); -// } -// -// OVERRIDES.put(override.hashCode(), override); -// } -// } -// } -// -// System.out.println("Successfully parsed scripts!"); -// } catch (Exception e) -// { -// CarryOn.LOGGER.error(e); -// } -// } + // public static void parseScripts() + // { + // OVERRIDES.clear(); + // + // try + // { + // if (!Settings.useScripts.get()) + // return; + // + // for (File file : scripts) + // { + // boolean errored = false; + // JsonParser parser = new JsonParser(); + // JsonObject json = (JsonObject) parser.parse(new + // FileReader(file.getAbsolutePath())); + // + // JsonObject object = (JsonObject) json.get("object"); + // JsonObject conditions = (JsonObject) json.get("conditions"); + // JsonObject render = (JsonObject) json.get("render"); + // JsonObject effects = (JsonObject) json.get("effects"); + // + // if ((object != null && conditions != null) || (object != null && render + // != null) || (object != null && effects != null)) + // { + // JsonObject block = (JsonObject) object.get("block"); + // JsonObject entity = (JsonObject) object.get("entity"); + // + // if ((block == null && entity == null) || (block != null && entity != + // null)) + // errored = true; + // + // if (!errored) + // { + // CarryOnOverride override = new CarryOnOverride(file.getAbsolutePath()); + // + // if (block != null) + // { + // override.setBlock(true); + // JsonElement name = block.get("name"); + // JsonElement material = block.get("material"); + // JsonElement hardness = block.get("hardness"); + // JsonElement resistance = block.get("resistance"); + // JsonObject nbt = (JsonObject) block.get("nbt"); + // + // if (name != null) + // override.setTypeNameBlock(name.getAsString()); + // if (material != null) + // override.setTypeMaterial(material.getAsString()); + // if (hardness != null) + // override.setTypeHardness(hardness.getAsString()); + // if (resistance != null) + // override.setTypeResistance(resistance.getAsString()); + // if (nbt != null) + // override.setTypeBlockTag(JsonToNBT.getTagFromJson(nbt.toString())); + // } else + // { + // override.setEntity(true); + // JsonElement name = entity.get("name"); + // JsonElement health = entity.get("health"); + // JsonElement height = entity.get("height"); + // JsonElement width = entity.get("width"); + // JsonObject nbt = (JsonObject) entity.get("nbt"); + // + // if (name != null) + // override.setTypeNameEntity(name.getAsString()); + // if (health != null) + // override.setTypeHealth(health.getAsString()); + // if (height != null) + // override.setTypeHeight(height.getAsString()); + // if (width != null) + // override.setTypeWidth(width.getAsString()); + // if (nbt != null) + // override.setTypeEntityTag(JsonToNBT.getTagFromJson(nbt.toString())); + // } + // + // if (conditions != null) + // { + // JsonElement gamestage = conditions.get("gamestage"); + // JsonElement achievement = conditions.get("advancement"); + // JsonElement xp = conditions.get("xp"); + // JsonElement gamemode = conditions.get("gamemode"); + // JsonElement scoreboard = conditions.get("scoreboard"); + // JsonElement position = conditions.get("position"); + // JsonElement potionEffects = conditions.get("effects"); + // + // if (gamestage != null) + // override.setConditionGamestage(gamestage.getAsString()); + // if (achievement != null) + // override.setConditionAchievement(achievement.getAsString()); + // if (xp != null) + // override.setConditionXp(xp.getAsString()); + // if (gamemode != null) + // override.setConditionGamemode(gamemode.getAsString()); + // if (scoreboard != null) + // override.setConditionScoreboard(scoreboard.getAsString()); + // if (position != null) + // override.setConditionPosition(position.getAsString()); + // if (potionEffects != null) + // override.setConditionEffects(potionEffects.getAsString()); + // } + // + // if (render != null) + // { + // JsonElement name_block = render.get("name_block"); + // JsonElement name_entity = render.get("name_entity"); + // JsonObject nbt = (JsonObject) render.get("nbt"); + // JsonElement translation = render.get("translation"); + // JsonElement rotation = render.get("rotation"); + // JsonElement scaled = render.get("scale"); + // JsonElement rotationLeftArm = render.get("rotation_left_arm"); + // JsonElement rotationRightArm = render.get("rotation_right_arm"); + // JsonElement renderLeftArm = render.get("render_left_arm"); + // JsonElement renderRightArm = render.get("render_right_arm"); + // + // if (name_block != null) + // override.setRenderNameBlock(name_block.getAsString()); + // if (name_entity != null) + // override.setRenderNameEntity(name_entity.getAsString()); + // if (translation != null) + // override.setRenderTranslation(translation.getAsString()); + // if (rotation != null) + // override.setRenderRotation(rotation.getAsString()); + // if (scaled != null) + // override.setRenderscaled(scaled.getAsString()); + // if (nbt != null) + // override.setRenderNBT(JsonToNBT.getTagFromJson(nbt.toString())); + // if (rotationLeftArm != null) + // override.setRenderRotationLeftArm(rotationLeftArm.getAsString()); + // if (rotationRightArm != null) + // override.setRenderRotationRightArm(rotationRightArm.getAsString()); + // if (renderLeftArm != null) + // override.setRenderLeftArm(renderLeftArm.getAsBoolean()); + // if (renderRightArm != null) + // override.setRenderRightArm(renderRightArm.getAsBoolean()); + // } + // + // if (effects != null) + // { + // JsonElement commandInit = effects.get("commandPickup"); + // JsonElement commandLoop = effects.get("commandLoop"); + // JsonElement commandPlace = effects.get("commandPlace"); + // + // if (commandInit != null) + // override.setCommandInit(commandInit.getAsString()); + // if (commandLoop != null) + // override.setCommandLoop(commandLoop.getAsString()); + // if (commandPlace != null) + // override.setCommandPlace(commandPlace.getAsString()); + // } + // + // OVERRIDES.put(override.hashCode(), override); + // } + // } + // } + // + // System.out.println("Successfully parsed scripts!"); + // } catch (Exception e) + // { + // CarryOn.LOGGER.error(e); + // } + // } } diff --git a/src/main/java/tschipp/carryon/common/scripting/ScriptReloadListener.java b/src/main/java/tschipp/carryon/common/scripting/ScriptReloadListener.java index 6e02bd3..541cef8 100644 --- a/src/main/java/tschipp/carryon/common/scripting/ScriptReloadListener.java +++ b/src/main/java/tschipp/carryon/common/scripting/ScriptReloadListener.java @@ -23,7 +23,7 @@ import tschipp.carryon.network.client.ScriptReloadPacket; @EventBusSubscriber(modid = CarryOn.MODID, bus = Bus.FORGE) public class ScriptReloadListener extends SimpleJsonResourceReloadListener { - private static final Gson GSON = (new GsonBuilder()).setPrettyPrinting().disableHtmlEscaping().create(); + private static final Gson GSON = new GsonBuilder().setPrettyPrinting().disableHtmlEscaping().create(); public ScriptReloadListener() { @@ -37,7 +37,7 @@ public class ScriptReloadListener extends SimpleJsonResourceReloadListener objects.forEach((path, jsonElem) -> { CarryOnOverride override = new CarryOnOverride(jsonElem, path); - if(!override.isInvalid) + if (!override.isInvalid) ScriptReader.OVERRIDES.put(override.hashCode(), override); }); @@ -46,7 +46,7 @@ public class ScriptReloadListener extends SimpleJsonResourceReloadListener CarryOn.network.send(PacketDistributor.ALL.noArg(), new ScriptReloadPacket(ScriptReader.OVERRIDES.values())); } } - + @SubscribeEvent public static void onDatapackRegister(AddReloadListenerEvent event) { diff --git a/src/main/java/tschipp/carryon/compat/obfuscate/ObfuscateEvents.java b/src/main/java/tschipp/carryon/compat/obfuscate/ObfuscateEvents.java index bff2469..7257461 100644 --- a/src/main/java/tschipp/carryon/compat/obfuscate/ObfuscateEvents.java +++ b/src/main/java/tschipp/carryon/compat/obfuscate/ObfuscateEvents.java @@ -1,100 +1,125 @@ -//package tschipp.carryon.compat.obfuscate; +// package tschipp.carryon.compat.obfuscate; // -//import com.mrcrayfish.obfuscate.client.event.PlayerModelEvent; +// import com.mrcrayfish.obfuscate.client.event.PlayerModelEvent; // -//import net.minecraft.client.model.PlayerModel; -//import net.minecraft.client.renderer.model.ModelRenderer; -//import net.minecraft.entity.player.PlayerEntity; -//import net.minecraft.world.item.ItemStack; -//import net.minecraftforge.api.distmarker.Dist; -//import net.minecraftforge.api.distmarker.OnlyIn; -//import net.minecraftforge.eventbus.api.SubscribeEvent; -//import tschipp.carryon.common.config.Configs.Settings; -//import tschipp.carryon.common.handler.RegistrationHandler; -//import tschipp.carryon.common.helper.ScriptParseHelper; -//import tschipp.carryon.common.item.ItemCarryonBlock; -//import tschipp.carryon.common.item.ItemCarryonEntity; -//import tschipp.carryon.common.scripting.CarryOnOverride; -//import tschipp.carryon.common.scripting.ScriptChecker; +// import net.minecraft.client.model.PlayerModel; +// import net.minecraft.client.renderer.model.ModelRenderer; +// import net.minecraft.entity.player.PlayerEntity; +// import net.minecraft.world.item.ItemStack; +// import net.minecraftforge.api.distmarker.Dist; +// import net.minecraftforge.api.distmarker.OnlyIn; +// import net.minecraftforge.eventbus.api.SubscribeEvent; +// import tschipp.carryon.common.config.Configs.Settings; +// import tschipp.carryon.common.handler.RegistrationHandler; +// import tschipp.carryon.common.helper.ScriptParseHelper; +// import tschipp.carryon.common.item.ItemCarryonBlock; +// import tschipp.carryon.common.item.ItemCarryonEntity; +// import tschipp.carryon.common.scripting.CarryOnOverride; +// import tschipp.carryon.common.scripting.ScriptChecker; // -//public class ObfuscateEvents -//{ +// public class ObfuscateEvents +// { // -// @SubscribeEvent -// public void preModelPlayerEvent(PlayerModelEvent.SetupAngles.Post event) -// { -// if(!Settings.renderArms.get()) -// return; -// -// PlayerEntity player = event.getPlayer(); +// @SubscribeEvent +// public void preModelPlayerEvent(PlayerModelEvent.SetupAngles.Post event) +// { +// if(!Settings.renderArms.get()) +// return; // -// Pose pose = player.getPose(); -// if (pose == Pose.SWIMMING || pose == Pose.FALL_FLYING) -// return; -// -// PlayerModel model = event.getModelPlayer(); -// ItemStack stack = player.getMainHandItem(); -// if (!stack.isEmpty() && stack.getItem() == RegistrationHandler.itemTile && ItemCarryonBlock.hasTileData(stack) || stack.getItem() == RegistrationHandler.itemEntity && ItemCarryonEntity.hasEntityData(stack)) -// { -// -// float rotation = 0; -// -// CarryOnOverride overrider = ScriptChecker.getOverride(player); -// if (overrider != null) -// { -// float[] rotLeft = null; -// float[] rotRight = null; -// if (overrider.getRenderRotationLeftArm() != null) -// rotLeft = ScriptParseHelper.getXYZArray(overrider.getRenderRotationLeftArm()); -// if (overrider.getRenderRotationRightArm() != null) -// rotRight = ScriptParseHelper.getXYZArray(overrider.getRenderRotationRightArm()); +// PlayerEntity player = event.getPlayer(); // -// boolean renderRight = overrider.isRenderRightArm(); -// boolean renderLeft = overrider.isRenderLeftArm(); +// Pose pose = player.getPose(); +// if (pose == Pose.SWIMMING || pose == Pose.FALL_FLYING) +// return; // -// if (renderLeft && rotLeft != null) -// { -// renderArmPre(model.leftArm, (float) rotLeft[0], (float) rotLeft[2], rotation); -// renderArmPre(model.leftSleeve, (float) rotLeft[0], (float) rotLeft[2], rotation); -// } -// else if (renderLeft) -// { -// renderArmPre(model.leftArm, 0.8F + (player.isShiftKeyDown() ? 0.2f : 0f) - (stack.getItem() == RegistrationHandler.itemEntity ? -0.2f : 0), (stack.getItem() == RegistrationHandler.itemEntity ? 0.15f : 0), rotation); -// renderArmPre(model.leftSleeve, 0.8F + (player.isShiftKeyDown() ? 0.2f : 0f) - (stack.getItem() == RegistrationHandler.itemEntity ? -0.2f : 0), (stack.getItem() == RegistrationHandler.itemEntity ? 0.15f : 0), rotation); -// } +// PlayerModel model = event.getModelPlayer(); +// ItemStack stack = player.getMainHandItem(); +// if (!stack.isEmpty() && stack.getItem() == RegistrationHandler.itemTile && +// ItemCarryonBlock.hasTileData(stack) || stack.getItem() == +// RegistrationHandler.itemEntity && ItemCarryonEntity.hasEntityData(stack)) +// { // -// if (renderRight && rotRight != null) -// { -// renderArmPre(model.rightArm, (float) rotRight[0], (float) rotRight[2], rotation); -// renderArmPre(model.rightSleeve, (float) rotRight[0], (float) rotRight[2], rotation); -// } -// else if (renderRight) -// { -// renderArmPre(model.rightArm, 0.8F + (player.isShiftKeyDown() ? 0.2f : 0f) - (stack.getItem() == RegistrationHandler.itemEntity ? -0.2f : 0), (stack.getItem() == RegistrationHandler.itemEntity ? -0.15f : 0), rotation); -// renderArmPre(model.rightSleeve, 0.8F + (player.isShiftKeyDown() ? 0.2f : 0f) - (stack.getItem() == RegistrationHandler.itemEntity ? -0.2f : 0), (stack.getItem() == RegistrationHandler.itemEntity ? -0.15f : 0), rotation); -// } +// float rotation = 0; // -// } -// else -// { -// renderArmPre(model.rightArm, 0.8F + (player.isShiftKeyDown() ? 0.2f : 0f) - (stack.getItem() == RegistrationHandler.itemEntity ? -0.2f : 0), (stack.getItem() == RegistrationHandler.itemEntity ? -0.15f : 0), rotation); -// renderArmPre(model.rightSleeve, 0.8F + (player.isShiftKeyDown() ? 0.2f : 0f) - (stack.getItem() == RegistrationHandler.itemEntity ? -0.2f : 0), (stack.getItem() == RegistrationHandler.itemEntity ? -0.15f : 0), rotation); -// renderArmPre(model.leftArm, 0.8F + (player.isShiftKeyDown() ? 0.2f : 0f) - (stack.getItem() == RegistrationHandler.itemEntity ? -0.2f : 0), (stack.getItem() == RegistrationHandler.itemEntity ? 0.15f : 0), rotation); -// renderArmPre(model.leftSleeve, 0.8F + (player.isShiftKeyDown() ? 0.2f : 0f) - (stack.getItem() == RegistrationHandler.itemEntity ? -0.2f : 0), (stack.getItem() == RegistrationHandler.itemEntity ? 0.15f : 0), rotation); -// } -// -// } -// -// } -// -// -// @OnlyIn(Dist.CLIENT) -// private void renderArmPre(ModelRenderer arm, float x, float z, float rotation) -// { -// arm.xRot = (float) -x; -// arm.yRot = (float) -Math.toRadians(rotation); -// arm.zRot = (float) z; -// } -// -// -//} +// CarryOnOverride overrider = ScriptChecker.getOverride(player); +// if (overrider != null) +// { +// float[] rotLeft = null; +// float[] rotRight = null; +// if (overrider.getRenderRotationLeftArm() != null) +// rotLeft = +// ScriptParseHelper.getXYZArray(overrider.getRenderRotationLeftArm()); +// if (overrider.getRenderRotationRightArm() != null) +// rotRight = +// ScriptParseHelper.getXYZArray(overrider.getRenderRotationRightArm()); +// +// boolean renderRight = overrider.isRenderRightArm(); +// boolean renderLeft = overrider.isRenderLeftArm(); +// +// if (renderLeft && rotLeft != null) +// { +// renderArmPre(model.leftArm, (float) rotLeft[0], (float) rotLeft[2], +// rotation); +// renderArmPre(model.leftSleeve, (float) rotLeft[0], (float) rotLeft[2], +// rotation); +// } +// else if (renderLeft) +// { +// renderArmPre(model.leftArm, 0.8F + (player.isShiftKeyDown() ? 0.2f : 0f) - +// (stack.getItem() == RegistrationHandler.itemEntity ? -0.2f : 0), +// (stack.getItem() == RegistrationHandler.itemEntity ? 0.15f : 0), rotation); +// renderArmPre(model.leftSleeve, 0.8F + (player.isShiftKeyDown() ? 0.2f : 0f) - +// (stack.getItem() == RegistrationHandler.itemEntity ? -0.2f : 0), +// (stack.getItem() == RegistrationHandler.itemEntity ? 0.15f : 0), rotation); +// } +// +// if (renderRight && rotRight != null) +// { +// renderArmPre(model.rightArm, (float) rotRight[0], (float) rotRight[2], +// rotation); +// renderArmPre(model.rightSleeve, (float) rotRight[0], (float) rotRight[2], +// rotation); +// } +// else if (renderRight) +// { +// renderArmPre(model.rightArm, 0.8F + (player.isShiftKeyDown() ? 0.2f : 0f) - +// (stack.getItem() == RegistrationHandler.itemEntity ? -0.2f : 0), +// (stack.getItem() == RegistrationHandler.itemEntity ? -0.15f : 0), rotation); +// renderArmPre(model.rightSleeve, 0.8F + (player.isShiftKeyDown() ? 0.2f : 0f) +// - (stack.getItem() == RegistrationHandler.itemEntity ? -0.2f : 0), +// (stack.getItem() == RegistrationHandler.itemEntity ? -0.15f : 0), rotation); +// } +// +// } +// else +// { +// renderArmPre(model.rightArm, 0.8F + (player.isShiftKeyDown() ? 0.2f : 0f) - +// (stack.getItem() == RegistrationHandler.itemEntity ? -0.2f : 0), +// (stack.getItem() == RegistrationHandler.itemEntity ? -0.15f : 0), rotation); +// renderArmPre(model.rightSleeve, 0.8F + (player.isShiftKeyDown() ? 0.2f : 0f) +// - (stack.getItem() == RegistrationHandler.itemEntity ? -0.2f : 0), +// (stack.getItem() == RegistrationHandler.itemEntity ? -0.15f : 0), rotation); +// renderArmPre(model.leftArm, 0.8F + (player.isShiftKeyDown() ? 0.2f : 0f) - +// (stack.getItem() == RegistrationHandler.itemEntity ? -0.2f : 0), +// (stack.getItem() == RegistrationHandler.itemEntity ? 0.15f : 0), rotation); +// renderArmPre(model.leftSleeve, 0.8F + (player.isShiftKeyDown() ? 0.2f : 0f) - +// (stack.getItem() == RegistrationHandler.itemEntity ? -0.2f : 0), +// (stack.getItem() == RegistrationHandler.itemEntity ? 0.15f : 0), rotation); +// } +// +// } +// +// } +// +// +// @OnlyIn(Dist.CLIENT) +// private void renderArmPre(ModelRenderer arm, float x, float z, float +// rotation) +// { +// arm.xRot = (float) -x; +// arm.yRot = (float) -Math.toRadians(rotation); +// arm.zRot = (float) z; +// } +// +// +// } diff --git a/src/main/java/tschipp/carryon/network/client/CarrySlotPacket.java b/src/main/java/tschipp/carryon/network/client/CarrySlotPacket.java index e69b9af..fcb3bb2 100644 --- a/src/main/java/tschipp/carryon/network/client/CarrySlotPacket.java +++ b/src/main/java/tschipp/carryon/network/client/CarrySlotPacket.java @@ -38,9 +38,9 @@ public class CarrySlotPacket public void toBytes(ByteBuf buf) { - buf.writeInt(slot); - buf.writeInt(carryOverride); - buf.writeInt(entityid); + buf.writeInt(this.slot); + buf.writeInt(this.carryOverride); + buf.writeInt(this.entityid); } public void handle(Supplier ctx) @@ -53,15 +53,13 @@ public class CarrySlotPacket if (world != null) { - Entity e = world.getEntity(entityid); + Entity e = world.getEntity(this.entityid); - if (e != null && e instanceof Player) + if (e instanceof Player player) { - Player player = (Player) e; - ctx.get().setPacketHandled(true); - if (slot >= 9) + if (this.slot >= 9) { player.getPersistentData().remove("carrySlot"); player.getPersistentData().remove("overrideKey"); @@ -69,9 +67,9 @@ public class CarrySlotPacket else { - player.getPersistentData().putInt("carrySlot", slot); - if (carryOverride != 0) - ScriptChecker.setCarryOnOverride(player, carryOverride); + player.getPersistentData().putInt("carrySlot", this.slot); + if (this.carryOverride != 0) + ScriptChecker.setCarryOnOverride(player, this.carryOverride); } } diff --git a/src/main/java/tschipp/carryon/network/client/ScriptReloadPacket.java b/src/main/java/tschipp/carryon/network/client/ScriptReloadPacket.java index 9dfbbb6..e0c9698 100644 --- a/src/main/java/tschipp/carryon/network/client/ScriptReloadPacket.java +++ b/src/main/java/tschipp/carryon/network/client/ScriptReloadPacket.java @@ -12,7 +12,7 @@ import tschipp.carryon.common.scripting.ScriptReader; public class ScriptReloadPacket { - private List overrides = new ArrayList(); + private List overrides = new ArrayList<>(); public ScriptReloadPacket() { @@ -20,22 +20,22 @@ public class ScriptReloadPacket public ScriptReloadPacket(Collection collection) { - overrides.addAll(collection); + this.overrides.addAll(collection); } public ScriptReloadPacket(FriendlyByteBuf buf) { int size = buf.readInt(); - for(int i = 0; i < size; i++) + for (int i = 0; i < size; i++) { - overrides.add(CarryOnOverride.deserialize(buf)); - } + this.overrides.add(CarryOnOverride.deserialize(buf)); + } } - + public void toBytes(FriendlyByteBuf buf) { - buf.writeInt(overrides.size()); - overrides.forEach(override -> override.serialize(buf)); + buf.writeInt(this.overrides.size()); + this.overrides.forEach(override -> override.serialize(buf)); } public void handle(Supplier ctx) @@ -45,8 +45,8 @@ public class ScriptReloadPacket ctx.get().enqueueWork(() -> { ScriptReader.OVERRIDES.clear(); - - overrides.forEach(override -> { + + this.overrides.forEach(override -> { ScriptReader.OVERRIDES.put(override.hashCode(), override); }); diff --git a/src/main/java/tschipp/carryon/network/server/SyncKeybindPacket.java b/src/main/java/tschipp/carryon/network/server/SyncKeybindPacket.java index 6449207..88374b0 100644 --- a/src/main/java/tschipp/carryon/network/server/SyncKeybindPacket.java +++ b/src/main/java/tschipp/carryon/network/server/SyncKeybindPacket.java @@ -23,7 +23,7 @@ public class SyncKeybindPacket public void toBytes(ByteBuf buf) { - buf.writeBoolean(pressed); + buf.writeBoolean(this.pressed); } public void handle(Supplier ctx) @@ -34,7 +34,7 @@ public class SyncKeybindPacket ServerPlayer player = ctx.get().getSender(); - CarryOnKeybinds.setKeyPressed(player, pressed); + CarryOnKeybinds.setKeyPressed(player, this.pressed); ctx.get().setPacketHandled(true); }); diff --git a/src/main/java/tschipp/carryon/proxy/ClientProxy.java b/src/main/java/tschipp/carryon/proxy/ClientProxy.java index 12506dd..88a804b 100644 --- a/src/main/java/tschipp/carryon/proxy/ClientProxy.java +++ b/src/main/java/tschipp/carryon/proxy/ClientProxy.java @@ -9,24 +9,24 @@ import tschipp.carryon.common.handler.RegistrationHandler; import tschipp.carryon.common.helper.KeyboardCallbackWrapper; import tschipp.carryon.common.helper.ScrollCallbackWrapper; -public class ClientProxy implements IProxy { - +public class ClientProxy implements IProxy +{ @Override public void setup(FMLCommonSetupEvent event) { RegistrationHandler.regClientEvents(); - + CarryOnKeybinds.init(); - - new ScrollCallbackWrapper().setup(Minecraft.getInstance());; + + new ScrollCallbackWrapper().setup(Minecraft.getInstance()); new KeyboardCallbackWrapper().setup(Minecraft.getInstance()); } @Override public Player getPlayer() { - + return Minecraft.getInstance().player; } diff --git a/src/main/java/tschipp/carryon/proxy/IProxy.java b/src/main/java/tschipp/carryon/proxy/IProxy.java index 42847f8..015374b 100644 --- a/src/main/java/tschipp/carryon/proxy/IProxy.java +++ b/src/main/java/tschipp/carryon/proxy/IProxy.java @@ -6,10 +6,10 @@ import net.minecraftforge.fml.event.lifecycle.FMLCommonSetupEvent; public interface IProxy { - + public void setup(final FMLCommonSetupEvent event); - + public Player getPlayer(); - + public Level getWorld(); }