Class CommonHooks
-
Nested Class Summary
-
Field Summary
Modifier and TypeFieldDescriptionprivate static ThreadLocal
<Player> private static final String
private static final Map
<EntityType<? extends LivingEntity>, AttributeSupplier> private static final Lazy
<Map<String, StructuresBecomeConfiguredFix.Conversion>> private static final org.apache.logging.log4j.Logger
private static final String
(package private) static final Pattern
static final int
private static final org.apache.logging.log4j.Marker
-
Constructor Summary
-
Method Summary
Modifier and TypeMethodDescriptionstatic boolean
canContinueUsing
(ItemStack from, ItemStack to) static boolean
canCropGrow
(Level level, BlockPos pos, BlockState state, boolean def) Checks if a crop can grow by firingCropGrowEvent.Pre
.static boolean
canEntityDestroy
(Level level, BlockPos pos, LivingEntity entity) static boolean
canMobEffectBeApplied
(LivingEntity entity, MobEffectInstance effect) Checks if a mob effect can be applied to an entity by firingMobEffectEvent.Applicable
.static boolean
static ItemAttributeModifiers
computeModifiedAttributes
(ItemStack stack, ItemAttributeModifiers defaultModifiers) Hook to fireItemAttributeModifierEvent
.static String
encodeLifecycle
(com.mojang.serialization.Lifecycle lifecycle) static BlockEvent.BreakEvent
fireBlockBreak
(Level level, GameType gameType, ServerPlayer player, BlockPos pos, BlockState state) FiresBlockEvent.BreakEvent
, pre-emptively canceling the event based on the conditions that will cause the block to not be broken anyway.static CriticalHitEvent
fireCriticalHit
(Player player, Entity target, boolean vanillaCritical, float damageModifier) Fires theCriticalHitEvent
and returns the resulting event.static void
fireCropGrowPost
(Level level, BlockPos pos, BlockState state) static Map
<EntityType<? extends LivingEntity>, AttributeSupplier> Deprecated.static Player
static ItemStack
static @Nullable String
getDefaultCreatorModId
(ItemStack itemStack) Used as the default implementation ofIItemExtension.getCreatorModId(net.minecraft.world.item.ItemStack)
.static double
getEntityVisibilityMultiplier
(LivingEntity entity, Entity lookingEntity, double originalMultiplier) static ItemStack
getProjectile
(LivingEntity entity, ItemStack projectileWeaponItem, ItemStack projectile) Hook to fireLivingGetProjectileEvent
.private static String
getRawText
(Component message) static @Nullable EntityDataSerializer
<?> getSerializer
(int id, CrudeIncrementalIntIdentityHashBiMap<EntityDataSerializer<?>> vanilla) static int
getSerializerId
(EntityDataSerializer<?> serializer, CrudeIncrementalIntIdentityHashBiMap<EntityDataSerializer<?>> vanilla) static ChatDecorator
getTagFromVanillaTier
(Tiers tier) static FluidType
getVanillaFluidType
(Fluid fluid) Returns a vanilla fluid type for the given fluid.static void
handleBlockDrops
(ServerLevel level, BlockPos pos, BlockState state, @Nullable BlockEntity blockEntity, List<ItemEntity> drops, @Nullable Entity breaker, ItemStack tool) Fires theBlockDropsEvent
when block drops (items and experience) are determined.isLivingOnLadder
(BlockState state, Level level, BlockPos pos, LivingEntity entity) private static boolean
isPotentialRegistryObject
(Object value) static @Nullable MobEffect
loadMobEffect
(CompoundTag nbt, String key, @Nullable MobEffect fallback) lootPoolsCodec
(BiConsumer<LootPool, String> nameSetter) static void
markComponentClassAsValid
(Class<?> clazz) Marks a class as being safe to use as adata component
.static void
Deprecated.modifyLoot
(List<ItemStack> list, LootContext context) Deprecated.static it.unimi.dsi.fastutil.objects.ObjectArrayList
<ItemStack> modifyLoot
(ResourceLocation lootTableId, it.unimi.dsi.fastutil.objects.ObjectArrayList<ItemStack> generatedLoot, LootContext context) Handles the modification of loot table drops via the registered Global Loot Modifiers, so that custom effects can be processed.static Component
newChatWithLinks
(String string) static Component
newChatWithLinks
(String string, boolean allowMissingHeader) static boolean
onAnvilChange
(AnvilMenu container, ItemStack left, ItemStack right, Container outputSlot, String name, long baseCost, Player player) static float
onAnvilRepair
(Player player, ItemStack output, ItemStack left, ItemStack right) static @Nullable GameType
onChangeGameType
(Player player, GameType currentGameType, GameType newGameType) static Collection
<CreativeModeTab> onCheckCreativeTabs
(CreativeModeTab... vanillaTabs) static void
onChunkUnload
(PoiManager poiManager, ChunkAccess chunkAccess) The goal here is to fix the POI memory leak that happens due toSectionStorage.storage
field never actually removing POIs long after they become irrelevant.onClientMineHold
(Player player, BlockPos pos, Direction face) static void
onDifficultyChange
(Difficulty difficulty, Difficulty oldDifficulty) static void
onEmptyClick
(Player player, InteractionHand hand) static void
onEmptyLeftClick
(Player player) static void
onEntityEnterSection
(Entity entity, long packedOldPos, long packedNewPos) static boolean
onFarmlandTrample
(Level level, BlockPos pos, BlockState state, float fallDistance, Entity entity) static int
onGrindstoneChange
(ItemStack top, ItemStack bottom, Container outputSlot, int xp) static boolean
onGrindstoneTake
(Container inputSlots, ContainerLevelAccess access, Function<Level, Integer> xpFunction) static @Nullable InteractionResult
onInteractEntity
(Player player, Entity entity, InteractionHand hand) static @Nullable InteractionResult
onInteractEntityAt
(Player player, Entity entity, HitResult ray, InteractionHand hand) static @Nullable InteractionResult
onInteractEntityAt
(Player player, Entity entity, Vec3 vec3d, InteractionHand hand) static @Nullable InteractionResult
onItemRightClick
(Player player, InteractionHand hand) static boolean
onItemStackedOn
(ItemStack carriedItem, ItemStack stackedOnItem, Slot slot, ClickAction action, Player player, SlotAccess carriedSlotAccess) onLeftClickBlock
(Player player, BlockPos pos, Direction face, ServerboundPlayerActionPacket.Action action) static boolean
onLivingAttack
(LivingEntity entity, DamageSource src, float amount) static void
onLivingBreathe
(LivingEntity entity, int consumeAirAmount, int refillAirAmount) Handles living entities being underwater.static LivingChangeTargetEvent
onLivingChangeTarget
(LivingEntity entity, LivingEntity originalTarget, LivingChangeTargetEvent.ILivingTargetType targetType) static float
onLivingDamage
(LivingEntity entity, DamageSource src, float amount) static boolean
onLivingDeath
(LivingEntity entity, DamageSource src) static boolean
onLivingDrops
(LivingEntity entity, DamageSource source, Collection<ItemEntity> drops, boolean recentlyHit) static @org.jetbrains.annotations.Nullable float[]
onLivingFall
(LivingEntity entity, float distance, float damageMultiplier) static float
onLivingHurt
(LivingEntity entity, DamageSource src, float amount) static void
onLivingJump
(LivingEntity entity) static LivingKnockBackEvent
onLivingKnockBack
(LivingEntity target, float strength, double ratioX, double ratioZ) static LivingSwapItemsEvent.Hands
onLivingSwapHandItems
(LivingEntity livingEntity) static boolean
onLivingUseTotem
(LivingEntity entity, DamageSource damageSource, ItemStack totem, InteractionHand hand) static int
onNoteChange
(Level level, BlockPos pos, BlockState state, int old, int _new) static InteractionResult
onPlaceItemIntoWorld
(UseOnContext context) static boolean
onPlayerAttack
(LivingEntity entity, DamageSource src, float amount) static boolean
onPlayerAttackTarget
(Player player, Entity target) static @Nullable ItemEntity
onPlayerTossEvent
(Player player, ItemStack item, boolean includeName) onRightClickBlock
(Player player, InteractionHand hand, BlockPos pos, BlockHitResult hitVec) static @Nullable Component
onServerChatSubmittedEvent
(ServerPlayer player, String plain, Component decorated) static ShieldBlockEvent
onShieldBlock
(LivingEntity blocker, DamageSource source, float blocked) static boolean
onTravelToDimension
(Entity entity, ResourceKey<Level> dimension) static boolean
onVanillaGameEvent
(Level level, Holder<GameEvent> vanillaEvent, Vec3 pos, GameEvent.Context context) private static boolean
overridesEqualsAndHashCode
(Class<?> clazz) static com.mojang.serialization.Lifecycle
parseLifecycle
(String lifecycle) static String
prefixNamespace
(ResourceLocation registryKey) This method is used to prefix the path, where elements of the associated registry are stored, with their namespace, if it is not minecraftstatic void
readAdditionalLevelSaveData
(CompoundTag rootTag, LevelStorageSource.LevelDirectory levelDirectory) static <T> @Nullable HolderLookup.RegistryLookup
<T> resolveLookup
(ResourceKey<? extends Registry<T>> key) Attempts to resolve aHolderLookup.RegistryLookup
using the current global state.static void
saveMobEffect
(CompoundTag nbt, String key, MobEffect effect) static void
setCraftingPlayer
(Player player) static boolean
shouldSuppressEnderManAnger
(EnderMan enderMan, Player player, ItemStack mask) static void
validateComponent
(@Nullable Object dataComponent) Checks that all data components override equals and hashCode.static <T> HolderLookup.RegistryLookup
<T> wrapRegistryLookup
(HolderLookup.RegistryLookup<T> lookup) static void
writeAdditionalLevelSaveData
(WorldData worldData, CompoundTag levelTag)
-
Field Details
-
LOGGER
private static final org.apache.logging.log4j.Logger LOGGER -
WORLDPERSISTENCE
private static final org.apache.logging.log4j.Marker WORLDPERSISTENCE -
URL_PATTERN
-
craftingPlayer
-
VANILLA_SERIALIZER_LIMIT
public static final int VANILLA_SERIALIZER_LIMIT- See Also:
-
VANILLA_DIMS
-
DIMENSIONS_KEY
- See Also:
-
SEED_KEY
- See Also:
-
FORGE_ATTRIBUTES
-
FORGE_CONVERSION_MAP
private static final Lazy<Map<String,StructuresBecomeConfiguredFix.Conversion>> FORGE_CONVERSION_MAP -
checkedComponentClasses
-
-
Constructor Details
-
CommonHooks
public CommonHooks()
-
-
Method Details
-
canContinueUsing
-
onItemStackedOn
public static boolean onItemStackedOn(ItemStack carriedItem, ItemStack stackedOnItem, Slot slot, ClickAction action, Player player, SlotAccess carriedSlotAccess) -
onDifficultyChange
-
onLivingChangeTarget
public static LivingChangeTargetEvent onLivingChangeTarget(LivingEntity entity, LivingEntity originalTarget, LivingChangeTargetEvent.ILivingTargetType targetType) -
onLivingAttack
-
onPlayerAttack
-
onLivingKnockBack
public static LivingKnockBackEvent onLivingKnockBack(LivingEntity target, float strength, double ratioX, double ratioZ) -
onLivingUseTotem
public static boolean onLivingUseTotem(LivingEntity entity, DamageSource damageSource, ItemStack totem, InteractionHand hand) -
onLivingHurt
-
onLivingDamage
-
onLivingDeath
-
onLivingDrops
public static boolean onLivingDrops(LivingEntity entity, DamageSource source, Collection<ItemEntity> drops, boolean recentlyHit) -
onLivingFall
@Nullable public static @org.jetbrains.annotations.Nullable float[] onLivingFall(LivingEntity entity, float distance, float damageMultiplier) -
getEntityVisibilityMultiplier
public static double getEntityVisibilityMultiplier(LivingEntity entity, Entity lookingEntity, double originalMultiplier) -
isLivingOnLadder
public static Optional<BlockPos> isLivingOnLadder(BlockState state, Level level, BlockPos pos, LivingEntity entity) -
onLivingJump
-
onPlayerTossEvent
@Nullable public static @Nullable ItemEntity onPlayerTossEvent(Player player, ItemStack item, boolean includeName) -
onVanillaGameEvent
public static boolean onVanillaGameEvent(Level level, Holder<GameEvent> vanillaEvent, Vec3 pos, GameEvent.Context context) -
getRawText
-
onServerChatSubmittedEvent
@Nullable public static @Nullable Component onServerChatSubmittedEvent(ServerPlayer player, String plain, Component decorated) -
getServerChatSubmittedDecorator
-
newChatWithLinks
-
newChatWithLinks
-
handleBlockDrops
public static void handleBlockDrops(ServerLevel level, BlockPos pos, BlockState state, @Nullable @Nullable BlockEntity blockEntity, List<ItemEntity> drops, @Nullable @Nullable Entity breaker, ItemStack tool) Fires theBlockDropsEvent
when block drops (items and experience) are determined. If the event is not cancelled, all drops will be added to the world, and thenBlockBehaviour.spawnAfterBreak(net.minecraft.world.level.block.state.BlockState, net.minecraft.server.level.ServerLevel, net.minecraft.core.BlockPos, net.minecraft.world.item.ItemStack, boolean)
will be called.- Parameters:
level
- The levelpos
- The broken block's positionstate
- The broken block's stateblockEntity
- The block entity from the given positiondrops
- The list of all items dropped by the block, captured fromBlock.getDrops(net.minecraft.world.level.block.state.BlockState, net.minecraft.server.level.ServerLevel, net.minecraft.core.BlockPos, net.minecraft.world.level.block.entity.BlockEntity)
breaker
- The entity who broke the block, or null if unknowntool
- The tool used when breaking the block; may be empty
-
fireBlockBreak
public static BlockEvent.BreakEvent fireBlockBreak(Level level, GameType gameType, ServerPlayer player, BlockPos pos, BlockState state) FiresBlockEvent.BreakEvent
, pre-emptively canceling the event based on the conditions that will cause the block to not be broken anyway.Note that undoing the pre-cancel will not permit breaking the block, since the vanilla conditions will always be checked.
- Parameters:
level
- The levelgameType
- The game type of the breaking playerplayer
- The breaking playerpos
- The position of the block being brokenstate
- The state of the block being broken- Returns:
- The event
-
onPlaceItemIntoWorld
-
onAnvilChange
-
onAnvilRepair
-
onGrindstoneChange
-
onGrindstoneTake
public static boolean onGrindstoneTake(Container inputSlots, ContainerLevelAccess access, Function<Level, Integer> xpFunction) -
setCraftingPlayer
-
getCraftingPlayer
-
getCraftingRemainingItem
-
onPlayerAttackTarget
-
onTravelToDimension
-
onInteractEntityAt
@Nullable public static @Nullable InteractionResult onInteractEntityAt(Player player, Entity entity, HitResult ray, InteractionHand hand) -
onInteractEntityAt
@Nullable public static @Nullable InteractionResult onInteractEntityAt(Player player, Entity entity, Vec3 vec3d, InteractionHand hand) -
onInteractEntity
@Nullable public static @Nullable InteractionResult onInteractEntity(Player player, Entity entity, InteractionHand hand) -
onItemRightClick
@Nullable public static @Nullable InteractionResult onItemRightClick(Player player, InteractionHand hand) -
onLeftClickBlock
public static PlayerInteractEvent.LeftClickBlock onLeftClickBlock(Player player, BlockPos pos, Direction face, ServerboundPlayerActionPacket.Action action) -
onClientMineHold
public static PlayerInteractEvent.LeftClickBlock onClientMineHold(Player player, BlockPos pos, Direction face) -
onRightClickBlock
public static PlayerInteractEvent.RightClickBlock onRightClickBlock(Player player, InteractionHand hand, BlockPos pos, BlockHitResult hitVec) -
onEmptyClick
-
onEmptyLeftClick
-
onChangeGameType
@Nullable public static @Nullable GameType onChangeGameType(Player player, GameType currentGameType, GameType newGameType) - Returns:
- null if game type should not be changed, desired new GameType otherwise
-
lootPoolsCodec
@Internal public static com.mojang.serialization.Codec<List<LootPool>> lootPoolsCodec(BiConsumer<LootPool, String> nameSetter) -
getVanillaFluidType
Returns a vanilla fluid type for the given fluid.- Parameters:
fluid
- the fluid looking for its type- Returns:
- the type of the fluid if vanilla
- Throws:
RuntimeException
- if the fluid is not a vanilla one
-
getTagFromVanillaTier
-
onCheckCreativeTabs
-
canCropGrow
Checks if a crop can grow by firingCropGrowEvent.Pre
.- Parameters:
level
- The level the crop is inpos
- The position of the cropstate
- The state of the cropdef
- The result of the default checks performed by the crop.- Returns:
- true if the crop can grow
-
fireCropGrowPost
-
fireCriticalHit
public static CriticalHitEvent fireCriticalHit(Player player, Entity target, boolean vanillaCritical, float damageModifier) Fires theCriticalHitEvent
and returns the resulting event.- Parameters:
player
- The attacking playertarget
- The attack targetvanillaCritical
- If the attack would have been a critical hit by vanilla's rules inPlayer.attack(Entity)
.damageModifier
- The base damage modifier. Vanilla critical hits have a damage modifier of 1.5.
-
computeModifiedAttributes
public static ItemAttributeModifiers computeModifiedAttributes(ItemStack stack, ItemAttributeModifiers defaultModifiers) Hook to fireItemAttributeModifierEvent
. Modders should useItemStack.forEachModifier(EquipmentSlot, BiConsumer)
instead. -
getProjectile
public static ItemStack getProjectile(LivingEntity entity, ItemStack projectileWeaponItem, ItemStack projectile) Hook to fireLivingGetProjectileEvent
. Returns the ammo to be used. -
getDefaultCreatorModId
Used as the default implementation ofIItemExtension.getCreatorModId(net.minecraft.world.item.ItemStack)
. Call that method instead. -
onFarmlandTrample
public static boolean onFarmlandTrample(Level level, BlockPos pos, BlockState state, float fallDistance, Entity entity) -
onNoteChange
-
getSerializer
@Nullable public static @Nullable EntityDataSerializer<?> getSerializer(int id, CrudeIncrementalIntIdentityHashBiMap<EntityDataSerializer<?>> vanilla) -
getSerializerId
public static int getSerializerId(EntityDataSerializer<?> serializer, CrudeIncrementalIntIdentityHashBiMap<EntityDataSerializer<?>> vanilla) -
canEntityDestroy
-
modifyLoot
Deprecated.All loot table drops should be passed to this function so that mod added effects (e.g. smelting enchantments) can be processed.- Parameters:
list
- The loot generatedcontext
- The loot context that generated that loot- Returns:
- The modified list
-
modifyLoot
public static it.unimi.dsi.fastutil.objects.ObjectArrayList<ItemStack> modifyLoot(ResourceLocation lootTableId, it.unimi.dsi.fastutil.objects.ObjectArrayList<ItemStack> generatedLoot, LootContext context) Handles the modification of loot table drops via the registered Global Loot Modifiers, so that custom effects can be processed.All loot-table generated loot should be passed to this function.
- Parameters:
lootTableId
- The ID of the loot table currently being queriedgeneratedLoot
- The loot generated by the loot tablecontext
- The loot context that generated the loot, unmodified- Returns:
- The modified list of drops
-
getModDataPacks
-
getModDataPacksWithVanilla
-
getAttributesView
@Deprecated public static Map<EntityType<? extends LivingEntity>,AttributeSupplier> getAttributesView()Deprecated.FOR INTERNAL USE ONLY, DO NOT CALL DIRECTLY -
modifyAttributes
Deprecated.FOR INTERNAL USE ONLY, DO NOT CALL DIRECTLY -
onEntityEnterSection
-
onShieldBlock
public static ShieldBlockEvent onShieldBlock(LivingEntity blocker, DamageSource source, float blocked) -
onLivingSwapHandItems
-
writeAdditionalLevelSaveData
@Internal public static void writeAdditionalLevelSaveData(WorldData worldData, CompoundTag levelTag) -
readAdditionalLevelSaveData
@Internal public static void readAdditionalLevelSaveData(CompoundTag rootTag, LevelStorageSource.LevelDirectory levelDirectory) - Parameters:
rootTag
- Level data file contents.levelDirectory
- Level currently being loaded.
-
encodeLifecycle
-
parseLifecycle
-
saveMobEffect
-
loadMobEffect
@Nullable public static @Nullable MobEffect loadMobEffect(CompoundTag nbt, String key, @Nullable @Nullable MobEffect fallback) -
shouldSuppressEnderManAnger
-
prefixNamespace
This method is used to prefix the path, where elements of the associated registry are stored, with their namespace, if it is not minecraft
This rules conflicts with equal paths out. If for example the mod
fancy_cheese
adds a registry namedcheeses
, but the modawesome_cheese
also adds a registry calledcheeses
, they are going to have the same pathcheeses
, just with different namespaces. Ifadditional_cheese
wants to add additional cheese toawesome_cheese
, but notfancy_cheese
, it can not differentiate both. Both paths will look likedata/additional_cheese/cheeses
.The fix, which is applied here prefixes the path of the registry with the namespace, so
fancy_cheese
's registry stores its elements indata/<namespace>/fancy_cheese/cheeses
andawesome_cheese
's registry stores its elements indata/namespace/awesome_cheese/cheeses
- Parameters:
registryKey
- key of the registry- Returns:
- path of the registry key. Prefixed with the namespace if it is not "minecraft"
-
wrapRegistryLookup
@Internal public static <T> HolderLookup.RegistryLookup<T> wrapRegistryLookup(HolderLookup.RegistryLookup<T> lookup) -
onLivingBreathe
Handles living entities being underwater. This fires theLivingBreatheEvent
and if the entity's air supply is less than or equal to zero also theLivingDrownEvent
. Additionally, when the entity is underwater it will dismount ifIEntityExtension.canBeRiddenUnderFluidType(FluidType, Entity)
returns false.- Parameters:
entity
- The living entity which is currently updatedconsumeAirAmount
- The amount of air to consume when the entity is unable to breatherefillAirAmount
- The amount of air to refill when the entity is able to breathe
-
markComponentClassAsValid
Marks a class as being safe to use as adata component
. Keep in mind that data components are compared withObject.equals(Object)
and hashed withObject.hashCode()
. They must also be immutable.Only call this method if the default implementations of
Object.equals(Object)
andObject.hashCode()
are suitable for this class, and if instances of this class are immutable. Typically, this is only the case for singletons such asBlock
instances. -
validateComponent
Checks that all data components override equals and hashCode. -
isPotentialRegistryObject
-
overridesEqualsAndHashCode
-
onChunkUnload
The goal here is to fix the POI memory leak that happens due toSectionStorage.storage
field never actually removing POIs long after they become irrelevant. We do it here in chunk unload event so that chunk that are fully unloaded now gets the POI removed from the POI cached storage map. -
canMobEffectBeApplied
Checks if a mob effect can be applied to an entity by firingMobEffectEvent.Applicable
.- Parameters:
entity
- The target entity the mob effect is being applied to.effect
- The mob effect being applied.- Returns:
- True if the mob effect can be applied, otherwise false.
-
resolveLookup
@Nullable public static <T> @Nullable HolderLookup.RegistryLookup<T> resolveLookup(ResourceKey<? extends Registry<T>> key) Attempts to resolve aHolderLookup.RegistryLookup
using the current global state.Prioritizes the server's lookup, only attempting to retrieve it from the client if the server is unavailable.
- Type Parameters:
T
- The type of registry being looked up- Parameters:
key
- The resource key for the target registry- Returns:
- A registry access, if one was available.
-
modifyLoot(ResourceLocation, ObjectArrayList, LootContext)
instead.