Add offhand attack cooldown logic from tinkers

figured if I do offhand attack in another mod, better to not run the client side logic twice
This commit is contained in:
KnightMiner committed 2021-07-03 20:58:11 -04:00
1 parent c277407be5
commit b30ad71fc5
12 files changed
+418 -3

No files matched your search

+1
View File
@@ -0,0 +1 @@
74700d556ca80c7a1db5fd4efb09c3ddb26cad66 data/mantle/tags/items/offhand_cooldown.json
@@ -0,0 +1,4 @@
{
"replace": false,
"values": []
}
+21 -3
View File
@@ -1,21 +1,28 @@
package slimeknights.mantle;
import net.minecraft.data.DataGenerator;
import net.minecraft.item.crafting.IRecipeSerializer;
import net.minecraft.util.ResourceLocation;
import net.minecraftforge.common.MinecraftForge;
import net.minecraftforge.common.crafting.CraftingHelper;
import net.minecraftforge.common.loot.GlobalLootModifierSerializer;
import net.minecraftforge.event.RegistryEvent;
import net.minecraftforge.event.entity.player.PlayerInteractEvent;
import net.minecraftforge.eventbus.api.EventPriority;
import net.minecraftforge.eventbus.api.IEventBus;
import net.minecraftforge.fml.ModLoadingContext;
import net.minecraftforge.fml.common.Mod;
import net.minecraftforge.fml.config.ModConfig;
import net.minecraftforge.fml.config.ModConfig.Type;
import net.minecraftforge.fml.event.lifecycle.FMLCommonSetupEvent;
import net.minecraftforge.fml.event.lifecycle.GatherDataEvent;
import net.minecraftforge.fml.javafmlmod.FMLJavaModLoadingContext;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import slimeknights.mantle.command.MantleCommand;
import slimeknights.mantle.config.Config;
import slimeknights.mantle.data.MantleItemTagProvider;
import slimeknights.mantle.data.MantleTags;
import slimeknights.mantle.item.LecternBookItem;
import slimeknights.mantle.loot.AddEntryLootModifier;
import slimeknights.mantle.loot.MantleLoot;
@@ -26,6 +33,7 @@ import slimeknights.mantle.recipe.crafting.ShapedRetexturedRecipe;
import slimeknights.mantle.recipe.ingredient.IngredientIntersection;
import slimeknights.mantle.recipe.ingredient.IngredientWithout;
import slimeknights.mantle.registration.adapter.RegistryAdapter;
import slimeknights.mantle.util.OffhandCooldownTracker;
/**
* Mantle
@@ -50,16 +58,26 @@ public class Mantle {
instance = this;
IEventBus bus = FMLJavaModLoadingContext.get().getModEventBus();
bus.addListener(this::commonSetup);
bus.addListener(Config::configChanged);
bus.addListener(EventPriority.NORMAL, false, FMLCommonSetupEvent.class, this::commonSetup);
bus.addListener(EventPriority.NORMAL, false, GatherDataEvent.class, this::gatherData);
bus.addListener(EventPriority.NORMAL, false, ModConfig.ModConfigEvent.class, Config::configChanged);
bus.addGenericListener(IRecipeSerializer.class, this::registerRecipeSerializers);
bus.addGenericListener(GlobalLootModifierSerializer.class, this::registerGlobalLootModifiers);
MinecraftForge.EVENT_BUS.addListener(LecternBookItem::interactWithBlock);
MinecraftForge.EVENT_BUS.addListener(EventPriority.NORMAL, false, PlayerInteractEvent.RightClickBlock.class, LecternBookItem::interactWithBlock);
}
private void commonSetup(final FMLCommonSetupEvent event) {
MantleNetwork.registerPackets();
MantleCommand.init();
OffhandCooldownTracker.register();
MantleTags.init();
}
private void gatherData(final GatherDataEvent event) {
if (event.includeServer()) {
DataGenerator dataGenerator = event.getGenerator();
dataGenerator.addProvider(new MantleItemTagProvider(dataGenerator, event.getExistingFileHelper()));
}
}
private void registerRecipeSerializers(final RegistryEvent.Register<IRecipeSerializer<?>> event) {
@@ -1,12 +1,24 @@
package slimeknights.mantle.client;
import com.mojang.blaze3d.matrix.MatrixStack;
import com.mojang.blaze3d.platform.GlStateManager;
import com.mojang.blaze3d.systems.RenderSystem;
import net.minecraft.client.GameSettings;
import net.minecraft.client.Minecraft;
import net.minecraft.client.gui.AbstractGui;
import net.minecraft.client.settings.AttackIndicatorStatus;
import net.minecraft.item.ItemStack;
import net.minecraft.resources.IReloadableResourceManager;
import net.minecraft.resources.IResourceManager;
import net.minecraft.util.HandSide;
import net.minecraft.world.GameType;
import net.minecraftforge.api.distmarker.Dist;
import net.minecraftforge.client.event.ModelRegistryEvent;
import net.minecraftforge.client.event.RenderGameOverlayEvent;
import net.minecraftforge.client.event.RenderGameOverlayEvent.ElementType;
import net.minecraftforge.client.model.ModelLoaderRegistry;
import net.minecraftforge.common.MinecraftForge;
import net.minecraftforge.eventbus.api.EventPriority;
import net.minecraftforge.eventbus.api.SubscribeEvent;
import net.minecraftforge.fml.common.Mod.EventBusSubscriber;
import net.minecraftforge.fml.common.Mod.EventBusSubscriber.Bus;
@@ -21,6 +33,8 @@ import slimeknights.mantle.client.model.fluid.FluidTextureModel;
import slimeknights.mantle.client.model.fluid.FluidsModel;
import slimeknights.mantle.client.model.inventory.InventoryModel;
import slimeknights.mantle.client.model.util.ModelHelper;
import slimeknights.mantle.data.MantleTags;
import slimeknights.mantle.util.OffhandCooldownTracker;
@SuppressWarnings("unused")
@EventBusSubscriber(modid = Mantle.modId, value = Dist.CLIENT, bus = Bus.MOD)
@@ -51,5 +65,65 @@ public class ClientEvents {
((IReloadableResourceManager)manager).addReloadListener(new BookLoader());
}
MinecraftForge.EVENT_BUS.register(new ExtraHeartRenderHandler());
MinecraftForge.EVENT_BUS.addListener(EventPriority.NORMAL, false, RenderGameOverlayEvent.Post.class, ClientEvents::renderOffhandAttackIndicator);
}
// registered with FORGE bus
private static void renderOffhandAttackIndicator(RenderGameOverlayEvent.Post event) {
// must have a player, not be in spectator, and have the indicator enabled
Minecraft minecraft = Minecraft.getInstance();
GameSettings settings = minecraft.gameSettings;
if (minecraft.player == null || minecraft.playerController == null || minecraft.playerController.getCurrentGameType() == GameType.SPECTATOR || settings.attackIndicator == AttackIndicatorStatus.OFF) {
return;
}
// must be holding something that can duel wield
ItemStack held = minecraft.player.getHeldItemOffhand();
if (!MantleTags.Items.OFFHAND_COOLDOWN.contains(held.getItem())) {
return;
}
// check if we have cooldown
float cooldown = OffhandCooldownTracker.getCooldown(minecraft.player);
if (cooldown >= 1.0f) {
return;
}
// show attack indicator
MatrixStack matrixStack = event.getMatrixStack();
switch (settings.attackIndicator) {
case CROSSHAIR:
if (event.getType() == ElementType.CROSSHAIRS && minecraft.gameSettings.getPointOfView().func_243192_a()) {
if (!settings.showDebugInfo || settings.hideGUI || minecraft.player.hasReducedDebug() || settings.reducedDebugInfo) {
// mostly cloned from vanilla attack indicator
RenderSystem.blendFuncSeparate(GlStateManager.SourceFactor.ONE_MINUS_DST_COLOR, GlStateManager.DestFactor.ONE_MINUS_SRC_COLOR, GlStateManager.SourceFactor.ONE, GlStateManager.DestFactor.ZERO);
int scaledHeight = minecraft.getMainWindow().getScaledHeight();
// integer division makes this a pain to line up, there might be a simplier version of this formula but I cannot think of one
int y = (scaledHeight / 2) - 14 + (2 * (scaledHeight % 2));
int x = minecraft.getMainWindow().getScaledWidth() / 2 - 8;
int width = (int)(cooldown * 17.0F);
minecraft.getTextureManager().bindTexture(AbstractGui.GUI_ICONS_LOCATION);
minecraft.ingameGUI.blit(matrixStack, x, y, 36, 94, 16, 4);
minecraft.ingameGUI.blit(matrixStack, x, y, 52, 94, width, 4);
}
}
break;
case HOTBAR:
if (event.getType() == ElementType.HOTBAR && minecraft.renderViewEntity == minecraft.player) {
int centerWidth = minecraft.getMainWindow().getScaledWidth() / 2;
int y = minecraft.getMainWindow().getScaledHeight() - 20;
int x;
// opposite of the vanilla hand location, extra bit to offset past the offhand slot
if (minecraft.player.getPrimaryHand() == HandSide.RIGHT) {
x = centerWidth - 91 - 22 - 32;
} else {
x = centerWidth + 91 + 6 + 32;
}
minecraft.getTextureManager().bindTexture(AbstractGui.GUI_ICONS_LOCATION);
int l1 = (int)(cooldown * 19.0F);
RenderSystem.color4f(1.0F, 1.0F, 1.0F, 1.0F);
minecraft.ingameGUI.blit(matrixStack, x, y, 0, 94, 18, 18);
minecraft.ingameGUI.blit(matrixStack, x, y + 18 - l1, 18, 112 - l1, 18, l1);
}
break;
}
}
}
@@ -0,0 +1,40 @@
package slimeknights.mantle.data;
import net.minecraft.data.DataGenerator;
import net.minecraft.data.TagsProvider;
import net.minecraft.item.Item;
import net.minecraft.util.ResourceLocation;
import net.minecraft.util.registry.Registry;
import net.minecraftforge.common.data.ExistingFileHelper;
import slimeknights.mantle.Mantle;
import javax.annotation.Nullable;
import java.nio.file.Path;
/**
* Tag provider for all mantle tags, doubles as an item tag provider without need for a block tag provider
*/
public class MantleItemTagProvider extends TagsProvider<Item> {
protected MantleItemTagProvider(DataGenerator dataGenerator, String modId, @Nullable ExistingFileHelper existingFileHelper) {
super(dataGenerator, Registry.ITEM, modId, existingFileHelper);
}
public MantleItemTagProvider(DataGenerator dataGenerator, @Nullable ExistingFileHelper existingFileHelper) {
this(dataGenerator, Mantle.modId, existingFileHelper);
}
@Override
public String getName() {
return "Mantle Item Tags";
}
@Override
protected void registerTags() {
this.getOrCreateBuilder(MantleTags.Items.OFFHAND_COOLDOWN);
}
@Override
protected Path makePath(ResourceLocation id) {
return this.generator.getOutputFolder().resolve("data/" + id.getNamespace() + "/tags/items/" + id.getPath() + ".json");
}
}
@@ -0,0 +1,23 @@
package slimeknights.mantle.data;
import net.minecraft.item.Item;
import net.minecraft.tags.ItemTags;
import net.minecraftforge.common.Tags.IOptionalNamedTag;
import slimeknights.mantle.Mantle;
/**
* All tags used in Mantle logic
*/
public class MantleTags {
/** Initializes the tags */
public static void init() {
Items.init();
}
public static class Items {
private static void init() {}
/** Items in this tag will render offhand attack indicators */
public static IOptionalNamedTag<Item> OFFHAND_COOLDOWN = ItemTags.createOptional(Mantle.getResource("offhand_cooldown"));
}
}
@@ -0,0 +1,7 @@
@ParametersAreNonnullByDefault
@MethodsReturnNonnullByDefault
package slimeknights.mantle.data;
import mcp.MethodsReturnNonnullByDefault;
import javax.annotation.ParametersAreNonnullByDefault;
@@ -4,6 +4,7 @@ import net.minecraftforge.fml.network.NetworkDirection;
import slimeknights.mantle.Mantle;
import slimeknights.mantle.network.packet.DropLecternBookPacket;
import slimeknights.mantle.network.packet.OpenLecternBookPacket;
import slimeknights.mantle.network.packet.SwingArmPacket;
import slimeknights.mantle.network.packet.UpdateHeldPagePacket;
import slimeknights.mantle.network.packet.UpdateLecternPagePacket;
@@ -19,5 +20,6 @@ public class MantleNetwork {
INSTANCE.registerPacket(UpdateHeldPagePacket.class, UpdateHeldPagePacket::new, NetworkDirection.PLAY_TO_SERVER);
INSTANCE.registerPacket(UpdateLecternPagePacket.class, UpdateLecternPagePacket::new, NetworkDirection.PLAY_TO_SERVER);
INSTANCE.registerPacket(DropLecternBookPacket.class, DropLecternBookPacket::new, NetworkDirection.PLAY_TO_SERVER);
INSTANCE.registerPacket(SwingArmPacket.class, SwingArmPacket::new, NetworkDirection.PLAY_TO_CLIENT);
}
}
@@ -132,4 +132,22 @@ public class NetworkWrapper {
Chunk chunk = serverWorld.getChunkAt(position);
network.send(PacketDistributor.TRACKING_CHUNK.with(() -> chunk), msg);
}
/**
* Sends a packet to all entities tracking the given entity
* @param msg Packet
* @param entity Entity to check
*/
public void sendToTrackingAndSelf(Object msg, Entity entity) {
this.network.send(PacketDistributor.TRACKING_ENTITY_AND_SELF.with(() -> entity), msg);
}
/**
* Sends a packet to all entities tracking the given entity
* @param msg Packet
* @param entity Entity to check
*/
public void sendToTracking(Object msg, Entity entity) {
this.network.send(PacketDistributor.TRACKING_ENTITY.with(() -> entity), msg);
}
}
@@ -0,0 +1,49 @@
package slimeknights.mantle.network.packet;
import net.minecraft.client.Minecraft;
import net.minecraft.entity.Entity;
import net.minecraft.entity.LivingEntity;
import net.minecraft.network.PacketBuffer;
import net.minecraft.util.Hand;
import net.minecraft.world.World;
import net.minecraftforge.fml.network.NetworkEvent.Context;
import slimeknights.mantle.util.OffhandCooldownTracker;
/** Packet to tell a client to swing an entity arm, as the vanilla one resets cooldown */
public class SwingArmPacket implements IThreadsafePacket {
private final int entityId;
private final Hand hand;
public SwingArmPacket(Entity entity, Hand hand) {
this.entityId = entity.getEntityId();
this.hand = hand;
}
public SwingArmPacket(PacketBuffer buffer) {
this.entityId = buffer.readVarInt();
this.hand = buffer.readEnumValue(Hand.class);
}
@Override
public void encode(PacketBuffer buffer) {
buffer.writeVarInt(entityId);
buffer.writeEnumValue(hand);
}
@Override
public void handleThreadsafe(Context context) {
HandleClient.handle(this);
}
private static class HandleClient {
private static void handle(SwingArmPacket packet) {
World world = Minecraft.getInstance().world;
if (world != null) {
Entity entity = world.getEntityByID(packet.entityId);
if (entity instanceof LivingEntity) {
OffhandCooldownTracker.swingHand((LivingEntity) entity, packet.hand, false);
}
}
}
}
}
@@ -0,0 +1,176 @@
package slimeknights.mantle.util;
import lombok.RequiredArgsConstructor;
import net.minecraft.entity.Entity;
import net.minecraft.entity.LivingEntity;
import net.minecraft.entity.player.PlayerEntity;
import net.minecraft.nbt.INBT;
import net.minecraft.util.Direction;
import net.minecraft.util.Hand;
import net.minecraft.util.ResourceLocation;
import net.minecraft.util.math.MathHelper;
import net.minecraftforge.common.MinecraftForge;
import net.minecraftforge.common.capabilities.Capability;
import net.minecraftforge.common.capabilities.Capability.IStorage;
import net.minecraftforge.common.capabilities.CapabilityInject;
import net.minecraftforge.common.capabilities.CapabilityManager;
import net.minecraftforge.common.capabilities.ICapabilityProvider;
import net.minecraftforge.common.util.LazyOptional;
import net.minecraftforge.common.util.NonNullFunction;
import net.minecraftforge.event.AttachCapabilitiesEvent;
import slimeknights.mantle.Mantle;
import slimeknights.mantle.network.MantleNetwork;
import slimeknights.mantle.network.packet.SwingArmPacket;
import javax.annotation.Nullable;
/**
* Logic to handle offhand having its own cooldown
*/
@RequiredArgsConstructor
public class OffhandCooldownTracker implements ICapabilityProvider {
public static final ResourceLocation KEY = Mantle.getResource("offhand_cooldown");
private static final NonNullFunction<OffhandCooldownTracker,Float> COOLDOWN_TRACKER = OffhandCooldownTracker::getCooldown;
private static final NonNullFunction<OffhandCooldownTracker,Boolean> ATTACK_READY = OffhandCooldownTracker::isAttackReady;
/**
* Capability instance for offhand cooldown
*/
@CapabilityInject(OffhandCooldownTracker.class)
public static Capability<OffhandCooldownTracker> CAPABILITY = null;
/** Registers the capability and subscribes to event listeners */
public static void register() {
// register a bunch of dumb unused things because I need to register one actually useful thing
CapabilityManager.INSTANCE.register(OffhandCooldownTracker.class, new IStorage<OffhandCooldownTracker>() {
@Nullable
@Override
public INBT writeNBT(Capability<OffhandCooldownTracker> capability, OffhandCooldownTracker instance, Direction side) {
return null;
}
@Override
public void readNBT(Capability<OffhandCooldownTracker> capability, OffhandCooldownTracker instance, Direction side, INBT nbt) {}
}, () -> new OffhandCooldownTracker(null));
MinecraftForge.EVENT_BUS.addGenericListener(Entity.class, OffhandCooldownTracker::attachCapability);
}
/**
* Called to add the capability handler to all players
* @param event Event
*/
private static void attachCapability(AttachCapabilitiesEvent<Entity> event) {
Entity entity = event.getObject();
if (entity instanceof PlayerEntity) {
event.addCapability(KEY, new OffhandCooldownTracker((PlayerEntity) entity));
}
}
/** Lazy optional of self for capability requirements */
private final LazyOptional<OffhandCooldownTracker> capabilityInstance = LazyOptional.of(() -> this);
/** Player receiving cooldowns */
@Nullable
private final PlayerEntity player;
/** Scale of the last cooldown */
private int lastCooldown = 0;
/** Time in ticks when the player can next attack for full power */
private int attackReady = 0;
@Override
public <T> LazyOptional<T> getCapability(Capability<T> cap, @Nullable Direction side) {
return cap == CAPABILITY ? this.capabilityInstance.cast() : LazyOptional.empty();
}
/** Null safe way to get the player's ticks existed */
private int getTicksExisted() {
if (player == null) {
return 0;
}
return player.ticksExisted;
}
/**
* Applies the given amount of cooldown
* @param cooldown Coolddown amount
*/
public void applyCooldown(int cooldown) {
this.lastCooldown = cooldown;
this.attackReady = getTicksExisted() + cooldown;
}
/**
* Returns a number from 0 to 1 denoting the current cooldown amount, akin to {@link PlayerEntity#getCooledAttackStrength(float)}
* @return number from 0 to 1, with 1 being no cooldown
*/
public float getCooldown() {
int ticksExisted = getTicksExisted();
if (ticksExisted > this.attackReady || this.lastCooldown == 0) {
return 1.0f;
}
return MathHelper.clamp((this.lastCooldown + ticksExisted - this.attackReady) / (float) this.lastCooldown, 0f, 1f);
}
/**
* Checks if we can perform another attack yet.
* This counteracts rapid attacks via click macros, in a similar way to vanilla by limiting to once every 10 ticks
*/
public boolean isAttackReady() {
return getTicksExisted() + this.lastCooldown > this.attackReady;
}
/* Helpers */
/**
* Gets the offhand cooldown for the given player
* @param player Player
* @return Offhand cooldown
*/
public static float getCooldown(PlayerEntity player) {
return player.getCapability(CAPABILITY).map(COOLDOWN_TRACKER).orElse(1.0f);
}
/**
* Applies cooldown to the given player
* @param player Player
* @param cooldown Cooldown to apply
*/
public static void applyCooldown(PlayerEntity player, int cooldown) {
player.getCapability(CAPABILITY).ifPresent(cap -> cap.applyCooldown(cooldown));
}
/**
* Applies cooldown to the given player
* @param player Player
*/
public static boolean isAttackReady(PlayerEntity player) {
return player.getCapability(CAPABILITY).map(ATTACK_READY).orElse(true);
}
/**
* Applies cooldown using attack speed
* @param attackSpeed Attack speed of the held item
* @param cooldownTime Relative cooldown time for the given source, 20 is vanilla
*/
public static void applyCooldown(PlayerEntity player, float attackSpeed, int cooldownTime) {
applyCooldown(player, Math.round(cooldownTime / attackSpeed));
}
/** Swings the entities hand without resetting cooldown */
public static void swingHand(LivingEntity entity, Hand hand, boolean updateSelf) {
if (!entity.isSwingInProgress || entity.swingProgressInt >= entity.getArmSwingAnimationEnd() / 2 || entity.swingProgressInt < 0) {
entity.swingProgressInt = -1;
entity.isSwingInProgress = true;
entity.swingingHand = hand;
if (!entity.world.isRemote) {
SwingArmPacket packet = new SwingArmPacket(entity, hand);
if (updateSelf) {
MantleNetwork.INSTANCE.sendToTrackingAndSelf(packet, entity);
} else {
MantleNetwork.INSTANCE.sendToTracking(packet, entity);
}
}
}
}
}
@@ -47,3 +47,6 @@ public net.minecraft.world.DimensionType field_236004_h_ # OVERWORLD_TYPE
# Ray trace for tags command
public net.minecraft.item.Item func_219968_a(Lnet/minecraft/world/World;Lnet/minecraft/entity/player/PlayerEntity;Lnet/minecraft/util/math/RayTraceContext$FluidMode;)Lnet/minecraft/util/math/BlockRayTraceResult; # rayTrace
# Fix hand swinging animations resetting cooldown
public net.minecraft.entity.LivingEntity func_82166_i()I # getArmSwingAnimationEnd