Rewrite our GameTest hooks to be sane.

Add game test to GlobalLootModifierTest which validates the smelting modifiers.
Removed FakePlayer system, it's broken and needs a major rewrite.
This commit is contained in:
LexManos committed 2023-10-06 21:01:02 -07:00
1 parent aff05a4cf3
commit 90dafb0df0
40 files changed
+519 -801

No files matched your search

@@ -182,7 +182,7 @@ public class ModListScreen extends Screen
RenderSystem.setShaderColor(1.0F, 1.0F, 1.0F, 1.0F);
// Draw the logo image inscribed in a rectangle with width entryWidth (minus some padding) and height 50
int headerHeight = 50;
guiGraphics.blitInscribed(logoPath, left + PADDING, relativeY, width - (PADDING * 2), headerHeight, logoDims.width, logoDims.height, false, true);
guiGraphics.blitInscribed(logoPath, left + PADDING, relativeY, width - (PADDING * 2), headerHeight, logoDims.width(), logoDims.height(), false, true);
relativeY += headerHeight + PADDING;
}
@@ -30,7 +30,6 @@ import com.mojang.serialization.Dynamic;
import com.mojang.serialization.DynamicOps;
import com.mojang.serialization.Lifecycle;
import io.netty.buffer.Unpooled;
import it.unimi.dsi.fastutil.objects.ObjectArrayList;
import net.minecraft.commands.CommandSourceStack;
import net.minecraft.commands.Commands;
@@ -43,7 +42,6 @@ import net.minecraft.core.HolderSet;
import net.minecraft.core.particles.ParticleTypes;
import net.minecraft.core.registries.Registries;
import net.minecraft.network.Connection;
import net.minecraft.network.FriendlyByteBuf;
import net.minecraft.network.chat.ClickEvent;
import net.minecraft.network.chat.Component;
import net.minecraft.network.chat.MutableComponent;
@@ -11,15 +11,12 @@ import net.minecraft.world.entity.item.ItemEntity;
import net.minecraft.world.item.Item;
import net.minecraft.world.item.ItemStack;
import net.minecraft.server.TickTask;
import net.minecraft.server.level.ServerLevel;
import net.minecraftforge.common.loot.LootModifierManager;
import net.minecraftforge.common.util.FakePlayerFactory;
import net.minecraftforge.event.AddReloadListenerEvent;
import net.minecraftforge.event.RegisterCommandsEvent;
import net.minecraftforge.event.entity.EntityJoinLevelEvent;
import net.minecraftforge.event.entity.player.PlayerEvent;
import net.minecraftforge.event.level.ChunkEvent;
import net.minecraftforge.event.level.LevelEvent;
import net.minecraftforge.event.network.ConnectionStartEvent;
import net.minecraftforge.eventbus.api.EventPriority;
import net.minecraftforge.eventbus.api.SubscribeEvent;
@@ -53,13 +50,6 @@ public class ForgeInternalHandler {
}
}
@SubscribeEvent(priority = EventPriority.HIGHEST)
public void onDimensionUnload(LevelEvent.Unload event) {
if (event.getLevel() instanceof ServerLevel)
FakePlayerFactory.unloadLevel((ServerLevel) event.getLevel());
}
@SubscribeEvent
public void onServerTick(ServerTickEvent event) {
WorldWorkerManager.tick(event.phase == TickEvent.Phase.START);
@@ -10,12 +10,9 @@ import net.minecraft.sounds.SoundEvent;
import net.minecraft.world.level.block.BucketPickup;
import net.minecraft.world.level.block.state.BlockState;
public interface IForgeBucketPickup
{
private BucketPickup self()
{
return (BucketPickup) this;
public interface IForgeBucketPickup {
private BucketPickup self() {
return (BucketPickup)this;
}
/**
@@ -27,8 +24,8 @@ public interface IForgeBucketPickup
*
* @return Sound event for pickup sound or empty if there isn't a pickup sound.
*/
default Optional<SoundEvent> getPickupSound(BlockState state)
{
@SuppressWarnings("deprecation")
default Optional<SoundEvent> getPickupSound(BlockState state) {
return self().getPickupSound();
}
}
@@ -13,10 +13,8 @@ import net.minecraft.world.level.Level;
import net.minecraft.world.phys.BlockHitResult;
import org.jetbrains.annotations.Nullable;
public interface IForgeDispensibleContainerItem
{
private DispensibleContainerItem self()
{
public interface IForgeDispensibleContainerItem {
private DispensibleContainerItem self() {
return (DispensibleContainerItem)this;
}
@@ -30,8 +28,8 @@ public interface IForgeDispensibleContainerItem
* @param container ItemStack of the container. May be null for backwards compatibility.
* @return true if emptying the contents of the container was successful, false otherwise
*/
default boolean emptyContents(@Nullable Player player, Level level, BlockPos pos, @Nullable BlockHitResult hitResult, @Nullable ItemStack container)
{
@SuppressWarnings("deprecation")
default boolean emptyContents(@Nullable Player player, Level level, BlockPos pos, @Nullable BlockHitResult hitResult, @Nullable ItemStack container) {
return self().emptyContents(player, level, pos, hitResult);
}
}
@@ -6,18 +6,15 @@
package net.minecraftforge.common.extensions;
import net.minecraft.world.entity.MobType;
import net.minecraft.world.item.CreativeModeTab;
import net.minecraft.world.item.Item;
import net.minecraft.world.item.ItemStack;
import net.minecraft.world.item.enchantment.Enchantment;
import net.minecraft.world.item.enchantment.EnchantmentCategory;
import java.util.Set;
public interface IForgeEnchantment
{
private Enchantment self()
{
return (Enchantment) this;
public interface IForgeEnchantment {
private Enchantment self() {
return (Enchantment)this;
}
/**
@@ -28,20 +25,18 @@ public interface IForgeEnchantment
* @return the damage bonus
*/
@SuppressWarnings("deprecation")
default float getDamageBonus(int level, MobType mobType, ItemStack enchantedItem)
{
default float getDamageBonus(int level, MobType mobType, ItemStack enchantedItem) {
return self().getDamageBonus(level, mobType);
}
/**
* Determines whether item variants of this enchantment can be added to a given creative tab with the allowed categories.
*
* @param book the item being added to the creative tab
* @param allowedCategories the enchantment categories allowed in the creative tab
* @return whether item variants of this enchantment can be added to a given creative tab with the allowed categories
*/
default boolean allowedInCreativeTab(Item book, Set<EnchantmentCategory> allowedCategories)
{
return self().isAllowedOnBooks() && allowedCategories.contains(self().category);
}
/**
* Determines whether item variants of this enchantment can be added to a given creative tab with the allowed categories.
*
* @param book the item being added to the creative tab
* @param allowedCategories the enchantment categories allowed in the creative tab
* @return whether item variants of this enchantment can be added to a given creative tab with the allowed categories
*/
default boolean allowedInCreativeTab(Item book, Set<EnchantmentCategory> allowedCategories) {
return self().isAllowedOnBooks() && allowedCategories.contains(self().category);
}
}
@@ -21,7 +21,6 @@ import net.minecraft.world.entity.EntityDimensions;
import net.minecraft.world.entity.MobCategory;
import net.minecraft.world.entity.Pose;
import net.minecraft.world.entity.item.ItemEntity;
import net.minecraft.world.item.SpawnEggItem;
import net.minecraft.world.item.ItemStack;
import net.minecraft.nbt.CompoundTag;
import net.minecraft.core.BlockPos;
@@ -29,31 +28,26 @@ import net.minecraft.world.level.material.FluidState;
import net.minecraft.world.phys.HitResult;
import net.minecraftforge.common.ForgeMod;
import net.minecraftforge.common.ForgeSpawnEggItem;
import net.minecraftforge.common.MinecraftForge;
import net.minecraftforge.common.SoundAction;
import net.minecraftforge.common.capabilities.ICapabilitySerializable;
import net.minecraftforge.entity.PartEntity;
import net.minecraftforge.event.entity.EntityEvent;
import net.minecraftforge.fluids.FluidType;
import org.jetbrains.annotations.Nullable;
public interface IForgeEntity extends ICapabilitySerializable<CompoundTag>
{
private Entity self() { return (Entity) this; }
public interface IForgeEntity extends ICapabilitySerializable<CompoundTag> {
private Entity self() {
return (Entity)this;
}
default void deserializeNBT(CompoundTag nbt)
{
default void deserializeNBT(CompoundTag nbt) {
self().load(nbt);
}
default CompoundTag serializeNBT()
{
CompoundTag ret = new CompoundTag();
String id = self().getEncodeId();
default CompoundTag serializeNBT() {
var ret = new CompoundTag();
var id = self().getEncodeId();
if (id != null)
{
ret.putString("id", self().getEncodeId());
}
return self().saveWithoutId(ret);
}
@@ -64,7 +58,6 @@ public interface IForgeEntity extends ICapabilitySerializable<CompoundTag>
Collection<ItemEntity> captureDrops();
Collection<ItemEntity> captureDrops(@Nullable Collection<ItemEntity> captureDrops);
/**
* Returns a NBTTagCompound that can be used to store custom data for this entity.
* It will be written, and read from disc, so it persists over world saves.
@@ -76,8 +69,7 @@ public interface IForgeEntity extends ICapabilitySerializable<CompoundTag>
* Used in model rendering to determine if the entity riding this entity should be in the 'sitting' position.
* @return false to prevent an entity that is mounted to this entity from displaying the 'sitting' animation.
*/
default boolean shouldRiderSit()
{
default boolean shouldRiderSit() {
return true;
}
@@ -87,15 +79,11 @@ public interface IForgeEntity extends ICapabilitySerializable<CompoundTag>
* @param target The full target the player is looking at
* @return A ItemStack to add to the player's inventory, empty ItemStack if nothing should be added.
*/
default ItemStack getPickedResult(HitResult target)
{
ItemStack result = self().getPickResult();
default ItemStack getPickedResult(HitResult target) {
var result = self().getPickResult();
if (result == null) {
SpawnEggItem egg = ForgeSpawnEggItem.fromEntityType(self().getType());
if (egg != null)
result = new ItemStack(egg);
else
result = ItemStack.EMPTY;
var egg = ForgeSpawnEggItem.fromEntityType(self().getType());
result = egg == null ? ItemStack.EMPTY : new ItemStack(egg);
}
return result;
}
@@ -106,8 +94,7 @@ public interface IForgeEntity extends ICapabilitySerializable<CompoundTag>
*
* @return if the entity can be interacted with from a rider
*/
default boolean canRiderInteract()
{
default boolean canRiderInteract() {
return false;
}
@@ -119,8 +106,7 @@ public interface IForgeEntity extends ICapabilitySerializable<CompoundTag>
* @return {@code true} if the vehicle can be ridden in under this fluid,
* {@code false} otherwise
*/
default boolean canBeRiddenUnderFluidType(FluidType type, Entity rider)
{
default boolean canBeRiddenUnderFluidType(FluidType type, Entity rider) {
return type.canRideVehicleUnder(self(), rider);
}
@@ -138,8 +124,7 @@ public interface IForgeEntity extends ICapabilitySerializable<CompoundTag>
* @param forSpawnCount If this is being invoked to check spawn count caps.
* @return If the creature is of the type provided
*/
default MobCategory getClassification(boolean forSpawnCount)
{
default MobCategory getClassification(boolean forSpawnCount) {
return self().getType().getCategory();
}
@@ -183,8 +168,7 @@ public interface IForgeEntity extends ICapabilitySerializable<CompoundTag>
* See {@link EnderDragon} for an example implementation.
* @return true if this is a multipart entity.
*/
default boolean isMultipartEntity()
{
default boolean isMultipartEntity() {
return false;
}
@@ -201,8 +185,7 @@ public interface IForgeEntity extends ICapabilitySerializable<CompoundTag>
* @return The child parts of this entity. The value to be returned here should be cached.
*/
@Nullable
default PartEntity<?>[] getParts()
{
default PartEntity<?>[] getParts() {
return null;
}
@@ -212,16 +195,13 @@ public interface IForgeEntity extends ICapabilitySerializable<CompoundTag>
* of the {@link net.minecraftforge.common.ForgeMod#STEP_HEIGHT_ADDITION} attribute
* (if this Entity is a {@link LivingEntity} and has the attribute), clamped at 0.
*/
default float getStepHeight()
{
default float getStepHeight() {
@SuppressWarnings("deprecation")
float vanillaStep = self().maxUpStep();
if (self() instanceof LivingEntity living)
{
if (self() instanceof LivingEntity living) {
AttributeInstance stepHeightAttribute = living.getAttribute(ForgeMod.STEP_HEIGHT_ADDITION.get());
if (stepHeightAttribute != null)
{
return (float) Math.max(0, vanillaStep + stepHeightAttribute.getValue());
}
}
return vanillaStep;
}
@@ -252,8 +232,7 @@ public interface IForgeEntity extends ICapabilitySerializable<CompoundTag>
* @return {@code true} if the entity is within the fluid type of the
* state, {@code false} otherwise
*/
default boolean isInFluidType(FluidState state)
{
default boolean isInFluidType(FluidState state) {
return this.isInFluidType(state.getFluidType());
}
@@ -264,8 +243,7 @@ public interface IForgeEntity extends ICapabilitySerializable<CompoundTag>
* @return {@code true} if the entity is within the fluid type,
* {@code false} otherwise
*/
default boolean isInFluidType(FluidType type)
{
default boolean isInFluidType(FluidType type) {
return this.getFluidTypeHeight(type) > 0.0D;
}
@@ -277,8 +255,7 @@ public interface IForgeEntity extends ICapabilitySerializable<CompoundTag>
* @return {@code true} if a fluid type meets the condition, {@code false}
* otherwise
*/
default boolean isInFluidType(BiPredicate<FluidType, Double> predicate)
{
default boolean isInFluidType(BiPredicate<FluidType, Double> predicate) {
return isInFluidType(predicate, false);
}
@@ -313,8 +290,7 @@ public interface IForgeEntity extends ICapabilitySerializable<CompoundTag>
*
* @return {@code true} if the fluid is on the entity's eyes, {@code false} otherwise
*/
default boolean isEyeInFluidType(FluidType type)
{
default boolean isEyeInFluidType(FluidType type) {
return type == this.getEyeInFluidType();
}
@@ -323,8 +299,7 @@ public interface IForgeEntity extends ICapabilitySerializable<CompoundTag>
*
* @return {@code true} if the entity can start swimming, {@code false} otherwise
*/
default boolean canStartSwimming()
{
default boolean canStartSwimming() {
return !this.getEyeInFluidType().isAir() && this.canSwimInFluidType(this.getEyeInFluidType());
}
@@ -335,8 +310,7 @@ public interface IForgeEntity extends ICapabilitySerializable<CompoundTag>
* @param type the type of the fluid
* @return a scalar to multiply to the fluid velocity
*/
default double getFluidMotionScale(FluidType type)
{
default double getFluidMotionScale(FluidType type) {
return type.motionScale(self());
}
@@ -346,8 +320,8 @@ public interface IForgeEntity extends ICapabilitySerializable<CompoundTag>
* @param type the type of the fluid
* @return {@code true} if the entity can be pushed by the fluid, {@code false} otherwise
*/
default boolean isPushedByFluid(FluidType type)
{
@SuppressWarnings("deprecation")
default boolean isPushedByFluid(FluidType type) {
return self().isPushedByFluid() && type.canPushEntity(self());
}
@@ -357,8 +331,7 @@ public interface IForgeEntity extends ICapabilitySerializable<CompoundTag>
* @param type the type of the fluid
* @return {@code true} if the entity can swim in the fluid, {@code false} otherwise
*/
default boolean canSwimInFluidType(FluidType type)
{
default boolean canSwimInFluidType(FluidType type) {
return type.canSwim(self());
}
@@ -368,8 +341,7 @@ public interface IForgeEntity extends ICapabilitySerializable<CompoundTag>
* @param type the type of the fluid
* @return {@code true} if the entity can be extinguished, {@code false} otherwise
*/
default boolean canFluidExtinguish(FluidType type)
{
default boolean canFluidExtinguish(FluidType type) {
return type.canExtinguish(self());
}
@@ -383,8 +355,7 @@ public interface IForgeEntity extends ICapabilitySerializable<CompoundTag>
* @param type the type of the fluid
* @return a scalar to multiply to the fall damage
*/
default float getFluidFallDistanceModifier(FluidType type)
{
default float getFluidFallDistanceModifier(FluidType type) {
return type.getFallDistanceModifier(self());
}
@@ -397,8 +368,7 @@ public interface IForgeEntity extends ICapabilitySerializable<CompoundTag>
* @return {@code true} if the entity can be hydrated, {@code false}
* otherwise
*/
default boolean canHydrateInFluidType(FluidType type)
{
default boolean canHydrateInFluidType(FluidType type) {
return type.canHydrate(self());
}
@@ -412,8 +382,7 @@ public interface IForgeEntity extends ICapabilitySerializable<CompoundTag>
* @return the sound to play when performing the action
*/
@Nullable
default SoundEvent getSoundFromFluidType(FluidType type, SoundAction action)
{
default SoundEvent getSoundFromFluidType(FluidType type, SoundAction action) {
return type.getSound(self(), action);
}
@@ -425,14 +394,12 @@ public interface IForgeEntity extends ICapabilitySerializable<CompoundTag>
* @param player the local player currently viewing this {@code Entity}
* @return {@code true} to enable outline processing
*/
default boolean hasCustomOutlineRendering(Player player)
{
default boolean hasCustomOutlineRendering(Player player) {
return false;
}
@Deprecated(forRemoval = true, since = "1.20.1") // Remove Entity Eye/Size hooks, as they need to be redesigned
default float getEyeHeightForge(Pose pose, EntityDimensions size)
{
default float getEyeHeightForge(Pose pose, EntityDimensions size) {
return self().getEyeHeightAccess(pose, size);
}
@@ -444,8 +411,7 @@ public interface IForgeEntity extends ICapabilitySerializable<CompoundTag>
* @param boat the boat the rider is within that is not inside a fluid
* @return {@code true} if the fluid height should be updated, {@code false} otherwise
*/
default boolean shouldUpdateFluidWhileBoating(FluidState state, Boat boat)
{
default boolean shouldUpdateFluidWhileBoating(FluidState state, Boat boat) {
return boat.shouldUpdateFluidWhileRiding(state, self());
}
}
@@ -13,22 +13,14 @@ import net.minecraft.world.entity.vehicle.Boat;
import net.minecraft.world.level.BlockGetter;
import net.minecraft.world.level.Explosion;
import net.minecraft.world.level.Level;
import net.minecraft.world.level.LevelReader;
import net.minecraft.world.level.block.state.BlockState;
import net.minecraft.world.level.material.Fluid;
import net.minecraft.world.level.material.FluidState;
import net.minecraft.world.level.pathfinder.BlockPathTypes;
import net.minecraft.world.phys.Vec3;
import net.minecraftforge.fluids.FluidType;
import org.jetbrains.annotations.Nullable;
public interface IForgeFluid
{
private Fluid self()
{
return (Fluid) this;
}
public interface IForgeFluid {
/**
* Returns the explosion resistance of the fluid.
*
@@ -39,8 +31,7 @@ public interface IForgeFluid
* @return the amount of the explosion the fluid can absorb
*/
@SuppressWarnings("deprecation")
default float getExplosionResistance(FluidState state, BlockGetter level, BlockPos pos, Explosion explosion)
{
default float getExplosionResistance(FluidState state, BlockGetter level, BlockPos pos, Explosion explosion) {
return state.getExplosionResistance();
}
@@ -65,8 +56,7 @@ public interface IForgeFluid
* @param gravity the gravity to apply to the entity
* @return {@code true} if custom movement logic is performed, {@code false} otherwise
*/
default boolean move(FluidState state, LivingEntity entity, Vec3 movementVector, double gravity)
{
default boolean move(FluidState state, LivingEntity entity, Vec3 movementVector, double gravity) {
return getFluidType().move(state, entity, movementVector, gravity);
}
@@ -78,8 +68,7 @@ public interface IForgeFluid
* @param pos the location of the fluid
* @return {@code true} if the fluid can create a source, {@code false} otherwise
*/
default boolean canConvertToSource(FluidState state, Level level, BlockPos pos)
{
default boolean canConvertToSource(FluidState state, Level level, BlockPos pos) {
return getFluidType().canConvertToSource(state, level, pos);
}
@@ -90,8 +79,7 @@ public interface IForgeFluid
* @param boat the boat trying to be used on the fluid
* @return {@code true} if the boat can be used, {@code false} otherwise
*/
default boolean supportsBoating(FluidState state, Boat boat)
{
default boolean supportsBoating(FluidState state, Boat boat) {
return getFluidType().supportsBoating(state, boat);
}
@@ -104,8 +92,7 @@ public interface IForgeFluid
* @param rider the rider of the boat
* @return {@code true} if the fluid height should be updated, {@code false} otherwise
*/
default boolean shouldUpdateWhileBoating(FluidState state, Boat boat, Entity rider)
{
default boolean shouldUpdateWhileBoating(FluidState state, Boat boat, Entity rider) {
return getFluidType().shouldUpdateWhileBoating(state, boat, rider);
}
@@ -122,8 +109,7 @@ public interface IForgeFluid
* @return the path type of this fluid
*/
@Nullable
default BlockPathTypes getBlockPathType(FluidState state, BlockGetter level, BlockPos pos, @org.jetbrains.annotations.Nullable Mob mob, boolean canFluidLog)
{
default BlockPathTypes getBlockPathType(FluidState state, BlockGetter level, BlockPos pos, @Nullable Mob mob, boolean canFluidLog) {
return getFluidType().getBlockPathType(state, level, pos, mob, canFluidLog);
}
@@ -141,8 +127,7 @@ public interface IForgeFluid
* @return the path type of this fluid
*/
@Nullable
default BlockPathTypes getAdjacentBlockPathType(FluidState state, BlockGetter level, BlockPos pos, @org.jetbrains.annotations.Nullable Mob mob, BlockPathTypes originalType)
{
default BlockPathTypes getAdjacentBlockPathType(FluidState state, BlockGetter level, BlockPos pos, @Nullable Mob mob, BlockPathTypes originalType) {
return getFluidType().getAdjacentBlockPathType(state, level, pos, mob, originalType);
}
@@ -163,8 +148,7 @@ public interface IForgeFluid
* @param sourcePos the position of the block being hydrated
* @return {@code true} if the block can be hydrated, {@code false} otherwise
*/
default boolean canHydrate(FluidState state, BlockGetter getter, BlockPos pos, BlockState source, BlockPos sourcePos)
{
default boolean canHydrate(FluidState state, BlockGetter getter, BlockPos pos, BlockState source, BlockPos sourcePos) {
return getFluidType().canHydrate(state, getter, pos, source, sourcePos);
}
@@ -176,8 +160,7 @@ public interface IForgeFluid
* @param pos the position of the fluid
* @return {@code true} if the block can be extinguished, {@code false} otherwise
*/
default boolean canExtinguish(FluidState state, BlockGetter getter, BlockPos pos)
{
default boolean canExtinguish(FluidState state, BlockGetter getter, BlockPos pos) {
return getFluidType().canExtinguish(state, getter, pos);
}
}
@@ -13,7 +13,6 @@ import net.minecraft.world.entity.vehicle.Boat;
import net.minecraft.world.level.BlockGetter;
import net.minecraft.world.level.Explosion;
import net.minecraft.world.level.Level;
import net.minecraft.world.level.LevelReader;
import net.minecraft.world.level.block.state.BlockState;
import net.minecraft.world.level.material.FluidState;
import net.minecraft.world.level.pathfinder.BlockPathTypes;
@@ -21,11 +20,9 @@ import net.minecraft.world.phys.Vec3;
import net.minecraftforge.fluids.FluidType;
import org.jetbrains.annotations.Nullable;
public interface IForgeFluidState
{
private FluidState self()
{
return (FluidState) this;
public interface IForgeFluidState {
private FluidState self() {
return (FluidState)this;
}
/**
@@ -36,8 +33,7 @@ public interface IForgeFluidState
* @param explosion the explosion the fluid is absorbing
* @return the amount of the explosion the fluid can absorb
*/
default float getExplosionResistance(BlockGetter level, BlockPos pos, Explosion explosion)
{
default float getExplosionResistance(BlockGetter level, BlockPos pos, Explosion explosion) {
return self().getType().getExplosionResistance(self(), level, pos, explosion);
}
@@ -46,8 +42,7 @@ public interface IForgeFluidState
*
* @return the type of this fluid
*/
default FluidType getFluidType()
{
default FluidType getFluidType() {
return self().getType().getFluidType();
}
@@ -61,8 +56,7 @@ public interface IForgeFluidState
* @param gravity the gravity to apply to the entity
* @return {@code true} if custom movement logic is performed, {@code false} otherwise
*/
default boolean move(LivingEntity entity, Vec3 movementVector, double gravity)
{
default boolean move(LivingEntity entity, Vec3 movementVector, double gravity) {
return self().getType().move(self(), entity, movementVector, gravity);
}
@@ -73,8 +67,7 @@ public interface IForgeFluidState
* @param pos the location of the fluid
* @return {@code true} if the fluid can create a source, {@code false} otherwise
*/
default boolean canConvertToSource(Level level, BlockPos pos)
{
default boolean canConvertToSource(Level level, BlockPos pos) {
return self().getType().canConvertToSource(self(), level, pos);
}
@@ -84,8 +77,7 @@ public interface IForgeFluidState
* @param boat the boat trying to be used on the fluid
* @return {@code true} if the boat can be used, {@code false} otherwise
*/
default boolean supportsBoating(Boat boat)
{
default boolean supportsBoating(Boat boat) {
return self().getType().supportsBoating(self(), boat);
}
@@ -97,8 +89,7 @@ public interface IForgeFluidState
* @param rider the rider of the boat
* @return {@code true} if the fluid height should be updated, {@code false} otherwise
*/
default boolean shouldUpdateWhileBoating(Boat boat, Entity rider)
{
default boolean shouldUpdateWhileBoating(Boat boat, Entity rider) {
return self().getType().shouldUpdateWhileBoating(self(), boat, rider);
}
@@ -114,8 +105,7 @@ public interface IForgeFluidState
* @return the path type of this fluid
*/
@Nullable
default BlockPathTypes getBlockPathType(BlockGetter level, BlockPos pos, @org.jetbrains.annotations.Nullable Mob mob, boolean canFluidLog)
{
default BlockPathTypes getBlockPathType(BlockGetter level, BlockPos pos, @Nullable Mob mob, boolean canFluidLog) {
return self().getType().getBlockPathType(self(), level, pos, mob, canFluidLog);
}
@@ -132,8 +122,7 @@ public interface IForgeFluidState
* @return the path type of this fluid
*/
@Nullable
default BlockPathTypes getAdjacentBlockPathType(BlockGetter level, BlockPos pos, @org.jetbrains.annotations.Nullable Mob mob, BlockPathTypes originalType)
{
default BlockPathTypes getAdjacentBlockPathType(BlockGetter level, BlockPos pos, @Nullable Mob mob, BlockPathTypes originalType) {
return self().getType().getAdjacentBlockPathType(self(), level, pos, mob, originalType);
}
@@ -153,8 +142,7 @@ public interface IForgeFluidState
* @param sourcePos the position of the block being hydrated
* @return {@code true} if the block can be hydrated, {@code false} otherwise
*/
default boolean canHydrate(BlockGetter getter, BlockPos pos, BlockState source, BlockPos sourcePos)
{
default boolean canHydrate(BlockGetter getter, BlockPos pos, BlockState source, BlockPos sourcePos) {
return self().getType().canHydrate(self(), getter, pos, source, sourcePos);
}
@@ -165,8 +153,7 @@ public interface IForgeFluidState
* @param pos the position of the fluid
* @return {@code true} if the block can be extinguished, {@code false} otherwise
*/
default boolean canExtinguish(BlockGetter getter, BlockPos pos)
{
default boolean canExtinguish(BlockGetter getter, BlockPos pos) {
return self().getType().canExtinguish(self(), getter, pos);
}
}
@@ -0,0 +1,45 @@
/*
* Copyright (c) Forge Development LLC and contributors
* SPDX-License-Identifier: LGPL-2.1-only
*/
package net.minecraftforge.common.extensions;
import java.util.UUID;
import com.mojang.authlib.GameProfile;
import io.netty.channel.embedded.EmbeddedChannel;
import net.minecraft.gametest.framework.GameTestHelper;
import net.minecraft.network.Connection;
import net.minecraft.network.ConnectionProtocol;
import net.minecraft.network.protocol.PacketFlow;
import net.minecraft.server.level.ServerPlayer;
import net.minecraft.server.network.CommonListenerCookie;
import net.minecraft.server.network.ServerGamePacketListenerImpl;
public interface IForgeGameTestHelper {
private GameTestHelper self() {
return (GameTestHelper)this;
}
default ServerPlayer makeMockServerPlayer() {
var level = self().getLevel();
var cookie = CommonListenerCookie.createInitial(new GameProfile(UUID.randomUUID(), "test-mock-player"));
var player = new ServerPlayer(level.getServer(), level, cookie.gameProfile(), cookie.clientInformation()) {
public boolean isSpectator() {
return false;
}
public boolean isCreative() {
return true;
}
};
var connection = new Connection(PacketFlow.SERVERBOUND);
var channel = new EmbeddedChannel(connection);
channel.attr(Connection.ATTRIBUTE_SERVERBOUND_PROTOCOL).set(ConnectionProtocol.PLAY.codec(PacketFlow.SERVERBOUND));
// This sets the connection/listener in the player
new ServerGamePacketListenerImpl(level.getServer(), connection, player, cookie);
return player;
}
}
@@ -39,27 +39,26 @@ import net.minecraft.world.InteractionResult;
import net.minecraft.core.BlockPos;
import net.minecraft.network.chat.Component;
import net.minecraft.world.level.Level;
import net.minecraftforge.common.ForgeHooks;
import net.minecraftforge.common.ToolAction;
import net.minecraftforge.common.ToolActions;
import net.minecraftforge.common.capabilities.ICapabilityProvider;
import net.minecraftforge.items.wrapper.ShulkerItemStackInvWrapper;
import net.minecraftforge.registries.IForgeRegistry;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
// TODO systemic review of all extension functions. lots of unused -C
public interface IForgeItem
{
private Item self()
{
return (Item) this;
public interface IForgeItem {
private Item self() {
return (Item)this;
}
/**
* ItemStack sensitive version of getItemAttributeModifiers
*/
@SuppressWarnings("deprecation")
default Multimap<Attribute, AttributeModifier> getAttributeModifiers(EquipmentSlot slot, ItemStack stack)
{
default Multimap<Attribute, AttributeModifier> getAttributeModifiers(EquipmentSlot slot, ItemStack stack) {
return self().getDefaultAttributeModifiers(slot);
}
@@ -71,8 +70,7 @@ public interface IForgeItem
* @param player The player that dropped the item
* @param item The item stack, before the item is removed.
*/
default boolean onDroppedByPlayer(ItemStack item, Player player)
{
default boolean onDroppedByPlayer(ItemStack item, Player player) {
return true;
}
@@ -85,8 +83,7 @@ public interface IForgeItem
* @param displayName the name that will be displayed unless it is changed in
* this method.
*/
default Component getHighlightTip(ItemStack item, Component displayName)
{
default Component getHighlightTip(ItemStack item, Component displayName) {
return displayName;
}
@@ -95,8 +92,7 @@ public interface IForgeItem
*
* @return Return PASS to allow vanilla handling, any other to skip normal code.
*/
default InteractionResult onItemUseFirst(ItemStack stack, UseOnContext context)
{
default InteractionResult onItemUseFirst(ItemStack stack, UseOnContext context) {
return InteractionResult.PASS;
}
@@ -105,8 +101,7 @@ public interface IForgeItem
*
* @return True if this item can be used as "currency" by piglins
*/
default boolean isPiglinCurrency(ItemStack stack)
{
default boolean isPiglinCurrency(ItemStack stack) {
return stack.getItem() == PiglinAi.BARTERING_ITEM;
}
@@ -118,8 +113,7 @@ public interface IForgeItem
*
* @return True if piglins are neutral to players wearing this item in an armor slot
*/
default boolean makesPiglinsNeutral(ItemStack stack, LivingEntity wearer)
{
default boolean makesPiglinsNeutral(ItemStack stack, LivingEntity wearer) {
return stack.getItem() instanceof ArmorItem && ((ArmorItem) stack.getItem()).getMaterial() == ArmorMaterials.GOLD;
}
@@ -134,8 +128,7 @@ public interface IForgeItem
* Determines the amount of durability the mending enchantment
* will repair, on average, per point of experience.
*/
default float getXpRepairRatio(ItemStack stack)
{
default float getXpRepairRatio(ItemStack stack) {
return 2f;
}
@@ -156,8 +149,7 @@ public interface IForgeItem
* @return The NBT tag
*/
@Nullable
default CompoundTag getShareTag(ItemStack stack)
{
default CompoundTag getShareTag(ItemStack stack) {
return stack.getTag();
}
@@ -168,8 +160,7 @@ public interface IForgeItem
* @param stack The stack that received NBT
* @param nbt Received NBT, can be null
*/
default void readShareTag(ItemStack stack, @Nullable CompoundTag nbt)
{
default void readShareTag(ItemStack stack, @Nullable CompoundTag nbt) {
stack.setTag(nbt);
}
@@ -184,8 +175,7 @@ public interface IForgeItem
* @param player The Player that is wielding the item
* @return True to prevent harvesting, false to continue as normal
*/
default boolean onBlockStartBreak(ItemStack itemstack, BlockPos pos, Player player)
{
default boolean onBlockStartBreak(ItemStack itemstack, BlockPos pos, Player player) {
return false;
}
@@ -207,9 +197,7 @@ public interface IForgeItem
* @param entity The entity using the item, typically a player
* @param count The amount of time in tick the item has been used for continuously
*/
default void onStopUsing(ItemStack stack, LivingEntity entity, int count)
{
}
default void onStopUsing(ItemStack stack, LivingEntity entity, int count) { }
/**
* Called when the player Left Clicks (attacks) an entity. Processed before
@@ -221,8 +209,7 @@ public interface IForgeItem
* @param entity The entity being attacked
* @return True to cancel the rest of the interaction.
*/
default boolean onLeftClickEntity(ItemStack stack, Player player, Entity entity)
{
default boolean onLeftClickEntity(ItemStack stack, Player player, Entity entity) {
return false;
}
@@ -234,12 +221,9 @@ public interface IForgeItem
* @return The resulting ItemStack
*/
@SuppressWarnings("deprecation")
default ItemStack getCraftingRemainingItem(ItemStack itemStack)
{
default ItemStack getCraftingRemainingItem(ItemStack itemStack) {
if (!hasCraftingRemainingItem(itemStack))
{
return ItemStack.EMPTY;
}
return new ItemStack(self().getCraftingRemainingItem());
}
@@ -250,8 +234,7 @@ public interface IForgeItem
* @return True if this item has a crafting remaining item
*/
@SuppressWarnings("deprecation")
default boolean hasCraftingRemainingItem(ItemStack stack)
{
default boolean hasCraftingRemainingItem(ItemStack stack) {
return self().hasCraftingRemainingItem();
}
@@ -263,8 +246,7 @@ public interface IForgeItem
* @param level The level the entity is in
* @return The normal lifespan in ticks.
*/
default int getEntityLifespan(ItemStack itemStack, Level level)
{
default int getEntityLifespan(ItemStack itemStack, Level level) {
return 6000;
}
@@ -278,8 +260,7 @@ public interface IForgeItem
* @return True of the item has a custom entity, If true,
* Item#createCustomEntity will be called
*/
default boolean hasCustomEntity(ItemStack stack)
{
default boolean hasCustomEntity(ItemStack stack) {
return false;
}
@@ -295,8 +276,7 @@ public interface IForgeItem
* @return A new Entity object to spawn or null
*/
@Nullable
default Entity createEntity(Level level, Entity location, ItemStack stack)
{
default Entity createEntity(Level level, Entity location, ItemStack stack) {
return null;
}
@@ -308,8 +288,7 @@ public interface IForgeItem
* @param entity The entity Item
* @return Return true to skip any further update code.
*/
default boolean onEntityItemUpdate(ItemStack stack, ItemEntity entity)
{
default boolean onEntityItemUpdate(ItemStack stack, ItemEntity entity) {
return false;
}
@@ -322,8 +301,7 @@ public interface IForgeItem
* @param pos Block position in level
* @param player The Player that is wielding the item
*/
default boolean doesSneakBypassUse(ItemStack stack, net.minecraft.world.level.LevelReader level, BlockPos pos, Player player)
{
default boolean doesSneakBypassUse(ItemStack stack, net.minecraft.world.level.LevelReader level, BlockPos pos, Player player) {
return false;
}
@@ -331,15 +309,12 @@ public interface IForgeItem
* Called to tick armor in the armor slot. Override to do something
*/
@Deprecated(forRemoval = true, since = "1.20.1") // Use onInventoryTick
default void onArmorTick(ItemStack stack, Level level, Player player)
{
}
default void onArmorTick(ItemStack stack, Level level, Player player){ }
/**
* Called to tick this items in a players inventory, the indexes are the global slot index.
*/
default void onInventoryTick(ItemStack stack, Level level, Player player, int slotIndex, int selectedIndex)
{
default void onInventoryTick(ItemStack stack, Level level, Player player, int slotIndex, int selectedIndex) {
// For compatibility reasons we have to use non-local index values, I think this is a vanilla bug but lets maintain compatibility
var inv = player.getInventory();
int vanillaIndex = slotIndex;
@@ -362,8 +337,7 @@ public interface IForgeItem
* @param entity The entity trying to equip the armor
* @return True if the given ItemStack can be inserted in the slot
*/
default boolean canEquip(ItemStack stack, EquipmentSlot armorType, Entity entity)
{
default boolean canEquip(ItemStack stack, EquipmentSlot armorType, Entity entity) {
return Mob.getEquipmentSlotForItem(stack) == armorType;
}
@@ -378,8 +352,7 @@ public interface IForgeItem
* decide
*/
@Nullable
default EquipmentSlot getEquipmentSlot(ItemStack stack)
{
default EquipmentSlot getEquipmentSlot(ItemStack stack) {
return null;
}
@@ -390,8 +363,7 @@ public interface IForgeItem
* @param book The book
* @return if the enchantment is allowed
*/
default boolean isBookEnchantable(ItemStack stack, ItemStack book)
{
default boolean isBookEnchantable(ItemStack stack, ItemStack book) {
return true;
}
@@ -409,8 +381,7 @@ public interface IForgeItem
* @return Path of texture to bind, or null to use default
*/
@Nullable
default String getArmorTexture(ItemStack stack, Entity entity, EquipmentSlot slot, String type)
{
default String getArmorTexture(ItemStack stack, Entity entity, EquipmentSlot slot, String type) {
return null;
}
@@ -420,8 +391,7 @@ public interface IForgeItem
* @param entity The entity swinging the item.
* @return True to cancel any further processing by EntityLiving
*/
default boolean onEntitySwing(ItemStack stack, LivingEntity entity)
{
default boolean onEntitySwing(ItemStack stack, LivingEntity entity) {
return false;
}
@@ -432,8 +402,7 @@ public interface IForgeItem
* @param stack The itemstack that is damaged
* @return the damage value
*/
default int getDamage(ItemStack stack)
{
default int getDamage(ItemStack stack) {
return !stack.hasTag() ? 0 : stack.getTag().getInt("Damage");
}
@@ -445,8 +414,7 @@ public interface IForgeItem
* @return the damage value
*/
@SuppressWarnings("deprecation")
default int getMaxDamage(ItemStack stack)
{
default int getMaxDamage(ItemStack stack) {
return self().getMaxDamage();
}
@@ -457,8 +425,7 @@ public interface IForgeItem
* @param stack the stack
* @return if the stack is damaged
*/
default boolean isDamaged(ItemStack stack)
{
default boolean isDamaged(ItemStack stack) {
return stack.getDamageValue() > 0;
}
@@ -469,8 +436,7 @@ public interface IForgeItem
* @param stack the stack
* @param damage the new damage value
*/
default void setDamage(ItemStack stack, int damage)
{
default void setDamage(ItemStack stack, int damage) {
stack.getOrCreateTag().putInt("Damage", Math.max(0, damage));
}
@@ -481,8 +447,7 @@ public interface IForgeItem
* @param toolAction The action being queried
* @return True if the stack can perform the action
*/
default boolean canPerformAction(ItemStack stack, ToolAction toolAction)
{
default boolean canPerformAction(ItemStack stack, ToolAction toolAction) {
return false;
}
@@ -493,8 +458,7 @@ public interface IForgeItem
* @param state The block trying to harvest
* @return true if the stack can harvest the block
*/
default boolean isCorrectToolForDrops(ItemStack stack, BlockState state)
{
default boolean isCorrectToolForDrops(ItemStack stack, BlockState state) {
return self().isCorrectToolForDrops(state);
}
@@ -506,8 +470,7 @@ public interface IForgeItem
* @return The maximum size this item can be stacked to
*/
@SuppressWarnings("deprecation")
default int getMaxStackSize(ItemStack stack)
{
default int getMaxStackSize(ItemStack stack) {
return self().getMaxStackSize();
}
@@ -517,8 +480,8 @@ public interface IForgeItem
* @param stack The ItemStack
* @return the enchantment value
*/
default int getEnchantmentValue(ItemStack stack)
{
@SuppressWarnings("deprecation")
default int getEnchantmentValue(ItemStack stack) {
return self().getEnchantmentValue();
}
@@ -535,8 +498,7 @@ public interface IForgeItem
* @param enchantment the enchantment to be applied
* @return true if the enchantment can be applied to this item
*/
default boolean canApplyAtEnchantingTable(ItemStack stack, Enchantment enchantment)
{
default boolean canApplyAtEnchantingTable(ItemStack stack, Enchantment enchantment) {
return enchantment.category.canEnchant(stack.getItem());
}
@@ -550,8 +512,7 @@ public interface IForgeItem
* @return Level of the enchantment, or 0 if not present
* @see #getAllEnchantments(ItemStack)
*/
default int getEnchantmentLevel(ItemStack stack, Enchantment enchantment)
{
default int getEnchantmentLevel(ItemStack stack, Enchantment enchantment) {
return EnchantmentHelper.getTagEnchantmentLevel(enchantment, stack);
}
@@ -564,8 +525,7 @@ public interface IForgeItem
* @return Map of all enchantments on the stack, empty if no enchantments are present
* @see #getEnchantmentLevel(ItemStack, Enchantment)
*/
default Map<Enchantment, Integer> getAllEnchantments(ItemStack stack)
{
default Map<Enchantment, Integer> getAllEnchantments(ItemStack stack) {
return EnchantmentHelper.deserializeEnchantments(stack.getEnchantmentTags());
}
@@ -579,8 +539,7 @@ public interface IForgeItem
* hold the exact same item.
* @return True to play the item change animation
*/
default boolean shouldCauseReequipAnimation(ItemStack oldStack, ItemStack newStack, boolean slotChanged)
{
default boolean shouldCauseReequipAnimation(ItemStack oldStack, ItemStack newStack, boolean slotChanged) {
return !oldStack.equals(newStack); // !ItemStack.areItemStacksEqual(oldStack, newStack);
}
@@ -593,8 +552,7 @@ public interface IForgeItem
* @param newStack The new stack
* @return True to reset block break progress
*/
default boolean shouldCauseBlockBreakReset(ItemStack oldStack, ItemStack newStack)
{
default boolean shouldCauseBlockBreakReset(ItemStack oldStack, ItemStack newStack) {
// Fix MC-176559 mending resets mining progress / breaking animation
if (!newStack.is(oldStack.getItem()))
return true;
@@ -631,13 +589,11 @@ public interface IForgeItem
* @param newStack the stack currently in the active hand
* @return true to set the new stack to active and continue using it
*/
default boolean canContinueUsing(ItemStack oldStack, ItemStack newStack)
{
if (oldStack == newStack) {
default boolean canContinueUsing(ItemStack oldStack, ItemStack newStack) {
if (oldStack == newStack)
return true;
} else {
else
return !oldStack.isEmpty() && !newStack.isEmpty() && ItemStack.isSameItem(newStack, oldStack);
}
}
/**
@@ -655,9 +611,8 @@ public interface IForgeItem
* associated mod and {@link IForgeRegistry#getKey(Object)} would return null.
*/
@Nullable
default String getCreatorModId(ItemStack itemStack)
{
return net.minecraftforge.common.ForgeHooks.getDefaultCreatorModId(itemStack);
default String getCreatorModId(ItemStack itemStack) {
return ForgeHooks.getDefaultCreatorModId(itemStack);
}
/**
@@ -675,10 +630,8 @@ public interface IForgeItem
* capabilities for the life of this item.
*/
@Nullable
default net.minecraftforge.common.capabilities.ICapabilityProvider initCapabilities(ItemStack stack, @Nullable CompoundTag nbt)
{
var ret = ShulkerItemStackInvWrapper.createDefaultProvider(stack);
return ret;
default ICapabilityProvider initCapabilities(ItemStack stack, @Nullable CompoundTag nbt) {
return ShulkerItemStackInvWrapper.createDefaultProvider(stack);
}
/**
@@ -690,8 +643,7 @@ public interface IForgeItem
* @param attacker The LivingEntity holding the ItemStack
* @return True if this ItemStack can disable the shield in question.
*/
default boolean canDisableShield(ItemStack stack, ItemStack shield, LivingEntity entity, LivingEntity attacker)
{
default boolean canDisableShield(ItemStack stack, ItemStack shield, LivingEntity entity, LivingEntity attacker) {
return this instanceof AxeItem;
}
@@ -700,8 +652,7 @@ public interface IForgeItem
* it not act as a fuel. Return -1 to let the default vanilla logic
* decide.
*/
default int getBurnTime(ItemStack itemStack, @Nullable RecipeType<?> recipeType)
{
default int getBurnTime(ItemStack itemStack, @Nullable RecipeType<?> recipeType) {
return -1;
}
@@ -713,9 +664,7 @@ public interface IForgeItem
* @param level the level the horse is in
* @param horse the horse wearing this armor
*/
default void onHorseArmorTick(ItemStack stack, Level level, Mob horse)
{
}
default void onHorseArmorTick(ItemStack stack, Level level, Mob horse) { }
/**
* Reduce the durability of this item by the amount given.
@@ -737,8 +686,8 @@ public interface IForgeItem
* @param itemEntity The item entity that was destroyed.
* @param damageSource Damage source that caused the item entity to "die".
*/
default void onDestroyed(ItemEntity itemEntity, DamageSource damageSource)
{
@SuppressWarnings("deprecation")
default void onDestroyed(ItemEntity itemEntity, DamageSource damageSource) {
self().onDestroyed(itemEntity);
}
@@ -750,8 +699,7 @@ public interface IForgeItem
* @param endermanEntity The enderman that the player look
* @return true if this Item can be used to hide player head for enderman
*/
default boolean isEnderMask(ItemStack stack, Player player, EnderMan endermanEntity)
{
default boolean isEnderMask(ItemStack stack, Player player, EnderMan endermanEntity) {
return stack.getItem() == Blocks.CARVED_PUMPKIN.asItem();
}
@@ -763,8 +711,7 @@ public interface IForgeItem
* @param entity The entity trying to fly.
* @return True if the entity can use Elytra flight.
*/
default boolean canElytraFly(ItemStack stack, LivingEntity entity)
{
default boolean canElytraFly(ItemStack stack, LivingEntity entity) {
return false;
}
@@ -780,8 +727,7 @@ public interface IForgeItem
* @param flightTicks The number of ticks the entity has been Elytra flying for.
* @return True if the entity should continue Elytra flight or False to stop.
*/
default boolean elytraFlightTick(ItemStack stack, LivingEntity entity, int flightTicks)
{
default boolean elytraFlightTick(ItemStack stack, LivingEntity entity, int flightTicks) {
return false;
}
@@ -794,8 +740,7 @@ public interface IForgeItem
*
* @return True if the entity can walk on powdered snow
*/
default boolean canWalkOnPowderedSnow(ItemStack stack, LivingEntity wearer)
{
default boolean canWalkOnPowderedSnow(ItemStack stack, LivingEntity wearer) {
return stack.is(Items.LEATHER_BOOTS);
}
@@ -805,8 +750,7 @@ public interface IForgeItem
*
* @param stack ItemStack in the Chest slot of the entity.
*/
default boolean isDamageable(ItemStack stack)
{
default boolean isDamageable(ItemStack stack) {
return self().canBeDepleted();
}
@@ -819,8 +763,7 @@ public interface IForgeItem
* @return the bounding box.
*/
@NotNull
default AABB getSweepHitBox(@NotNull ItemStack stack, @NotNull Player player, @NotNull Entity target)
{
default AABB getSweepHitBox(@NotNull ItemStack stack, @NotNull Player player, @NotNull Entity target) {
return target.getBoundingBox().inflate(1.0D, 0.25D, 1.0D);
}
@@ -830,8 +773,7 @@ public interface IForgeItem
* @param stack the stack
* @return the default hide flags
*/
default int getDefaultTooltipHideFlags(@NotNull ItemStack stack)
{
default int getDefaultTooltipHideFlags(@NotNull ItemStack stack) {
return 0;
}
@@ -846,9 +788,9 @@ public interface IForgeItem
* @param entity The entity which wants to eat the food. Be aware that this can be null!
* @return The current FoodProperties for the item.
*/
@SuppressWarnings("deprecation")
@Nullable // read javadoc to find a potential problem
default FoodProperties getFoodProperties(ItemStack stack, @Nullable LivingEntity entity)
{
default FoodProperties getFoodProperties(ItemStack stack, @Nullable LivingEntity entity) {
return self().getFoodProperties();
}
@@ -861,16 +803,14 @@ public interface IForgeItem
* @param inventorySlot the inventory slot of the item being up for replacement
* @return true to leave this stack in the hotbar if possible
*/
default boolean isNotReplaceableByPickAction(ItemStack stack, Player player, int inventorySlot)
{
default boolean isNotReplaceableByPickAction(ItemStack stack, Player player, int inventorySlot) {
return stack.isEnchanted();
}
/**
* {@return true if the given ItemStack can be put into a grindstone to be repaired and/or stripped of its enchantments}
*/
default boolean canGrindstoneRepair(ItemStack stack)
{
default boolean canGrindstoneRepair(ItemStack stack) {
return false;
}
}
@@ -11,18 +11,17 @@ import net.minecraft.world.phys.Vec3;
import net.minecraftforge.common.ForgeMod;
import net.minecraftforge.fluids.FluidType;
public interface IForgeLivingEntity extends IForgeEntity
{
default LivingEntity self()
{
return (LivingEntity) this;
public interface IForgeLivingEntity extends IForgeEntity {
default LivingEntity self() {
return (LivingEntity)this;
}
@Override
default boolean canSwimInFluidType(FluidType type)
{
if (type == ForgeMod.WATER_TYPE.get()) return !self().isSensitiveToWater();
else return IForgeEntity.super.canSwimInFluidType(type);
default boolean canSwimInFluidType(FluidType type) {
if (type == ForgeMod.WATER_TYPE.get())
return !self().isSensitiveToWater();
else
return IForgeEntity.super.canSwimInFluidType(type);
}
/**
@@ -30,8 +29,7 @@ public interface IForgeLivingEntity extends IForgeEntity
*
* @param type the type of the fluid
*/
default void jumpInFluid(FluidType type)
{
default void jumpInFluid(FluidType type) {
self().setDeltaMovement(self().getDeltaMovement().add(0.0D, (double)0.04F * self().getAttributeValue(ForgeMod.SWIM_SPEED.get()), 0.0D));
}
@@ -40,8 +38,7 @@ public interface IForgeLivingEntity extends IForgeEntity
*
* @param type the type of the fluid
*/
default void sinkInFluid(FluidType type)
{
default void sinkInFluid(FluidType type) {
self().setDeltaMovement(self().getDeltaMovement().add(0.0D, (double)-0.04F * self().getAttributeValue(ForgeMod.SWIM_SPEED.get()), 0.0D));
}
@@ -51,10 +48,12 @@ public interface IForgeLivingEntity extends IForgeEntity
* @param type the type of the fluid
* @return {@code true} if the entity can drown in the fluid, {@code false} otherwise
*/
default boolean canDrownInFluidType(FluidType type)
{
if (type == ForgeMod.WATER_TYPE.get()) return !self().canBreatheUnderwater();
return type.canDrownIn(self());
@SuppressWarnings("deprecation")
default boolean canDrownInFluidType(FluidType type) {
if (type == ForgeMod.WATER_TYPE.get())
return !self().canBreatheUnderwater();
return
type.canDrownIn(self());
}
/**
@@ -67,8 +66,7 @@ public interface IForgeLivingEntity extends IForgeEntity
* @param gravity the gravity to apply to the entity
* @return {@code true} if custom movement logic is performed, {@code false} otherwise
*/
default boolean moveInFluid(FluidState state, Vec3 movementVector, double gravity)
{
default boolean moveInFluid(FluidState state, Vec3 movementVector, double gravity) {
return state.move(self(), movementVector, gravity);
}
}
@@ -11,11 +11,8 @@ import net.minecraft.world.effect.MobEffect;
import net.minecraft.world.item.ItemStack;
import net.minecraft.nbt.CompoundTag;
import net.minecraft.nbt.ListTag;
import net.minecraft.world.effect.MobEffectInstance;
public interface IForgeMobEffectInstance
{
public interface IForgeMobEffectInstance {
/***
* Returns a list of curative items for the potion effect
* By default, this list is initialized using {@link MobEffect#getCurativeItems()}
@@ -8,17 +8,14 @@ package net.minecraftforge.common.extensions;
import java.util.Collection;
import org.jetbrains.annotations.Nullable;
import net.minecraft.server.packs.PackResources;
import net.minecraft.server.packs.PackType;
import net.minecraft.server.packs.resources.ResourceManager;
import net.minecraftforge.resource.DelegatingPackResources;
public interface IForgePackResources
{
public interface IForgePackResources {
/**
* {@return {@code true} if the pack should be hidden from any user interfaces}
*/
default boolean isHidden()
{
default boolean isHidden() {
return false;
}
@@ -30,5 +27,8 @@ public interface IForgePackResources
* @return Collection of nested {@code PackResource}, or null if this pack has no children
* @see DelegatingPackResources
*/
@Nullable default Collection<PackResources> getChildren() { return null; }
@Nullable
default Collection<PackResources> getChildren() {
return null;
}
}
@@ -6,7 +6,6 @@
package net.minecraftforge.common.extensions;
import net.minecraft.core.BlockPos;
import net.minecraft.util.Mth;
import net.minecraft.world.entity.Entity;
import net.minecraft.world.entity.player.Player;
import net.minecraft.world.phys.AABB;
@@ -14,20 +13,16 @@ import net.minecraft.world.phys.HitResult;
import net.minecraft.world.phys.Vec3;
import net.minecraftforge.common.ForgeMod;
public interface IForgePlayer
{
private Player self()
{
return (Player) this;
public interface IForgePlayer {
private Player self() {
return (Player)this;
}
/**
* The entity reach is increased by 3 for creative players, unless it is currently zero, which disables attacks and entity interactions.
* @return The entity reach of this player.
*/
default double getEntityReach()
{
default double getEntityReach() {
double range = self().getAttributeValue(ForgeMod.ENTITY_REACH.get());
return range == 0 ? 0 : range + (self().isCreative() ? 3 : 0);
}
@@ -36,8 +31,7 @@ public interface IForgePlayer
* The reach distance is increased by 0.5 for creative players, unless it is currently zero, which disables interactions.
* @return The reach distance of this player.
*/
default double getBlockReach()
{
default double getBlockReach() {
double reach = self().getAttributeValue(ForgeMod.BLOCK_REACH.get());
return reach == 0 ? 0 : reach + (self().isCreative() ? 0.5 : 0);
}
@@ -50,8 +44,7 @@ public interface IForgePlayer
* @return If the player can attack the entity.
* @apiNote Do not use for block checks, as this method uses {@link #getEntityReach()}
*/
default boolean canReach(Vec3 entityHitVec, double padding)
{
default boolean canReach(Vec3 entityHitVec, double padding) {
return self().getEyePosition().closerThan(entityHitVec, getEntityReach() + padding);
}
@@ -63,8 +56,7 @@ public interface IForgePlayer
* @return If the player can attack the passed entity.
* @apiNote Prefer using {@link #canReach(Vec3, double)} if you have a {@link HitResult} available.
*/
default boolean canReach(Entity entity, double padding)
{
default boolean canReach(Entity entity, double padding) {
return isCloseEnough(entity, getEntityReach() + padding);
}
@@ -75,8 +67,7 @@ public interface IForgePlayer
* @param padding Extra validation distance.
* @return If the player can interact with this location.
*/
default boolean canReach(BlockPos pos, double padding)
{
default boolean canReach(BlockPos pos, double padding) {
double reach = this.getBlockReach() + padding;
return self().getEyePosition().distanceToSqr(Vec3.atCenterOf(pos)) < reach * reach;
}
@@ -88,8 +79,7 @@ public interface IForgePlayer
* @return If the eye-to-center distance between this player and the passed entity is less than dist.
* @implNote This method inflates the bounding box by the pick radius, which differs from vanilla. But vanilla doesn't use the pick radius, the only entity with > 0 is AbstractHurtingProjectile.
*/
default boolean isCloseEnough(Entity entity, double dist)
{
default boolean isCloseEnough(Entity entity, double dist) {
Vec3 eye = self().getEyePosition();
AABB aabb = entity.getBoundingBox().inflate(entity.getPickRadius());
return aabb.distanceToSqr(eye) < dist * dist;
@@ -6,24 +6,16 @@
package net.minecraftforge.common.extensions;
import net.minecraft.world.item.ItemStack;
import net.minecraft.world.item.alchemy.Potion;
import net.minecraft.world.item.alchemy.PotionUtils;
public interface IForgePotion
{
private Potion self()
{
return (Potion) this;
}
public interface IForgePotion {
/**
* Determines whether the potion bottle item should be enchanted.
* Not called for tipped arrows or if the item is already enchanted.
* @param stack The potion bottle
* @return whether the item should appear enchanted.
*/
default boolean isFoil(ItemStack stack)
{
default boolean isFoil(ItemStack stack) {
return !PotionUtils.getMobEffects(stack).isEmpty();
}
}
@@ -1,155 +0,0 @@
/*
* Copyright (c) Forge Development LLC and contributors
* SPDX-License-Identifier: LGPL-2.1-only
*/
package net.minecraftforge.common.util;
import com.mojang.authlib.GameProfile;
import java.util.Set;
import javax.annotation.ParametersAreNonnullByDefault;
import net.minecraft.network.Connection;
import net.minecraft.network.PacketSendListener;
import net.minecraft.network.chat.ChatType;
import net.minecraft.network.chat.Component;
import net.minecraft.network.chat.PlayerChatMessage;
import net.minecraft.network.protocol.Packet;
import net.minecraft.network.protocol.PacketFlow;
import net.minecraft.network.protocol.game.ServerboundAcceptTeleportationPacket;
import net.minecraft.network.protocol.game.ServerboundBlockEntityTagQuery;
import net.minecraft.network.protocol.game.ServerboundChangeDifficultyPacket;
import net.minecraft.network.protocol.game.ServerboundChatAckPacket;
import net.minecraft.network.protocol.game.ServerboundChatCommandPacket;
import net.minecraft.network.protocol.game.ServerboundChatPacket;
import net.minecraft.network.protocol.game.ServerboundChatSessionUpdatePacket;
import net.minecraft.network.protocol.game.ServerboundClientCommandPacket;
import net.minecraft.network.protocol.game.ServerboundCommandSuggestionPacket;
import net.minecraft.network.protocol.game.ServerboundContainerButtonClickPacket;
import net.minecraft.network.protocol.game.ServerboundContainerClickPacket;
import net.minecraft.network.protocol.game.ServerboundContainerClosePacket;
import net.minecraft.network.protocol.game.ServerboundEditBookPacket;
import net.minecraft.network.protocol.game.ServerboundEntityTagQuery;
import net.minecraft.network.protocol.game.ServerboundInteractPacket;
import net.minecraft.network.protocol.game.ServerboundJigsawGeneratePacket;
import net.minecraft.network.protocol.game.ServerboundLockDifficultyPacket;
import net.minecraft.network.protocol.game.ServerboundMovePlayerPacket;
import net.minecraft.network.protocol.game.ServerboundMoveVehiclePacket;
import net.minecraft.network.protocol.game.ServerboundPaddleBoatPacket;
import net.minecraft.network.protocol.game.ServerboundPickItemPacket;
import net.minecraft.network.protocol.game.ServerboundPlaceRecipePacket;
import net.minecraft.network.protocol.game.ServerboundPlayerAbilitiesPacket;
import net.minecraft.network.protocol.game.ServerboundPlayerActionPacket;
import net.minecraft.network.protocol.game.ServerboundPlayerCommandPacket;
import net.minecraft.network.protocol.game.ServerboundPlayerInputPacket;
import net.minecraft.network.protocol.game.ServerboundRecipeBookChangeSettingsPacket;
import net.minecraft.network.protocol.game.ServerboundRecipeBookSeenRecipePacket;
import net.minecraft.network.protocol.game.ServerboundRenameItemPacket;
import net.minecraft.network.protocol.game.ServerboundSeenAdvancementsPacket;
import net.minecraft.network.protocol.game.ServerboundSelectTradePacket;
import net.minecraft.network.protocol.game.ServerboundSetBeaconPacket;
import net.minecraft.network.protocol.game.ServerboundSetCarriedItemPacket;
import net.minecraft.network.protocol.game.ServerboundSetCommandBlockPacket;
import net.minecraft.network.protocol.game.ServerboundSetCommandMinecartPacket;
import net.minecraft.network.protocol.game.ServerboundSetCreativeModeSlotPacket;
import net.minecraft.network.protocol.game.ServerboundSetJigsawBlockPacket;
import net.minecraft.network.protocol.game.ServerboundSetStructureBlockPacket;
import net.minecraft.network.protocol.game.ServerboundSignUpdatePacket;
import net.minecraft.network.protocol.game.ServerboundSwingPacket;
import net.minecraft.network.protocol.game.ServerboundTeleportToEntityPacket;
import net.minecraft.network.protocol.game.ServerboundUseItemOnPacket;
import net.minecraft.network.protocol.game.ServerboundUseItemPacket;
import net.minecraft.server.MinecraftServer;
import net.minecraft.server.level.ClientInformation;
import net.minecraft.server.level.ServerLevel;
import net.minecraft.server.level.ServerPlayer;
import net.minecraft.server.network.CommonListenerCookie;
import net.minecraft.server.network.ServerGamePacketListenerImpl;
import net.minecraft.stats.Stat;
import net.minecraft.world.damagesource.DamageSource;
import net.minecraft.world.entity.RelativeMovement;
import net.minecraft.world.entity.player.Player;
import net.minecraftforge.server.ServerLifecycleHooks;
import org.jetbrains.annotations.Nullable;
/**
* A basic fake server player implementation that can be used to simulate player actions.
*/
// TODO: Re-write this whole system to be less hacky. Use until we get a good replacement.
public class FakePlayer extends ServerPlayer {
protected FakePlayer(ServerLevel level, GameProfile name, ClientInformation info) {
super(level.getServer(), level, name, info);
}
@Override public void displayClientMessage(Component chatComponent, boolean actionBar) { }
@Override public void awardStat(Stat stat, int amount) { }
@Override public boolean isInvulnerableTo(DamageSource source) { return true; }
@Override public boolean canHarmPlayer(Player player) { return false; }
@Override public void die(DamageSource source) { }
@Override public void tick() { }
@Override @Nullable public MinecraftServer getServer() { return ServerLifecycleHooks.getCurrentServer(); }
@ParametersAreNonnullByDefault
static class NetHandler extends ServerGamePacketListenerImpl {
private static final Connection DUMMY_CONNECTION = new Connection(PacketFlow.CLIENTBOUND);
NetHandler(MinecraftServer server, ServerPlayer player, CommonListenerCookie cookie) {
super(server, DUMMY_CONNECTION, player, cookie);
}
@Override public void tick() { }
@Override public void resetPosition() { }
@Override public void disconnect(Component message) { }
@Override public void handlePlayerInput(ServerboundPlayerInputPacket packet) { }
@Override public void handleMoveVehicle(ServerboundMoveVehiclePacket packet) { }
@Override public void handleAcceptTeleportPacket(ServerboundAcceptTeleportationPacket packet) { }
@Override public void handleRecipeBookSeenRecipePacket(ServerboundRecipeBookSeenRecipePacket packet) { }
@Override public void handleRecipeBookChangeSettingsPacket(ServerboundRecipeBookChangeSettingsPacket packet) { }
@Override public void handleSeenAdvancements(ServerboundSeenAdvancementsPacket packet) { }
@Override public void handleCustomCommandSuggestions(ServerboundCommandSuggestionPacket packet) { }
@Override public void handleSetCommandBlock(ServerboundSetCommandBlockPacket packet) { }
@Override public void handleSetCommandMinecart(ServerboundSetCommandMinecartPacket packet) { }
@Override public void handlePickItem(ServerboundPickItemPacket packet) { }
@Override public void handleRenameItem(ServerboundRenameItemPacket packet) { }
@Override public void handleSetBeaconPacket(ServerboundSetBeaconPacket packet) { }
@Override public void handleSetStructureBlock(ServerboundSetStructureBlockPacket packet) { }
@Override public void handleSetJigsawBlock(ServerboundSetJigsawBlockPacket packet) { }
@Override public void handleJigsawGenerate(ServerboundJigsawGeneratePacket packet) { }
@Override public void handleSelectTrade(ServerboundSelectTradePacket packet) { }
@Override public void handleEditBook(ServerboundEditBookPacket packet) { }
@Override public void handleEntityTagQuery(ServerboundEntityTagQuery packet) { }
@Override public void handleBlockEntityTagQuery(ServerboundBlockEntityTagQuery packet) { }
@Override public void handleMovePlayer(ServerboundMovePlayerPacket packet) { }
@Override public void teleport(double x, double y, double z, float yaw, float pitch) { }
@Override public void handlePlayerAction(ServerboundPlayerActionPacket packet) { }
@Override public void handleUseItemOn(ServerboundUseItemOnPacket packet) { }
@Override public void handleUseItem(ServerboundUseItemPacket packet) { }
@Override public void handleTeleportToEntityPacket(ServerboundTeleportToEntityPacket packet) { }
@Override public void handlePaddleBoat(ServerboundPaddleBoatPacket packet) { }
@Override public void onDisconnect(Component message) { }
@Override public void send(Packet<?> packet) { }
@Override public void send(Packet<?> packet, @Nullable PacketSendListener sendListener) { }
@Override public void handleSetCarriedItem(ServerboundSetCarriedItemPacket packet) { }
@Override public void handleChat(ServerboundChatPacket packet) { }
@Override public void handleAnimate(ServerboundSwingPacket packet) { }
@Override public void handlePlayerCommand(ServerboundPlayerCommandPacket packet) { }
@Override public void handleInteract(ServerboundInteractPacket packet) { }
@Override public void handleClientCommand(ServerboundClientCommandPacket packet) { }
@Override public void handleContainerClose(ServerboundContainerClosePacket packet) { }
@Override public void handleContainerClick(ServerboundContainerClickPacket packet) { }
@Override public void handlePlaceRecipe(ServerboundPlaceRecipePacket packet) { }
@Override public void handleContainerButtonClick(ServerboundContainerButtonClickPacket packet) { }
@Override public void handleSetCreativeModeSlot(ServerboundSetCreativeModeSlotPacket packet) { }
@Override public void handleSignUpdate(ServerboundSignUpdatePacket packet) { }
@Override public void handlePlayerAbilities(ServerboundPlayerAbilitiesPacket packet) { }
@Override public void handleChangeDifficulty(ServerboundChangeDifficultyPacket packet) { }
@Override public void handleLockDifficulty(ServerboundLockDifficultyPacket packet) { }
@Override public void teleport(double x, double y, double z, float yaw, float pitch, Set<RelativeMovement> relativeSet) { }
@Override public void ackBlockChangesUpTo(int sequence) { }
@Override public void handleChatCommand(ServerboundChatCommandPacket packet) { }
@Override public void handleChatAck(ServerboundChatAckPacket packet) { }
@Override public void addPendingMessage(PlayerChatMessage message) { }
@Override public void sendPlayerChatMessage(PlayerChatMessage message, ChatType.Bound boundChatType) { }
@Override public void sendDisguisedChatMessage(Component content, ChatType.Bound boundChatType) { }
@Override public void handleChatSessionUpdate(ServerboundChatSessionUpdatePacket packet) { }
}
}
@@ -1,49 +0,0 @@
/*
* Copyright (c) Forge Development LLC and contributors
* SPDX-License-Identifier: LGPL-2.1-only
*/
package net.minecraftforge.common.util;
import java.util.Map;
import java.util.UUID;
import com.google.common.collect.Maps;
import com.mojang.authlib.GameProfile;
import net.minecraft.server.level.ServerLevel;
import net.minecraft.server.network.CommonListenerCookie;
// TODO: Re-write this whole system to be less hacky. Use until we get a good replacement.
public class FakePlayerFactory {
private static final GameProfile MINECRAFT = new GameProfile(UUID.fromString("41C82C87-7AfB-4024-BA57-13D2C99CAE77"), "[Minecraft]");
// Map of all active fake player usernames to their entities
private static final Map<FakePlayerKey, FakePlayer> fakePlayers = Maps.newHashMap();
private record FakePlayerKey(ServerLevel level, GameProfile username) { }
public static FakePlayer getMinecraft(ServerLevel level) {
return get(level, MINECRAFT);
}
/**
* Get a fake player with a given username,
* Mods should either hold weak references to the return value, or listen for a
* WorldEvent.Unload and kill all references to prevent worlds staying in memory,
* or call this function every time and let Forge take care of the cleanup.
*/
public static FakePlayer get(ServerLevel level, GameProfile username) {
FakePlayerKey key = new FakePlayerKey(level, username);
return fakePlayers.computeIfAbsent(key, FakePlayerFactory::create);
}
public static void unloadLevel(ServerLevel level) {
fakePlayers.entrySet().removeIf(entry -> entry.getValue().level() == level);
}
private static FakePlayer create(FakePlayerKey key) {
var cookie = CommonListenerCookie.createInitial(key.username());
var ret = new FakePlayer(key.level(), cookie.gameProfile(), cookie.clientInformation());
new FakePlayer.NetHandler(key.level().getServer(), ret, cookie);
return ret;
}
}
@@ -33,17 +33,16 @@ import java.util.function.Supplier;
*
* @see SoundType
*/
public class ForgeSoundType extends SoundType
{
public class ForgeSoundType extends SoundType {
private final Supplier<SoundEvent> breakSound;
private final Supplier<SoundEvent> stepSound;
private final Supplier<SoundEvent> placeSound;
private final Supplier<SoundEvent> hitSound;
private final Supplier<SoundEvent> fallSound;
public ForgeSoundType(float volumeIn, float pitchIn, Supplier<SoundEvent> breakSoundIn, Supplier<SoundEvent> stepSoundIn, Supplier<SoundEvent> placeSoundIn, Supplier<SoundEvent> hitSoundIn, Supplier<SoundEvent> fallSoundIn)
{
super(volumeIn, pitchIn, (SoundEvent) null, (SoundEvent) null, (SoundEvent) null, (SoundEvent) null, (SoundEvent) null);
@SuppressWarnings("deprecation")
public ForgeSoundType(float volumeIn, float pitchIn, Supplier<SoundEvent> breakSoundIn, Supplier<SoundEvent> stepSoundIn, Supplier<SoundEvent> placeSoundIn, Supplier<SoundEvent> hitSoundIn, Supplier<SoundEvent> fallSoundIn) {
super(volumeIn, pitchIn, null, null, null, null, null);
this.breakSound = breakSoundIn;
this.stepSound = stepSoundIn;
this.placeSound = placeSoundIn;
@@ -53,36 +52,31 @@ public class ForgeSoundType extends SoundType
@NotNull
@Override
public SoundEvent getBreakSound()
{
public SoundEvent getBreakSound() {
return breakSound.get();
}
@NotNull
@Override
public SoundEvent getStepSound()
{
public SoundEvent getStepSound() {
return stepSound.get();
}
@NotNull
@Override
public SoundEvent getPlaceSound()
{
public SoundEvent getPlaceSound() {
return placeSound.get();
}
@NotNull
@Override
public SoundEvent getHitSound()
{
public SoundEvent getHitSound() {
return hitSound.get();
}
@NotNull
@Override
public SoundEvent getFallSound()
{
public SoundEvent getFallSound() {
return fallSound.get();
}
}
@@ -5,7 +5,6 @@
package net.minecraftforge.common.util;
import java.lang.ref.WeakReference;
import java.util.HashSet;
import java.util.Objects;
import java.util.Optional;
@@ -5,53 +5,11 @@
package net.minecraftforge.common.util;
import com.google.common.base.MoreObjects;
import com.google.common.base.Preconditions;
import javax.annotation.Nonnegative;
public final class Size2i
{
@Nonnegative
public final int width;
@Nonnegative
public final int height;
@SuppressWarnings("ConstantConditions")
public Size2i(@Nonnegative int width, @Nonnegative int height)
{
public record Size2i(int width, int height) {
public Size2i {
Preconditions.checkArgument(width >= 0, "width must be greater or equal 0");
Preconditions.checkArgument(height >= 0, "height must be greater or equal 0");
this.width = width;
this.height = height;
}
@Override
public boolean equals(Object obj)
{
if (obj instanceof Size2i)
{
Size2i other = (Size2i)obj;
return (width == other.width) && (height == other.height);
}
return false;
}
@Override
public int hashCode()
{
int hash = 17;
hash = hash * 31 + width;
hash = hash * 31 + height;
return hash;
}
@Override
public String toString()
{
return MoreObjects.toStringHelper(this)
.add("width", width)
.add("height", height)
.toString();
}
}
@@ -382,7 +382,10 @@ public class ForgeEventFactory {
return post(event) ? null : event.getFinalState();
}
public static int onApplyBonemeal(@NotNull Player player, @NotNull Level level, @NotNull BlockPos pos, @NotNull BlockState state, @NotNull ItemStack stack) {
public static int onApplyBonemeal(@Nullable Player player, Level level, BlockPos pos, BlockState state, ItemStack stack) {
if (player == null)
return 0;
var event = new BonemealEvent(player, level, pos, state, stack);
if (post(event)) return -1;
if (event.getResult() == Result.ALLOW) {
@@ -22,38 +22,34 @@ import java.util.Set;
* <p>
* Fired on the Mod bus, see {@link IModBusEvent}.
*/
public class RegisterGameTestsEvent extends Event implements IModBusEvent
{
public class RegisterGameTestsEvent extends Event implements IModBusEvent {
private final Set<Method> gameTestMethods;
public RegisterGameTestsEvent(Set<Method> gameTestMethods)
{
public RegisterGameTestsEvent(Set<Method> gameTestMethods) {
this.gameTestMethods = gameTestMethods;
}
/**
* Registers an entire class to the game test registry.
* All methods annotated with {@link GameTest} or {@link GameTestGenerator} will be registered.
* If the set of enabled namespaces is non-empty,
* a method will only be registered if its {@link GameTest#templateNamespace() template namespace} is in an enabled namespace.
* If the set of enabled batches is non-empty, a method will only be registered if its
* {@link GameTest#batch() batch} is listed.
*
* @param testClass the test class to register to the game test registry
*/
public void register(Class<?> testClass)
{
public void register(Class<?> testClass) {
Arrays.stream(testClass.getDeclaredMethods()).forEach(this::register);
}
/**
* Registers a single method to the game test registry.
* The method will only be registered if it is annotated with {@link GameTest} or {@link GameTestGenerator}.
* If the set of enabled namespaces is non-empty,
* the method will only be registered if its {@link GameTest#templateNamespace() template namespace} is an enabled namespace.
* If the set of enabled batches is non-empty, the method will only be registered if its
* {@link GameTest#batch() batch} is listed.
*
* @param testMethod the test method to register to the game test registry
*/
public void register(Method testMethod)
{
public void register(Method testMethod) {
this.gameTestMethods.add(testMethod);
}
}
@@ -6,12 +6,14 @@
package net.minecraftforge.event.entity.player;
import net.minecraftforge.eventbus.api.Cancelable;
import net.minecraftforge.eventbus.api.Event.HasResult;
import net.minecraft.world.level.block.state.BlockState;
import net.minecraft.world.entity.player.Player;
import net.minecraft.world.item.ItemStack;
import net.minecraft.core.BlockPos;
import net.minecraft.world.level.Level;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
/**
* This event is called when a player attempts to use Bonemeal on a block.
@@ -23,17 +25,15 @@ import org.jetbrains.annotations.NotNull;
* setResult(ALLOW) is the same as the old setHandled()
*/
@Cancelable
@net.minecraftforge.eventbus.api.Event.HasResult
public class BonemealEvent extends PlayerEvent
{
@HasResult
// TODO: Redesign BonemealEvent the whole thing, it doens't make sense.
public class BonemealEvent extends PlayerEvent {
private final Level level;
private final BlockPos pos;
private final BlockState block;
private final ItemStack stack;
public BonemealEvent(@NotNull Player player, @NotNull Level level, @NotNull BlockPos pos, @NotNull BlockState block, @NotNull ItemStack stack)
{
public BonemealEvent(@Nullable Player player, Level level, BlockPos pos, BlockState block, ItemStack stack) {
super(player);
this.level = level;
this.pos = pos;
@@ -41,24 +41,20 @@ public class BonemealEvent extends PlayerEvent
this.stack = stack;
}
public Level getLevel()
{
public Level getLevel() {
return level;
}
public BlockPos getPos()
{
public BlockPos getPos() {
return pos;
}
public BlockState getBlock()
{
public BlockState getBlock() {
return block;
}
@NotNull
public ItemStack getStack()
{
public ItemStack getStack() {
return stack;
}
}
@@ -8,44 +8,50 @@ package net.minecraftforge.gametest;
import net.minecraft.SharedConstants;
import net.minecraft.gametest.framework.GameTest;
import net.minecraft.gametest.framework.GameTestRegistry;
import net.minecraft.gametest.framework.TestFunction;
import net.minecraftforge.event.RegisterGameTestsEvent;
import net.minecraftforge.fml.ModList;
import net.minecraftforge.fml.ModLoader;
import net.minecraftforge.fml.common.Mod;
import net.minecraftforge.fml.loading.FMLLoader;
import net.minecraftforge.forgespi.language.ModFileScanData;
import net.minecraftforge.forgespi.language.ModFileScanData.AnnotationData;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.jetbrains.annotations.ApiStatus;
import org.jetbrains.annotations.Nullable;
import org.objectweb.asm.Type;
import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashSet;
import java.util.Locale;
import java.util.Set;
import java.util.stream.Collectors;
public class ForgeGameTestHooks
{
/**
* Internal class used to glue mods into the game test framework.
* Modders should use the supplied annotations and {@link RegisterGameTestsEvent}
*/
@ApiStatus.Internal
public class ForgeGameTestHooks {
private static boolean registeredGametests = false;
private static final Logger LOGGER = LogManager.getLogger();
private static final Type GAME_TEST_HOLDER = Type.getType(GameTestHolder.class);
private static final String DEFAULT_BATCH = getDefaultBatch();
public static boolean isGametestEnabled()
{
public static boolean isGametestEnabled() {
return !FMLLoader.isProduction() && (SharedConstants.IS_RUNNING_IN_IDE || isGametestServer() || Boolean.getBoolean("forge.enableGameTest"));
}
public static boolean isGametestServer()
{
public static boolean isGametestServer() {
return !FMLLoader.isProduction() && Boolean.getBoolean("forge.gameTestServer");
}
@SuppressWarnings("deprecation")
public static void registerGametests()
{
if (!registeredGametests && isGametestEnabled() && ModLoader.isLoadingStateValid())
{
public static void registerGametests() {
if (!registeredGametests && isGametestEnabled() && ModLoader.isLoadingStateValid()) {
Set<String> enabledNamespaces = getEnabledNamespaces();
LOGGER.info("Enabled Gametest Namespaces: {}", enabledNamespaces);
@@ -55,13 +61,12 @@ public class ForgeGameTestHooks
ModLoader.get().postEvent(event);
ModList.get().getAllScanData().stream()
.map(ModFileScanData::getAnnotations)
.flatMap(Collection::stream)
.filter(a -> GAME_TEST_HOLDER.equals(a.annotationType()))
.forEach(a -> addGameTestMethods(a, gameTestMethods));
.map(ModFileScanData::getAnnotations)
.flatMap(Collection::stream)
.filter(a -> GAME_TEST_HOLDER.equals(a.annotationType()))
.forEach(a -> addGameTestMethods(a, gameTestMethods));
for (Method gameTestMethod : gameTestMethods)
{
for (Method gameTestMethod : gameTestMethods) {
GameTestRegistry.register(gameTestMethod, enabledNamespaces);
}
@@ -69,61 +74,118 @@ public class ForgeGameTestHooks
}
}
private static Set<String> getEnabledNamespaces()
{
private static Set<String> getEnabledNamespaces() {
String enabledNamespacesStr = System.getProperty("forge.enabledGameTestNamespaces");
if (enabledNamespacesStr == null)
{
return Set.of();
}
return Arrays.stream(enabledNamespacesStr.split(",")).filter(s -> !s.isBlank()).collect(Collectors.toUnmodifiableSet());
}
private static void addGameTestMethods(AnnotationData annotationData, Set<Method> gameTestMethods)
{
try
{
private static void addGameTestMethods(AnnotationData annotationData, Set<Method> gameTestMethods) {
try {
Class<?> clazz = Class.forName(annotationData.clazz().getClassName(), true, ForgeGameTestHooks.class.getClassLoader());
gameTestMethods.addAll(Arrays.asList(clazz.getDeclaredMethods()));
}
catch (ClassNotFoundException e)
{
} catch (ClassNotFoundException e) {
// Should not be possible
throw new RuntimeException(e);
}
}
public static String getTemplateNamespace(Method method)
{
GameTest gameTest = method.getAnnotation(GameTest.class);
if (gameTest != null && !gameTest.templateNamespace().isEmpty())
{
return gameTest.templateNamespace();
}
GameTestHolder gameTestHolder = method.getDeclaringClass().getAnnotation(GameTestHolder.class);
if (gameTestHolder != null)
{
return gameTestHolder.value();
}
return "minecraft";
public static String getTestName(Method method, GameTest meta) {
var name = method.getName().toLowerCase(Locale.ENGLISH);
return getPrefixed(method, name);
}
public static boolean prefixGameTestTemplate(Method method)
{
PrefixGameTestTemplate annotation = method.getAnnotation(PrefixGameTestTemplate.class);
private static String getPrefixed(Method method, String name) {
var prefix = getPrefix(method);
return prefix == null ? name : prefix + '.' + name;
}
if (annotation == null)
{
annotation = method.getDeclaringClass().getAnnotation(PrefixGameTestTemplate.class);
@Nullable
private static String getPrefix(Method method) {
var cls = method.getDeclaringClass();
var shouldPrefix = !method.isAnnotationPresent(GameTestDontPrefix.class) &&
!cls.isAnnotationPresent(GameTestDontPrefix.class);
if (!shouldPrefix)
return null;
var prefix = cls.getAnnotation(GameTestPrefix.class);
if (prefix != null)
return prefix.value();
var holder = cls.getAnnotation(GameTestHolder.class);
if (holder != null && !holder.value().isEmpty())
return holder.value();
var mod = method.getDeclaringClass().getAnnotation(Mod.class);
if (mod != null)
return mod.value();
return cls.getSimpleName().toLowerCase(Locale.ENGLISH);
}
public static String getTestTemplate(Method method, GameTest meta, String testName) {
// If we have a ':' assume we specified the exact template path
if (meta.template().indexOf(':') != -1)
return meta.template();
String template = null;
if (meta.template().isEmpty())
template = testName;
else
template = getPrefixed(method, meta.template());
var cls = method.getDeclaringClass();
var holder = cls.getAnnotation(GameTestHolder.class);
if (holder != null && !holder.namespace().isEmpty())
return holder.namespace() + ':' + template;
var mod = cls.getAnnotation(Mod.class);
if (mod != null)
return mod.value() + ':' + template;
return template;
}
private static String getDefaultBatch() {
try {
return (String)GameTest.class.getDeclaredMethod("batch").getDefaultValue();
} catch (NoSuchMethodException | SecurityException e) {
e.printStackTrace(); // Should never happen, but just in case.
return "defaultBatch";
}
}
public static String getTestBatch(Method method, GameTest gametest) {
var batch = gametest.batch();
if (DEFAULT_BATCH.equals(batch)) {
var prefix = getPrefix(method);
return prefix == null ? batch : prefix;
}
// The vanilla game test system prefixes the classname by default, so we preserve that behavior here.
return annotation == null || annotation.value();
return getPrefixed(method, batch.toLowerCase(Locale.ENGLISH));
}
public static void addTest(Collection<TestFunction> functions, Set<String> classes, Set<String> filters, TestFunction func) {
boolean allowed = filters.isEmpty() || filters.stream().anyMatch(f -> f.equals(func.getBatchName()) || func.getBatchName().startsWith(f + '.'));
if (!allowed)
return;
functions.add(func);
var batch = func.getBatchName();
classes.add(batch);
int idx = batch.indexOf('.');
while (idx != -1) {
batch = batch.substring(0, idx);
idx = batch.indexOf('.');
classes.add(batch);
}
}
}
@@ -0,0 +1,22 @@
/*
* Copyright (c) Forge Development LLC and contributors
* SPDX-License-Identifier: LGPL-2.1-only
*/
package net.minecraftforge.gametest;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* When used on a class, this disables the prefix for all contained tests.
* <p>
* When used on a method, this disables it for the single test.
*
* @see GameTestPrefix
*/
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.TYPE, ElementType.METHOD})
public @interface GameTestDontPrefix {}
@@ -19,10 +19,31 @@ import java.lang.annotation.Target;
*/
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
public @interface GameTestHolder
{
public @interface GameTestHolder {
/**
* Used as the default {@link GameTest#templateNamespace() template namespace} for any game tests in the class that do not specify one.
* The default batch for all tests in this class that do not manually specify one.
* It it recommended that this includes your mod id.
* <br/>
* This is also used when filtering out which batches to run during automation.
* the filters will be tested against the prefix of the batch name. So it is
* recommended to be structured in a logical fashion.
* <pre>
* Examples:
* forge.tags.items
* forge.tags.blocks
* forge.global_loot_modifiers.block_drops
* forge.global_loot_modifiers.tool_filter
* </pre>
*
* The filter 'forge.global_loot_modifiers' would execute both the block_drops and tool_filter batches.
* <p>
* This will default to your modid if it is on the same class that is annotated with {@link net.minecraftforge.fml.common.Mod @Mod}
*/
String value() default "minecraft";
String value() default "";
/**
* Used as the default namespace to use for {@link GameTest#template() templates} for any game tests in the class.
* Defaults to the modid if in a class with @Mod or else defaults to "minecraft"
*/
String namespace() default "";
}
@@ -7,10 +7,8 @@ package net.minecraftforge.gametest;
import net.minecraft.server.Main;
public class GameTestMain
{
public static void main(String[] args)
{
public class GameTestMain {
public static void main(String[] args) {
System.setProperty("forge.enableGameTest", "true");
System.setProperty("forge.gameTestServer", "true");
Main.main(args);
@@ -0,0 +1,27 @@
/*
* Copyright (c) Forge Development LLC and contributors
* SPDX-License-Identifier: LGPL-2.1-only
*/
package net.minecraftforge.gametest;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* This sets the prefix to prepend to test names and templates.
* <p>
* If this annotation cannot be found the default behavior is to
* look for the {@ Mod @Mod} annotation and use the mod id. If that is
* not found the {@link Class#getSimpleName() simple class name} is used.
*/
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.TYPE})
public @interface GameTestPrefix {
/**
* The prefix to use instead of {@link Class#getSimpleName() simple class name}
*/
String value();
}
@@ -1,38 +0,0 @@
/*
* Copyright (c) Forge Development LLC and contributors
* SPDX-License-Identifier: LGPL-2.1-only
*/
package net.minecraftforge.gametest;
import net.minecraft.gametest.framework.GameTest;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* When used on a class, this sets the default state for whether
* to prefix any contained game test templates with the {@link Class#getSimpleName() simple class name} or not.
* <p>
* When used on a method, this defines whether the specific method should be prefixed with the simple class name or not.
* <p>
* If this annotation cannot be found on a game test method or its containing class, the default behavior is to prefix the class name.
* <p>
* Method annotations override any class annotations.
*
* @see GameTestHolder
*/
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.TYPE, ElementType.METHOD})
public @interface PrefixGameTestTemplate
{
/**
* Whether to prefix the game test template with the containing class' {@link Class#getSimpleName() simple name}.
* For example, true in a class named "MyTest" would result in "mytest.structure" while false would result in "structure".
* <p>
* Only applies to methods annotated with {@link GameTest}.
*/
boolean value() default true;
}