Update to 1.17

Update to Official classnames
Patchwork
Make the game compile and run
Merge in the new HUD overlay API
Merge in the new render properties API
PEEL
Use Gradle 7.2 snapshot to fix eclipse integration bug in 7.1, Would use 7.0 but FG needs 7.1 for some reason.
New FML installer
Update to 1.17.1

Co-authored-by: LexManos <[email protected]>
Co-authored-by: SizableShrimp <[email protected]>
Co-authored-by: cpw <[email protected]>
Co-authored-by: Curle <[email protected]>
Co-authored-by: Unnoen <[email protected]>
Co-authored-by: covers1624 <[email protected]>
Co-authored-by: DaemonUmbra <[email protected]>
Co-authored-by: gigaherz <[email protected]>
Signed-off-by: SizableShrimp <[email protected]>
This commit is contained in:
authored and Curle committed 2021-07-22 19:57:02 +01:00
1 parent 064ae6961b
commit be5446b91c
1990 files changed
+35661 -37544

No files matched your search

@@ -24,7 +24,7 @@ import com.google.common.graph.GraphBuilder;
import com.google.common.graph.MutableGraph;
import net.minecraft.advancements.Advancement;
import net.minecraft.advancements.AdvancementProgress;
import net.minecraft.advancements.PlayerAdvancements;
import net.minecraft.server.PlayerAdvancements;
import net.minecraftforge.fml.loading.toposort.TopologicalSort;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
@@ -23,17 +23,17 @@ import java.util.Random;
import javax.annotation.Nullable;
import net.minecraft.entity.Entity;
import net.minecraft.entity.merchant.villager.VillagerTrades.ITrade;
import net.minecraft.item.ItemStack;
import net.minecraft.item.Items;
import net.minecraft.item.MerchantOffer;
import net.minecraft.world.entity.Entity;
import net.minecraft.world.entity.npc.VillagerTrades.ItemListing;
import net.minecraft.world.item.ItemStack;
import net.minecraft.world.item.Items;
import net.minecraft.world.item.trading.MerchantOffer;
/**
* A default, exposed implementation of ITrade. All of the other implementations of ITrade (in VillagerTrades) are not public.
* This class contains everything needed to make a MerchantOffer, the actual "trade" object shown in trading guis.
*/
public class BasicTrade implements ITrade
public class BasicTrade implements ItemListing
{
protected final ItemStack price;
@@ -29,15 +29,16 @@ import javax.annotation.Nullable;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import net.minecraft.world.biome.Biomes;
import net.minecraft.util.RegistryKey;
import net.minecraft.util.registry.Registry;
import net.minecraft.world.biome.*;
import net.minecraft.world.level.biome.Biomes;
import net.minecraft.resources.ResourceKey;
import net.minecraft.core.Registry;
import static net.minecraftforge.common.BiomeDictionary.Type.*;
import net.minecraftforge.registries.ForgeRegistries;
import com.google.common.collect.ImmutableList;
import net.minecraft.world.level.biome.Biome;
public class BiomeDictionary
{
private static final boolean DEBUG = false;
@@ -103,8 +104,8 @@ public class BiomeDictionary
private final String name;
private final List<Type> subTypes;
private final Set<RegistryKey<Biome>> biomes = new HashSet<>();
private final Set<RegistryKey<Biome>> biomesUn = Collections.unmodifiableSet(biomes);
private final Set<ResourceKey<Biome>> biomes = new HashSet<>();
private final Set<ResourceKey<Biome>> biomesUn = Collections.unmodifiableSet(biomes);
private Type(String name, Type... subTypes)
{
@@ -164,17 +165,17 @@ public class BiomeDictionary
}
@Nullable
public static Type fromVanilla(Biome.Category category)
public static Type fromVanilla(Biome.BiomeCategory category)
{
if (category == Biome.Category.NONE)
if (category == Biome.BiomeCategory.NONE)
return null;
if (category == Biome.Category.THEEND)
if (category == Biome.BiomeCategory.THEEND)
return VOID;
return getType(category.name());
}
}
private static final Map<RegistryKey<Biome>, BiomeInfo> biomeInfoMap = new HashMap<>();
private static final Map<ResourceKey<Biome>, BiomeInfo> biomeInfoMap = new HashMap<>();
private static class BiomeInfo
{
@@ -192,7 +193,7 @@ public class BiomeDictionary
* Adds the given types to the biome.
*
*/
public static void addTypes(RegistryKey<Biome> biome, Type... types)
public static void addTypes(ResourceKey<Biome> biome, Type... types)
{
Collection<Type> supertypes = listSupertypes(types);
Collections.addAll(supertypes, types);
@@ -212,7 +213,7 @@ public class BiomeDictionary
*
*/
@Nonnull
public static Set<RegistryKey<Biome>> getBiomes(Type type)
public static Set<ResourceKey<Biome>> getBiomes(Type type)
{
return type.biomesUn;
}
@@ -222,7 +223,7 @@ public class BiomeDictionary
*
*/
@Nonnull
public static Set<Type> getTypes(RegistryKey<Biome> biome)
public static Set<Type> getTypes(ResourceKey<Biome> biome)
{
return getBiomeInfo(biome).typesUn;
}
@@ -232,7 +233,7 @@ public class BiomeDictionary
*
* @return returns true if a common type is found, false otherwise
*/
public static boolean areSimilar(RegistryKey<Biome> biomeA, RegistryKey<Biome> biomeB)
public static boolean areSimilar(ResourceKey<Biome> biomeA, ResourceKey<Biome> biomeB)
{
Set<Type> typesA = getTypes(biomeA);
Set<Type> typesB = getTypes(biomeB);
@@ -243,7 +244,7 @@ public class BiomeDictionary
* Checks if the given type has been added to the given biome.
*
*/
public static boolean hasType(RegistryKey<Biome> biome, Type type)
public static boolean hasType(ResourceKey<Biome> biome, Type type)
{
return getTypes(biome).contains(type);
}
@@ -252,13 +253,13 @@ public class BiomeDictionary
* Checks if any type has been added to the given biome.
*
*/
public static boolean hasAnyType(RegistryKey<Biome> biome)
public static boolean hasAnyType(ResourceKey<Biome> biome)
{
return !getBiomeInfo(biome).types.isEmpty();
}
//Internal implementation
private static BiomeInfo getBiomeInfo(RegistryKey<Biome> biome)
private static BiomeInfo getBiomeInfo(ResourceKey<Biome> biome)
{
return biomeInfoMap.computeIfAbsent(biome, k -> new BiomeInfo());
}
@@ -372,7 +373,7 @@ public class BiomeDictionary
Type.byName.forEach((name, type) ->
buf.append(" ").append(type.name).append(": ")
.append(type.biomes.stream()
.map(RegistryKey::location)
.map(ResourceKey::location)
.sorted((a,b) -> a.compareNamespaced(b))
.map(Object::toString)
.collect(Collectors.joining(", "))
@@ -381,11 +382,11 @@ public class BiomeDictionary
);
boolean missing = false;
List<RegistryKey<Biome>> all = StreamSupport.stream(ForgeRegistries.BIOMES.spliterator(), false)
.map(b -> RegistryKey.create(Registry.BIOME_REGISTRY, b.getRegistryName()))
List<ResourceKey<Biome>> all = StreamSupport.stream(ForgeRegistries.BIOMES.spliterator(), false)
.map(b -> ResourceKey.create(Registry.BIOME_REGISTRY, b.getRegistryName()))
.sorted().collect(Collectors.toList());
for (RegistryKey<Biome> key : all) {
for (ResourceKey<Biome> key : all) {
if (!biomeInfoMap.containsKey(key)) {
if (!missing) {
buf.append("Missing:\n");
@@ -27,16 +27,16 @@ import java.util.List;
import com.google.common.collect.ImmutableList;
import net.minecraft.world.biome.Biomes;
import net.minecraft.util.RegistryKey;
import net.minecraft.util.WeightedRandom;
import net.minecraft.world.biome.Biome;
import net.minecraft.world.level.biome.Biomes;
import net.minecraft.resources.ResourceKey;
import net.minecraft.util.WeighedRandom;
import net.minecraft.world.level.biome.Biome;
public class BiomeManager
{
private static TrackedList<BiomeEntry>[] biomes = setupBiomes();
private static final List<RegistryKey<Biome>> additionalOverworldBiomes = new ArrayList<>();
private static final List<RegistryKey<Biome>> additionalOverworldBiomesView = Collections.unmodifiableList(additionalOverworldBiomes);
private static final List<ResourceKey<Biome>> additionalOverworldBiomes = new ArrayList<>();
private static final List<ResourceKey<Biome>> additionalOverworldBiomesView = Collections.unmodifiableList(additionalOverworldBiomes);
private static TrackedList<BiomeEntry>[] setupBiomes()
{
@@ -103,7 +103,7 @@ public class BiomeManager
/**
* Add biomes that you add to the overworld without using {@link BiomeManager#addBiome(BiomeType, BiomeEntry)}
*/
public static void addAdditionalOverworldBiomes(RegistryKey<Biome> biome)
public static void addAdditionalOverworldBiomes(ResourceKey<Biome> biome)
{
if (!"minecraft".equals(biome.location().getNamespace()) && additionalOverworldBiomes.stream().noneMatch(entry -> entry.location().equals(biome.location())))
{
@@ -133,7 +133,7 @@ public class BiomeManager
/**
* @return list of biomes that might be generated in the overworld in addition to the vanilla biomes
*/
public static List<RegistryKey<Biome>> getAdditionalOverworldBiomes()
public static List<ResourceKey<Biome>> getAdditionalOverworldBiomes()
{
return additionalOverworldBiomesView;
}
@@ -157,17 +157,17 @@ public class BiomeManager
DESERT, DESERT_LEGACY, WARM, COOL, ICY;
}
public static class BiomeEntry extends WeightedRandom.Item
public static class BiomeEntry extends WeighedRandom.WeighedRandomItem
{
private final RegistryKey<Biome> key;
private final ResourceKey<Biome> key;
public BiomeEntry(RegistryKey<Biome> key, int weight)
public BiomeEntry(ResourceKey<Biome> key, int weight)
{
super(weight);
this.key = key;
}
public RegistryKey<Biome> getKey()
public ResourceKey<Biome> getKey()
{
return this.key;
}
@@ -23,8 +23,8 @@ import java.util.ArrayList;
import java.util.Iterator;
import java.util.Random;
import net.minecraft.entity.EntityType;
import net.minecraft.util.WeightedRandom;
import net.minecraft.world.entity.EntityType;
import net.minecraft.util.WeighedRandom;
public class DungeonHooks
{
@@ -93,12 +93,12 @@ public class DungeonHooks
*/
public static EntityType<?> getRandomDungeonMob(Random rand)
{
DungeonMob mob = WeightedRandom.getRandomItem(rand, dungeonMobs);
DungeonMob mob = WeighedRandom.getRandomItem(rand, dungeonMobs).orElseThrow();
return mob.type;
}
public static class DungeonMob extends WeightedRandom.Item
public static class DungeonMob extends WeighedRandom.WeighedRandomItem
{
public final EntityType<?> type;
public DungeonMob(int weight, EntityType<?> type)
@@ -21,13 +21,13 @@ package net.minecraftforge.common;
import com.google.common.base.Preconditions;
import com.google.common.collect.MapMaker;
import net.minecraft.util.math.AxisAlignedBB;
import net.minecraft.util.math.BlockPos;
import net.minecraft.util.math.ChunkPos;
import net.minecraft.util.math.vector.Vector3d;
import net.minecraft.world.IWorldReader;
import net.minecraft.world.World;
import net.minecraft.world.chunk.IChunk;
import net.minecraft.world.phys.AABB;
import net.minecraft.core.BlockPos;
import net.minecraft.world.level.ChunkPos;
import net.minecraft.world.phys.Vec3;
import net.minecraft.world.level.LevelReader;
import net.minecraft.world.level.Level;
import net.minecraft.world.level.chunk.ChunkAccess;
import net.minecraftforge.common.ticket.AABBTicket;
import net.minecraftforge.common.ticket.ChunkTicketManager;
import net.minecraftforge.common.ticket.SimpleTicket;
@@ -42,7 +42,7 @@ import java.util.WeakHashMap;
public class FarmlandWaterManager
{
private static final boolean DEBUG = Boolean.parseBoolean(System.getProperty("forge.debugFarmlandWaterManager", "false"));
private static final Map<IWorldReader, Map<ChunkPos, ChunkTicketManager<Vector3d>>> customWaterHandler = new WeakHashMap<>();
private static final Map<LevelReader, Map<ChunkPos, ChunkTicketManager<Vec3>>> customWaterHandler = new WeakHashMap<>();
private static final Logger LOGGER = LogManager.getLogger();
/**
@@ -58,11 +58,11 @@ public class FarmlandWaterManager
* @return The ticket for your requested region.
*/
@SuppressWarnings("unchecked")
public static<T extends SimpleTicket<Vector3d>> T addCustomTicket(World world, T ticket, ChunkPos masterChunk, ChunkPos... additionalChunks)
public static<T extends SimpleTicket<Vec3>> T addCustomTicket(Level world, T ticket, ChunkPos masterChunk, ChunkPos... additionalChunks)
{
Preconditions.checkArgument(!world.isClientSide, "Water region is only determined server-side");
Map<ChunkPos, ChunkTicketManager<Vector3d>> ticketMap = customWaterHandler.computeIfAbsent(world, id -> new MapMaker().weakValues().makeMap());
ChunkTicketManager<Vector3d>[] additionalTickets = new ChunkTicketManager[additionalChunks.length];
Map<ChunkPos, ChunkTicketManager<Vec3>> ticketMap = customWaterHandler.computeIfAbsent(world, id -> new MapMaker().weakValues().makeMap());
ChunkTicketManager<Vec3>[] additionalTickets = new ChunkTicketManager[additionalChunks.length];
for (int i = 0; i < additionalChunks.length; i++)
additionalTickets[i] = ticketMap.computeIfAbsent(additionalChunks[i], ChunkTicketManager::new);
ticket.setManager(ticketMap.computeIfAbsent(masterChunk, ChunkTicketManager::new), additionalTickets);
@@ -81,7 +81,7 @@ public class FarmlandWaterManager
* @param aabb The region where blocks should be watered
* @return The ticket for your requested region.
*/
public static AABBTicket addAABBTicket(World world, AxisAlignedBB aabb)
public static AABBTicket addAABBTicket(Level world, AABB aabb)
{
if (DEBUG)
LOGGER.info("FarmlandWaterManager: New AABBTicket, aabb={}", aabb);
@@ -115,7 +115,7 @@ public class FarmlandWaterManager
return addCustomTicket(world, new AABBTicket(aabb), masterPos, posSet.toArray(new ChunkPos[0]));
}
private static double getDistanceSq(ChunkPos pos, Vector3d vec3d)
private static double getDistanceSq(ChunkPos pos, Vec3 vec3d)
{
//See ChunkPos#getDistanceSq
double d0 = (double)(pos.x * 16 + 8);
@@ -129,13 +129,13 @@ public class FarmlandWaterManager
* Tests if a block is in a region that is watered by blocks. This does not check vanilla water, see {@link net.minecraft.block.FarmlandBlock#hasWater(IWorldReader, BlockPos)}
* @return true if there is a ticket with an AABB that includes your block
*/
public static boolean hasBlockWaterTicket(IWorldReader world, BlockPos pos)
public static boolean hasBlockWaterTicket(LevelReader world, BlockPos pos)
{
ChunkTicketManager<Vector3d> ticketManager = getTicketManager(new ChunkPos(pos.getX() >> 4, pos.getZ() >> 4), world);
ChunkTicketManager<Vec3> ticketManager = getTicketManager(new ChunkPos(pos.getX() >> 4, pos.getZ() >> 4), world);
if (ticketManager != null)
{
Vector3d posAsVec3d = new Vector3d(pos.getX() + 0.5, pos.getY() + 0.5, pos.getZ() + 0.5);
for (SimpleTicket<Vector3d> ticket : ticketManager.getTickets()) {
Vec3 posAsVec3d = new Vec3(pos.getX() + 0.5, pos.getY() + 0.5, pos.getZ() + 0.5);
for (SimpleTicket<Vec3> ticket : ticketManager.getTickets()) {
if (ticket.matches(posAsVec3d))
return true;
}
@@ -143,9 +143,9 @@ public class FarmlandWaterManager
return false;
}
static void removeTickets(IChunk chunk)
static void removeTickets(ChunkAccess chunk)
{
ChunkTicketManager<Vector3d> ticketManager = getTicketManager(chunk.getPos(), chunk.getWorldForge());
ChunkTicketManager<Vec3> ticketManager = getTicketManager(chunk.getPos(), chunk.getWorldForge());
if (ticketManager != null)
{
if (DEBUG)
@@ -156,9 +156,9 @@ public class FarmlandWaterManager
}
}
private static ChunkTicketManager<Vector3d> getTicketManager(ChunkPos pos, IWorldReader world) {
private static ChunkTicketManager<Vec3> getTicketManager(ChunkPos pos, LevelReader world) {
Preconditions.checkArgument(!world.isClientSide(), "Water region is only determined server-side");
Map<ChunkPos, ChunkTicketManager<Vector3d>> ticketMap = customWaterHandler.get(world);
Map<ChunkPos, ChunkTicketManager<Vec3>> ticketMap = customWaterHandler.get(world);
if (ticketMap == null)
{
return null;
@@ -19,10 +19,10 @@
package net.minecraftforge.common;
import static net.minecraftforge.fml.loading.LogMarkers.FORGEMOD;
import static net.minecraftforge.fml.Logging.FORGEMOD;
import net.minecraftforge.eventbus.api.SubscribeEvent;
import net.minecraftforge.fml.config.ModConfig;
import net.minecraftforge.fml.event.config.ModConfigEvent;
import org.apache.commons.lang3.tuple.Pair;
import org.apache.logging.log4j.LogManager;
@@ -34,7 +34,7 @@ public class ForgeConfig
{
public static class Server {
public final BooleanValue removeErroringEntities;
public final BooleanValue removeErroringTileEntities;
public final BooleanValue removeErroringBlockEntities;
public final BooleanValue fullBoundingBoxLadders;
@@ -60,11 +60,11 @@ public class ForgeConfig
.worldRestart()
.define("removeErroringEntities", false);
removeErroringTileEntities = builder
.comment("Set this to true to remove any TileEntity that throws an error in its update method instead of closing the server and reporting a crash log. BE WARNED THIS COULD SCREW UP EVERYTHING USE SPARINGLY WE ARE NOT RESPONSIBLE FOR DAMAGES.")
.translation("forge.configgui.removeErroringTileEntities")
removeErroringBlockEntities = builder
.comment("Set this to true to remove any BlockEntity that throws an error in its update method instead of closing the server and reporting a crash log. BE WARNED THIS COULD SCREW UP EVERYTHING USE SPARINGLY WE ARE NOT RESPONSIBLE FOR DAMAGES.")
.translation("forge.configgui.removeErroringBlockEntities")
.worldRestart()
.define("removeErroringTileEntities", false);
.define("removeErroringBlockEntities", false);
fullBoundingBoxLadders = builder
.comment("Set this to true to check the entire entity's collision bounding box for ladders instead of just the block they are in. Causes noticeable differences in mechanics so default is vanilla behavior. Default: false.")
@@ -237,12 +237,12 @@ public class ForgeConfig
}
@SubscribeEvent
public static void onLoad(final ModConfig.Loading configEvent) {
public static void onLoad(final ModConfigEvent.Loading configEvent) {
LogManager.getLogger().debug(FORGEMOD, "Loaded forge config file {}", configEvent.getConfig().getFileName());
}
@SubscribeEvent
public static void onFileChange(final ModConfig.Reloading configEvent) {
public static void onFileChange(final ModConfigEvent.Reloading configEvent) {
LogManager.getLogger().debug(FORGEMOD, "Forge config just got changed on the file system!");
}
@@ -44,7 +44,7 @@ import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import com.google.common.annotations.VisibleForTesting;
import net.minecraft.util.SharedConstants;
import net.minecraftforge.fml.config.IConfigSpec;
import net.minecraftforge.fml.loading.FMLEnvironment;
import org.apache.commons.lang3.tuple.Pair;
import org.apache.logging.log4j.LogManager;
@@ -68,7 +68,7 @@ import com.google.common.collect.ObjectArrays;
* Like {@link com.electronwill.nightconfig.core.ConfigSpec} except in builder format, and extended to accept comments, language keys,
* and other things Forge configs would find useful.
*/
public class ForgeConfigSpec extends UnmodifiableConfigWrapper<UnmodifiableConfig> //TODO: Remove extends and pipe everything through getSpec/getValues?
public class ForgeConfigSpec extends UnmodifiableConfigWrapper<UnmodifiableConfig> implements IConfigSpec<ForgeConfigSpec>//TODO: Remove extends and pipe everything through getSpec/getValues?
{
private Map<List<String>, String> levelComments = new HashMap<>();
@@ -101,6 +101,11 @@ public class ForgeConfigSpec extends UnmodifiableConfigWrapper<UnmodifiableConfi
this.afterReload();
}
@Override
public void acceptConfig(final CommentedConfig data) {
setConfig(data);
}
public boolean isCorrecting() {
return isCorrecting;
}
@@ -638,7 +643,11 @@ public class ForgeConfigSpec extends UnmodifiableConfigWrapper<UnmodifiableConfi
private boolean worldRestart = false;
private Class<?> clazz;
public void setComment(String... value) { this.comment = value == null ? new String[] {""} : value; } // TODO 1.17: this should throw an IllegalStateException in future
public void setComment(String... value)
{
validate(value == null, "Passed in null value for comment");
this.comment = value;
}
public boolean hasComment() { return this.comment.length > 0; }
public String[] getComment() { return this.comment; }
public String buildComment() { return LINE_JOINER.join(comment); }
@@ -793,8 +802,7 @@ public class ForgeConfigSpec extends UnmodifiableConfigWrapper<UnmodifiableConfi
public static class ConfigValue<T>
{
@VisibleForTesting
static boolean USE_CACHES = true;
private static boolean USE_CACHES = true;
private final Builder parent;
private final List<String> path;
@@ -55,85 +55,77 @@ import javax.annotation.Nullable;
import it.unimi.dsi.fastutil.longs.LongSet;
import net.minecraft.advancements.Advancement;
import net.minecraft.block.Block;
import net.minecraft.block.material.Material;
import net.minecraft.entity.ai.attributes.Attribute;
import net.minecraft.entity.ai.attributes.AttributeModifier;
import net.minecraft.entity.ai.attributes.AttributeModifierMap;
import net.minecraft.entity.ai.attributes.GlobalEntityTypeAttributes;
import net.minecraft.fluid.*;
import net.minecraft.inventory.EquipmentSlotType;
import net.minecraft.item.crafting.IRecipeType;
import net.minecraft.loot.LootContext;
import net.minecraft.loot.LootTable;
import net.minecraft.loot.LootTableManager;
import net.minecraft.tags.ITag;
import net.minecraft.world.level.block.Block;
import net.minecraft.world.entity.ai.attributes.Attribute;
import net.minecraft.world.entity.ai.attributes.AttributeModifier;
import net.minecraft.world.entity.ai.attributes.AttributeSupplier;
import net.minecraft.world.entity.ai.attributes.DefaultAttributes;
import net.minecraft.world.entity.EquipmentSlot;
import net.minecraft.world.item.crafting.RecipeType;
import net.minecraft.world.level.storage.loot.LootContext;
import net.minecraft.world.level.storage.loot.LootTable;
import net.minecraft.world.level.storage.loot.LootTables;
import net.minecraft.tags.Tag;
import net.minecraft.util.*;
import net.minecraft.block.BlockState;
import net.minecraft.world.level.block.state.BlockState;
import net.minecraft.client.Minecraft;
import net.minecraft.client.gui.screen.Screen;
import net.minecraft.enchantment.EnchantmentHelper;
import net.minecraft.entity.Entity;
import net.minecraft.entity.EntityType;
import net.minecraft.entity.MobEntity;
import net.minecraft.entity.SpawnReason;
import net.minecraft.entity.LivingEntity;
import net.minecraft.entity.item.ItemEntity;
import net.minecraft.entity.item.minecart.ContainerMinecartEntity;
import net.minecraft.entity.player.PlayerEntity;
import net.minecraft.entity.player.ServerPlayerEntity;
import net.minecraft.entity.player.PlayerInventory;
import net.minecraft.block.Blocks;
import net.minecraft.inventory.container.RepairContainer;
import net.minecraft.inventory.IInventory;
import net.minecraft.item.Item;
import net.minecraft.item.AxeItem;
import net.minecraft.item.BucketItem;
import net.minecraft.item.EnchantedBookItem;
import net.minecraft.item.HoeItem;
import net.minecraft.item.PickaxeItem;
import net.minecraft.item.PotionItem;
import net.minecraft.item.ShovelItem;
import net.minecraft.item.SpawnEggItem;
import net.minecraft.item.ItemStack;
import net.minecraft.item.TippedArrowItem;
import net.minecraft.item.ItemUseContext;
import net.minecraft.nbt.CompoundNBT;
import net.minecraft.nbt.ListNBT;
import net.minecraft.network.play.ServerPlayNetHandler;
import net.minecraft.network.IPacket;
import net.minecraft.network.datasync.IDataSerializer;
import net.minecraft.network.play.server.SChangeBlockPacket;
import net.minecraft.potion.Potion;
import net.minecraft.potion.PotionUtils;
import net.minecraft.client.gui.screens.Screen;
import net.minecraft.world.item.enchantment.EnchantmentHelper;
import net.minecraft.world.entity.Entity;
import net.minecraft.world.entity.EntityType;
import net.minecraft.world.entity.Mob;
import net.minecraft.world.entity.MobSpawnType;
import net.minecraft.world.entity.LivingEntity;
import net.minecraft.world.entity.item.ItemEntity;
import net.minecraft.world.entity.vehicle.AbstractMinecartContainer;
import net.minecraft.world.entity.player.Player;
import net.minecraft.server.level.ServerPlayer;
import net.minecraft.world.entity.player.Inventory;
import net.minecraft.world.level.block.Blocks;
import net.minecraft.world.inventory.AnvilMenu;
import net.minecraft.world.Container;
import net.minecraft.world.item.Item;
import net.minecraft.world.item.BucketItem;
import net.minecraft.world.item.EnchantedBookItem;
import net.minecraft.world.item.PotionItem;
import net.minecraft.world.item.SpawnEggItem;
import net.minecraft.world.item.ItemStack;
import net.minecraft.world.item.TippedArrowItem;
import net.minecraft.world.item.context.UseOnContext;
import net.minecraft.nbt.CompoundTag;
import net.minecraft.nbt.ListTag;
import net.minecraft.server.network.ServerGamePacketListenerImpl;
import net.minecraft.network.protocol.Packet;
import net.minecraft.network.syncher.EntityDataSerializer;
import net.minecraft.network.protocol.game.ClientboundBlockUpdatePacket;
import net.minecraft.world.item.alchemy.Potion;
import net.minecraft.world.item.alchemy.PotionUtils;
import net.minecraft.stats.Stats;
import net.minecraft.util.math.vector.Vector3d;
import net.minecraft.util.registry.DynamicRegistries;
import net.minecraft.util.registry.Registry;
import net.minecraft.util.registry.SimpleRegistry;
import net.minecraft.util.registry.WorldSettingsImport;
import net.minecraft.util.registry.WorldGenSettingsExport;
import net.minecraft.util.text.*;
import net.minecraft.world.phys.Vec3;
import net.minecraft.core.RegistryAccess;
import net.minecraft.core.Registry;
import net.minecraft.core.MappedRegistry;
import net.minecraft.resources.RegistryReadOps;
import net.minecraft.resources.RegistryWriteOps;
import net.minecraft.world.*;
import net.minecraft.world.chunk.IChunk;
import net.minecraft.world.gen.DimensionSettings;
import net.minecraft.world.gen.feature.structure.Structure;
import net.minecraft.world.gen.settings.DimensionGeneratorSettings;
import net.minecraft.world.spawner.AbstractSpawner;
import net.minecraft.tileentity.FurnaceTileEntity;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.util.SoundEvents;
import net.minecraft.util.math.AxisAlignedBB;
import net.minecraft.util.math.BlockPos;
import net.minecraft.util.math.MathHelper;
import net.minecraft.util.math.RayTraceResult;
import net.minecraft.util.math.BlockRayTraceResult;
import net.minecraft.util.math.EntityRayTraceResult;
import net.minecraft.util.text.event.ClickEvent;
import net.minecraft.world.biome.Biome;
import net.minecraft.world.biome.BiomeAmbience;
import net.minecraft.world.biome.BiomeGenerationSettings;
import net.minecraft.world.biome.MobSpawnInfo;
import net.minecraft.world.level.chunk.ChunkAccess;
import net.minecraft.world.level.levelgen.NoiseGeneratorSettings;
import net.minecraft.world.level.levelgen.feature.StructureFeature;
import net.minecraft.world.level.levelgen.WorldGenSettings;
import net.minecraft.world.level.BaseSpawner;
import net.minecraft.world.level.block.entity.FurnaceBlockEntity;
import net.minecraft.world.level.block.entity.BlockEntity;
import net.minecraft.sounds.SoundEvents;
import net.minecraft.world.phys.AABB;
import net.minecraft.core.BlockPos;
import net.minecraft.world.phys.HitResult;
import net.minecraft.world.phys.BlockHitResult;
import net.minecraft.world.phys.EntityHitResult;
import net.minecraft.network.chat.ClickEvent;
import net.minecraft.world.level.biome.Biome;
import net.minecraft.world.level.biome.BiomeSpecialEffects;
import net.minecraft.world.level.biome.BiomeGenerationSettings;
import net.minecraft.world.level.biome.MobSpawnSettings;
import net.minecraftforge.common.loot.IGlobalLootModifier;
import net.minecraftforge.common.loot.LootModifierManager;
import net.minecraftforge.common.loot.LootTableIdCondition;
@@ -174,8 +166,8 @@ import net.minecraftforge.event.world.NoteBlockEvent;
import net.minecraftforge.eventbus.api.Event.Result;
import net.minecraftforge.fluids.FluidAttributes;
import net.minecraftforge.fml.ModLoader;
import net.minecraftforge.fml.common.ObfuscationReflectionHelper;
import net.minecraftforge.fml.packs.ResourcePackLoader;
import net.minecraftforge.fml.util.ObfuscationReflectionHelper;
import net.minecraftforge.fmllegacy.packs.ResourcePackLoader;
import net.minecraftforge.registries.DataSerializerEntry;
import net.minecraftforge.registries.ForgeRegistries;
import net.minecraftforge.registries.ForgeRegistry;
@@ -188,6 +180,30 @@ import org.apache.logging.log4j.Marker;
import org.apache.logging.log4j.MarkerManager;
import org.apache.logging.log4j.util.TriConsumer;
import net.minecraft.ChatFormatting;
import net.minecraft.core.Direction;
import net.minecraft.network.chat.Component;
import net.minecraft.network.chat.MutableComponent;
import net.minecraft.network.chat.TextColor;
import net.minecraft.network.chat.TextComponent;
import net.minecraft.resources.ResourceKey;
import net.minecraft.resources.ResourceLocation;
import net.minecraft.world.damagesource.DamageSource;
import net.minecraft.world.level.BlockGetter;
import net.minecraft.world.level.GameType;
import net.minecraft.world.level.Level;
import net.minecraft.world.level.LevelAccessor;
import net.minecraft.world.level.LevelReader;
import net.minecraft.world.level.block.state.pattern.BlockInWorld;
import net.minecraft.world.level.dimension.DimensionType;
import net.minecraft.world.level.dimension.LevelStem;
import net.minecraft.world.level.material.EmptyFluid;
import net.minecraft.world.level.material.Fluid;
import net.minecraft.world.level.material.FluidState;
import net.minecraft.world.level.material.Fluids;
import net.minecraft.world.level.material.LavaFluid;
import net.minecraft.world.level.material.WaterFluid;
public class ForgeHooks
{
private static final Logger LOGGER = LogManager.getLogger();
@@ -203,7 +219,7 @@ public class ForgeHooks
return false;
}
public static boolean canHarvestBlock(@Nonnull BlockState state, @Nonnull PlayerEntity player, @Nonnull IBlockReader world, @Nonnull BlockPos pos)
public static boolean canHarvestBlock(@Nonnull BlockState state, @Nonnull Player player, @Nonnull BlockGetter world, @Nonnull BlockPos pos)
{
//state = state.getActualState(world, pos);
if (!state.requiresCorrectToolForDrops())
@@ -221,7 +237,7 @@ public class ForgeHooks
return ForgeEventFactory.doPlayerHarvestCheck(player, state, toolLevel >= state.getHarvestLevel());
}
public static boolean isToolEffective(IWorldReader world, BlockPos pos, @Nonnull ItemStack stack)
public static boolean isToolEffective(LevelReader world, BlockPos pos, @Nonnull ItemStack stack)
{
BlockState state = world.getBlockState(pos);
//state = state.getActualState(world, pos);
@@ -240,20 +256,6 @@ public class ForgeHooks
return;
toolInit = true;
Set<Block> blocks = getPrivateValue(PickaxeItem.class, null, 0);
blocks.forEach(block -> blockToolSetter.accept(block, ToolType.PICKAXE, 0));
blocks = getPrivateValue(ShovelItem.class, null, 0);
blocks.forEach(block -> blockToolSetter.accept(block, ToolType.SHOVEL, 0));
//Axes check Materials and Blocks now.
Set<Material> materials = getPrivateValue(AxeItem.class, null, 0);
for (Block block : ForgeRegistries.BLOCKS)
if (materials.contains(block.defaultBlockState().getMaterial()))
blockToolSetter.accept(block, ToolType.AXE, 0);
blocks = getPrivateValue(AxeItem.class, null, 1);
blocks.forEach(block -> blockToolSetter.accept(block, ToolType.AXE, 0));
blocks = getPrivateValue(HoeItem.class, null, 0);
blocks.forEach(block -> blockToolSetter.accept(block, ToolType.HOE, 0));
//This is taken from PickaxeItem, if that changes update here.
for (Block block : new Block[]{Blocks.OBSIDIAN, Blocks.CRYING_OBSIDIAN, Blocks.NETHERITE_BLOCK, Blocks.RESPAWN_ANCHOR, Blocks.ANCIENT_DEBRIS})
blockToolSetter.accept(block, ToolType.PICKAXE, 3);
@@ -267,21 +269,21 @@ public class ForgeHooks
* Called when a player uses 'pick block', calls new Entity and Block hooks.
*/
@SuppressWarnings("resource")
public static boolean onPickBlock(RayTraceResult target, PlayerEntity player, World world)
public static boolean onPickBlock(HitResult target, Player player, Level world)
{
ItemStack result = ItemStack.EMPTY;
boolean isCreative = player.abilities.instabuild;
TileEntity te = null;
boolean isCreative = player.getAbilities().instabuild;
BlockEntity te = null;
if (target.getType() == RayTraceResult.Type.BLOCK)
if (target.getType() == HitResult.Type.BLOCK)
{
BlockPos pos = ((BlockRayTraceResult)target).getBlockPos();
BlockPos pos = ((BlockHitResult)target).getBlockPos();
BlockState state = world.getBlockState(pos);
if (state.isAir(world, pos))
if (state.isAir())
return false;
if (isCreative && Screen.hasControlDown() && state.hasTileEntity())
if (isCreative && Screen.hasControlDown() && state.hasBlockEntity())
te = world.getBlockEntity(pos);
result = state.getPickBlock(target, world, pos, player);
@@ -289,9 +291,9 @@ public class ForgeHooks
if (result.isEmpty())
LOGGER.warn("Picking on: [{}] {} gave null item", target.getType(), state.getBlock().getRegistryName());
}
else if (target.getType() == RayTraceResult.Type.ENTITY)
else if (target.getType() == HitResult.Type.ENTITY)
{
Entity entity = ((EntityRayTraceResult)target).getEntity();
Entity entity = ((EntityHitResult)target).getEntity();
result = entity.getPickedResult(target);
if (result.isEmpty())
@@ -306,15 +308,15 @@ public class ForgeHooks
if (isCreative)
{
player.inventory.setPickedItem(result);
Minecraft.getInstance().gameMode.handleCreativeModeItemAdd(player.getItemInHand(Hand.MAIN_HAND), 36 + player.inventory.selected);
player.getInventory().setPickedItem(result);
Minecraft.getInstance().gameMode.handleCreativeModeItemAdd(player.getItemInHand(InteractionHand.MAIN_HAND), 36 + player.getInventory().selected);
return true;
}
int slot = player.inventory.findSlotMatchingItem(result);
int slot = player.getInventory().findSlotMatchingItem(result);
if (slot != -1)
{
if (PlayerInventory.isHotbarSlot(slot))
player.inventory.selected = slot;
if (Inventory.isHotbarSlot(slot))
player.getInventory().selected = slot;
else
Minecraft.getInstance().gameMode.handlePickItem(slot);
return true;
@@ -342,7 +344,7 @@ public class ForgeHooks
public static boolean onLivingAttack(LivingEntity entity, DamageSource src, float amount)
{
return entity instanceof PlayerEntity || !MinecraftForge.EVENT_BUS.post(new LivingAttackEvent(entity, src, amount));
return entity instanceof Player || !MinecraftForge.EVENT_BUS.post(new LivingAttackEvent(entity, src, amount));
}
public static boolean onPlayerAttack(LivingEntity entity, DamageSource src, float amount)
@@ -403,28 +405,15 @@ public class ForgeHooks
return event.getLootingLevel();
}
/**
* TODO 1.17 remove
* Unused
*/
@Deprecated
public static double getPlayerVisibilityDistance(PlayerEntity player, double xzDistance, double maxXZDistance)
{
PlayerEvent.Visibility event = new PlayerEvent.Visibility(player);
MinecraftForge.EVENT_BUS.post(event);
double value = event.getVisibilityModifier() * xzDistance;
return value >= maxXZDistance ? maxXZDistance : value;
}
public static double getEntityVisibilityMultiplier(LivingEntity entity, Entity lookingEntity, double originalMultiplier){
LivingEvent.LivingVisibilityEvent event = new LivingEvent.LivingVisibilityEvent(entity, lookingEntity, originalMultiplier);
MinecraftForge.EVENT_BUS.post(event);
return Math.max(0,event.getVisibilityModifier());
}
public static boolean isLivingOnLadder(@Nonnull BlockState state, @Nonnull World world, @Nonnull BlockPos pos, @Nonnull LivingEntity entity)
public static boolean isLivingOnLadder(@Nonnull BlockState state, @Nonnull Level world, @Nonnull BlockPos pos, @Nonnull LivingEntity entity)
{
boolean isSpectator = (entity instanceof PlayerEntity && ((PlayerEntity)entity).isSpectator());
boolean isSpectator = (entity instanceof Player && ((Player)entity).isSpectator());
if (isSpectator) return false;
if (!ForgeConfig.SERVER.fullBoundingBoxLadders.get())
{
@@ -432,10 +421,10 @@ public class ForgeHooks
}
else
{
AxisAlignedBB bb = entity.getBoundingBox();
int mX = MathHelper.floor(bb.minX);
int mY = MathHelper.floor(bb.minY);
int mZ = MathHelper.floor(bb.minZ);
AABB bb = entity.getBoundingBox();
int mX = Mth.floor(bb.minX);
int mY = Mth.floor(bb.minY);
int mZ = Mth.floor(bb.minZ);
for (int y2 = mY; y2 < bb.maxY; y2++)
{
for (int x2 = mX; x2 < bb.maxX; x2++)
@@ -461,7 +450,7 @@ public class ForgeHooks
}
@Nullable
public static ItemEntity onPlayerTossEvent(@Nonnull PlayerEntity player, @Nonnull ItemStack item, boolean includeName)
public static ItemEntity onPlayerTossEvent(@Nonnull Player player, @Nonnull ItemStack item, boolean includeName)
{
player.captureDrops(Lists.newArrayList());
ItemEntity ret = player.drop(item, false, includeName);
@@ -480,7 +469,7 @@ public class ForgeHooks
}
@Nullable
public static ITextComponent onServerChatEvent(ServerPlayNetHandler net, String raw, ITextComponent comp)
public static Component onServerChatEvent(ServerGamePacketListenerImpl net, String raw, Component comp)
{
ServerChatEvent event = new ServerChatEvent(net.player, raw, comp);
if (MinecraftForge.EVENT_BUS.post(event))
@@ -497,13 +486,13 @@ public class ForgeHooks
"((?:[a-z0-9]{2,}:\\/\\/)?(?:(?:[0-9]{1,3}\\.){3}[0-9]{1,3}|(?:[-\\w_]{1,}\\.[a-z]{2,}?))(?::[0-9]{1,5})?.*?(?=[!\"\u00A7 \n]|$))",
Pattern.CASE_INSENSITIVE);
public static ITextComponent newChatWithLinks(String string){ return newChatWithLinks(string, true); }
public static ITextComponent newChatWithLinks(String string, boolean allowMissingHeader)
public static Component newChatWithLinks(String string){ return newChatWithLinks(string, true); }
public static Component newChatWithLinks(String string, boolean allowMissingHeader)
{
// Includes ipv4 and domain pattern
// Matches an ip (xx.xxx.xx.xxx) or a domain (something.com) with or
// without a protocol or path.
IFormattableTextComponent ichat = null;
MutableComponent ichat = null;
Matcher matcher = URL_PATTERN.matcher(string);
int lastEnd = 0;
@@ -518,13 +507,13 @@ public class ForgeHooks
if (part.length() > 0)
{
if (ichat == null)
ichat = new StringTextComponent(part);
ichat = new TextComponent(part);
else
ichat.append(part);
}
lastEnd = end;
String url = string.substring(start, end);
IFormattableTextComponent link = new StringTextComponent(url);
MutableComponent link = new TextComponent(url);
try
{
@@ -534,7 +523,7 @@ public class ForgeHooks
if (!allowMissingHeader)
{
if (ichat == null)
ichat = new StringTextComponent(url);
ichat = new TextComponent(url);
else
ichat.append(url);
continue;
@@ -545,29 +534,29 @@ public class ForgeHooks
catch (URISyntaxException e)
{
// Bad syntax bail out!
if (ichat == null) ichat = new StringTextComponent(url);
if (ichat == null) ichat = new TextComponent(url);
else ichat.append(url);
continue;
}
// Set the click event and append the link.
ClickEvent click = new ClickEvent(ClickEvent.Action.OPEN_URL, url);
link.setStyle(link.getStyle().withClickEvent(click).setUnderlined(true).withColor(Color.fromLegacyFormat(TextFormatting.BLUE)));
link.setStyle(link.getStyle().withClickEvent(click).setUnderlined(true).withColor(TextColor.fromLegacyFormat(ChatFormatting.BLUE)));
if (ichat == null)
ichat = new StringTextComponent("");
ichat = new TextComponent("");
ichat.append(link);
}
// Append the rest of the message.
String end = string.substring(lastEnd);
if (ichat == null)
ichat = new StringTextComponent(end);
ichat = new TextComponent(end);
else if (end.length() > 0)
ichat.append(new StringTextComponent(string.substring(lastEnd)));
ichat.append(new TextComponent(string.substring(lastEnd)));
return ichat;
}
public static int onBlockBreakEvent(World world, GameType gameType, ServerPlayerEntity entityPlayer, BlockPos pos)
public static int onBlockBreakEvent(Level world, GameType gameType, ServerPlayer entityPlayer, BlockPos pos)
{
// Logic from tryHarvestBlock for pre-canceling the event
boolean preCancelEvent = false;
@@ -584,7 +573,7 @@ public class ForgeHooks
if (!entityPlayer.mayBuild())
{
if (itemstack.isEmpty() || !itemstack.hasAdventureModeBreakTagForBlock(world.getTagManager(), new CachedBlockInfo(world, pos, false)))
if (itemstack.isEmpty() || !itemstack.hasAdventureModeBreakTagForBlock(world.getTagManager(), new BlockInWorld(world, pos, false)))
preCancelEvent = true;
}
}
@@ -592,7 +581,7 @@ public class ForgeHooks
// Tell client the block is gone immediately then process events
if (world.getBlockEntity(pos) == null)
{
entityPlayer.connection.send(new SChangeBlockPacket(DUMMY_WORLD, pos));
entityPlayer.connection.send(new ClientboundBlockUpdatePacket(DUMMY_WORLD, pos));
}
// Post the block break event
@@ -605,13 +594,13 @@ public class ForgeHooks
if (event.isCanceled())
{
// Let the client know the block still exists
entityPlayer.connection.send(new SChangeBlockPacket(world, pos));
entityPlayer.connection.send(new ClientboundBlockUpdatePacket(world, pos));
// Update any tile entity data for this block
TileEntity tileentity = world.getBlockEntity(pos);
if (tileentity != null)
BlockEntity blockEntity = world.getBlockEntity(pos);
if (blockEntity != null)
{
IPacket<?> pkt = tileentity.getUpdatePacket();
Packet<?> pkt = blockEntity.getUpdatePacket();
if (pkt != null)
{
entityPlayer.connection.send(pkt);
@@ -621,19 +610,19 @@ public class ForgeHooks
return event.isCanceled() ? -1 : event.getExpToDrop();
}
public static ActionResultType onPlaceItemIntoWorld(@Nonnull ItemUseContext context)
public static InteractionResult onPlaceItemIntoWorld(@Nonnull UseOnContext context)
{
ItemStack itemstack = context.getItemInHand();
World world = context.getLevel();
Level world = context.getLevel();
PlayerEntity player = context.getPlayer();
if (player != null && !player.abilities.mayBuild && !itemstack.hasAdventureModePlaceTagForBlock(world.getTagManager(), new CachedBlockInfo(world, context.getClickedPos(), false)))
return ActionResultType.PASS;
Player player = context.getPlayer();
if (player != null && !player.getAbilities().mayBuild && !itemstack.hasAdventureModePlaceTagForBlock(world.getTagManager(), new BlockInWorld(world, context.getClickedPos(), false)))
return InteractionResult.PASS;
// handle all placement events here
Item item = itemstack.getItem();
int size = itemstack.getCount();
CompoundNBT nbt = null;
CompoundTag nbt = null;
if (itemstack.getTag() != null)
nbt = itemstack.getTag().copy();
@@ -641,7 +630,7 @@ public class ForgeHooks
world.captureBlockSnapshots = true;
ItemStack copy = itemstack.copy();
ActionResultType ret = itemstack.getItem().useOn(context);
InteractionResult ret = itemstack.getItem().useOn(context);
if (itemstack.isEmpty())
ForgeEventFactory.onPlayerDestroyItem(player, copy, context.getHand());
@@ -651,7 +640,7 @@ public class ForgeHooks
{
// save new item data
int newSize = itemstack.getCount();
CompoundNBT newNBT = null;
CompoundTag newNBT = null;
if (itemstack.getTag() != null)
{
newNBT = itemstack.getTag().copy();
@@ -678,7 +667,7 @@ public class ForgeHooks
if (eventResult)
{
ret = ActionResultType.FAIL; // cancel placement
ret = InteractionResult.FAIL; // cancel placement
// revert back all captured blocks
for (BlockSnapshot blocksnapshot : Lists.reverse(blockSnapshots))
{
@@ -711,13 +700,7 @@ public class ForgeHooks
return ret;
}
@Deprecated // TODO: Remove 1.17 - Use player-contextual version below.
public static boolean onAnvilChange(RepairContainer container, @Nonnull ItemStack left, @Nonnull ItemStack right, IInventory outputSlot, String name, int baseCost)
{
return onAnvilChange(container, left, right, outputSlot, name, baseCost, null);
}
public static boolean onAnvilChange(RepairContainer container, @Nonnull ItemStack left, @Nonnull ItemStack right, IInventory outputSlot, String name, int baseCost, PlayerEntity player)
public static boolean onAnvilChange(AnvilMenu container, @Nonnull ItemStack left, @Nonnull ItemStack right, Container outputSlot, String name, int baseCost, Player player)
{
AnvilUpdateEvent e = new AnvilUpdateEvent(left, right, name, baseCost, player);
if (MinecraftForge.EVENT_BUS.post(e)) return false;
@@ -729,19 +712,19 @@ public class ForgeHooks
return false;
}
public static float onAnvilRepair(PlayerEntity player, @Nonnull ItemStack output, @Nonnull ItemStack left, @Nonnull ItemStack right)
public static float onAnvilRepair(Player player, @Nonnull ItemStack output, @Nonnull ItemStack left, @Nonnull ItemStack right)
{
AnvilRepairEvent e = new AnvilRepairEvent(player, left, right, output);
MinecraftForge.EVENT_BUS.post(e);
return e.getBreakChance();
}
private static ThreadLocal<PlayerEntity> craftingPlayer = new ThreadLocal<PlayerEntity>();
public static void setCraftingPlayer(PlayerEntity player)
private static ThreadLocal<Player> craftingPlayer = new ThreadLocal<Player>();
public static void setCraftingPlayer(Player player)
{
craftingPlayer.set(player);
}
public static PlayerEntity getCraftingPlayer()
public static Player getCraftingPlayer()
{
return craftingPlayer.get();
}
@@ -761,88 +744,80 @@ public class ForgeHooks
return ItemStack.EMPTY;
}
public static boolean onPlayerAttackTarget(PlayerEntity player, Entity target)
public static boolean onPlayerAttackTarget(Player player, Entity target)
{
if (MinecraftForge.EVENT_BUS.post(new AttackEntityEvent(player, target))) return false;
ItemStack stack = player.getMainHandItem();
return stack.isEmpty() || !stack.getItem().onLeftClickEntity(stack, player, target);
}
public static boolean onTravelToDimension(Entity entity, RegistryKey<World> dimension)
public static boolean onTravelToDimension(Entity entity, ResourceKey<Level> dimension)
{
EntityTravelToDimensionEvent event = new EntityTravelToDimensionEvent(entity, dimension);
MinecraftForge.EVENT_BUS.post(event);
if (event.isCanceled())
{
// Revert variable back to true as it would have been set to false
if (entity instanceof ContainerMinecartEntity)
if (entity instanceof AbstractMinecartContainer)
{
((ContainerMinecartEntity) entity).dropContentsWhenDead(true);
((AbstractMinecartContainer) entity).dropContentsWhenDead(true);
}
}
return !event.isCanceled();
}
public static ActionResultType onInteractEntityAt(PlayerEntity player, Entity entity, RayTraceResult ray, Hand hand)
public static InteractionResult onInteractEntityAt(Player player, Entity entity, HitResult ray, InteractionHand hand)
{
Vector3d vec3d = ray.getLocation().subtract(entity.position());
Vec3 vec3d = ray.getLocation().subtract(entity.position());
return onInteractEntityAt(player, entity, vec3d, hand);
}
public static ActionResultType onInteractEntityAt(PlayerEntity player, Entity entity, Vector3d vec3d, Hand hand)
public static InteractionResult onInteractEntityAt(Player player, Entity entity, Vec3 vec3d, InteractionHand hand)
{
PlayerInteractEvent.EntityInteractSpecific evt = new PlayerInteractEvent.EntityInteractSpecific(player, hand, entity, vec3d);
MinecraftForge.EVENT_BUS.post(evt);
return evt.isCanceled() ? evt.getCancellationResult() : null;
}
public static ActionResultType onInteractEntity(PlayerEntity player, Entity entity, Hand hand)
public static InteractionResult onInteractEntity(Player player, Entity entity, InteractionHand hand)
{
PlayerInteractEvent.EntityInteract evt = new PlayerInteractEvent.EntityInteract(player, hand, entity);
MinecraftForge.EVENT_BUS.post(evt);
return evt.isCanceled() ? evt.getCancellationResult() : null;
}
public static ActionResultType onItemRightClick(PlayerEntity player, Hand hand)
public static InteractionResult onItemRightClick(Player player, InteractionHand hand)
{
PlayerInteractEvent.RightClickItem evt = new PlayerInteractEvent.RightClickItem(player, hand);
MinecraftForge.EVENT_BUS.post(evt);
return evt.isCanceled() ? evt.getCancellationResult() : null;
}
public static PlayerInteractEvent.LeftClickBlock onLeftClickBlock(PlayerEntity player, BlockPos pos, Direction face)
public static PlayerInteractEvent.LeftClickBlock onLeftClickBlock(Player player, BlockPos pos, Direction face)
{
PlayerInteractEvent.LeftClickBlock evt = new PlayerInteractEvent.LeftClickBlock(player, pos, face);
MinecraftForge.EVENT_BUS.post(evt);
return evt;
}
@Deprecated //Use RayTraceResult version. TODO: Remove 1.17
public static PlayerInteractEvent.RightClickBlock onRightClickBlock(PlayerEntity player, Hand hand, BlockPos pos, Direction face)
{
PlayerInteractEvent.RightClickBlock evt = new PlayerInteractEvent.RightClickBlock(player, hand, pos, face);
MinecraftForge.EVENT_BUS.post(evt);
return evt;
}
public static PlayerInteractEvent.RightClickBlock onRightClickBlock(PlayerEntity player, Hand hand, BlockPos pos, BlockRayTraceResult hitVec)
public static PlayerInteractEvent.RightClickBlock onRightClickBlock(Player player, InteractionHand hand, BlockPos pos, BlockHitResult hitVec)
{
PlayerInteractEvent.RightClickBlock evt = new PlayerInteractEvent.RightClickBlock(player, hand, pos, hitVec);
MinecraftForge.EVENT_BUS.post(evt);
return evt;
}
public static void onEmptyClick(PlayerEntity player, Hand hand)
public static void onEmptyClick(Player player, InteractionHand hand)
{
MinecraftForge.EVENT_BUS.post(new PlayerInteractEvent.RightClickEmpty(player, hand));
}
public static void onEmptyLeftClick(PlayerEntity player)
public static void onEmptyLeftClick(Player player)
{
MinecraftForge.EVENT_BUS.post(new PlayerInteractEvent.LeftClickEmpty(player));
}
public static boolean onChangeGameMode(PlayerEntity player, GameType currentGameMode, GameType newGameMode)
public static boolean onChangeGameMode(Player player, GameType currentGameMode, GameType newGameMode)
{
if (currentGameMode != newGameMode)
{
@@ -865,7 +840,7 @@ public class ForgeHooks
}
@Nullable
public static LootTable loadLootTable(Gson gson, ResourceLocation name, JsonElement data, boolean custom, LootTableManager lootTableManager)
public static LootTable loadLootTable(Gson gson, ResourceLocation name, JsonElement data, boolean custom, LootTables lootTableManager)
{
Deque<LootTableContext> que = lootContext.get();
if (que == null)
@@ -934,10 +909,10 @@ public class ForgeHooks
@FunctionalInterface
public interface BiomeCallbackFunction
{
Biome apply(final Biome.Climate climate, final Biome.Category category, final Float depth, final Float scale, final BiomeAmbience effects, final BiomeGenerationSettings gen, final MobSpawnInfo spawns);
Biome apply(final Biome.ClimateSettings climate, final Biome.BiomeCategory category, final Float depth, final Float scale, final BiomeSpecialEffects effects, final BiomeGenerationSettings gen, final MobSpawnSettings spawns);
}
public static Biome enhanceBiome(@Nullable final ResourceLocation name, final Biome.Climate climate, final Biome.Category category, final Float depth, final Float scale, final BiomeAmbience effects, final BiomeGenerationSettings gen, final MobSpawnInfo spawns, final RecordCodecBuilder.Instance<Biome> codec, final BiomeCallbackFunction callback)
public static Biome enhanceBiome(@Nullable final ResourceLocation name, final Biome.ClimateSettings climate, final Biome.BiomeCategory category, final Float depth, final Float scale, final BiomeSpecialEffects effects, final BiomeGenerationSettings gen, final MobSpawnSettings spawns, final RecordCodecBuilder.Instance<Biome> codec, final BiomeCallbackFunction callback)
{
BiomeGenerationSettingsBuilder genBuilder = new BiomeGenerationSettingsBuilder(gen);
MobSpawnInfoBuilder spawnBuilder = new MobSpawnInfoBuilder(spawns);
@@ -996,7 +971,7 @@ public class ForgeHooks
ctx.resetPoolCtx();
if (json.has("name"))
return JSONUtils.getAsString(json, "name");
return GsonHelper.getAsString(json, "name");
if (ctx.custom)
return "custom#" + json.hashCode(); //We don't care about custom ones modders shouldn't be editing them!
@@ -1015,36 +990,36 @@ public class ForgeHooks
ctx.entryCount++;
if (json.has("entryName"))
return ctx.validateEntryName(JSONUtils.getAsString(json, "entryName"));
return ctx.validateEntryName(GsonHelper.getAsString(json, "entryName"));
if (ctx.custom)
return "custom#" + json.hashCode(); //We don't care about custom ones modders shouldn't be editing them!
String name = null;
if ("item".equals(type))
name = JSONUtils.getAsString(json, "name");
name = GsonHelper.getAsString(json, "name");
else if ("loot_table".equals(type))
name = JSONUtils.getAsString(json, "name");
name = GsonHelper.getAsString(json, "name");
else if ("empty".equals(type))
name = "empty";
return ctx.validateEntryName(name);
}
public static boolean onCropsGrowPre(World worldIn, BlockPos pos, BlockState state, boolean def)
public static boolean onCropsGrowPre(Level worldIn, BlockPos pos, BlockState state, boolean def)
{
BlockEvent ev = new BlockEvent.CropGrowEvent.Pre(worldIn,pos,state);
MinecraftForge.EVENT_BUS.post(ev);
return (ev.getResult() == net.minecraftforge.eventbus.api.Event.Result.ALLOW || (ev.getResult() == net.minecraftforge.eventbus.api.Event.Result.DEFAULT && def));
}
public static void onCropsGrowPost(World worldIn, BlockPos pos, BlockState state)
public static void onCropsGrowPost(Level worldIn, BlockPos pos, BlockState state)
{
MinecraftForge.EVENT_BUS.post(new BlockEvent.CropGrowEvent.Post(worldIn, pos, state, worldIn.getBlockState(pos)));
}
@Nullable
public static CriticalHitEvent getCriticalHit(PlayerEntity player, Entity target, boolean vanillaCritical, float damageModifier)
public static CriticalHitEvent getCriticalHit(Player player, Entity target, boolean vanillaCritical, float damageModifier)
{
CriticalHitEvent hitResult = new CriticalHitEvent(player, target, damageModifier, vanillaCritical);
MinecraftForge.EVENT_BUS.post(hitResult);
@@ -1055,7 +1030,7 @@ public class ForgeHooks
return null;
}
public static void onAdvancement(ServerPlayerEntity player, Advancement advancement)
public static void onAdvancement(ServerPlayer player, Advancement advancement)
{
MinecraftForge.EVENT_BUS.post(new AdvancementEvent(player, advancement));
}
@@ -1063,7 +1038,7 @@ public class ForgeHooks
/**
* Hook to fire {@link ItemAttributeModifierEvent}. Modders should use {@link ItemStack#getAttributeModifiers(EquipmentSlotType)} instead.
*/
public static Multimap<Attribute,AttributeModifier> getAttributeModifiers(ItemStack stack, EquipmentSlotType equipmentSlot, Multimap<Attribute,AttributeModifier> attributes)
public static Multimap<Attribute,AttributeModifier> getAttributeModifiers(ItemStack stack, EquipmentSlot equipmentSlot, Multimap<Attribute,AttributeModifier> attributes)
{
ItemAttributeModifierEvent event = new ItemAttributeModifierEvent(stack, equipmentSlot, attributes);
MinecraftForge.EVENT_BUS.post(event);
@@ -1083,10 +1058,10 @@ public class ForgeHooks
{
if (item instanceof EnchantedBookItem)
{
ListNBT enchantmentsNbt = EnchantedBookItem.getEnchantments(itemStack);
ListTag enchantmentsNbt = EnchantedBookItem.getEnchantments(itemStack);
if (enchantmentsNbt.size() == 1)
{
CompoundNBT nbttagcompound = enchantmentsNbt.getCompound(0);
CompoundTag nbttagcompound = enchantmentsNbt.getCompound(0);
ResourceLocation resourceLocation = ResourceLocation.tryParse(nbttagcompound.getString("id"));
if (resourceLocation != null && ForgeRegistries.ENCHANTMENTS.containsKey(resourceLocation))
{
@@ -1115,7 +1090,7 @@ public class ForgeHooks
return modId;
}
public static boolean onFarmlandTrample(World world, BlockPos pos, BlockState state, float fallDistance, Entity entity)
public static boolean onFarmlandTrample(Level world, BlockPos pos, BlockState state, float fallDistance, Entity entity)
{
if (entity.canTrample(state, pos, fallDistance))
{
@@ -1149,10 +1124,10 @@ public class ForgeHooks
}
private static final DummyBlockReader DUMMY_WORLD = new DummyBlockReader();
private static class DummyBlockReader implements IBlockReader {
private static class DummyBlockReader implements BlockGetter {
@Override
public TileEntity getBlockEntity(BlockPos pos) {
public BlockEntity getBlockEntity(BlockPos pos) {
return null;
}
@@ -1166,58 +1141,54 @@ public class ForgeHooks
return Fluids.EMPTY.defaultFluidState();
}
@Override
public int getHeight() {
return 0;
}
@Override
public int getMinBuildHeight() {
return 0;
}
}
public static int onNoteChange(World world, BlockPos pos, BlockState state, int old, int _new) {
public static int onNoteChange(Level world, BlockPos pos, BlockState state, int old, int _new) {
NoteBlockEvent.Change event = new NoteBlockEvent.Change(world, pos, state, old, _new);
if (MinecraftForge.EVENT_BUS.post(event))
return -1;
return event.getVanillaNoteId();
}
public static int canEntitySpawn(MobEntity entity, IWorld world, double x, double y, double z, AbstractSpawner spawner, SpawnReason spawnReason) {
public static int canEntitySpawn(Mob entity, LevelAccessor world, double x, double y, double z, BaseSpawner spawner, MobSpawnType spawnReason) {
Result res = ForgeEventFactory.canEntitySpawn(entity, world, x, y, z, null, spawnReason);
return res == Result.DEFAULT ? 0 : res == Result.DENY ? -1 : 1;
}
public static <T> void deserializeTagAdditions(List<ITag.ITagEntry> list, JsonObject json, List<ITag.Proxy> allList)
public static <T> void deserializeTagAdditions(List<Tag.Entry> list, JsonObject json, List<Tag.BuilderEntry> allList)
{
//TODO 1.17 remove parsing the forge added "optional" array. Still here for compatibility with previously created tags.
if (json.has("optional"))
{
for (JsonElement entry : JSONUtils.getAsJsonArray(json, "optional"))
{
String s = JSONUtils.convertToString(entry, "value");
if (!s.startsWith("#"))
list.add(new ITag.OptionalItemEntry(new ResourceLocation(s)));
else
list.add(new ITag.OptionalTagEntry(new ResourceLocation(s.substring(1))));
}
}
if (json.has("remove"))
{
for (JsonElement entry : JSONUtils.getAsJsonArray(json, "remove"))
for (JsonElement entry : GsonHelper.getAsJsonArray(json, "remove"))
{
String s = JSONUtils.convertToString(entry, "value");
ITag.ITagEntry dummy;
String s = GsonHelper.convertToString(entry, "value");
Tag.Entry dummy;
if (!s.startsWith("#"))
dummy = new ITag.ItemEntry(new ResourceLocation(s));
dummy = new Tag.ElementEntry(new ResourceLocation(s));
else
dummy = new ITag.TagEntry(new ResourceLocation(s.substring(1)));
dummy = new Tag.TagEntry(new ResourceLocation(s.substring(1)));
allList.removeIf(e -> e.getEntry().equals(dummy));
}
}
}
private static final Map<IDataSerializer<?>, DataSerializerEntry> serializerEntries = GameData.getSerializerMap();
private static final Map<EntityDataSerializer<?>, DataSerializerEntry> serializerEntries = GameData.getSerializerMap();
//private static final ForgeRegistry<DataSerializerEntry> serializerRegistry = (ForgeRegistry<DataSerializerEntry>) ForgeRegistries.DATA_SERIALIZERS;
// Do not reimplement this ^ it introduces a chicken-egg scenario by classloading registries during bootstrap
@Nullable
public static IDataSerializer<?> getSerializer(int id, IntIdentityHashBiMap<IDataSerializer<?>> vanilla)
public static EntityDataSerializer<?> getSerializer(int id, CrudeIncrementalIntIdentityHashBiMap<EntityDataSerializer<?>> vanilla)
{
IDataSerializer<?> serializer = vanilla.byId(id);
EntityDataSerializer<?> serializer = vanilla.byId(id);
if (serializer == null)
{
DataSerializerEntry entry = ((ForgeRegistry<DataSerializerEntry>)ForgeRegistries.DATA_SERIALIZERS).getValue(id);
@@ -1226,7 +1197,7 @@ public class ForgeHooks
return serializer;
}
public static int getSerializerId(IDataSerializer<?> serializer, IntIdentityHashBiMap<IDataSerializer<?>> vanilla)
public static int getSerializerId(EntityDataSerializer<?> serializer, CrudeIncrementalIntIdentityHashBiMap<EntityDataSerializer<?>> vanilla)
{
int id = vanilla.getId(serializer);
if (id < 0)
@@ -1237,7 +1208,7 @@ public class ForgeHooks
return id;
}
public static boolean canEntityDestroy(World world, BlockPos pos, LivingEntity entity)
public static boolean canEntityDestroy(Level world, BlockPos pos, LivingEntity entity)
{
BlockState state = world.getBlockState(pos);
return ForgeEventFactory.getMobGriefingEvent(world, entity) && state.canEntityDestroy(world, pos, entity) && ForgeEventFactory.onEntityDestroyBlock(entity, pos, state);
@@ -1245,16 +1216,10 @@ public class ForgeHooks
private static final Map<IRegistryDelegate<Item>, Integer> VANILLA_BURNS = new HashMap<>();
@Deprecated // use variant with IRecipeType
public static int getBurnTime(ItemStack stack)
{
return getBurnTime(stack, null);
}
/**
* Gets the burn time of this itemstack.
*/
public static int getBurnTime(ItemStack stack, @Nullable IRecipeType<?> recipeType)
public static int getBurnTime(ItemStack stack, @Nullable RecipeType<?> recipeType)
{
if (stack.isEmpty())
{
@@ -1272,7 +1237,7 @@ public class ForgeHooks
public static synchronized void updateBurns()
{
VANILLA_BURNS.clear();
FurnaceTileEntity.getFuel().entrySet().forEach(e -> VANILLA_BURNS.put(e.getKey().delegate, e.getValue()));
FurnaceBlockEntity.getFuel().entrySet().forEach(e -> VANILLA_BURNS.put(e.getKey().delegate, e.getValue()));
}
/**
@@ -1336,7 +1301,7 @@ public class ForgeHooks
* When a structure mod is removed, this map may contain null keys. This will make the world unable to save if this persists.
* If we remove a structure from the save data in this way, we then mark the chunk for saving
*/
public static void fixNullStructureReferences(IChunk chunk, Map<Structure<?>, LongSet> structureReferences)
public static void fixNullStructureReferences(ChunkAccess chunk, Map<StructureFeature<?>, LongSet> structureReferences)
{
if (structureReferences.remove(null) != null)
{
@@ -1349,7 +1314,7 @@ public class ForgeHooks
private static final String DIMENSIONS_KEY = "dimensions";
private static final String SEED_KEY = "seed";
//No to static init!
private static final LazyValue<Codec<SimpleRegistry<Dimension>>> CODEC = new LazyValue<>(() -> SimpleRegistry.dataPackCodec(Registry.LEVEL_STEM_REGISTRY, Lifecycle.stable(), Dimension.CODEC).xmap(Dimension::sortMap, Function.identity()));
private static final LazyLoadedValue<Codec<MappedRegistry<LevelStem>>> CODEC = new LazyLoadedValue<>(() -> MappedRegistry.dataPackCodec(Registry.LEVEL_STEM_REGISTRY, Lifecycle.stable(), LevelStem.CODEC).xmap(LevelStem::sortMap, Function.identity()));
/**
* Restores previously "deleted" dimensions to the world.
@@ -1357,10 +1322,10 @@ public class ForgeHooks
*/
public static <T> Dynamic<T> fixUpDimensionsData(Dynamic<T> data)
{
if(!(data.getOps() instanceof WorldSettingsImport))
if(!(data.getOps() instanceof RegistryReadOps))
return data;
WorldSettingsImport<T> ops = (WorldSettingsImport<T>) data.getOps();
RegistryReadOps<T> ops = (RegistryReadOps<T>) data.getOps();
Dynamic<T> dymData = data.get(DIMENSIONS_KEY).orElseEmptyMap();
Dynamic<T> withInjected = dymData.asMapOpt().map(current ->
{
@@ -1371,7 +1336,7 @@ public class ForgeHooks
if (!currentDimNames.containsAll(VANILLA_DIMS))
{
LOGGER.warn("Detected missing vanilla dimensions from the world!");
DynamicRegistries regs = ObfuscationReflectionHelper.getPrivateValue(WorldSettingsImport.class, ops, "field_240872_" + "d_");
RegistryAccess regs = ObfuscationReflectionHelper.getPrivateValue(RegistryReadOps.class, ops, "f_13563" + "6_");
if (regs == null) // should not happen, but it could after a MC version update.
throw new RuntimeException("Could not access dynamic registries using reflection. " +
"The world was detected to have missing vanilla dimensions and the attempted fix did not work.");
@@ -1379,30 +1344,30 @@ public class ForgeHooks
long seed = data.get(SEED_KEY).get().result().map(d -> d.asLong(0L)).orElse(0L);
Registry<Biome> biomeReg = regs.registryOrThrow(Registry.BIOME_REGISTRY);
Registry<DimensionType> typeReg = regs.registryOrThrow(Registry.DIMENSION_TYPE_REGISTRY);
Registry<DimensionSettings> noiseReg = regs.registryOrThrow(Registry.NOISE_GENERATOR_SETTINGS_REGISTRY);
Registry<NoiseGeneratorSettings> noiseReg = regs.registryOrThrow(Registry.NOISE_GENERATOR_SETTINGS_REGISTRY);
//Loads the default nether and end
SimpleRegistry<Dimension> dimReg = DimensionType.defaultDimensions(typeReg, biomeReg, noiseReg, seed);
MappedRegistry<LevelStem> dimReg = DimensionType.defaultDimensions(typeReg, biomeReg, noiseReg, seed);
//Loads the default overworld
dimReg = DimensionGeneratorSettings.withOverworld(typeReg, dimReg, DimensionGeneratorSettings.makeDefaultOverworld(biomeReg, noiseReg, seed));
dimReg = WorldGenSettings.withOverworld(typeReg, dimReg, WorldGenSettings.makeDefaultOverworld(biomeReg, noiseReg, seed));
// Encode and decode the registry. This adds any dimensions from datapacks (see SimpleRegistryCodec#decode), but only the vanilla overrides are needed.
// This assumes that the datapacks for the vanilla dimensions have not changed since they were "deleted"
// If they did, this will be seen in newly generated chunks.
// Since this is to fix an older world, from before the fixes by forge, there is no way to know the state of the dimension when it was "deleted".
dimReg = CODEC.get().encodeStart(WorldGenSettingsExport.create(ops, regs), dimReg).flatMap(t -> CODEC.get().parse(ops, t)).result().orElse(dimReg);
dimReg = CODEC.get().encodeStart(RegistryWriteOps.create(ops, regs), dimReg).flatMap(t -> CODEC.get().parse(ops, t)).result().orElse(dimReg);
for (String name : VANILLA_DIMS)
{
if (currentDimNames.contains(name))
continue;
Dimension dim = dimReg.get(new ResourceLocation(name));
LevelStem dim = dimReg.get(new ResourceLocation(name));
if (dim == null)
{
LOGGER.error("The world is missing dimension: " + name + ", but the attempt to re-inject it failed.");
continue;
}
LOGGER.info("Fixing world: re-injected dimension: " + name);
Optional<T> dimT = Dimension.CODEC.encodeStart(WorldGenSettingsExport.create(ops, regs), dim).resultOrPartial(s->{});
Optional<T> dimT = LevelStem.CODEC.encodeStart(RegistryWriteOps.create(ops, regs), dim).resultOrPartial(s->{});
if (dimT.isPresent())
currentList.add(Pair.of(name, dimT.get()));
else
@@ -1417,10 +1382,10 @@ public class ForgeHooks
return data.set(DIMENSIONS_KEY, withInjected);
}
private static final Map<EntityType<? extends LivingEntity>, AttributeModifierMap> FORGE_ATTRIBUTES = new HashMap<>();
private static final Map<EntityType<? extends LivingEntity>, AttributeSupplier> FORGE_ATTRIBUTES = new HashMap<>();
/** FOR INTERNAL USE ONLY, DO NOT CALL DIRECTLY */
@Deprecated
public static Map<EntityType<? extends LivingEntity>, AttributeModifierMap> getAttributesView()
public static Map<EntityType<? extends LivingEntity>, AttributeSupplier> getAttributesView()
{
return Collections.unmodifiableMap(FORGE_ATTRIBUTES);
}
@@ -1429,7 +1394,7 @@ public class ForgeHooks
* ONLY EXISTS FOR LEGACY REASONS SHOULD BE REMOVED IN 1.17
*/
@Deprecated /// Internal use only, Remove in 1.17
public static AttributeModifierMap putAttributesOld(EntityType<? extends LivingEntity> type, AttributeModifierMap map)
public static AttributeSupplier putAttributesOld(EntityType<? extends LivingEntity> type, AttributeSupplier map)
{
LOGGER.warn("Called deprecated GlobalEntityTypeAttributes#put for {}, use EntityAttributeCreationEvent instead.", type.getRegistryName());
return FORGE_ATTRIBUTES.put(type, map);
@@ -1440,13 +1405,13 @@ public class ForgeHooks
public static void modifyAttributes()
{
ModLoader.get().postEvent(new EntityAttributeCreationEvent(FORGE_ATTRIBUTES));
Map<EntityType<? extends LivingEntity>, AttributeModifierMap.MutableAttribute> finalMap = new HashMap<>();
Map<EntityType<? extends LivingEntity>, AttributeSupplier.Builder> finalMap = new HashMap<>();
ModLoader.get().postEvent(new EntityAttributeModificationEvent(finalMap));
finalMap.forEach((k, v) ->
{
AttributeModifierMap modifiers = GlobalEntityTypeAttributes.getSupplier(k);
AttributeModifierMap.MutableAttribute newMutable = modifiers != null ? new AttributeModifierMap.MutableAttribute(modifiers) : new AttributeModifierMap.MutableAttribute();
AttributeSupplier modifiers = DefaultAttributes.getSupplier(k);
AttributeSupplier.Builder newMutable = modifiers != null ? new AttributeSupplier.Builder(modifiers) : new AttributeSupplier.Builder();
newMutable.combine(v);
FORGE_ATTRIBUTES.put(k, newMutable.build());
});
@@ -19,14 +19,13 @@
package net.minecraftforge.common;
import net.minecraft.entity.Entity;
import net.minecraft.entity.item.ItemEntity;
import net.minecraft.entity.player.ServerPlayerEntity;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraft.util.concurrent.ThreadTaskExecutor;
import net.minecraft.util.concurrent.TickDelayedTask;
import net.minecraft.world.server.ServerWorld;
import net.minecraft.world.entity.Entity;
import net.minecraft.world.entity.item.ItemEntity;
import net.minecraft.world.item.Item;
import net.minecraft.world.item.ItemStack;
import net.minecraft.util.thread.BlockableEventLoop;
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;
@@ -40,10 +39,9 @@ import net.minecraftforge.eventbus.api.SubscribeEvent;
import net.minecraftforge.event.TagsUpdatedEvent;
import net.minecraftforge.event.TickEvent;
import net.minecraftforge.event.TickEvent.ClientTickEvent;
import net.minecraftforge.event.TickEvent.Phase;
import net.minecraftforge.event.TickEvent.ServerTickEvent;
import net.minecraftforge.fml.LogicalSide;
import net.minecraftforge.fml.LogicalSidedProvider;
import net.minecraftforge.fmllegacy.LogicalSidedProvider;
import net.minecraftforge.server.command.ForgeCommand;
import net.minecraftforge.server.command.ConfigCommand;
@@ -62,10 +60,10 @@ public class ForgeInternalHandler
Entity newEntity = item.createEntity(event.getWorld(), entity, stack);
if (newEntity != null)
{
entity.remove();
entity.remove(false);
event.setCanceled(true);
ThreadTaskExecutor<Runnable> executor = LogicalSidedProvider.WORKQUEUE.get(event.getWorld().isClientSide ? LogicalSide.CLIENT : LogicalSide.SERVER);
executor.tell(new TickDelayedTask(0, () -> event.getWorld().addFreshEntity(newEntity)));
BlockableEventLoop<Runnable> executor = LogicalSidedProvider.WORKQUEUE.get(event.getWorld().isClientSide ? LogicalSide.CLIENT : LogicalSide.SERVER);
executor.tell(new TickTask(0, () -> event.getWorld().addFreshEntity(newEntity)));
}
}
}
@@ -75,8 +73,8 @@ public class ForgeInternalHandler
@SubscribeEvent(priority = EventPriority.HIGHEST)
public void onDimensionUnload(WorldEvent.Unload event)
{
if (event.getWorld() instanceof ServerWorld)
FakePlayerFactory.unloadWorld((ServerWorld) event.getWorld());
if (event.getWorld() instanceof ServerLevel)
FakePlayerFactory.unloadWorld((ServerLevel) event.getWorld());
}
@SubscribeEvent
@@ -19,17 +19,17 @@
package net.minecraftforge.common;
import net.minecraft.command.arguments.ArgumentSerializer;
import net.minecraft.command.arguments.ArgumentTypes;
import net.minecraft.command.arguments.IArgumentSerializer;
import net.minecraft.entity.ai.attributes.Attribute;
import net.minecraft.entity.ai.attributes.RangedAttribute;
import net.minecraft.fluid.Fluid;
import net.minecraft.item.Items;
import net.minecraft.util.SoundEvent;
import net.minecraft.util.registry.Registry;
import net.minecraft.world.storage.IServerConfiguration;
import net.minecraft.world.storage.SaveFormat;
import net.minecraft.commands.synchronization.EmptyArgumentSerializer;
import net.minecraft.commands.synchronization.ArgumentTypes;
import net.minecraft.commands.synchronization.ArgumentSerializer;
import net.minecraft.world.entity.ai.attributes.Attribute;
import net.minecraft.world.entity.ai.attributes.RangedAttribute;
import net.minecraft.world.level.material.Fluid;
import net.minecraft.world.item.Items;
import net.minecraft.sounds.SoundEvent;
import net.minecraft.core.Registry;
import net.minecraft.world.level.storage.WorldData;
import net.minecraft.world.level.storage.LevelStorageSource;
import net.minecraftforge.api.distmarker.Dist;
import net.minecraftforge.client.ForgeHooksClient;
import net.minecraftforge.common.data.ExistingFileHelper;
@@ -43,10 +43,15 @@ import net.minecraftforge.fluids.ForgeFlowingFluid;
import net.minecraftforge.fml.*;
import net.minecraftforge.fml.config.ModConfig;
import net.minecraftforge.fml.event.lifecycle.*;
import net.minecraftforge.fml.event.server.FMLServerStoppingEvent;
import net.minecraftforge.fmllegacy.FMLWorldPersistenceHook;
import net.minecraftforge.fmllegacy.RegistryObject;
import net.minecraftforge.fmllegacy.WorldPersistenceHooks;
import net.minecraftforge.fmllegacy.event.lifecycle.FMLModIdMappingEvent;
import net.minecraftforge.fmllegacy.network.FMLNetworkConstants;
import net.minecraftforge.fmlserverevents.FMLServerStoppingEvent;
import net.minecraftforge.fml.javafmlmod.FMLJavaModLoadingContext;
import net.minecraftforge.fml.loading.FMLEnvironment;
import net.minecraftforge.fml.loading.progress.StartupMessageManager;
import net.minecraftforge.forge.event.lifecycle.GatherDataEvent;
import net.minecraftforge.network.VanillaPacketSplitter;
import net.minecraftforge.registries.DeferredRegister;
import net.minecraftforge.server.command.EnumArgument;
@@ -55,15 +60,14 @@ import net.minecraftforge.registries.ForgeRegistries;
import net.minecraftforge.versions.forge.ForgeVersion;
import net.minecraftforge.versions.mcp.MCPVersion;
import org.apache.commons.lang3.tuple.Pair;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import net.minecraft.data.DataGenerator;
import net.minecraft.item.crafting.IRecipe;
import net.minecraft.item.crafting.IRecipeSerializer;
import net.minecraft.nbt.CompoundNBT;
import net.minecraft.util.ResourceLocation;
import net.minecraft.world.item.crafting.Recipe;
import net.minecraft.world.item.crafting.RecipeSerializer;
import net.minecraft.nbt.CompoundTag;
import net.minecraft.resources.ResourceLocation;
import net.minecraftforge.common.crafting.CompoundIngredient;
import net.minecraftforge.common.crafting.ConditionalRecipe;
import net.minecraftforge.common.crafting.CraftingHelper;
@@ -132,11 +136,16 @@ public class ForgeMod implements WorldPersistenceHooks.WorldPersistenceHook
LOGGER.info(FORGEMOD,"Forge mod loading, version {}, for MC {} with MCP {}", ForgeVersion.getVersion(), MCPVersion.getMCVersion(), MCPVersion.getMCPVersion());
INSTANCE = this;
MinecraftForge.initialize();
CrashReportExtender.registerCrashCallable("Crash Report UUID", ()-> {
CrashReportCallables.registerCrashCallable("Crash Report UUID", ()-> {
final UUID uuid = UUID.randomUUID();
LOGGER.fatal("Preparing crash report with UUID {}", uuid);
return uuid.toString();
});
LOGGER.debug(FORGEMOD, "Loading Network data for FML net version: {}", FMLNetworkConstants.init());
CrashReportCallables.registerCrashCallable("FML", ForgeVersion::getSpec);
CrashReportCallables.registerCrashCallable("Forge", ()->ForgeVersion.getGroup()+":"+ForgeVersion.getVersion());
WorldPersistenceHooks.addHook(this);
WorldPersistenceHooks.addHook(new FMLWorldPersistenceHook());
final IEventBus modEventBus = FMLJavaModLoadingContext.get().getModEventBus();
@@ -153,7 +162,7 @@ public class ForgeMod implements WorldPersistenceHooks.WorldPersistenceHook
ModLoadingContext.get().registerConfig(ModConfig.Type.COMMON, ForgeConfig.commonSpec);
modEventBus.register(ForgeConfig.class);
// Forge does not display problems when the remote is not matching.
ModLoadingContext.get().registerExtensionPoint(ExtensionPoint.DISPLAYTEST, ()-> Pair.of(()->"ANY", (remote, isServer)-> true));
ModLoadingContext.get().registerExtensionPoint(IExtensionPoint.DisplayTest.class, ()->new IExtensionPoint.DisplayTest(()->"ANY", (remote, isServer)-> true));
StartupMessageManager.addModMessage("Forge version "+ForgeVersion.getVersion());
MinecraftForge.EVENT_BUS.addListener(VillagerTradingManager::loadTrades);
@@ -178,8 +187,8 @@ public class ForgeMod implements WorldPersistenceHooks.WorldPersistenceHook
@SuppressWarnings({"unchecked", "rawtypes"})
private void registerArgumentTypes()
{
ArgumentTypes.register("forge:enum", EnumArgument.class, (IArgumentSerializer) new EnumArgument.Serializer());
ArgumentTypes.register("forge:modid", ModIdArgument.class, new ArgumentSerializer<>(ModIdArgument::modIdArgument));
ArgumentTypes.register("forge:enum", EnumArgument.class, (ArgumentSerializer) new EnumArgument.Serializer());
ArgumentTypes.register("forge:modid", ModIdArgument.class, new EmptyArgumentSerializer<>(ModIdArgument::modIdArgument));
}
public void loadComplete(FMLLoadCompleteEvent event)
@@ -194,10 +203,10 @@ public class ForgeMod implements WorldPersistenceHooks.WorldPersistenceHook
}
@Override
public CompoundNBT getDataForWriting(SaveFormat.LevelSave levelSave, IServerConfiguration serverInfo)
public CompoundTag getDataForWriting(LevelStorageSource.LevelStorageAccess levelSave, WorldData serverInfo)
{
CompoundNBT forgeData = new CompoundNBT();
CompoundNBT dims = new CompoundNBT();
CompoundTag forgeData = new CompoundTag();
CompoundTag dims = new CompoundTag();
//TODO Dimensions
// DimensionManager.writeRegistry(dims);
if (!dims.isEmpty())
@@ -206,7 +215,7 @@ public class ForgeMod implements WorldPersistenceHooks.WorldPersistenceHook
}
@Override
public void readData(SaveFormat.LevelSave levelSave, IServerConfiguration serverInfo, CompoundNBT tag)
public void readData(LevelStorageSource.LevelStorageAccess levelSave, WorldData serverInfo, CompoundTag tag)
{
//TODO Dimensions
// if (tag.contains("dims", 10))
@@ -274,7 +283,7 @@ public class ForgeMod implements WorldPersistenceHooks.WorldPersistenceHook
}
@SubscribeEvent //ModBus, can't use addListener due to nested genetics.
public void registerRecipeSerialziers(RegistryEvent.Register<IRecipeSerializer<?>> event)
public void registerRecipeSerialziers(RegistryEvent.Register<RecipeSerializer<?>> event)
{
CraftingHelper.register(AndCondition.Serializer.INSTANCE);
CraftingHelper.register(FalseCondition.Serializer.INSTANCE);
@@ -289,7 +298,7 @@ public class ForgeMod implements WorldPersistenceHooks.WorldPersistenceHook
CraftingHelper.register(new ResourceLocation("forge", "nbt"), NBTIngredient.Serializer.INSTANCE);
CraftingHelper.register(new ResourceLocation("minecraft", "item"), VanillaIngredientSerializer.INSTANCE);
event.getRegistry().register(new ConditionalRecipe.Serializer<IRecipe<?>>().setRegistryName(new ResourceLocation("forge", "conditional")));
event.getRegistry().register(new ConditionalRecipe.Serializer<Recipe<?>>().setRegistryName(new ResourceLocation("forge", "conditional")));
}
@@ -33,21 +33,18 @@ import java.util.concurrent.Executor;
import java.util.function.Supplier;
import java.util.stream.Collectors;
import javax.annotation.Nullable;
import net.minecraft.block.Block;
import net.minecraft.entity.EntityType;
import net.minecraft.fluid.Fluid;
import net.minecraft.item.Item;
import net.minecraft.resources.IResourceManager;
import net.minecraft.tags.ITag;
import net.minecraft.tags.ITag.INamedTag;
import net.minecraft.tags.ITagCollection;
import net.minecraft.tags.ITagCollectionSupplier;
import net.minecraft.tags.TagCollectionReader;
import net.minecraft.tags.TagRegistry;
import net.minecraft.tags.TagRegistryManager;
import net.minecraft.util.ResourceLocation;
import net.minecraft.server.packs.resources.ResourceManager;
import net.minecraft.tags.Tag;
import net.minecraft.tags.Tag.Named;
import net.minecraft.tags.TagCollection;
import net.minecraft.tags.TagContainer;
import net.minecraft.tags.TagLoader;
import net.minecraft.tags.StaticTagHelper;
import net.minecraft.tags.StaticTags;
import net.minecraft.resources.ResourceLocation;
import net.minecraftforge.common.Tags.IOptionalNamedTag;
import net.minecraftforge.fml.network.FMLPlayMessages.SyncCustomTagTypes;
import net.minecraftforge.common.extensions.IForgeTagContainer;
import net.minecraftforge.fmllegacy.network.FMLPlayMessages.SyncCustomTagTypes;
import net.minecraftforge.registries.ForgeRegistry;
import net.minecraftforge.registries.IForgeRegistry;
import net.minecraftforge.registries.IForgeRegistryEntry;
@@ -58,14 +55,14 @@ import org.apache.logging.log4j.Logger;
public class ForgeTagHandler
{
private static final Logger LOGGER = LogManager.getLogger();
private static Map<ResourceLocation, ITagCollection<?>> customTagTypes = Collections.emptyMap();
private static Map<ResourceLocation, TagCollection<?>> customTagTypes = Collections.emptyMap();
private static Set<ResourceLocation> customTagTypeNames = Collections.emptySet();
private static boolean tagTypesSet = false;
@Nullable
private static <T extends IForgeRegistryEntry<T>> TagRegistry<T> getTagRegistry(IForgeRegistry<T> registry)
private static <T extends IForgeRegistryEntry<T>> StaticTagHelper<T> getTagRegistry(IForgeRegistry<T> registry)
{
return (TagRegistry<T>) TagRegistryManager.get(registry.getRegistryName());
return (StaticTagHelper<T>) StaticTags.get(registry.getRegistryName());
}
private static void validateRegistrySupportsTags(IForgeRegistry<?> registry)
@@ -86,16 +83,16 @@ public class ForgeTagHandler
* @param <T> Type of the registry
* @return A named tag
*/
public static <T extends IForgeRegistryEntry<T>> ITag.INamedTag<T> makeWrapperTag(IForgeRegistry<T> registry, ResourceLocation name)
public static <T extends IForgeRegistryEntry<T>> Named<T> makeWrapperTag(IForgeRegistry<T> registry, ResourceLocation name)
{
validateRegistrySupportsTags(registry);
if (tagTypesSet)
{
TagRegistry<T> tagRegistry = getTagRegistry(registry);
StaticTagHelper<T> tagRegistry = getTagRegistry(registry);
if (tagRegistry == null) throw new IllegalArgumentException("Registry " + registry.getRegistryName() + " does not support tag types.");
return tagRegistry.bind(name.toString());
}
return TagRegistry.createDelayedTag(registry.getRegistryName(), name);
return StaticTagHelper.createDelayedTag(registry.getRegistryName(), name);
}
/**
@@ -127,11 +124,11 @@ public class ForgeTagHandler
validateRegistrySupportsTags(registry);
if (tagTypesSet)
{
TagRegistry<T> tagRegistry = getTagRegistry(registry);
StaticTagHelper<T> tagRegistry = getTagRegistry(registry);
if (tagRegistry == null) throw new IllegalArgumentException("Registry " + registry.getRegistryName() + " does not support tag types.");
return tagRegistry.createOptional(name, defaults);
}
return TagRegistry.createDelayedOptional(registry.getRegistryName(), name, defaults);
return StaticTagHelper.createDelayedOptional(registry.getRegistryName(), name, defaults);
}
/**
@@ -144,7 +141,7 @@ public class ForgeTagHandler
* @implNote This method only errors instantly if tag types have already been set, otherwise the error is delayed until after registries finish initializing
* and we can validate if the custom registry really does support custom tags.
*/
public static <T extends IForgeRegistryEntry<T>> ITag.INamedTag<T> makeWrapperTag(ResourceLocation registryName, ResourceLocation name)
public static <T extends IForgeRegistryEntry<T>> Named<T> makeWrapperTag(ResourceLocation registryName, ResourceLocation name)
{
if (tagTypesSet)
{
@@ -152,7 +149,7 @@ public class ForgeTagHandler
if (registry == null) throw new IllegalArgumentException("Could not find registry named: " + registryName);
return makeWrapperTag(registry, name);
}
return TagRegistry.createDelayedTag(registryName, name);
return StaticTagHelper.createDelayedTag(registryName, name);
}
/**
@@ -189,7 +186,7 @@ public class ForgeTagHandler
if (registry == null) throw new IllegalArgumentException("Could not find registry named: " + registryName);
return createOptionalTag(registry, name, defaults);
}
return TagRegistry.createDelayedOptional(registryName, name, defaults);
return StaticTagHelper.createDelayedOptional(registryName, name, defaults);
}
/**
@@ -203,9 +200,9 @@ public class ForgeTagHandler
/**
* Gets a map of registry name to tag collection for all custom tag types.
*
* @apiNote Prefer interacting with this via the current {@link ITagCollectionSupplier} and using one of the forge extension getCustomTypeCollection methods
* @apiNote Prefer interacting with this via the current {@link IForgeTagContainer} and using one of the forge extension getCustomTypeCollection methods
*/
public static Map<ResourceLocation, ITagCollection<?>> getCustomTagTypes()
public static Map<ResourceLocation, TagCollection<?>> getCustomTagTypes()
{
return customTagTypes;
}
@@ -225,7 +222,7 @@ public class ForgeTagHandler
// Note: If this ends up being a hotspot due to lots of mods having lots of statically registered tags
// that get loaded/registered before the new registry event is fired/processed everywhere then this
// potentially should end up being moved into an async processor.
TagRegistry.performDelayedAdd();
StaticTagHelper.performDelayedAdd();
}
/**
@@ -233,16 +230,16 @@ public class ForgeTagHandler
*
* @apiNote Internal: For use by NetworkTagManager
*/
public static Map<ResourceLocation, TagCollectionReader<?>> createCustomTagTypeReaders()
public static Map<ResourceLocation, TagLoader<?>> createCustomTagTypeReaders()
{
LOGGER.debug("Gathering custom tag collection reader from types.");
ImmutableMap.Builder<ResourceLocation, TagCollectionReader<?>> builder = ImmutableMap.builder();
ImmutableMap.Builder<ResourceLocation, TagLoader<?>> builder = ImmutableMap.builder();
for (ResourceLocation registryName : customTagTypeNames)
{
ForgeRegistry<?> registry = RegistryManager.ACTIVE.getRegistry(registryName);
if (registry != null && registry.getTagFolder() != null)
{
builder.put(registryName, new TagCollectionReader<>(rl -> Optional.ofNullable(registry.getValue(rl)), "tags/" + registry.getTagFolder(), registryName.getPath()));
builder.put(registryName, new TagLoader<>(rl -> Optional.ofNullable(registry.getValue(rl)), "tags/" + registry.getTagFolder()));
}
}
return builder.build();
@@ -255,22 +252,22 @@ public class ForgeTagHandler
*/
public static void resetCachedTagCollections(boolean makeEmpty, boolean withOptional)
{
ImmutableMap.Builder<ResourceLocation, ITagCollection<?>> builder = ImmutableMap.builder();
ImmutableMap.Builder<ResourceLocation, TagCollection<?>> builder = ImmutableMap.builder();
for (ResourceLocation registryName : customTagTypeNames)
{
TagRegistry<?> tagRegistry = TagRegistryManager.get(registryName);
StaticTagHelper<?> tagRegistry = StaticTags.get(registryName);
if (tagRegistry != null)
{
if (makeEmpty)
{
if (withOptional)
builder.put(registryName, tagRegistry.reinjectOptionalTags(ITagCollection.of(Collections.emptyMap())));
builder.put(registryName, tagRegistry.reinjectOptionalTags(TagCollection.of(Collections.emptyMap())));
else
builder.put(registryName, ITagCollection.of(Collections.emptyMap()));
builder.put(registryName, TagCollection.of(Collections.emptyMap()));
}
else
{
builder.put(registryName, ITagCollection.of(tagRegistry.getWrappers().stream().distinct().collect(Collectors.toMap(INamedTag::getName, namedTag -> namedTag))));
builder.put(registryName, TagCollection.of(tagRegistry.getWrappers().stream().distinct().collect(Collectors.toMap(Named::getName, namedTag -> namedTag))));
}
}
}
@@ -282,7 +279,7 @@ public class ForgeTagHandler
*
* @apiNote Internal: For use by TagCollectionManager
*/
public static ITagCollectionSupplier populateTagCollectionManager(ITagCollection<Block> blockTags, ITagCollection<Item> itemTags, ITagCollection<Fluid> fluidTags, ITagCollection<EntityType<?>> entityTypeTags)
public static void populateTagCollectionManager()
{
//Default the tag collections
resetCachedTagCollections(false, false);
@@ -290,7 +287,6 @@ public class ForgeTagHandler
{
LOGGER.debug("Populated the TagCollectionManager with {} extra types", customTagTypes.size());
}
return ITagCollectionSupplier.of(blockTags, itemTags, fluidTags, entityTypeTags);
}
/**
@@ -300,10 +296,10 @@ public class ForgeTagHandler
*/
public static void updateCustomTagTypes(List<TagCollectionReaderInfo> tagCollectionReaders)
{
ImmutableMap.Builder<ResourceLocation, ITagCollection<?>> builder = ImmutableMap.builder();
ImmutableMap.Builder<ResourceLocation, TagCollection<?>> builder = ImmutableMap.builder();
for (TagCollectionReaderInfo info : tagCollectionReaders)
{
builder.put(info.tagType, info.reader.load(info.tagBuilders));
builder.put(info.tagType, info.reader.build(info.tagBuilders));
}
customTagTypes = builder.build();
}
@@ -324,12 +320,14 @@ public class ForgeTagHandler
*
* @apiNote Internal: For use by NetworkTagManager
*/
public static CompletableFuture<List<TagCollectionReaderInfo>> getCustomTagTypeReloadResults(IResourceManager resourceManager, Executor backgroundExecutor, Map<ResourceLocation, TagCollectionReader<?>> readers)
public static CompletableFuture<List<TagCollectionReaderInfo>> getCustomTagTypeReloadResults(ResourceManager resourceManager, Executor backgroundExecutor, Map<ResourceLocation, TagLoader<?>> readers)
{
CompletableFuture<List<TagCollectionReaderInfo>> customResults = CompletableFuture.completedFuture(new ArrayList<>());
for (Map.Entry<ResourceLocation, TagCollectionReader<?>> entry : readers.entrySet())
for (Entry<ResourceLocation, TagLoader<?>> entry : readers.entrySet())
{
customResults = customResults.thenCombine(entry.getValue().prepare(resourceManager, backgroundExecutor), (results, result) -> {
CompletableFuture<Map<ResourceLocation, Tag.Builder>> collectionFuture =
CompletableFuture.supplyAsync(() -> entry.getValue().load(resourceManager), backgroundExecutor);
customResults = customResults.thenCombine(collectionFuture, (results, result) -> {
results.add(new TagCollectionReaderInfo(entry.getKey(), entry.getValue(), result));
return results;
});
@@ -344,71 +342,47 @@ public class ForgeTagHandler
*/
public static void reinjectOptionalTagsCustomTypes()
{
ImmutableMap.Builder<ResourceLocation, ITagCollection<?>> builder = ImmutableMap.builder();
for (Entry<ResourceLocation, ITagCollection<?>> entry : customTagTypes.entrySet())
ImmutableMap.Builder<ResourceLocation, TagCollection<?>> builder = ImmutableMap.builder();
for (Entry<ResourceLocation, TagCollection<?>> entry : customTagTypes.entrySet())
{
ResourceLocation registry = entry.getKey();
TagRegistry<?> tagRegistry = TagRegistryManager.get(registry);
ITagCollection<?> tagCollection = entry.getValue();
builder.put(registry, tagRegistry == null ? tagCollection : tagRegistry.reinjectOptionalTags((ITagCollection) tagCollection));
StaticTagHelper<?> tagRegistry = StaticTags.get(registry);
TagCollection<?> tagCollection = entry.getValue();
builder.put(registry, tagRegistry == null ? tagCollection : tagRegistry.reinjectOptionalTags((TagCollection) tagCollection));
}
customTagTypes = builder.build();
}
/**
* Gets an {@link ITagCollectionSupplier} with empty custom tag type collections to allow for checking if the client is requiring any tags of custom tag types.
* Gets an {@link IForgeTagContainer} with empty custom tag type collections to allow for checking if the client is requiring any tags of custom tag types.
*
* @apiNote Internal: For use with validating missing tags when connecting to a vanilla server
*/
public static ITagCollectionSupplier withNoCustom(ITagCollectionSupplier tagCollectionSupplier)
public static TagContainer withNoCustom(TagContainer tagCollectionSupplier)
{
ImmutableMap.Builder<ResourceLocation, ITagCollection<?>> builder = ImmutableMap.builder();
ImmutableMap.Builder<ResourceLocation, TagCollection<?>> builder = ImmutableMap.builder();
for (ResourceLocation registryName : customTagTypeNames)
{
TagRegistry<?> tagRegistry = TagRegistryManager.get(registryName);
StaticTagHelper<?> tagRegistry = StaticTags.get(registryName);
if (tagRegistry != null)
{
builder.put(registryName, ITagCollection.of(Collections.emptyMap()));
builder.put(registryName, TagCollection.of(Collections.emptyMap()));
}
}
return withSpecificCustom(tagCollectionSupplier, builder.build());
}
/**
* Gets an {@link ITagCollectionSupplier} with specific custom tag types for testing if any tags are missing.
* Gets an {@link IForgeTagContainer} with specific custom tag types for testing if any tags are missing.
*
* @apiNote Internal
*/
public static ITagCollectionSupplier withSpecificCustom(ITagCollectionSupplier tagCollectionSupplier, Map<ResourceLocation, ITagCollection<?>> customTagTypes)
public static TagContainer withSpecificCustom(TagContainer tagCollectionSupplier, Map<ResourceLocation, TagCollection<?>> customTagTypes)
{
return new ITagCollectionSupplier()
return new TagContainer(tagCollectionSupplier.collections)
{
@Override
public ITagCollection<Block> getBlocks()
{
return tagCollectionSupplier.getBlocks();
}
@Override
public ITagCollection<Item> getItems()
{
return tagCollectionSupplier.getItems();
}
@Override
public ITagCollection<Fluid> getFluids()
{
return tagCollectionSupplier.getFluids();
}
@Override
public ITagCollection<EntityType<?>> getEntityTypes()
{
return tagCollectionSupplier.getEntityTypes();
}
@Override
public Map<ResourceLocation, ITagCollection<?>> getCustomTagTypes()
public Map<ResourceLocation, TagCollection<?>> getCustomTagTypes()
{
return customTagTypes;
}
@@ -424,10 +398,10 @@ public class ForgeTagHandler
{
private final ResourceLocation tagType;
private final TagCollectionReader<?> reader;
private final Map<ResourceLocation, ITag.Builder> tagBuilders;
private final TagLoader<?> reader;
private final Map<ResourceLocation, Tag.Builder> tagBuilders;
private TagCollectionReaderInfo(ResourceLocation tagType, TagCollectionReader<?> reader, Map<ResourceLocation, ITag.Builder> tagBuilders)
private TagCollectionReaderInfo(ResourceLocation tagType, TagLoader<?> reader, Map<ResourceLocation, Tag.Builder> tagBuilders)
{
this.tagType = tagType;
this.reader = reader;
@@ -20,7 +20,7 @@
package net.minecraftforge.common;
import com.mojang.serialization.Codec;
import net.minecraft.util.IStringSerializable;
import net.minecraft.util.StringRepresentable;
import java.util.function.Function;
import java.util.function.Supplier;
@@ -57,7 +57,7 @@ public interface IExtensibleEnum
/**
* Use this instead of {@link IStringSerializable#createEnumCodec(Supplier, Function)} for extensible enums because this not cache the enum values on construction
*/
static <E extends Enum<E> & IStringSerializable> Codec<E> createCodecForExtensibleEnum(Supplier<E[]> valuesSupplier, Function<? super String, ? extends E> enumValueFromNameFunction) {
return IStringSerializable.fromStringResolver(Enum::ordinal, (id) -> valuesSupplier.get()[id], enumValueFromNameFunction);
static <E extends Enum<E> & StringRepresentable> Codec<E> createCodecForExtensibleEnum(Supplier<E[]> valuesSupplier, Function<? super String, ? extends E> enumValueFromNameFunction) {
return StringRepresentable.fromStringResolver(Enum::ordinal, (id) -> valuesSupplier.get()[id], enumValueFromNameFunction);
}
}
@@ -22,10 +22,10 @@ package net.minecraftforge.common;
import java.util.Collections;
import java.util.List;
import net.minecraft.entity.player.PlayerEntity;
import net.minecraft.item.ItemStack;
import net.minecraft.util.math.BlockPos;
import net.minecraft.world.World;
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 javax.annotation.Nonnull;
import javax.annotation.Nullable;
@@ -49,7 +49,7 @@ public interface IForgeShearable
* @param pos Block's position in world.
* @return If this is shearable, and onSheared should be called.
*/
default boolean isShearable(@Nonnull ItemStack item, World world, BlockPos pos)
default boolean isShearable(@Nonnull ItemStack item, Level world, BlockPos pos)
{
return true;
}
@@ -73,7 +73,7 @@ public interface IForgeShearable
* @return A List containing all items from this shearing. May be empty.
*/
@Nonnull
default List<ItemStack> onSheared(@Nullable PlayerEntity player, @Nonnull ItemStack item, World world, BlockPos pos, int fortune)
default List<ItemStack> onSheared(@Nullable Player player, @Nonnull ItemStack item, Level world, BlockPos pos, int fortune)
{
return Collections.emptyList();
}
@@ -19,9 +19,9 @@
package net.minecraftforge.common;
import net.minecraft.util.math.AxisAlignedBB;
import net.minecraft.entity.Entity;
import net.minecraft.entity.item.minecart.AbstractMinecartEntity;
import net.minecraft.world.phys.AABB;
import net.minecraft.world.entity.Entity;
import net.minecraft.world.entity.vehicle.AbstractMinecart;
/**
* This class defines a replacement for the default minecart collision code.
@@ -38,7 +38,7 @@ public interface IMinecartCollisionHandler
* @param cart The cart that called the collision.
* @param other The object it collided with.
*/
void onEntityCollision(AbstractMinecartEntity cart, Entity other);
void onEntityCollision(AbstractMinecart cart, Entity other);
/**
* This function replaced the function of the same name in EntityMinecart.
@@ -48,7 +48,7 @@ public interface IMinecartCollisionHandler
* @param other The entity requesting the collision box.
* @return The collision box or null.
*/
AxisAlignedBB getCollisionBox(AbstractMinecartEntity cart, Entity other);
AABB getCollisionBox(AbstractMinecart cart, Entity other);
/**
* This function is used to define the box used for detecting minecart collisions.
@@ -56,7 +56,7 @@ public interface IMinecartCollisionHandler
* @param cart The cart for which the collision box was requested.
* @return The collision box, cannot be null.
*/
AxisAlignedBB getMinecartCollisionBox(AbstractMinecartEntity cart);
AABB getMinecartCollisionBox(AbstractMinecart cart);
/**
* This function replaces the function of the same name in EntityMinecart.
@@ -64,6 +64,6 @@ public interface IMinecartCollisionHandler
* @param cart The cart for which the bounding box was requested.
* @return The bounding box or null.
*/
AxisAlignedBB getBoundingBox(AbstractMinecartEntity cart);
AABB getBoundingBox(AbstractMinecart cart);
}
@@ -19,18 +19,18 @@
package net.minecraftforge.common;
import net.minecraft.block.CropsBlock;
import net.minecraft.block.FlowerBlock;
import net.minecraft.block.SaplingBlock;
import net.minecraft.block.BlockState;
import net.minecraft.block.Blocks;
import net.minecraft.util.math.BlockPos;
import net.minecraft.world.IBlockReader;
import net.minecraft.world.level.block.CropBlock;
import net.minecraft.world.level.block.FlowerBlock;
import net.minecraft.world.level.block.SaplingBlock;
import net.minecraft.world.level.block.state.BlockState;
import net.minecraft.world.level.block.Blocks;
import net.minecraft.core.BlockPos;
import net.minecraft.world.level.BlockGetter;
public interface IPlantable
{
default PlantType getPlantType(IBlockReader world, BlockPos pos) {
if (this instanceof CropsBlock) return PlantType.CROP;
default PlantType getPlantType(BlockGetter world, BlockPos pos) {
if (this instanceof CropBlock) return PlantType.CROP;
if (this instanceof SaplingBlock) return PlantType.PLAINS;
if (this instanceof FlowerBlock) return PlantType.PLAINS;
if (this == Blocks.DEAD_BUSH) return PlantType.DESERT;
@@ -42,5 +42,5 @@ public interface IPlantable
return net.minecraftforge.common.PlantType.PLAINS;
}
BlockState getPlant(IBlockReader world, BlockPos pos);
BlockState getPlant(BlockGetter world, BlockPos pos);
}
@@ -21,7 +21,6 @@ package net.minecraftforge.common;
import net.minecraftforge.eventbus.api.BusBuilder;
import net.minecraftforge.eventbus.api.IEventBus;
import net.minecraft.crash.CrashReport;
import net.minecraftforge.versions.forge.ForgeVersion;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
@@ -19,11 +19,6 @@
package net.minecraftforge.common;
import net.minecraft.block.BlockState;
import net.minecraft.util.Direction;
import net.minecraft.util.math.BlockPos;
import net.minecraft.world.IBlockReader;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.regex.Pattern;
@@ -19,15 +19,15 @@
package net.minecraftforge.common;
import net.minecraft.block.Block;
import net.minecraft.fluid.Fluid;
import net.minecraft.item.DyeColor;
import net.minecraft.item.Item;
import net.minecraft.world.level.block.Block;
import net.minecraft.world.level.material.Fluid;
import net.minecraft.world.item.DyeColor;
import net.minecraft.world.item.Item;
import net.minecraft.tags.BlockTags;
import net.minecraft.tags.FluidTags;
import net.minecraft.tags.ItemTags;
import net.minecraft.util.ResourceLocation;
import net.minecraft.tags.ITag.INamedTag;
import net.minecraft.resources.ResourceLocation;
import net.minecraft.tags.Tag.Named;
public class Tags
{
@@ -307,7 +307,7 @@ public class Tags
}
}
public interface IOptionalNamedTag<T> extends INamedTag<T>
public interface IOptionalNamedTag<T> extends Named<T>
{
/**
* Returns true if the current state is defaulted. This means we have connected to a server that does not contain this tag.
@@ -26,26 +26,26 @@ import java.util.Map;
import it.unimi.dsi.fastutil.ints.Int2ObjectMap;
import it.unimi.dsi.fastutil.ints.Int2ObjectOpenHashMap;
import net.minecraft.entity.merchant.villager.VillagerProfession;
import net.minecraft.entity.merchant.villager.VillagerTrades;
import net.minecraft.entity.merchant.villager.VillagerTrades.ITrade;
import net.minecraft.util.NonNullList;
import net.minecraft.world.entity.npc.VillagerProfession;
import net.minecraft.world.entity.npc.VillagerTrades;
import net.minecraft.world.entity.npc.VillagerTrades.ItemListing;
import net.minecraft.core.NonNullList;
import net.minecraftforge.event.village.VillagerTradesEvent;
import net.minecraftforge.event.village.WandererTradesEvent;
import net.minecraftforge.fml.event.server.FMLServerAboutToStartEvent;
import net.minecraftforge.fmlserverevents.FMLServerAboutToStartEvent;
import net.minecraftforge.registries.ForgeRegistries;
public class VillagerTradingManager
{
private static final Map<VillagerProfession, Int2ObjectMap<ITrade[]>> VANILLA_TRADES = new HashMap<>();
private static final Int2ObjectMap<ITrade[]> WANDERER_TRADES = new Int2ObjectOpenHashMap<>();
private static final Map<VillagerProfession, Int2ObjectMap<ItemListing[]>> VANILLA_TRADES = new HashMap<>();
private static final Int2ObjectMap<ItemListing[]> WANDERER_TRADES = new Int2ObjectOpenHashMap<>();
static
{
VillagerTrades.TRADES.entrySet().forEach(e ->
{
Int2ObjectMap<ITrade[]> copy = new Int2ObjectOpenHashMap<>();
Int2ObjectMap<ItemListing[]> copy = new Int2ObjectOpenHashMap<>();
e.getValue().int2ObjectEntrySet().forEach(ent -> copy.put(ent.getIntKey(), Arrays.copyOf(ent.getValue(), ent.getValue().length)));
VANILLA_TRADES.put(e.getKey(), copy);
});
@@ -63,13 +63,13 @@ public class VillagerTradingManager
*/
private static void postWandererEvent()
{
List<ITrade> generic = NonNullList.create();
List<ITrade> rare = NonNullList.create();
List<ItemListing> generic = NonNullList.create();
List<ItemListing> rare = NonNullList.create();
Arrays.stream(WANDERER_TRADES.get(1)).forEach(generic::add);
Arrays.stream(WANDERER_TRADES.get(2)).forEach(rare::add);
MinecraftForge.EVENT_BUS.post(new WandererTradesEvent(generic, rare));
VillagerTrades.WANDERING_TRADER_TRADES.put(1, generic.toArray(new ITrade[0]));
VillagerTrades.WANDERING_TRADER_TRADES.put(2, rare.toArray(new ITrade[0]));
VillagerTrades.WANDERING_TRADER_TRADES.put(1, generic.toArray(new ItemListing[0]));
VillagerTrades.WANDERING_TRADER_TRADES.put(2, rare.toArray(new ItemListing[0]));
}
/**
@@ -79,8 +79,8 @@ public class VillagerTradingManager
{
for (VillagerProfession prof : ForgeRegistries.PROFESSIONS)
{
Int2ObjectMap<ITrade[]> trades = VANILLA_TRADES.getOrDefault(prof, new Int2ObjectOpenHashMap<>());
Int2ObjectMap<List<ITrade>> mutableTrades = new Int2ObjectOpenHashMap<>();
Int2ObjectMap<ItemListing[]> trades = VANILLA_TRADES.getOrDefault(prof, new Int2ObjectOpenHashMap<>());
Int2ObjectMap<List<ItemListing>> mutableTrades = new Int2ObjectOpenHashMap<>();
for (int i = 1; i < 6; i++)
{
mutableTrades.put(i, NonNullList.create());
@@ -90,8 +90,8 @@ public class VillagerTradingManager
Arrays.stream(e.getValue()).forEach(mutableTrades.get(e.getIntKey())::add);
});
MinecraftForge.EVENT_BUS.post(new VillagerTradesEvent(mutableTrades, prof));
Int2ObjectMap<ITrade[]> newTrades = new Int2ObjectOpenHashMap<>();
mutableTrades.int2ObjectEntrySet().forEach(e -> newTrades.put(e.getIntKey(), e.getValue().toArray(new ITrade[0])));
Int2ObjectMap<ItemListing[]> newTrades = new Int2ObjectOpenHashMap<>();
mutableTrades.int2ObjectEntrySet().forEach(e -> newTrades.put(e.getIntKey(), e.getValue().toArray(new ItemListing[0])));
VillagerTrades.TRADES.put(prof, newTrades);
}
}
@@ -55,7 +55,7 @@ public final class Event implements Comparable<Event>
@Override
public int compareTo(Event event)
{
return new Float(offset).compareTo(event.offset);
return Float.compare(offset, event.offset);
}
@Override
@@ -22,7 +22,7 @@ package net.minecraftforge.common.animation;
import java.io.IOException;
import java.util.regex.Pattern;
import net.minecraft.util.IStringSerializable;
import net.minecraft.util.StringRepresentable;
import java.util.function.Function;
import com.google.common.base.Objects;
@@ -41,7 +41,7 @@ import javax.annotation.Nullable;
*/
public final class TimeValues
{
public static enum IdentityValue implements ITimeValue, IStringSerializable
public static enum IdentityValue implements ITimeValue, StringRepresentable
{
INSTANCE;
@@ -231,7 +231,7 @@ public final class TimeValues
}
}
public static final class ParameterValue implements ITimeValue, IStringSerializable
public static final class ParameterValue implements ITimeValue, StringRepresentable
{
private final String parameterName;
private final Function<String, ITimeValue> valueResolver;
@@ -344,9 +344,9 @@ public final class TimeValues
write(out, p.f);
out.endArray();
}
else if(parameter instanceof IStringSerializable)
else if(parameter instanceof StringRepresentable)
{
out.value("#" + ((IStringSerializable)parameter).getSerializedName());
out.value("#" + ((StringRepresentable)parameter).getSerializedName());
}
}
@@ -19,8 +19,8 @@
package net.minecraftforge.common.brewing;
import net.minecraft.item.ItemStack;
import net.minecraft.item.crafting.Ingredient;
import net.minecraft.world.item.ItemStack;
import net.minecraft.world.item.crafting.Ingredient;
import javax.annotation.Nonnull;
@@ -22,9 +22,9 @@ package net.minecraftforge.common.brewing;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import net.minecraft.item.ItemStack;
import net.minecraft.item.crafting.Ingredient;
import net.minecraft.util.NonNullList;
import net.minecraft.world.item.ItemStack;
import net.minecraft.world.item.crafting.Ingredient;
import net.minecraft.core.NonNullList;
public class BrewingRecipeRegistry {
@@ -19,7 +19,7 @@
package net.minecraftforge.common.brewing;
import net.minecraft.item.ItemStack;
import net.minecraft.world.item.ItemStack;
public interface IBrewingRecipe {
@@ -19,10 +19,10 @@
package net.minecraftforge.common.brewing;
import net.minecraft.item.Items;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraft.potion.PotionBrewing;
import net.minecraft.world.item.Items;
import net.minecraft.world.item.Item;
import net.minecraft.world.item.ItemStack;
import net.minecraft.world.item.alchemy.PotionBrewing;
/**
* Used in BrewingRecipeRegistry to maintain the vanilla behaviour.
@@ -21,5 +21,6 @@
@MethodsReturnNonnullByDefault
package net.minecraftforge.common.brewing;
import mcp.MethodsReturnNonnullByDefault;
import net.minecraft.MethodsReturnNonnullByDefault;
import javax.annotation.ParametersAreNonnullByDefault;
@@ -19,16 +19,9 @@
package net.minecraftforge.common.capabilities;
import java.util.concurrent.Callable;
import com.google.common.base.Throwables;
import net.minecraft.nbt.INBT;
import net.minecraft.util.Direction;
import net.minecraftforge.common.util.LazyOptional;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
/**
* This is the core holder object Capabilities.
@@ -39,104 +32,12 @@ import javax.annotation.Nullable;
*/
public class Capability<T>
{
public static interface IStorage<T>
{
/**
* Serialize the capability instance to a NBTTag.
* This allows for a central implementation of saving the data.
*
* It is important to note that it is up to the API defining
* the capability what requirements the 'instance' value must have.
*
* Due to the possibility of manipulating internal data, some
* implementations MAY require that the 'instance' be an instance
* of the 'default' implementation.
*
* Review the API docs for more info.
*
* @param capability The Capability being stored.
* @param instance An instance of that capabilities interface.
* @param side The side of the object the instance is associated with.
* @return a NBT holding the data. Null if no data needs to be stored.
*/
@Nullable
INBT writeNBT(Capability<T> capability, T instance, Direction side);
/**
* Read the capability instance from a NBT tag.
*
* This allows for a central implementation of saving the data.
*
* It is important to note that it is up to the API defining
* the capability what requirements the 'instance' value must have.
*
* Due to the possibility of manipulating internal data, some
* implementations MAY require that the 'instance' be an instance
* of the 'default' implementation.
*
* Review the API docs for more info. *
*
* @param capability The Capability being stored.
* @param instance An instance of that capabilities interface.
* @param side The side of the object the instance is associated with.
* @param nbt A NBT holding the data. Must not be null, as doesn't make sense to call this function with nothing to read...
*/
void readNBT(Capability<T> capability, T instance, Direction side, INBT nbt);
}
/**
* @return The unique name of this capability, typically this is
* the fully qualified class name for the target interface.
*/
public String getName() { return name; }
/**
* @return An instance of the default storage handler. You can safely use this store your default implementation in NBT.
*/
public IStorage<T> getStorage() { return storage; }
/**
* Quick access to the IStorage's readNBT.
* See {@link IStorage#readNBT(Capability, Object, EnumFacing, NBTBase)} for documentation.
*/
public void readNBT(T instance, Direction side, INBT nbt)
{
storage.readNBT(this, instance, side, nbt);
}
/**
* Quick access to the IStorage's writeNBT.
* See {@link IStorage#writeNBT(Capability, Object, EnumFacing)} for documentation.
*/
@Nullable
public INBT writeNBT(T instance, Direction side)
{
return storage.writeNBT(this, instance, side);
}
/**
* A NEW instance of the default implementation.
*
* If it important to note that if you want to use the default storage
* you may be required to use this exact implementation.
* Refer to the owning API of the Capability in question.
*
* @return A NEW instance of the default implementation.
*/
@Nullable
public T getDefaultInstance()
{
try
{
return this.factory.call();
}
catch (Exception e)
{
Throwables.throwIfUnchecked(e);
throw new RuntimeException(e);
}
}
public @Nonnull <R> LazyOptional<R> orEmpty(Capability<R> toCheck, LazyOptional<T> inst)
{
return this == toCheck ? inst.cast() : LazyOptional.empty();
@@ -144,13 +45,9 @@ public class Capability<T>
// INTERNAL
private final String name;
private final IStorage<T> storage;
private final Callable<? extends T> factory;
Capability(String name, IStorage<T> storage, Callable<? extends T> factory)
Capability(String name)
{
this.name = name;
this.storage = storage;
this.factory = factory;
}
}
@@ -27,11 +27,11 @@ import java.util.Map;
import com.google.common.collect.Lists;
import mcp.MethodsReturnNonnullByDefault;
import net.minecraft.nbt.INBT;
import net.minecraft.nbt.CompoundNBT;
import net.minecraft.util.Direction;
import net.minecraft.util.ResourceLocation;
import net.minecraft.MethodsReturnNonnullByDefault;
import net.minecraft.nbt.Tag;
import net.minecraft.nbt.CompoundTag;
import net.minecraft.core.Direction;
import net.minecraft.resources.ResourceLocation;
import net.minecraftforge.common.util.INBTSerializable;
import net.minecraftforge.common.util.LazyOptional;
@@ -47,10 +47,10 @@ import net.minecraftforge.common.util.LazyOptional;
*/
@ParametersAreNonnullByDefault
@MethodsReturnNonnullByDefault
public final class CapabilityDispatcher implements INBTSerializable<CompoundNBT>, ICapabilityProvider
public final class CapabilityDispatcher implements INBTSerializable<CompoundTag>, ICapabilityProvider
{
private ICapabilityProvider[] caps;
private INBTSerializable<INBT>[] writers;
private INBTSerializable<Tag>[] writers;
private String[] names;
private final List<Runnable> listeners;
@@ -63,7 +63,7 @@ public final class CapabilityDispatcher implements INBTSerializable<CompoundNBT>
public CapabilityDispatcher(Map<ResourceLocation, ICapabilityProvider> list, List<Runnable> listeners, @Nullable ICapabilityProvider parent)
{
List<ICapabilityProvider> lstCaps = Lists.newArrayList();
List<INBTSerializable<INBT>> lstWriters = Lists.newArrayList();
List<INBTSerializable<Tag>> lstWriters = Lists.newArrayList();
List<String> lstNames = Lists.newArrayList();
this.listeners = listeners;
@@ -72,7 +72,7 @@ public final class CapabilityDispatcher implements INBTSerializable<CompoundNBT>
lstCaps.add(parent);
if (parent instanceof INBTSerializable)
{
lstWriters.add((INBTSerializable<INBT>)parent);
lstWriters.add((INBTSerializable<Tag>)parent);
lstNames.add("Parent");
}
}
@@ -83,7 +83,7 @@ public final class CapabilityDispatcher implements INBTSerializable<CompoundNBT>
lstCaps.add(prov);
if (prov instanceof INBTSerializable)
{
lstWriters.add((INBTSerializable<INBT>)prov);
lstWriters.add((INBTSerializable<Tag>)prov);
lstNames.add(entry.getKey().toString());
}
}
@@ -119,9 +119,9 @@ public final class CapabilityDispatcher implements INBTSerializable<CompoundNBT>
}
@Override
public CompoundNBT serializeNBT()
public CompoundTag serializeNBT()
{
CompoundNBT nbt = new CompoundNBT();
CompoundTag nbt = new CompoundTag();
for (int x = 0; x < writers.length; x++)
{
nbt.put(names[x], writers[x].serializeNBT());
@@ -130,7 +130,7 @@ public final class CapabilityDispatcher implements INBTSerializable<CompoundNBT>
}
@Override
public void deserializeNBT(CompoundNBT nbt)
public void deserializeNBT(CompoundTag nbt)
{
for (int x = 0; x < writers.length; x++)
{
@@ -29,7 +29,6 @@ import java.util.IdentityHashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.Callable;
import net.minecraftforge.forgespi.language.ModFileScanData;
import org.apache.logging.log4j.LogManager;
@@ -53,15 +52,11 @@ public enum CapabilityManager
* To retrieve the Capability instance, use the @CapabilityInject annotation.
* This method is safe to call during parallel mod loading.
*
* @param type The Interface to be registered
* @param storage A default implementation of the storage handler.
* @param factory A Factory that will produce new instances of the default implementation.
* @param type The class type to be registered
*/
public <T> void register(Class<T> type, Capability.IStorage<T> storage, Callable<? extends T> factory)
public <T> void register(Class<T> type)
{
Objects.requireNonNull(type,"Attempted to register a capability with invalid type");
Objects.requireNonNull(storage,"Attempted to register a capability with no storage implementation");
Objects.requireNonNull(factory,"Attempted to register a capability with no default implementation factory");
String realName = type.getName().intern();
Capability<T> cap;
@@ -72,7 +67,7 @@ public enum CapabilityManager
throw new IllegalArgumentException("Cannot register a capability implementation multiple times : "+ realName);
}
cap = new Capability<>(realName, storage, factory);
cap = new Capability<>(realName);
providers.put(realName, cap);
}
@@ -87,7 +82,7 @@ public enum CapabilityManager
final List<ModFileScanData.AnnotationData> capabilities = data.stream()
.map(ModFileScanData::getAnnotations)
.flatMap(Collection::stream)
.filter(a -> CAP_INJECT.equals(a.getAnnotationType()))
.filter(a -> CAP_INJECT.equals(a.annotationType()))
.collect(Collectors.toList());
final IdentityHashMap<String, List<Function<Capability<?>, Object>>> m = new IdentityHashMap<>();
capabilities.forEach(entry -> attachCapabilityToMethod(m, entry));
@@ -96,9 +91,9 @@ public enum CapabilityManager
private static void attachCapabilityToMethod(Map<String, List<Function<Capability<?>, Object>>> cbs, ModFileScanData.AnnotationData entry)
{
final String targetClass = entry.getClassType().getClassName();
final String targetName = entry.getMemberName();
Type type = (Type)entry.getAnnotationData().get("value");
final String targetClass = entry.clazz().getClassName();
final String targetName = entry.memberName();
Type type = (Type)entry.annotationData().get("value");
if (type == null)
{
LOGGER.warn(CAPABILITIES,"Unable to inject capability at {}.{} (Invalid Annotation)", targetClass, targetName);
@@ -108,7 +103,7 @@ public enum CapabilityManager
List<Function<Capability<?>, Object>> list = cbs.computeIfAbsent(capabilityName, k -> new ArrayList<>());
if (entry.getMemberName().indexOf('(') > 0)
if (entry.memberName().indexOf('(') > 0)
{
list.add(input -> {
try
@@ -22,9 +22,9 @@ package net.minecraftforge.common.capabilities;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import javax.annotation.ParametersAreNonnullByDefault;
import mcp.MethodsReturnNonnullByDefault;
import net.minecraft.nbt.CompoundNBT;
import net.minecraft.util.Direction;
import net.minecraft.MethodsReturnNonnullByDefault;
import net.minecraft.nbt.CompoundTag;
import net.minecraft.core.Direction;
import net.minecraftforge.common.util.LazyOptional;
import net.minecraftforge.event.ForgeEventFactory;
@@ -78,7 +78,7 @@ public abstract class CapabilityProvider<B extends CapabilityProvider<B>> implem
}
}
protected final @Nullable CompoundNBT serializeCaps()
protected final @Nullable CompoundTag serializeCaps()
{
final CapabilityDispatcher disp = getCapabilities();
if (disp != null)
@@ -88,7 +88,7 @@ public abstract class CapabilityProvider<B extends CapabilityProvider<B>> implem
return null;
}
protected final void deserializeCaps(CompoundNBT tag)
protected final void deserializeCaps(CompoundTag tag)
{
final CapabilityDispatcher disp = getCapabilities();
if (disp != null)
@@ -22,7 +22,7 @@ package net.minecraftforge.common.capabilities;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import net.minecraft.util.Direction;
import net.minecraft.core.Direction;
import net.minecraftforge.common.util.LazyOptional;
public interface ICapabilityProvider
@@ -19,8 +19,8 @@
package net.minecraftforge.common.capabilities;
import net.minecraft.nbt.INBT;
import net.minecraft.nbt.Tag;
import net.minecraftforge.common.util.INBTSerializable;
//Just a mix of the two, useful in patches to lower the size.
public interface ICapabilitySerializable<T extends INBT> extends ICapabilityProvider, INBTSerializable<T>{}
public interface ICapabilitySerializable<T extends Tag> extends ICapabilityProvider, INBTSerializable<T>{}
@@ -22,8 +22,8 @@ package net.minecraftforge.common.command;
import com.mojang.brigadier.StringReader;
import com.mojang.brigadier.exceptions.CommandSyntaxException;
import com.mojang.brigadier.suggestion.SuggestionsBuilder;
import net.minecraft.command.arguments.EntitySelector;
import net.minecraft.command.arguments.EntitySelectorParser;
import net.minecraft.commands.arguments.selector.EntitySelector;
import net.minecraft.commands.arguments.selector.EntitySelectorParser;
import java.util.Arrays;
import java.util.HashMap;
@@ -20,9 +20,9 @@
package net.minecraftforge.common.command;
import com.mojang.brigadier.exceptions.CommandSyntaxException;
import net.minecraft.command.arguments.EntitySelector;
import net.minecraft.command.arguments.EntitySelectorParser;
import net.minecraft.util.text.ITextComponent;
import net.minecraft.commands.arguments.selector.EntitySelector;
import net.minecraft.commands.arguments.selector.EntitySelectorParser;
import net.minecraft.network.chat.Component;
/**
* Implementations of this interface can be registered using {@link EntitySelectorManager#register}
@@ -40,5 +40,5 @@ public interface IEntitySelectorType
/**
* Returns an {@link ITextComponent} containing a short description for this selector type.
*/
ITextComponent getSuggestionTooltip();
Component getSuggestionTooltip();
}
@@ -37,9 +37,9 @@ import com.google.gson.JsonSyntaxException;
import it.unimi.dsi.fastutil.ints.IntArrayList;
import it.unimi.dsi.fastutil.ints.IntComparators;
import it.unimi.dsi.fastutil.ints.IntList;
import net.minecraft.item.ItemStack;
import net.minecraft.item.crafting.Ingredient;
import net.minecraft.network.PacketBuffer;
import net.minecraft.world.item.ItemStack;
import net.minecraft.world.item.crafting.Ingredient;
import net.minecraft.network.FriendlyByteBuf;
public class CompoundIngredient extends Ingredient
{
@@ -147,7 +147,7 @@ public class CompoundIngredient extends Ingredient
public static final Serializer INSTANCE = new Serializer();
@Override
public CompoundIngredient parse(PacketBuffer buffer)
public CompoundIngredient parse(FriendlyByteBuf buffer)
{
return new CompoundIngredient(Stream.generate(() -> Ingredient.fromNetwork(buffer)).limit(buffer.readVarInt()).collect(Collectors.toList()));
}
@@ -159,7 +159,7 @@ public class CompoundIngredient extends Ingredient
}
@Override
public void write(PacketBuffer buffer, CompoundIngredient ingredient)
public void write(FriendlyByteBuf buffer, CompoundIngredient ingredient)
{
buffer.writeVarInt(ingredient.children.size());
ingredient.children.forEach(c -> c.toNetwork(buffer));
@@ -30,8 +30,8 @@ import com.google.gson.JsonObject;
import com.google.gson.JsonSyntaxException;
import net.minecraft.advancements.Advancement;
import net.minecraft.data.IFinishedRecipe;
import net.minecraft.util.JSONUtils;
import net.minecraft.data.recipes.FinishedRecipe;
import net.minecraft.util.GsonHelper;
import net.minecraftforge.common.crafting.conditions.ICondition;
import javax.annotation.Nullable;
@@ -55,7 +55,7 @@ public class ConditionalAdvancement
*/
@Nullable
public static JsonObject processConditional(JsonObject json) {
JsonArray entries = JSONUtils.getAsJsonArray(json, "advancements", null);
JsonArray entries = GsonHelper.getAsJsonArray(json, "advancements", null);
if (entries == null)
{
return CraftingHelper.processConditions(json, "conditions") ? json : null;
@@ -66,8 +66,8 @@ public class ConditionalAdvancement
{
if (!ele.isJsonObject())
throw new JsonSyntaxException("Invalid advancement entry at index " + idx + " Must be JsonObject");
if (CraftingHelper.processConditions(JSONUtils.getAsJsonArray(ele.getAsJsonObject(), "conditions")))
return JSONUtils.getAsJsonObject(ele.getAsJsonObject(), "advancement");
if (CraftingHelper.processConditions(GsonHelper.getAsJsonArray(ele.getAsJsonObject(), "conditions")))
return GsonHelper.getAsJsonObject(ele.getAsJsonObject(), "advancement");
idx++;
}
return null;
@@ -102,7 +102,7 @@ public class ConditionalAdvancement
return addAdvancement(advancement::serializeToJson);
}
public Builder addAdvancement(IFinishedRecipe fromRecipe)
public Builder addAdvancement(FinishedRecipe fromRecipe)
{
return addAdvancement(fromRecipe::serializeAdvancement);
}
@@ -28,13 +28,13 @@ import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonSyntaxException;
import net.minecraft.data.IFinishedRecipe;
import net.minecraft.item.crafting.IRecipe;
import net.minecraft.item.crafting.IRecipeSerializer;
import net.minecraft.item.crafting.RecipeManager;
import net.minecraft.network.PacketBuffer;
import net.minecraft.util.JSONUtils;
import net.minecraft.util.ResourceLocation;
import net.minecraft.data.recipes.FinishedRecipe;
import net.minecraft.world.item.crafting.Recipe;
import net.minecraft.world.item.crafting.RecipeSerializer;
import net.minecraft.world.item.crafting.RecipeManager;
import net.minecraft.network.FriendlyByteBuf;
import net.minecraft.util.GsonHelper;
import net.minecraft.resources.ResourceLocation;
import net.minecraftforge.common.crafting.conditions.ICondition;
import net.minecraftforge.registries.ObjectHolder;
@@ -43,19 +43,19 @@ import javax.annotation.Nullable;
public class ConditionalRecipe
{
@ObjectHolder("forge:conditional")
public static final IRecipeSerializer<IRecipe<?>> SERIALZIER = null;
public static final RecipeSerializer<Recipe<?>> SERIALZIER = null;
public static Builder builder()
{
return new Builder();
}
public static class Serializer<T extends IRecipe<?>> implements IRecipeSerializer<T>
public static class Serializer<T extends Recipe<?>> implements RecipeSerializer<T>
{
private ResourceLocation name;
@Override
public IRecipeSerializer<?> setRegistryName(ResourceLocation name)
public RecipeSerializer<?> setRegistryName(ResourceLocation name)
{
this.name = name;
return this;
@@ -68,9 +68,9 @@ public class ConditionalRecipe
}
@Override
public Class<IRecipeSerializer<?>> getRegistryType()
public Class<RecipeSerializer<?>> getRegistryType()
{
return Serializer.<IRecipeSerializer<?>>castClass(IRecipeSerializer.class);
return Serializer.<RecipeSerializer<?>>castClass(RecipeSerializer.class);
}
@SuppressWarnings("unchecked") // Need this wrapper, because generics
@@ -83,28 +83,28 @@ public class ConditionalRecipe
@Override
public T fromJson(ResourceLocation recipeId, JsonObject json)
{
JsonArray items = JSONUtils.getAsJsonArray(json, "recipes");
JsonArray items = GsonHelper.getAsJsonArray(json, "recipes");
int idx = 0;
for (JsonElement ele : items)
{
if (!ele.isJsonObject())
throw new JsonSyntaxException("Invalid recipes entry at index " + idx + " Must be JsonObject");
if (CraftingHelper.processConditions(JSONUtils.getAsJsonArray(ele.getAsJsonObject(), "conditions")))
return (T)RecipeManager.fromJson(recipeId, JSONUtils.getAsJsonObject(ele.getAsJsonObject(), "recipe"));
if (CraftingHelper.processConditions(GsonHelper.getAsJsonArray(ele.getAsJsonObject(), "conditions")))
return (T)RecipeManager.fromJson(recipeId, GsonHelper.getAsJsonObject(ele.getAsJsonObject(), "recipe"));
idx++;
}
return null;
}
//Should never get here as we return one of the recipes we wrap.
@Override public T fromNetwork(ResourceLocation recipeId, PacketBuffer buffer) { return null; }
@Override public void toNetwork(PacketBuffer buffer, T recipe) {}
@Override public T fromNetwork(ResourceLocation recipeId, FriendlyByteBuf buffer) { return null; }
@Override public void toNetwork(FriendlyByteBuf buffer, T recipe) {}
}
public static class Builder
{
private List<ICondition[]> conditions = new ArrayList<>();
private List<IFinishedRecipe> recipes = new ArrayList<>();
private List<FinishedRecipe> recipes = new ArrayList<>();
private ResourceLocation advId;
private ConditionalAdvancement.Builder adv;
@@ -116,13 +116,13 @@ public class ConditionalRecipe
return this;
}
public Builder addRecipe(Consumer<Consumer<IFinishedRecipe>> callable)
public Builder addRecipe(Consumer<Consumer<FinishedRecipe>> callable)
{
callable.accept(this::addRecipe);
return this;
}
public Builder addRecipe(IFinishedRecipe recipe)
public Builder addRecipe(FinishedRecipe recipe)
{
if (currentConditions.isEmpty())
throw new IllegalStateException("Can not add a recipe with no conditions.");
@@ -168,12 +168,12 @@ public class ConditionalRecipe
return this;
}
public void build(Consumer<IFinishedRecipe> consumer, String namespace, String path)
public void build(Consumer<FinishedRecipe> consumer, String namespace, String path)
{
build(consumer, new ResourceLocation(namespace, path));
}
public void build(Consumer<IFinishedRecipe> consumer, ResourceLocation id)
public void build(Consumer<FinishedRecipe> consumer, ResourceLocation id)
{
if (!currentConditions.isEmpty())
throw new IllegalStateException("Invalid ConditionalRecipe builder, Orphaned conditions");
@@ -189,15 +189,15 @@ public class ConditionalRecipe
}
}
private static class Finished implements IFinishedRecipe
private static class Finished implements FinishedRecipe
{
private final ResourceLocation id;
private final List<ICondition[]> conditions;
private final List<IFinishedRecipe> recipes;
private final List<FinishedRecipe> recipes;
private final ResourceLocation advId;
private final ConditionalAdvancement.Builder adv;
private Finished(ResourceLocation id, List<ICondition[]> conditions, List<IFinishedRecipe> recipes, @Nullable ResourceLocation advId, @Nullable ConditionalAdvancement.Builder adv)
private Finished(ResourceLocation id, List<ICondition[]> conditions, List<FinishedRecipe> recipes, @Nullable ResourceLocation advId, @Nullable ConditionalAdvancement.Builder adv)
{
this.id = id;
this.conditions = conditions;
@@ -230,7 +230,7 @@ public class ConditionalRecipe
}
@Override
public IRecipeSerializer<?> getType()
public RecipeSerializer<?> getType()
{
return SERIALZIER;
}
@@ -36,16 +36,16 @@ import com.google.gson.JsonObject;
import com.google.gson.JsonSyntaxException;
import com.mojang.brigadier.exceptions.CommandSyntaxException;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraft.item.crafting.Ingredient;
import net.minecraft.world.item.Item;
import net.minecraft.world.item.ItemStack;
import net.minecraft.world.item.crafting.Ingredient;
import net.minecraftforge.common.crafting.conditions.ICondition;
import net.minecraftforge.common.crafting.conditions.IConditionSerializer;
import net.minecraft.nbt.JsonToNBT;
import net.minecraft.nbt.CompoundNBT;
import net.minecraft.network.PacketBuffer;
import net.minecraft.util.JSONUtils;
import net.minecraft.util.ResourceLocation;
import net.minecraft.nbt.TagParser;
import net.minecraft.nbt.CompoundTag;
import net.minecraft.network.FriendlyByteBuf;
import net.minecraft.util.GsonHelper;
import net.minecraft.resources.ResourceLocation;
import net.minecraftforge.registries.ForgeRegistries;
import org.apache.logging.log4j.LogManager;
@@ -85,7 +85,7 @@ public class CraftingHelper
{
return ingredients.inverse().get(serializer);
}
public static <T extends Ingredient> void write(PacketBuffer buffer, T ingredient)
public static <T extends Ingredient> void write(FriendlyByteBuf buffer, T ingredient)
{
@SuppressWarnings("unchecked") //I wonder if there is a better way generic wise...
IIngredientSerializer<T> serializer = (IIngredientSerializer<T>)ingredient.getSerializer();
@@ -100,7 +100,7 @@ public class CraftingHelper
serializer.write(buffer, ingredient);
}
public static Ingredient getIngredient(ResourceLocation type, PacketBuffer buffer)
public static Ingredient getIngredient(ResourceLocation type, FriendlyByteBuf buffer)
{
IIngredientSerializer<?> serializer = ingredients.get(type);
if (serializer == null)
@@ -144,7 +144,7 @@ public class CraftingHelper
JsonObject obj = (JsonObject)json;
String type = JSONUtils.getAsString(obj, "type", "minecraft:item");
String type = GsonHelper.getAsString(obj, "type", "minecraft:item");
if (type.isEmpty())
throw new JsonSyntaxException("Ingredient type can not be an empty string");
@@ -157,7 +157,7 @@ public class CraftingHelper
public static ItemStack getItemStack(JsonObject json, boolean readNBT)
{
String itemName = JSONUtils.getAsString(json, "item");
String itemName = GsonHelper.getAsString(json, "item");
Item item = ForgeRegistries.ITEMS.getValue(new ResourceLocation(itemName));
@@ -170,13 +170,13 @@ public class CraftingHelper
try
{
JsonElement element = json.get("nbt");
CompoundNBT nbt;
CompoundTag nbt;
if(element.isJsonObject())
nbt = JsonToNBT.parseTag(GSON.toJson(element));
nbt = TagParser.parseTag(GSON.toJson(element));
else
nbt = JsonToNBT.parseTag(JSONUtils.convertToString(element, "nbt"));
nbt = TagParser.parseTag(GsonHelper.convertToString(element, "nbt"));
CompoundNBT tmp = new CompoundNBT();
CompoundTag tmp = new CompoundTag();
if (nbt.contains("ForgeCaps"))
{
tmp.put("ForgeCaps", nbt.get("ForgeCaps"));
@@ -185,7 +185,7 @@ public class CraftingHelper
tmp.put("tag", nbt);
tmp.putString("id", itemName);
tmp.putInt("Count", JSONUtils.getAsInt(json, "count", 1));
tmp.putInt("Count", GsonHelper.getAsInt(json, "count", 1));
return ItemStack.of(tmp);
}
@@ -195,12 +195,12 @@ public class CraftingHelper
}
}
return new ItemStack(item, JSONUtils.getAsInt(json, "count", 1));
return new ItemStack(item, GsonHelper.getAsInt(json, "count", 1));
}
public static boolean processConditions(JsonObject json, String memberName)
{
return !json.has(memberName) || processConditions(JSONUtils.getAsJsonArray(json, memberName));
return !json.has(memberName) || processConditions(GsonHelper.getAsJsonArray(json, memberName));
}
public static boolean processConditions(JsonArray conditions)
@@ -219,7 +219,7 @@ public class CraftingHelper
public static ICondition getCondition(JsonObject json)
{
ResourceLocation type = new ResourceLocation(JSONUtils.getAsString(json, "type"));
ResourceLocation type = new ResourceLocation(GsonHelper.getAsString(json, "type"));
IConditionSerializer<?> serializer = conditions.get(type);
if (serializer == null)
throw new JsonSyntaxException("Unknown condition type: " + type.toString());
@@ -21,14 +21,14 @@ package net.minecraftforge.common.crafting;
import com.google.gson.JsonObject;
import net.minecraft.item.crafting.Ingredient;
import net.minecraft.network.PacketBuffer;
import net.minecraft.world.item.crafting.Ingredient;
import net.minecraft.network.FriendlyByteBuf;
public interface IIngredientSerializer<T extends Ingredient>
{
T parse(PacketBuffer buffer);
T parse(FriendlyByteBuf buffer);
T parse(JsonObject json);
void write(PacketBuffer buffer, T ingredient);
void write(FriendlyByteBuf buffer, T ingredient);
}
@@ -19,8 +19,8 @@
package net.minecraftforge.common.crafting;
import net.minecraft.inventory.CraftResultInventory;
import net.minecraft.inventory.CraftingInventory;
import net.minecraft.world.inventory.ResultContainer;
import net.minecraft.world.inventory.CraftingContainer;
/**
* This interface is to be implemented on Container objects.
@@ -34,12 +34,12 @@ public interface IRecipeContainer
* The equivalent for {@link ContainerWorkbench} is {@link ContainerWorkbench#craftResult}.
* The equivalent for {@link ContainerPlayer} is {@link ContainerPlayer#craftResult}.
*/
CraftResultInventory getCraftResult();
ResultContainer getCraftResult();
/**
* The crafting matrix of your container, where ingredients go for crafting.
* The equivalent for {@link ContainerWorkbench} is {@link ContainerWorkbench#craftMatrix}.
* The equivalent for {@link ContainerPlayer} is {@link ContainerPlayer#craftMatrix}.
*/
CraftingInventory getCraftMatrix();
CraftingContainer getCraftMatrix();
}
@@ -19,15 +19,15 @@
package net.minecraftforge.common.crafting;
import net.minecraft.inventory.IInventory;
import net.minecraft.item.crafting.IRecipe;
import net.minecraft.world.Container;
import net.minecraft.world.item.crafting.Recipe;
/**
* Used to mark a recipe that shape matters so that the recipe
* book and auto crafting picks the correct shape.
* Note: These methods can't be named 'getHeight' or 'getWidth' due to obfusication issues.
*/
public interface IShapedRecipe<T extends IInventory> extends IRecipe<T>
public interface IShapedRecipe<T extends Container> extends Recipe<T>
{
int getRecipeWidth();
int getRecipeHeight();
@@ -26,16 +26,16 @@ import javax.annotation.Nullable;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import net.minecraft.item.ItemStack;
import net.minecraft.item.crafting.Ingredient;
import net.minecraft.network.PacketBuffer;
import net.minecraft.world.item.ItemStack;
import net.minecraft.world.item.crafting.Ingredient;
import net.minecraft.network.FriendlyByteBuf;
public class NBTIngredient extends Ingredient
{
private final ItemStack stack;
protected NBTIngredient(ItemStack stack)
{
super(Stream.of(new Ingredient.SingleItemList(stack)));
super(Stream.of(new Ingredient.ItemValue(stack)));
this.stack = stack;
}
@@ -77,7 +77,7 @@ public class NBTIngredient extends Ingredient
public static final Serializer INSTANCE = new Serializer();
@Override
public NBTIngredient parse(PacketBuffer buffer) {
public NBTIngredient parse(FriendlyByteBuf buffer) {
return new NBTIngredient(buffer.readItem());
}
@@ -87,7 +87,7 @@ public class NBTIngredient extends Ingredient
}
@Override
public void write(PacketBuffer buffer, NBTIngredient ingredient) {
public void write(FriendlyByteBuf buffer, NBTIngredient ingredient) {
buffer.writeItem(ingredient.stack);
}
}
@@ -25,10 +25,10 @@ import java.util.Collections;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import net.minecraft.item.ItemStack;
import net.minecraft.item.crafting.Ingredient.IItemList;
import net.minecraft.world.item.ItemStack;
import net.minecraft.world.item.crafting.Ingredient.Value;
public class StackList implements IItemList
public class StackList implements Value
{
private Collection<ItemStack> items;
public StackList(Collection<ItemStack> items)
@@ -23,17 +23,17 @@ import java.util.stream.Stream;
import com.google.gson.JsonObject;
import net.minecraft.item.ItemStack;
import net.minecraft.item.crafting.Ingredient;
import net.minecraft.network.PacketBuffer;
import net.minecraft.world.item.ItemStack;
import net.minecraft.world.item.crafting.Ingredient;
import net.minecraft.network.FriendlyByteBuf;
public class VanillaIngredientSerializer implements IIngredientSerializer<Ingredient>
{
public static final VanillaIngredientSerializer INSTANCE = new VanillaIngredientSerializer();
public Ingredient parse(PacketBuffer buffer)
public Ingredient parse(FriendlyByteBuf buffer)
{
return Ingredient.fromValues(Stream.generate(() -> new Ingredient.SingleItemList(buffer.readItem())).limit(buffer.readVarInt()));
return Ingredient.fromValues(Stream.generate(() -> new Ingredient.ItemValue(buffer.readItem())).limit(buffer.readVarInt()));
}
public Ingredient parse(JsonObject json)
@@ -41,7 +41,7 @@ public class VanillaIngredientSerializer implements IIngredientSerializer<Ingred
return Ingredient.fromValues(Stream.of(Ingredient.valueFromJson(json)));
}
public void write(PacketBuffer buffer, Ingredient ingredient)
public void write(FriendlyByteBuf buffer, Ingredient ingredient)
{
ItemStack[] items = ingredient.getItems();
buffer.writeVarInt(items.length);
@@ -28,8 +28,8 @@ import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonSyntaxException;
import net.minecraft.util.JSONUtils;
import net.minecraft.util.ResourceLocation;
import net.minecraft.util.GsonHelper;
import net.minecraft.resources.ResourceLocation;
import net.minecraftforge.common.crafting.CraftingHelper;
public class AndCondition implements ICondition
@@ -91,7 +91,7 @@ public class AndCondition implements ICondition
public AndCondition read(JsonObject json)
{
List<ICondition> children = new ArrayList<>();
for (JsonElement j : JSONUtils.getAsJsonArray(json, "values"))
for (JsonElement j : GsonHelper.getAsJsonArray(json, "values"))
{
if (!j.isJsonObject())
throw new JsonSyntaxException("And condition values must be an array of JsonObjects");
@@ -20,7 +20,7 @@
package net.minecraftforge.common.crafting.conditions;
import com.google.gson.JsonObject;
import net.minecraft.util.ResourceLocation;
import net.minecraft.resources.ResourceLocation;
public final class FalseCondition implements ICondition
{
@@ -19,7 +19,7 @@
package net.minecraftforge.common.crafting.conditions;
import net.minecraft.util.ResourceLocation;
import net.minecraft.resources.ResourceLocation;
public interface ICondition
{
@@ -21,7 +21,7 @@ package net.minecraftforge.common.crafting.conditions;
import com.google.gson.JsonObject;
import net.minecraft.util.ResourceLocation;
import net.minecraft.resources.ResourceLocation;
public interface IConditionSerializer<T extends ICondition>
{
@@ -21,8 +21,8 @@ package net.minecraftforge.common.crafting.conditions;
import com.google.gson.JsonObject;
import net.minecraft.util.JSONUtils;
import net.minecraft.util.ResourceLocation;
import net.minecraft.util.GsonHelper;
import net.minecraft.resources.ResourceLocation;
import net.minecraftforge.registries.ForgeRegistries;
public class ItemExistsCondition implements ICondition
@@ -76,7 +76,7 @@ public class ItemExistsCondition implements ICondition
@Override
public ItemExistsCondition read(JsonObject json)
{
return new ItemExistsCondition(new ResourceLocation(JSONUtils.getAsString(json, "item")));
return new ItemExistsCondition(new ResourceLocation(GsonHelper.getAsString(json, "item")));
}
@Override
@@ -21,8 +21,8 @@ package net.minecraftforge.common.crafting.conditions;
import com.google.gson.JsonObject;
import net.minecraft.util.JSONUtils;
import net.minecraft.util.ResourceLocation;
import net.minecraft.util.GsonHelper;
import net.minecraft.resources.ResourceLocation;
import net.minecraftforge.fml.ModList;
public class ModLoadedCondition implements ICondition
@@ -66,7 +66,7 @@ public class ModLoadedCondition implements ICondition
@Override
public ModLoadedCondition read(JsonObject json)
{
return new ModLoadedCondition(JSONUtils.getAsString(json, "modid"));
return new ModLoadedCondition(GsonHelper.getAsString(json, "modid"));
}
@Override
@@ -20,8 +20,8 @@
package net.minecraftforge.common.crafting.conditions;
import com.google.gson.JsonObject;
import net.minecraft.util.JSONUtils;
import net.minecraft.util.ResourceLocation;
import net.minecraft.util.GsonHelper;
import net.minecraft.resources.ResourceLocation;
import net.minecraftforge.common.crafting.CraftingHelper;
public class NotCondition implements ICondition
@@ -65,7 +65,7 @@ public class NotCondition implements ICondition
@Override
public NotCondition read(JsonObject json)
{
return new NotCondition(CraftingHelper.getCondition(JSONUtils.getAsJsonObject(json, "value")));
return new NotCondition(CraftingHelper.getCondition(GsonHelper.getAsJsonObject(json, "value")));
}
@Override
@@ -28,8 +28,8 @@ import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonSyntaxException;
import net.minecraft.util.JSONUtils;
import net.minecraft.util.ResourceLocation;
import net.minecraft.util.GsonHelper;
import net.minecraft.resources.ResourceLocation;
import net.minecraftforge.common.crafting.CraftingHelper;
public class OrCondition implements ICondition
@@ -92,7 +92,7 @@ public class OrCondition implements ICondition
public OrCondition read(JsonObject json)
{
List<ICondition> children = new ArrayList<>();
for (JsonElement j : JSONUtils.getAsJsonArray(json, "values"))
for (JsonElement j : GsonHelper.getAsJsonArray(json, "values"))
{
if (!j.isJsonObject())
throw new JsonSyntaxException("Or condition values must be an array of JsonObjects");
@@ -21,11 +21,12 @@ package net.minecraftforge.common.crafting.conditions;
import com.google.gson.JsonObject;
import net.minecraft.item.Item;
import net.minecraft.tags.ITag;
import net.minecraft.tags.TagCollectionManager;
import net.minecraft.util.JSONUtils;
import net.minecraft.util.ResourceLocation;
import net.minecraft.core.Registry;
import net.minecraft.world.item.Item;
import net.minecraft.tags.Tag;
import net.minecraft.tags.SerializationTags;
import net.minecraft.util.GsonHelper;
import net.minecraft.resources.ResourceLocation;
public class TagEmptyCondition implements ICondition
{
@@ -56,7 +57,7 @@ public class TagEmptyCondition implements ICondition
@Override
public boolean test()
{
ITag<Item> tag = TagCollectionManager.getInstance().getItems().getTag(tag_name);
Tag<Item> tag = SerializationTags.getInstance().getOrEmpty(Registry.ITEM_REGISTRY).getTag(tag_name);
return tag == null || tag.getValues().isEmpty();
}
@@ -79,7 +80,7 @@ public class TagEmptyCondition implements ICondition
@Override
public TagEmptyCondition read(JsonObject json)
{
return new TagEmptyCondition(new ResourceLocation(JSONUtils.getAsString(json, "tag")));
return new TagEmptyCondition(new ResourceLocation(GsonHelper.getAsString(json, "tag")));
}
@Override
@@ -21,7 +21,7 @@ package net.minecraftforge.common.crafting.conditions;
import com.google.gson.JsonObject;
import net.minecraft.util.ResourceLocation;
import net.minecraft.resources.ResourceLocation;
public final class TrueCondition implements ICondition
{
@@ -22,5 +22,6 @@
@MethodsReturnNonnullByDefault
package net.minecraftforge.common.crafting;
import mcp.MethodsReturnNonnullByDefault;
import net.minecraft.MethodsReturnNonnullByDefault;
import javax.annotation.ParametersAreNonnullByDefault;
@@ -23,37 +23,39 @@ import java.io.File;
import java.io.IOException;
import java.nio.file.Path;
import java.util.Collection;
import java.util.Collections;
import java.util.Set;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.collect.HashMultimap;
import com.google.common.collect.Multimap;
import net.minecraft.data.IDataProvider;
import net.minecraft.client.resources.ResourceIndex;
import net.minecraft.client.resources.VirtualAssetsPack;
import net.minecraft.resources.FilePack;
import net.minecraft.resources.FolderPack;
import net.minecraft.resources.IResource;
import net.minecraft.resources.IResourceManager;
import net.minecraft.resources.IResourcePack;
import net.minecraft.resources.ResourcePackType;
import net.minecraft.resources.SimpleReloadableResourceManager;
import net.minecraft.resources.VanillaPack;
import net.minecraft.util.ResourceLocation;
import net.minecraft.client.resources.ClientPackSource;
import net.minecraft.client.resources.AssetIndex;
import net.minecraft.client.resources.DefaultClientPackResources;
import net.minecraft.data.DataProvider;
import net.minecraft.data.HashCache;
import net.minecraft.server.packs.FilePackResources;
import net.minecraft.server.packs.FolderPackResources;
import net.minecraft.server.packs.repository.ServerPacksSource;
import net.minecraft.server.packs.resources.Resource;
import net.minecraft.server.packs.resources.ResourceManager;
import net.minecraft.server.packs.PackResources;
import net.minecraft.server.packs.PackType;
import net.minecraft.server.packs.resources.SimpleReloadableResourceManager;
import net.minecraft.server.packs.VanillaPackResources;
import net.minecraft.resources.ResourceLocation;
import net.minecraftforge.client.model.generators.ModelBuilder;
import net.minecraftforge.fml.ModList;
import net.minecraftforge.fml.event.lifecycle.GatherDataEvent;
import net.minecraftforge.fml.loading.moddiscovery.ModFileInfo;
import net.minecraftforge.fml.packs.ModFileResourcePack;
import net.minecraftforge.forge.event.lifecycle.GatherDataEvent;
import net.minecraftforge.fmllegacy.packs.ModFileResourcePack;
import net.minecraftforge.forgespi.language.IModFileInfo;
import javax.annotation.Nullable;
/**
* Enables data providers to check if other data files currently exist. The
* instance provided in the {@link GatherDataEvent} utilizes the standard
* resources (via {@link VanillaPack}), forge's resources, as well as any
* resources (via {@link VanillaPackResources}), forge's resources, as well as any
* extra resource packs passed in via the {@code --existing} argument,
* or mod resources via the {@code --existing-mod} argument.
*/
@@ -61,7 +63,7 @@ public class ExistingFileHelper {
public interface IResourceType {
ResourcePackType getPackType();
PackType getPackType();
String getSuffix();
@@ -70,16 +72,16 @@ public class ExistingFileHelper {
public static class ResourceType implements IResourceType {
final ResourcePackType packType;
final PackType packType;
final String suffix, prefix;
public ResourceType(ResourcePackType type, String suffix, String prefix) {
public ResourceType(PackType type, String suffix, String prefix) {
this.packType = type;
this.suffix = suffix;
this.prefix = prefix;
}
@Override
public ResourcePackType getPackType() { return packType; }
public PackType getPackType() { return packType; }
@Override
public String getSuffix() { return suffix; }
@@ -90,12 +92,7 @@ public class ExistingFileHelper {
private final SimpleReloadableResourceManager clientResources, serverData;
private final boolean enable;
private final Multimap<ResourcePackType, ResourceLocation> generated = HashMultimap.create();
@Deprecated//TODO: Remove in 1.17
public ExistingFileHelper(Collection<Path> existingPacks, boolean enable) {
this(existingPacks, Collections.emptySet(), enable);
}
private final Multimap<PackType, ResourceLocation> generated = HashMultimap.create();
/**
* Create a new helper. This should probably <em>NOT</em> be used by mods, as
@@ -108,33 +105,29 @@ public class ExistingFileHelper {
* @param existingPacks
* @param existingMods
* @param enable
* @param assetIndex
* @param assetsDir
*/
@Deprecated // TODO: Remove in 1.17
public ExistingFileHelper(Collection<Path> existingPacks, Set<String> existingMods, boolean enable) {
this(existingPacks, existingMods, enable, null, null);
}
public ExistingFileHelper(Collection<Path> existingPacks, final Set<String> existingMods, boolean enable, @Nullable final String assetIndex, @Nullable final File assetsDir) {
this.clientResources = new SimpleReloadableResourceManager(ResourcePackType.CLIENT_RESOURCES);
this.serverData = new SimpleReloadableResourceManager(ResourcePackType.SERVER_DATA);
this.clientResources = new SimpleReloadableResourceManager(PackType.CLIENT_RESOURCES);
this.serverData = new SimpleReloadableResourceManager(PackType.SERVER_DATA);
this.clientResources.add(new VanillaPack("minecraft", "realms"));
this.clientResources.add(new VanillaPackResources(ClientPackSource.BUILT_IN, "minecraft", "realms"));
if (assetIndex != null && assetsDir != null)
{
this.clientResources.add(new VirtualAssetsPack(new ResourceIndex(assetsDir, assetIndex)));
this.clientResources.add(new DefaultClientPackResources(ClientPackSource.BUILT_IN, new AssetIndex(assetsDir, assetIndex)));
}
this.serverData.add(new VanillaPack("minecraft"));
this.serverData.add(new VanillaPackResources(ServerPacksSource.BUILT_IN_METADATA, "minecraft"));
for (Path existing : existingPacks) {
File file = existing.toFile();
IResourcePack pack = file.isDirectory() ? new FolderPack(file) : new FilePack(file);
PackResources pack = file.isDirectory() ? new FolderPackResources(file) : new FilePackResources(file);
this.clientResources.add(pack);
this.serverData.add(pack);
}
for (String existingMod : existingMods) {
ModFileInfo modFileInfo = ModList.get().getModFileById(existingMod);
IModFileInfo modFileInfo = ModList.get().getModFileById(existingMod);
if (modFileInfo != null) {
IResourcePack pack = new ModFileResourcePack(modFileInfo.getFile());
PackResources pack = new ModFileResourcePack(modFileInfo.getFile());
this.clientResources.add(pack);
this.serverData.add(pack);
}
@@ -142,8 +135,8 @@ public class ExistingFileHelper {
this.enable = enable;
}
private IResourceManager getManager(ResourcePackType packType) {
return packType == ResourcePackType.CLIENT_RESOURCES ? clientResources : serverData;
private ResourceManager getManager(PackType packType) {
return packType == PackType.CLIENT_RESOURCES ? clientResources : serverData;
}
private ResourceLocation getLocation(ResourceLocation base, String suffix, String prefix) {
@@ -159,7 +152,7 @@ public class ExistingFileHelper {
* @return {@code true} if the resource exists in any pack, {@code false}
* otherwise
*/
public boolean exists(ResourceLocation loc, ResourcePackType packType) {
public boolean exists(ResourceLocation loc, PackType packType) {
if (!enable) {
return true;
}
@@ -195,7 +188,7 @@ public class ExistingFileHelper {
* @return {@code true} if the resource exists in any pack, {@code false}
* otherwise
*/
public boolean exists(ResourceLocation loc, ResourcePackType packType, String pathSuffix, String pathPrefix) {
public boolean exists(ResourceLocation loc, PackType packType, String pathSuffix, String pathPrefix) {
return exists(getLocation(loc, pathSuffix, pathPrefix), packType);
}
@@ -206,7 +199,7 @@ public class ExistingFileHelper {
* <p>
* This should be called by data providers immediately when a new data object is
* created, i.e. not during
* {@link IDataProvider#act(net.minecraft.data.DirectoryCache) act} but instead
* {@link DataProvider#run(net.minecraft.data.HashCache) run} but instead
* when the "builder" (or whatever intermediate object) is created, such as a
* {@link ModelBuilder}.
* <p>
@@ -227,7 +220,7 @@ public class ExistingFileHelper {
* <p>
* This should be called by data providers immediately when a new data object is
* created, i.e. not during
* {@link IDataProvider#act(net.minecraft.data.DirectoryCache) act} but instead
* {@link DataProvider#run(HashCache) run} but instead
* when the "builder" (or whatever intermediate object) is created, such as a
* {@link ModelBuilder}.
* <p>
@@ -241,17 +234,17 @@ public class ExistingFileHelper {
* @param pathPrefix a string to append before the path, before a slash, e.g.
* {@code "models"}
*/
public void trackGenerated(ResourceLocation loc, ResourcePackType packType, String pathSuffix, String pathPrefix) {
public void trackGenerated(ResourceLocation loc, PackType packType, String pathSuffix, String pathPrefix) {
this.generated.put(packType, getLocation(loc, pathSuffix, pathPrefix));
}
@VisibleForTesting
public IResource getResource(ResourceLocation loc, ResourcePackType packType, String pathSuffix, String pathPrefix) throws IOException {
public Resource getResource(ResourceLocation loc, PackType packType, String pathSuffix, String pathPrefix) throws IOException {
return getResource(getLocation(loc, pathSuffix, pathPrefix), packType);
}
@VisibleForTesting
public IResource getResource(ResourceLocation loc, ResourcePackType packType) throws IOException {
public Resource getResource(ResourceLocation loc, PackType packType) throws IOException {
return getManager(packType).getResource(loc);
}
@@ -20,22 +20,22 @@
package net.minecraftforge.common.data;
import net.minecraft.data.DataGenerator;
import net.minecraft.item.DyeColor;
import net.minecraft.world.item.DyeColor;
import net.minecraft.tags.BlockTags;
import net.minecraft.tags.ITag;
import net.minecraft.util.ResourceLocation;
import net.minecraft.tags.Tag;
import net.minecraft.resources.ResourceLocation;
import net.minecraftforge.common.Tags;
import net.minecraftforge.registries.ForgeRegistries;
import net.minecraft.block.Block;
import net.minecraft.block.Blocks;
import net.minecraft.data.BlockTagsProvider;
import net.minecraft.world.level.block.Block;
import net.minecraft.world.level.block.Blocks;
import net.minecraft.data.tags.BlockTagsProvider;
import static net.minecraftforge.common.Tags.Blocks.*;
import java.util.Locale;
import java.util.function.Consumer;
public class ForgeBlockTagsProvider extends BlockTagsProvider
public final class ForgeBlockTagsProvider extends BlockTagsProvider
{
public ForgeBlockTagsProvider(DataGenerator gen, ExistingFileHelper existingFileHelper)
{
@@ -97,13 +97,13 @@ public class ForgeBlockTagsProvider extends BlockTagsProvider
tag(STORAGE_BLOCKS_NETHERITE).add(Blocks.NETHERITE_BLOCK);
}
private void addColored(Consumer<Block> consumer, ITag.INamedTag<Block> group, String pattern)
private void addColored(Consumer<Block> consumer, Tag.Named<Block> group, String pattern)
{
String prefix = group.getName().getPath().toUpperCase(Locale.ENGLISH) + '_';
for (DyeColor color : DyeColor.values())
{
ResourceLocation key = new ResourceLocation("minecraft", pattern.replace("{color}", color.getName()));
ITag.INamedTag<Block> tag = getForgeTag(prefix + color.getName());
Tag.Named<Block> tag = getForgeTag(prefix + color.getName());
Block block = ForgeRegistries.BLOCKS.getValue(key);
if (block == null || block == Blocks.AIR)
throw new IllegalStateException("Unknown vanilla block: " + key.toString());
@@ -113,12 +113,12 @@ public class ForgeBlockTagsProvider extends BlockTagsProvider
}
@SuppressWarnings("unchecked")
private ITag.INamedTag<Block> getForgeTag(String name)
private Tag.Named<Block> getForgeTag(String name)
{
try
{
name = name.toUpperCase(Locale.ENGLISH);
return (ITag.INamedTag<Block>)Tags.Blocks.class.getDeclaredField(name).get(null);
return (Tag.Named<Block>)Tags.Blocks.class.getDeclaredField(name).get(null);
}
catch (IllegalArgumentException | IllegalAccessException | NoSuchFieldException | SecurityException e)
{
@@ -20,12 +20,12 @@
package net.minecraftforge.common.data;
import net.minecraft.data.DataGenerator;
import net.minecraft.data.FluidTagsProvider;
import net.minecraft.data.tags.FluidTagsProvider;
import net.minecraftforge.common.ForgeMod;
import static net.minecraftforge.common.Tags.Fluids.MILK;
public class ForgeFluidTagsProvider extends FluidTagsProvider
public final class ForgeFluidTagsProvider extends FluidTagsProvider
{
public ForgeFluidTagsProvider(DataGenerator gen, ExistingFileHelper existingFileHelper)
{
@@ -22,19 +22,19 @@ package net.minecraftforge.common.data;
import java.util.Locale;
import java.util.function.Consumer;
import net.minecraft.block.Block;
import net.minecraft.data.BlockTagsProvider;
import net.minecraft.world.level.block.Block;
import net.minecraft.data.tags.BlockTagsProvider;
import net.minecraft.data.DataGenerator;
import net.minecraft.data.ItemTagsProvider;
import net.minecraft.item.DyeColor;
import net.minecraft.item.Item;
import net.minecraft.item.Items;
import net.minecraft.tags.ITag;
import net.minecraft.util.ResourceLocation;
import net.minecraft.data.tags.ItemTagsProvider;
import net.minecraft.world.item.DyeColor;
import net.minecraft.world.item.Item;
import net.minecraft.world.item.Items;
import net.minecraft.tags.Tag;
import net.minecraft.resources.ResourceLocation;
import net.minecraftforge.common.Tags;
import net.minecraftforge.registries.ForgeRegistries;
public class ForgeItemTagsProvider extends ItemTagsProvider
public final class ForgeItemTagsProvider extends ItemTagsProvider
{
public ForgeItemTagsProvider(DataGenerator gen, BlockTagsProvider blockTagProvider, ExistingFileHelper existingFileHelper)
{
@@ -141,13 +141,13 @@ public class ForgeItemTagsProvider extends ItemTagsProvider
tag(Tags.Items.STRING).add(Items.STRING);
}
private void addColored(Consumer<ITag.INamedTag<Item>> consumer, ITag.INamedTag<Item> group, String pattern)
private void addColored(Consumer<Tag.Named<Item>> consumer, Tag.Named<Item> group, String pattern)
{
String prefix = group.getName().getPath().toUpperCase(Locale.ENGLISH) + '_';
for (DyeColor color : DyeColor.values())
{
ResourceLocation key = new ResourceLocation("minecraft", pattern.replace("{color}", color.getName()));
ITag.INamedTag<Item> tag = getForgeItemTag(prefix + color.getName());
Tag.Named<Item> tag = getForgeItemTag(prefix + color.getName());
Item item = ForgeRegistries.ITEMS.getValue(key);
if (item == null || item == Items.AIR)
throw new IllegalStateException("Unknown vanilla item: " + key.toString());
@@ -156,26 +156,26 @@ public class ForgeItemTagsProvider extends ItemTagsProvider
}
}
private void func_240521_a_Colored(ITag.INamedTag<Block> blockGroup, ITag.INamedTag<Item> itemGroup)
private void func_240521_a_Colored(Tag.Named<Block> blockGroup, Tag.Named<Item> itemGroup)
{
String blockPre = blockGroup.getName().getPath().toUpperCase(Locale.ENGLISH) + '_';
String itemPre = itemGroup.getName().getPath().toUpperCase(Locale.ENGLISH) + '_';
for (DyeColor color : DyeColor.values())
{
ITag.INamedTag<Block> from = getForgeBlockTag(blockPre + color.getName());
ITag.INamedTag<Item> to = getForgeItemTag(itemPre + color.getName());
Tag.Named<Block> from = getForgeBlockTag(blockPre + color.getName());
Tag.Named<Item> to = getForgeItemTag(itemPre + color.getName());
copy(from, to);
}
copy(getForgeBlockTag(blockPre + "colorless"), getForgeItemTag(itemPre + "colorless"));
}
@SuppressWarnings("unchecked")
private ITag.INamedTag<Block> getForgeBlockTag(String name)
private Tag.Named<Block> getForgeBlockTag(String name)
{
try
{
name = name.toUpperCase(Locale.ENGLISH);
return (ITag.INamedTag<Block>)Tags.Blocks.class.getDeclaredField(name).get(null);
return (Tag.Named<Block>)Tags.Blocks.class.getDeclaredField(name).get(null);
}
catch (IllegalArgumentException | IllegalAccessException | NoSuchFieldException | SecurityException e)
{
@@ -184,12 +184,12 @@ public class ForgeItemTagsProvider extends ItemTagsProvider
}
@SuppressWarnings("unchecked")
private ITag.INamedTag<Item> getForgeItemTag(String name)
private Tag.Named<Item> getForgeItemTag(String name)
{
try
{
name = name.toUpperCase(Locale.ENGLISH);
return (ITag.INamedTag<Item>)Tags.Items.class.getDeclaredField(name).get(null);
return (Tag.Named<Item>)Tags.Items.class.getDeclaredField(name).get(null);
}
catch (IllegalArgumentException | IllegalAccessException | NoSuchFieldException | SecurityException e)
{
@@ -20,47 +20,54 @@
package net.minecraftforge.common.data;
import com.mojang.datafixers.util.Pair;
import net.minecraft.advancements.criterion.ItemPredicate;
import net.minecraft.advancements.critereon.ItemPredicate;
import net.minecraft.data.DataGenerator;
import net.minecraft.data.LootTableProvider;
import net.minecraft.item.Item;
import net.minecraft.item.Items;
import net.minecraft.tags.ITag;
import net.minecraft.util.ResourceLocation;
import net.minecraft.loot.*;
import net.minecraft.loot.conditions.Alternative;
import net.minecraft.loot.conditions.ILootCondition;
import net.minecraft.loot.conditions.Inverted;
import net.minecraft.loot.conditions.MatchTool;
import net.minecraft.data.loot.LootTableProvider;
import net.minecraft.world.item.Item;
import net.minecraft.world.item.Items;
import net.minecraft.tags.Tag;
import net.minecraft.resources.ResourceLocation;
import net.minecraft.world.level.storage.loot.predicates.AlternativeLootItemCondition;
import net.minecraft.world.level.storage.loot.predicates.LootItemCondition;
import net.minecraft.world.level.storage.loot.predicates.InvertedLootItemCondition;
import net.minecraft.world.level.storage.loot.predicates.MatchTool;
import net.minecraftforge.common.Tags;
import net.minecraftforge.fml.common.ObfuscationReflectionHelper;
import net.minecraftforge.fml.util.ObfuscationReflectionHelper;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.function.BiConsumer;
import java.util.function.Consumer;
import java.util.function.Supplier;
import java.util.stream.Collectors;
import net.minecraft.world.level.storage.loot.LootPool;
import net.minecraft.world.level.storage.loot.LootTable;
import net.minecraft.world.level.storage.loot.ValidationContext;
import net.minecraft.world.level.storage.loot.entries.CompositeEntryBase;
import net.minecraft.world.level.storage.loot.entries.LootPoolEntryContainer;
import net.minecraft.world.level.storage.loot.parameters.LootContextParamSet;
/**
* Currently used only for replacing shears item to shears tag
*/
public class ForgeLootTableProvider extends LootTableProvider {
public final class ForgeLootTableProvider extends LootTableProvider {
public ForgeLootTableProvider(DataGenerator gen) {
super(gen);
}
@Override
protected void validate(Map<ResourceLocation, LootTable> map, ValidationTracker validationtracker) {
protected void validate(Map<ResourceLocation, LootTable> map, ValidationContext validationtracker) {
// do not validate against all registered loot tables
}
@Override
protected List<Pair<Supplier<Consumer<BiConsumer<ResourceLocation, LootTable.Builder>>>, LootParameterSet>> getTables() {
protected List<Pair<Supplier<Consumer<BiConsumer<ResourceLocation, LootTable.Builder>>>, LootContextParamSet>> getTables() {
return super.getTables().stream().map(pair -> {
// provides new consumer with filtering only changed loot tables and replacing condition item to condition tag
return new Pair<Supplier<Consumer<BiConsumer<ResourceLocation, LootTable.Builder>>>, LootParameterSet>(() -> replaceAndFilterChangesOnly(pair.getFirst().get()), pair.getSecond());
return new Pair<Supplier<Consumer<BiConsumer<ResourceLocation, LootTable.Builder>>>, LootContextParamSet>(() -> replaceAndFilterChangesOnly(pair.getFirst().get()), pair.getSecond());
}).collect(Collectors.toList());
}
@@ -72,12 +79,12 @@ public class ForgeLootTableProvider extends LootTableProvider {
});
}
private boolean findAndReplaceInLootTableBuilder(LootTable.Builder builder, Item from, ITag.INamedTag<Item> to) {
List<LootPool> lootPools = ObfuscationReflectionHelper.getPrivateValue(LootTable.Builder.class, builder, "field_216041" + "_a");
private boolean findAndReplaceInLootTableBuilder(LootTable.Builder builder, Item from, Tag.Named<Item> to) {
List<LootPool> lootPools = ObfuscationReflectionHelper.getPrivateValue(LootTable.Builder.class, builder, "f_7915" + "6_");
boolean found = false;
if (lootPools == null) {
throw new IllegalStateException(LootTable.Builder.class.getName() + " is missing field field_216041" + "_a");
throw new IllegalStateException(LootTable.Builder.class.getName() + " is missing field f_7915" + "6_");
}
for (LootPool lootPool : lootPools) {
@@ -89,39 +96,39 @@ public class ForgeLootTableProvider extends LootTableProvider {
return found;
}
private boolean findAndReplaceInLootPool(LootPool lootPool, Item from, ITag.INamedTag<Item> to) {
List<LootEntry> lootEntries = ObfuscationReflectionHelper.getPrivateValue(LootPool.class, lootPool, "field_186453" +"_a");
List<ILootCondition> lootConditions = ObfuscationReflectionHelper.getPrivateValue(LootPool.class, lootPool, "field_186454" + "_b");
private boolean findAndReplaceInLootPool(LootPool lootPool, Item from, Tag.Named<Item> to) {
List<LootPoolEntryContainer> lootEntries = ObfuscationReflectionHelper.getPrivateValue(LootPool.class, lootPool, "f_7902" +"3_");
List<LootItemCondition> lootConditions = ObfuscationReflectionHelper.getPrivateValue(LootPool.class, lootPool, "f_7902" + "4_");
boolean found = false;
if (lootEntries == null) {
throw new IllegalStateException(LootPool.class.getName() + " is missing field field_186453" + "_a");
throw new IllegalStateException(LootPool.class.getName() + " is missing field f_7902" + "3_");
}
for (LootEntry lootEntry : lootEntries) {
if (lootEntry instanceof ParentedLootEntry) {
if (findAndReplaceInParentedLootEntry((ParentedLootEntry) lootEntry, from, to)) {
for (LootPoolEntryContainer lootEntry : lootEntries) {
if (lootEntry instanceof CompositeEntryBase) {
if (findAndReplaceInParentedLootEntry((CompositeEntryBase) lootEntry, from, to)) {
found = true;
}
}
}
if (lootConditions == null) {
throw new IllegalStateException(LootPool.class.getName() + " is missing field field_186454" + "_b");
throw new IllegalStateException(LootPool.class.getName() + " is missing field f_7902" + "4_");
}
for (int i = 0; i < lootConditions.size(); i++) {
ILootCondition lootCondition = lootConditions.get(i);
LootItemCondition lootCondition = lootConditions.get(i);
if (lootCondition instanceof MatchTool && checkMatchTool((MatchTool) lootCondition, from)) {
lootConditions.set(i, MatchTool.toolMatches(ItemPredicate.Builder.item().of(to)).build());
found = true;
} else if (lootCondition instanceof Inverted) {
ILootCondition invLootCondition = ObfuscationReflectionHelper.getPrivateValue(Inverted.class, (Inverted) lootCondition, "field_215981" + "_a");
} else if (lootCondition instanceof InvertedLootItemCondition) {
LootItemCondition invLootCondition = ObfuscationReflectionHelper.getPrivateValue(InvertedLootItemCondition.class, (InvertedLootItemCondition) lootCondition, "f_8168" + "1_");
if (invLootCondition instanceof MatchTool && checkMatchTool((MatchTool) invLootCondition, from)) {
lootConditions.set(i, Inverted.invert(MatchTool.toolMatches(ItemPredicate.Builder.item().of(to))).build());
lootConditions.set(i, InvertedLootItemCondition.invert(MatchTool.toolMatches(ItemPredicate.Builder.item().of(to))).build());
found = true;
} else if (invLootCondition instanceof Alternative && findAndReplaceInAlternative((Alternative) invLootCondition, from, to)) {
} else if (invLootCondition instanceof AlternativeLootItemCondition && findAndReplaceInAlternative((AlternativeLootItemCondition) invLootCondition, from, to)) {
found = true;
}
}
@@ -130,15 +137,15 @@ public class ForgeLootTableProvider extends LootTableProvider {
return found;
}
private boolean findAndReplaceInParentedLootEntry(ParentedLootEntry entry, Item from, ITag.INamedTag<Item> to) {
LootEntry[] lootEntries = ObfuscationReflectionHelper.getPrivateValue(ParentedLootEntry.class, entry, "field_216147" + "_c");
private boolean findAndReplaceInParentedLootEntry(CompositeEntryBase entry, Item from, Tag.Named<Item> to) {
LootPoolEntryContainer[] lootEntries = ObfuscationReflectionHelper.getPrivateValue(CompositeEntryBase.class, entry, "f_7942" + "8_");
boolean found = false;
if (lootEntries == null) {
throw new IllegalStateException(ParentedLootEntry.class.getName() + " is missing field field_216147" + "_c");
throw new IllegalStateException(CompositeEntryBase.class.getName() + " is missing field f_7942" + "8_");
}
for (LootEntry lootEntry : lootEntries) {
for (LootPoolEntryContainer lootEntry : lootEntries) {
if (findAndReplaceInLootEntry(lootEntry, from, to)) {
found = true;
}
@@ -147,16 +154,16 @@ public class ForgeLootTableProvider extends LootTableProvider {
return found;
}
private boolean findAndReplaceInLootEntry(LootEntry entry, Item from, ITag.INamedTag<Item> to) {
ILootCondition[] lootConditions = ObfuscationReflectionHelper.getPrivateValue(LootEntry.class, entry, "field_216144" + "_d");
private boolean findAndReplaceInLootEntry(LootPoolEntryContainer entry, Item from, Tag.Named<Item> to) {
LootItemCondition[] lootConditions = ObfuscationReflectionHelper.getPrivateValue(LootPoolEntryContainer.class, entry, "f_7963" + "6_");
boolean found = false;
if (lootConditions == null) {
throw new IllegalStateException(LootEntry.class.getName() + " is missing field field_216144" + "_d");
throw new IllegalStateException(LootPoolEntryContainer.class.getName() + " is missing field f_7963" + "6_");
}
for (int i = 0; i < lootConditions.length; i++) {
if (lootConditions[i] instanceof Alternative && findAndReplaceInAlternative((Alternative) lootConditions[i], from, to)) {
if (lootConditions[i] instanceof AlternativeLootItemCondition && findAndReplaceInAlternative((AlternativeLootItemCondition) lootConditions[i], from, to)) {
found = true;
} else if (lootConditions[i] instanceof MatchTool && checkMatchTool((MatchTool) lootConditions[i], from)) {
lootConditions[i] = MatchTool.toolMatches(ItemPredicate.Builder.item().of(to)).build();
@@ -167,12 +174,12 @@ public class ForgeLootTableProvider extends LootTableProvider {
return found;
}
private boolean findAndReplaceInAlternative(Alternative alternative, Item from, ITag.INamedTag<Item> to) {
ILootCondition[] lootConditions = ObfuscationReflectionHelper.getPrivateValue(Alternative.class, alternative, "field_215962" + "_a");
private boolean findAndReplaceInAlternative(AlternativeLootItemCondition alternative, Item from, Tag.Named<Item> to) {
LootItemCondition[] lootConditions = ObfuscationReflectionHelper.getPrivateValue(AlternativeLootItemCondition.class, alternative, "f_8146" + "8_");
boolean found = false;
if (lootConditions == null) {
throw new IllegalStateException(Alternative.class.getName() + " is missing field field_215962" + "_a");
throw new IllegalStateException(AlternativeLootItemCondition.class.getName() + " is missing field f_8146" + "8_");
}
for (int i = 0; i < lootConditions.length; i++) {
@@ -186,8 +193,8 @@ public class ForgeLootTableProvider extends LootTableProvider {
}
private boolean checkMatchTool(MatchTool lootCondition, Item expected) {
ItemPredicate predicate = ObfuscationReflectionHelper.getPrivateValue(MatchTool.class, lootCondition, "field_216014" + "_a");
Item item = ObfuscationReflectionHelper.getPrivateValue(ItemPredicate.class, predicate, "field_192496" + "_b");
return item != null && item.equals(expected);
ItemPredicate predicate = ObfuscationReflectionHelper.getPrivateValue(MatchTool.class, lootCondition, "f_8199" + "3_");
Set<Item> items = ObfuscationReflectionHelper.getPrivateValue(ItemPredicate.class, predicate, "f_15142" + "7_");
return items != null && items.contains(expected);
}
}
@@ -31,28 +31,28 @@ import java.util.function.Consumer;
import com.google.gson.JsonObject;
import net.minecraft.block.Blocks;
import net.minecraft.world.level.block.Blocks;
import net.minecraft.data.DataGenerator;
import net.minecraft.data.DirectoryCache;
import net.minecraft.data.IFinishedRecipe;
import net.minecraft.data.RecipeProvider;
import net.minecraft.data.ShapedRecipeBuilder;
import net.minecraft.data.ShapelessRecipeBuilder;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraft.item.Items;
import net.minecraft.item.crafting.Ingredient;
import net.minecraft.item.crafting.Ingredient.IItemList;
import net.minecraft.item.crafting.Ingredient.TagList;
import net.minecraft.item.crafting.Ingredient.SingleItemList;
import net.minecraft.tags.ITag;
import net.minecraft.util.IItemProvider;
import net.minecraft.util.ResourceLocation;
import net.minecraft.data.HashCache;
import net.minecraft.data.recipes.FinishedRecipe;
import net.minecraft.data.recipes.RecipeProvider;
import net.minecraft.data.recipes.ShapedRecipeBuilder;
import net.minecraft.data.recipes.ShapelessRecipeBuilder;
import net.minecraft.world.item.Item;
import net.minecraft.world.item.ItemStack;
import net.minecraft.world.item.Items;
import net.minecraft.world.item.crafting.Ingredient;
import net.minecraft.world.item.crafting.Ingredient.Value;
import net.minecraft.world.item.crafting.Ingredient.TagValue;
import net.minecraft.world.item.crafting.Ingredient.ItemValue;
import net.minecraft.tags.Tag;
import net.minecraft.world.level.ItemLike;
import net.minecraft.resources.ResourceLocation;
import net.minecraftforge.common.Tags;
public class ForgeRecipeProvider extends RecipeProvider
public final class ForgeRecipeProvider extends RecipeProvider
{
private Map<Item, ITag<Item>> replacements = new HashMap<>();
private Map<Item, Tag<Item>> replacements = new HashMap<>();
private Set<ResourceLocation> excludes = new HashSet<>();
public ForgeRecipeProvider(DataGenerator generatorIn)
@@ -60,18 +60,18 @@ public class ForgeRecipeProvider extends RecipeProvider
super(generatorIn);
}
private void exclude(IItemProvider item)
private void exclude(ItemLike item)
{
excludes.add(item.asItem().getRegistryName());
}
private void replace(IItemProvider item, ITag<Item> tag)
private void replace(ItemLike item, Tag<Item> tag)
{
replacements.put(item.asItem(), tag);
}
@Override
protected void buildShapelessRecipes(Consumer<IFinishedRecipe> consumer)
protected void buildCraftingRecipes(Consumer<FinishedRecipe> consumer)
{
replace(Items.STICK, Tags.Items.RODS_WOODEN);
replace(Items.GOLD_INGOT, Tags.Items.INGOTS_GOLD);
@@ -94,19 +94,19 @@ public class ForgeRecipeProvider extends RecipeProvider
exclude(Blocks.COBBLESTONE_SLAB);
exclude(Blocks.COBBLESTONE_WALL);
super.buildShapelessRecipes(vanilla -> {
IFinishedRecipe modified = enhance(vanilla);
super.buildCraftingRecipes(vanilla -> {
FinishedRecipe modified = enhance(vanilla);
if (modified != null)
consumer.accept(modified);
});
}
@Override
protected void saveAdvancement(DirectoryCache cache, JsonObject advancementJson, Path pathIn) {
protected void saveAdvancement(HashCache cache, JsonObject advancementJson, Path pathIn) {
//NOOP - We dont replace any of the advancement things yet...
}
private IFinishedRecipe enhance(IFinishedRecipe vanilla)
private FinishedRecipe enhance(FinishedRecipe vanilla)
{
if (vanilla instanceof ShapelessRecipeBuilder.Result)
return enhance((ShapelessRecipeBuilder.Result)vanilla);
@@ -115,7 +115,7 @@ public class ForgeRecipeProvider extends RecipeProvider
return null;
}
private IFinishedRecipe enhance(ShapelessRecipeBuilder.Result vanilla)
private FinishedRecipe enhance(ShapelessRecipeBuilder.Result vanilla)
{
List<Ingredient> ingredients = getField(ShapelessRecipeBuilder.Result.class, vanilla, 4);
boolean modified = false;
@@ -131,7 +131,7 @@ public class ForgeRecipeProvider extends RecipeProvider
return modified ? vanilla : null;
}
private IFinishedRecipe enhance(ShapedRecipeBuilder.Result vanilla)
private FinishedRecipe enhance(ShapedRecipeBuilder.Result vanilla)
{
Map<Character, Ingredient> ingredients = getField(ShapedRecipeBuilder.Result.class, vanilla, 5);
boolean modified = false;
@@ -153,17 +153,17 @@ public class ForgeRecipeProvider extends RecipeProvider
return null;
boolean modified = false;
List<IItemList> items = new ArrayList<>();
IItemList[] vanillaItems = getField(Ingredient.class, vanilla, 2); //This will probably crash between versions, if null fix index
for (IItemList entry : vanillaItems)
List<Value> items = new ArrayList<>();
Value[] vanillaItems = getField(Ingredient.class, vanilla, 2); //This will probably crash between versions, if null fix index
for (Value entry : vanillaItems)
{
if (entry instanceof SingleItemList)
if (entry instanceof ItemValue)
{
ItemStack stack = entry.getItems().stream().findFirst().orElse(ItemStack.EMPTY);
ITag<Item> replacement = replacements.get(stack.getItem());
Tag<Item> replacement = replacements.get(stack.getItem());
if (replacement != null)
{
items.add(new TagList(replacement));
items.add(new TagValue(replacement));
modified = true;
}
else
@@ -25,9 +25,9 @@ import java.nio.file.Path;
import java.util.Map;
import javax.annotation.Nullable;
import net.minecraft.data.DataGenerator;
import net.minecraft.data.TagsProvider;
import net.minecraft.util.ResourceLocation;
import net.minecraft.util.registry.Registry;
import net.minecraft.data.tags.TagsProvider;
import net.minecraft.resources.ResourceLocation;
import net.minecraft.core.Registry;
import net.minecraftforge.registries.ForgeRegistries;
import net.minecraftforge.registries.ForgeRegistry;
import net.minecraftforge.registries.GameData;
@@ -24,13 +24,12 @@ import com.google.gson.GsonBuilder;
import com.google.gson.JsonObject;
import cpw.mods.modlauncher.api.LamdbaExceptionUtils;
import net.minecraft.data.DataGenerator;
import net.minecraft.data.DirectoryCache;
import net.minecraft.data.IDataProvider;
import net.minecraft.util.ResourceLocation;
import net.minecraft.data.HashCache;
import net.minecraft.data.DataProvider;
import net.minecraft.resources.ResourceLocation;
import net.minecraft.util.Tuple;
import net.minecraftforge.common.loot.GlobalLootModifierSerializer;
import net.minecraftforge.common.loot.IGlobalLootModifier;
import net.minecraftforge.common.loot.LootModifier;
import java.io.IOException;
import java.nio.file.Path;
@@ -41,11 +40,11 @@ import java.util.Map;
import java.util.stream.Collectors;
/**
* Provider for forge's GlobalLootModifier system. See {@link LootModifier} and {@link GlobalLootModifierSerializer}.
* Provider for forge's GlobalLootModifier system. See {@link net.minecraftforge.common.loot.LootModifier} and {@link GlobalLootModifierSerializer}.
*
* This provider only requires implementing {@link #start()} and calling {@link #add} from it.
*/
public abstract class GlobalLootModifierProvider implements IDataProvider
public abstract class GlobalLootModifierProvider implements DataProvider
{
private static final Gson GSON = new GsonBuilder().setPrettyPrinting().create();
private final DataGenerator gen;
@@ -73,7 +72,7 @@ public abstract class GlobalLootModifierProvider implements IDataProvider
protected abstract void start();
@Override
public void run(DirectoryCache cache) throws IOException
public void run(HashCache cache) throws IOException
{
start();
@@ -89,14 +88,14 @@ public abstract class GlobalLootModifierProvider implements IDataProvider
JsonObject json = pair.getB();
json.addProperty("type", pair.getA().getRegistryName().toString());
IDataProvider.save(GSON, cache, json, modifierPath);
DataProvider.save(GSON, cache, json, modifierPath);
}));
JsonObject forgeJson = new JsonObject();
forgeJson.addProperty("replace", this.replace);
forgeJson.add("entries", GSON.toJsonTree(entries.stream().map(ResourceLocation::toString).collect(Collectors.toList())));
IDataProvider.save(GSON, cache, forgeJson, forgePath);
DataProvider.save(GSON, cache, forgeJson, forgePath);
}
/**
@@ -33,19 +33,18 @@ import org.apache.commons.lang3.text.translate.JavaUnicodeEscaper;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import net.minecraft.block.Block;
import net.minecraft.world.level.block.Block;
import net.minecraft.data.DataGenerator;
import net.minecraft.data.DirectoryCache;
import net.minecraft.data.IDataProvider;
import net.minecraft.enchantment.Enchantment;
import net.minecraft.entity.EntityType;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraft.potion.Effect;
import net.minecraft.world.biome.Biome;
import net.minecraft.data.HashCache;
import net.minecraft.data.DataProvider;
import net.minecraft.world.item.enchantment.Enchantment;
import net.minecraft.world.entity.EntityType;
import net.minecraft.world.item.Item;
import net.minecraft.world.item.ItemStack;
import net.minecraft.world.effect.MobEffect;
@SuppressWarnings("deprecation")
public abstract class LanguageProvider implements IDataProvider {
public abstract class LanguageProvider implements DataProvider {
private static final Gson GSON = (new GsonBuilder()).setPrettyPrinting().disableHtmlEscaping().create();
private final Map<String, String> data = new TreeMap<>();
private final DataGenerator gen;
@@ -61,7 +60,7 @@ public abstract class LanguageProvider implements IDataProvider {
protected abstract void addTranslations();
@Override
public void run(DirectoryCache cache) throws IOException {
public void run(HashCache cache) throws IOException {
addTranslations();
if (!data.isEmpty())
save(cache, data, this.gen.getOutputFolder().resolve("assets/" + modid + "/lang/" + locale + ".json"));
@@ -72,10 +71,10 @@ public abstract class LanguageProvider implements IDataProvider {
return "Languages: " + locale;
}
private void save(DirectoryCache cache, Object object, Path target) throws IOException {
private void save(HashCache cache, Object object, Path target) throws IOException {
String data = GSON.toJson(object);
data = JavaUnicodeEscaper.outsideOf(0, 0x7f).translate(data); // Escape unicode after the fact so that it's not double escaped by GSON
String hash = IDataProvider.SHA1.hashUnencodedChars(data).toString();
String hash = DataProvider.SHA1.hashUnencodedChars(data).toString();
if (!Objects.equals(cache.getHash(target), hash) || !Files.exists(target)) {
Files.createDirectories(target.getParent());
@@ -129,11 +128,11 @@ public abstract class LanguageProvider implements IDataProvider {
}
*/
public void addEffect(Supplier<? extends Effect> key, String name) {
public void addEffect(Supplier<? extends MobEffect> key, String name) {
add(key.get(), name);
}
public void add(Effect key, String name) {
public void add(MobEffect key, String name) {
add(key.getDescriptionId(), name);
}
@@ -23,7 +23,7 @@ import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonPrimitive;
import net.minecraft.util.ResourceLocation;
import net.minecraft.resources.ResourceLocation;
import javax.annotation.Nullable;
import java.util.ArrayList;
@@ -23,11 +23,11 @@ import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonObject;
import net.minecraft.data.DataGenerator;
import net.minecraft.data.DirectoryCache;
import net.minecraft.data.IDataProvider;
import net.minecraft.resources.ResourcePackType;
import net.minecraft.util.ResourceLocation;
import net.minecraft.util.SoundEvent;
import net.minecraft.data.HashCache;
import net.minecraft.data.DataProvider;
import net.minecraft.resources.ResourceLocation;
import net.minecraft.server.packs.PackType;
import net.minecraft.sounds.SoundEvent;
import net.minecraftforge.registries.ForgeRegistries;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
@@ -44,7 +44,7 @@ import java.util.stream.Collectors;
* Data provider for the {@code sounds.json} file, which identifies sound definitions
* for the various sound events in Minecraft.
*/
public abstract class SoundDefinitionsProvider implements IDataProvider
public abstract class SoundDefinitionsProvider implements DataProvider
{
private static final Logger LOGGER = LogManager.getLogger();
private static final Gson GSON = new GsonBuilder().setPrettyPrinting().disableHtmlEscaping().create();
@@ -74,7 +74,7 @@ public abstract class SoundDefinitionsProvider implements IDataProvider
public abstract void registerSounds();
@Override
public void run(DirectoryCache cache) throws IOException
public void run(HashCache cache) throws IOException
{
this.sounds.clear();
this.registerSounds();
@@ -249,7 +249,7 @@ public abstract class SoundDefinitionsProvider implements IDataProvider
private boolean validateSound(final String soundName, final ResourceLocation name)
{
final boolean valid = this.helper.exists(name, ResourcePackType.CLIENT_RESOURCES, ".ogg", "sounds");
final boolean valid = this.helper.exists(name, PackType.CLIENT_RESOURCES, ".ogg", "sounds");
if (!valid)
{
final String path = name.getNamespace() + ":sounds/" + name.getPath() + ".ogg";
@@ -268,9 +268,9 @@ public abstract class SoundDefinitionsProvider implements IDataProvider
return valid;
}
private void save(final DirectoryCache cache, final Path targetFile) throws IOException
private void save(final HashCache cache, final Path targetFile) throws IOException
{
IDataProvider.save(GSON, cache, this.mapToJson(this.sounds), targetFile);
DataProvider.save(GSON, cache, this.mapToJson(this.sounds), targetFile);
}
private JsonObject mapToJson(final Map<String, SoundDefinition> map)
@@ -21,5 +21,5 @@
@MethodsReturnNonnullByDefault
package net.minecraftforge.common.data;
import mcp.MethodsReturnNonnullByDefault;
import net.minecraft.MethodsReturnNonnullByDefault;
import javax.annotation.ParametersAreNonnullByDefault;
@@ -19,34 +19,21 @@
package net.minecraftforge.common.extensions;
import net.minecraft.entity.item.minecart.AbstractMinecartEntity;
import net.minecraft.item.Items;
import net.minecraft.item.ItemStack;
import net.minecraft.world.entity.vehicle.AbstractMinecart;
import net.minecraft.world.item.Items;
import net.minecraft.world.item.ItemStack;
import net.minecraft.tags.BlockTags;
import net.minecraft.util.math.BlockPos;
import net.minecraft.util.math.MathHelper;
import net.minecraftforge.common.IMinecartCollisionHandler;
import net.minecraft.core.BlockPos;
import net.minecraft.util.Mth;
public interface IForgeEntityMinecart
public interface IForgeAbstractMinecart
{
public static float DEFAULT_MAX_SPEED_AIR_LATERAL = 0.4f;
public static float DEFAULT_MAX_SPEED_AIR_VERTICAL = -1.0f;
public static double DEFAULT_AIR_DRAG = 0.95f;
/** TODO: Remove 1.17 */
public static IMinecartCollisionHandler COLLISIONS = null;
default AbstractMinecartEntity getMinecart() {
return (AbstractMinecartEntity)this;
}
/**
* Gets the current global Minecart Collision handler if none
* is registered, returns null
* TODO: remove 1.17
* @return The collision handler or null
*/
default IMinecartCollisionHandler getCollisionHandler() {
return COLLISIONS;
private AbstractMinecart self() {
return (AbstractMinecart)this;
}
/**
@@ -54,11 +41,11 @@ public interface IForgeEntityMinecart
*/
default BlockPos getCurrentRailPosition()
{
int x = MathHelper.floor(getMinecart().getX());
int y = MathHelper.floor(getMinecart().getY());
int z = MathHelper.floor(getMinecart().getZ());
int x = Mth.floor(self().getX());
int y = Mth.floor(self().getY());
int z = Mth.floor(self().getZ());
BlockPos pos = new BlockPos(x, y, z);
if (getMinecart().level.getBlockState(pos.below()).is(BlockTags.RAILS)) pos = pos.below();
if (self().level.getBlockState(pos.below()).is(BlockTags.RAILS)) pos = pos.below();
return pos;
}
@@ -78,15 +65,7 @@ public interface IForgeEntityMinecart
*/
default ItemStack getCartItem()
{
switch (getMinecart().getMinecartType())
{
case FURNACE: return new ItemStack(Items.FURNACE_MINECART);
case CHEST: return new ItemStack(Items.CHEST_MINECART);
case TNT: return new ItemStack(Items.TNT_MINECART);
case HOPPER: return new ItemStack(Items.HOPPER_MINECART);
case COMMAND_BLOCK: return new ItemStack(Items.COMMAND_BLOCK_MINECART);
default: return new ItemStack(Items.MINECART);
}
return new ItemStack(Items.MINECART);
}
/**
@@ -116,7 +95,7 @@ public interface IForgeEntityMinecart
* @return True if powered.
*/
default boolean isPoweredCart() {
return getMinecart().getMinecartType() == AbstractMinecartEntity.Type.FURNACE;
return self().getMinecartType() == AbstractMinecart.Type.FURNACE;
}
/**
@@ -124,7 +103,7 @@ public interface IForgeEntityMinecart
* @return True if this cart can be ridden.
*/
default boolean canBeRidden() {
return getMinecart().getMinecartType() == AbstractMinecartEntity.Type.RIDEABLE;
return self().getMinecartType() == AbstractMinecart.Type.RIDEABLE;
}
/**
@@ -19,24 +19,18 @@
package net.minecraftforge.common.extensions;
import net.minecraft.block.AbstractBlock;
import net.minecraft.block.BlockState;
import net.minecraft.entity.item.minecart.AbstractMinecartEntity;
import net.minecraft.state.properties.RailShape;
import net.minecraft.util.math.BlockPos;
import net.minecraft.world.IBlockReader;
import net.minecraft.world.World;
import net.minecraft.world.level.block.state.BlockState;
import net.minecraft.world.entity.vehicle.AbstractMinecart;
import net.minecraft.world.level.block.state.properties.RailShape;
import net.minecraft.core.BlockPos;
import net.minecraft.world.level.BlockGetter;
import net.minecraft.world.level.Level;
import javax.annotation.Nullable;
public interface IAbstractRailBlock
public interface IForgeBaseRailBlock
{
default AbstractBlock getAbstractBlock()
{
return (AbstractBlock)this;
}
/**
* Return true if the rail can make corners.
* Used by placement logic.
@@ -44,7 +38,7 @@ public interface IAbstractRailBlock
* @param pos Block's position in world
* @return True if the rail can make corners.
*/
boolean isFlexibleRail(BlockState state, IBlockReader world, BlockPos pos);
boolean isFlexibleRail(BlockState state, BlockGetter world, BlockPos pos);
/**
* Returns true if the rail can make up and down slopes.
@@ -53,7 +47,7 @@ public interface IAbstractRailBlock
* @param pos Block's position in world
* @return True if the rail can make slopes.
*/
default boolean canMakeSlopes(BlockState state, IBlockReader world, BlockPos pos)
default boolean canMakeSlopes(BlockState state, BlockGetter world, BlockPos pos)
{
return true;
}
@@ -70,7 +64,7 @@ public interface IAbstractRailBlock
* @param cart The cart asking for the metadata, null if it is not called by EntityMinecart.
* @return The direction.
*/
RailShape getRailDirection(BlockState state, IBlockReader world, BlockPos pos, @Nullable AbstractMinecartEntity cart);
RailShape getRailDirection(BlockState state, BlockGetter world, BlockPos pos, @Nullable AbstractMinecart cart);
/**
* Returns the max speed of the rail at the specified position.
@@ -79,7 +73,7 @@ public interface IAbstractRailBlock
* @param pos Block's position in world
* @return The max speed of the current rail.
*/
default float getRailMaxSpeed(BlockState state, World world, BlockPos pos, net.minecraft.entity.item.minecart.AbstractMinecartEntity cart)
default float getRailMaxSpeed(BlockState state, Level world, BlockPos pos, AbstractMinecart cart)
{
return 0.4f;
}
@@ -91,5 +85,5 @@ public interface IAbstractRailBlock
* @param cart The cart on the rail.
* @param pos Block's position in world
*/
default void onMinecartPass(BlockState state, World world, BlockPos pos, net.minecraft.entity.item.minecart.AbstractMinecartEntity cart){}
default void onMinecartPass(BlockState state, Level world, BlockPos pos, AbstractMinecart cart){}
}
@@ -23,48 +23,58 @@ import java.util.Optional;
import java.util.Set;
import javax.annotation.Nullable;
import net.minecraft.block.*;
import net.minecraft.block.material.Material;
import net.minecraft.client.particle.ParticleManager;
import net.minecraft.client.renderer.ActiveRenderInfo;
import net.minecraft.enchantment.EnchantmentHelper;
import net.minecraft.entity.Entity;
import net.minecraft.entity.MobEntity;
import net.minecraft.entity.LivingEntity;
import net.minecraft.entity.EntitySpawnPlacementRegistry;
import net.minecraft.entity.EntityType;
import net.minecraft.entity.boss.dragon.EnderDragonEntity;
import net.minecraft.entity.boss.WitherEntity;
import net.minecraft.entity.player.PlayerEntity;
import net.minecraft.entity.projectile.WitherSkullEntity;
import net.minecraft.fluid.FluidState;
import net.minecraft.potion.Effects;
import net.minecraft.item.AxeItem;
import net.minecraft.item.HoeItem;
import net.minecraft.item.ItemStack;
import net.minecraft.item.ShovelItem;
import net.minecraft.pathfinding.PathNodeType;
import net.minecraft.world.entity.Entity;
import net.minecraft.world.entity.Mob;
import net.minecraft.world.entity.LivingEntity;
import net.minecraft.world.entity.SpawnPlacements;
import net.minecraft.world.entity.EntityType;
import net.minecraft.world.entity.boss.enderdragon.EnderDragon;
import net.minecraft.world.entity.boss.wither.WitherBoss;
import net.minecraft.world.entity.player.Player;
import net.minecraft.world.entity.projectile.WitherSkull;
import net.minecraft.world.level.block.LadderBlock;
import net.minecraft.world.level.block.TrapDoorBlock;
import net.minecraft.world.level.material.FluidState;
import net.minecraft.world.item.AxeItem;
import net.minecraft.world.item.ItemStack;
import net.minecraft.world.item.ShovelItem;
import net.minecraft.world.level.pathfinder.BlockPathTypes;
import net.minecraft.tags.BlockTags;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.util.Direction;
import net.minecraft.util.ResourceLocation;
import net.minecraft.util.Rotation;
import net.minecraft.util.math.BlockPos;
import net.minecraft.util.math.RayTraceResult;
import net.minecraft.util.math.vector.Vector3d;
import net.minecraft.world.*;
import net.minecraft.world.server.ServerWorld;
import net.minecraftforge.api.distmarker.Dist;
import net.minecraftforge.api.distmarker.OnlyIn;
import net.minecraft.core.Direction;
import net.minecraft.resources.ResourceLocation;
import net.minecraft.world.level.block.Rotation;
import net.minecraft.core.BlockPos;
import net.minecraft.world.phys.HitResult;
import net.minecraft.world.phys.Vec3;
import net.minecraft.server.level.ServerLevel;
import net.minecraftforge.common.ForgeHooks;
import net.minecraftforge.common.IPlantable;
import net.minecraftforge.common.Tags;
import net.minecraftforge.common.ToolType;
import net.minecraft.world.level.BlockAndTintGetter;
import net.minecraft.world.level.BlockGetter;
import net.minecraft.world.level.Explosion;
import net.minecraft.world.level.Level;
import net.minecraft.world.level.LevelAccessor;
import net.minecraft.world.level.LevelReader;
import net.minecraft.world.level.block.BeaconBeamBlock;
import net.minecraft.world.level.block.BedBlock;
import net.minecraft.world.level.block.Block;
import net.minecraft.world.level.block.Blocks;
import net.minecraft.world.level.block.FarmBlock;
import net.minecraft.world.level.block.FenceGateBlock;
import net.minecraft.world.level.block.FireBlock;
import net.minecraft.world.level.block.HalfTransparentBlock;
import net.minecraft.world.level.block.HorizontalDirectionalBlock;
import net.minecraft.world.level.block.LeavesBlock;
import net.minecraft.world.level.block.SoundType;
import net.minecraft.world.level.block.state.BlockState;
@SuppressWarnings("deprecation")
public interface IForgeBlock
{
default Block getBlock()
private Block self()
{
return (Block) this;
}
@@ -74,9 +84,9 @@ public interface IForgeBlock
* between 0 and 1.
* <p>
* Note that entities may reduce slipperiness by a certain factor of their own;
* for {@link net.minecraft.entity.LivingEntity}, this is {@code .91}.
* {@link net.minecraft.entity.item.ItemEntity} uses {@code .98}, and
* {@link net.minecraft.entity.projectile.FishingBobberEntity} uses {@code .92}.
* for {@link net.minecraft.world.entity.LivingEntity}, this is {@code .91}.
* {@link net.minecraft.world.entity.item.ItemEntity} uses {@code .98}, and
* {@link net.minecraft.world.entity.projectile.FishingHook} uses {@code .92}.
*
* @param state state of the block
* @param world the world
@@ -84,9 +94,9 @@ public interface IForgeBlock
* @param entity the entity in question
* @return the factor by which the entity's motion should be multiplied
*/
default float getSlipperiness(BlockState state, IWorldReader world, BlockPos pos, @Nullable Entity entity)
default float getFriction(BlockState state, LevelReader world, BlockPos pos, @Nullable Entity entity)
{
return getBlock().getFriction();
return self().getFriction();
}
/**
@@ -97,7 +107,7 @@ public interface IForgeBlock
* @param pos
* @return The light value
*/
default int getLightValue(BlockState state, IBlockReader world, BlockPos pos)
default int getLightEmission(BlockState state, BlockGetter world, BlockPos pos)
{
return state.getLightEmission();
}
@@ -111,9 +121,9 @@ public interface IForgeBlock
* @param entity The entity trying to use the ladder, CAN be null.
* @return True if the block should act like a ladder
*/
default boolean isLadder(BlockState state, IWorldReader world, BlockPos pos, LivingEntity entity)
default boolean isLadder(BlockState state, LevelReader world, BlockPos pos, LivingEntity entity)
{
return state.getBlock().is(BlockTags.CLIMBABLE);
return state.is(BlockTags.CLIMBABLE);
}
/**
@@ -125,7 +135,7 @@ public interface IForgeBlock
* @param trapdoorState The current state of the open trapdoor above
* @return True if the block should act like a ladder
*/
default boolean makesOpenTrapdoorAboveClimbable(BlockState state, IWorldReader world, BlockPos pos, BlockState trapdoorState)
default boolean makesOpenTrapdoorAboveClimbable(BlockState state, LevelReader world, BlockPos pos, BlockState trapdoorState)
{
return state.getBlock() instanceof LadderBlock && state.getValue(LadderBlock.FACING) == trapdoorState.getValue(TrapDoorBlock.FACING);
}
@@ -138,43 +148,11 @@ public interface IForgeBlock
* @param pos Block position in world
* @return True if the block should deal damage
*/
default boolean isBurning(BlockState state, IBlockReader world, BlockPos pos)
default boolean isBurning(BlockState state, BlockGetter world, BlockPos pos)
{
return this == Blocks.FIRE || this == Blocks.LAVA;
}
/**
* Called throughout the code as a replacement for block instanceof BlockContainer
* Moving this to the Block base class allows for mods that wish to extend vanilla
* blocks, and also want to have a tile entity on that block, may.
*
* Return true from this function to specify this block has a tile entity.
*
* @param state State of the current block
* @return True if block has a tile entity, false otherwise
*/
default boolean hasTileEntity(BlockState state)
{
return this instanceof ITileEntityProvider;
}
/**
* Called throughout the code as a replacement for ITileEntityProvider.createNewTileEntity
* Return the same thing you would from that function.
* This will fall back to ITileEntityProvider.createNewTileEntity(World) if this block is a ITileEntityProvider
*
* @param state The state of the current block
* @param world The world to create the TE in
* @return A instance of a class extending TileEntity
*/
@Nullable
default TileEntity createTileEntity(BlockState state, IBlockReader world)
{
if (getBlock() instanceof ITileEntityProvider)
return ((ITileEntityProvider)getBlock()).newBlockEntity(world);
return null;
}
/**
* Determines if the player can harvest this block, obtaining it's drops when the block is destroyed.
*
@@ -183,7 +161,7 @@ public interface IForgeBlock
* @param player The player damaging the block
* @return True to spawn the drops
*/
default public boolean canHarvestBlock(BlockState state, IBlockReader world, BlockPos pos, PlayerEntity player)
default public boolean canHarvestBlock(BlockState state, BlockGetter world, BlockPos pos, Player player)
{
return ForgeHooks.canHarvestBlock(state, player, world, pos);
}
@@ -208,9 +186,9 @@ public interface IForgeBlock
* @param fluid The current fluid state at current position
* @return True if the block is actually destroyed.
*/
default boolean removedByPlayer(BlockState state, World world, BlockPos pos, PlayerEntity player, boolean willHarvest, FluidState fluid)
default boolean removedByPlayer(BlockState state, Level world, BlockPos pos, Player player, boolean willHarvest, FluidState fluid)
{
getBlock().playerWillDestroy(world, pos, state, player);
self().playerWillDestroy(world, pos, state, player);
return world.setBlock(pos, fluid.createLegacyBlock(), world.isClientSide ? 11 : 3);
}
@@ -225,9 +203,9 @@ public interface IForgeBlock
* @param player The player or camera entity, null in some cases.
* @return True to treat this as a bed
*/
default boolean isBed(BlockState state, IBlockReader world, BlockPos pos, @Nullable Entity player)
default boolean isBed(BlockState state, BlockGetter world, BlockPos pos, @Nullable Entity player)
{
return this.getBlock() instanceof BedBlock; //TODO: Forge: Keep isBed function?
return self() instanceof BedBlock; //TODO: Forge: Keep isBed function?
}
/**
@@ -235,17 +213,18 @@ public interface IForgeBlock
* respawning at this block.
*
* @param state The current state
* @param type The entity type used when checking if a dismount blockstate is dangerous. Currently always PLAYER.
* @param world The current world
* @param pos Block position in world
* @param orientation The angle the entity had when setting the respawn point
* @param entity The entity respawning, often null
* @return The spawn position or the empty optional if respawning here is not possible
*/
default Optional<Vector3d> getRespawnPosition(BlockState state, EntityType<?> type, IWorldReader world, BlockPos pos, float orientation, @Nullable LivingEntity entity)
default Optional<Vec3> getRespawnPosition(BlockState state, EntityType<?> type, LevelReader world, BlockPos pos, float orientation, @Nullable LivingEntity entity)
{
if (isBed(state, world, pos, entity) && world instanceof World && BedBlock.canSetSpawn((World) world))
if (isBed(state, world, pos, entity) && world instanceof Level level && BedBlock.canSetSpawn(level))
{
return getBedSpawnPosition(type, state, world, pos, orientation, entity);
return BedBlock.findStandUpPosition(type, world, pos, orientation);
}
return Optional.empty();
}
@@ -260,44 +239,21 @@ public interface IForgeBlock
* @param type The Mob Category Type
* @return True to allow a mob of the specified category to spawn, false to prevent it.
*/
default boolean canCreatureSpawn(BlockState state, IBlockReader world, BlockPos pos, EntitySpawnPlacementRegistry.PlacementType type, EntityType<?> entityType)
default boolean canCreatureSpawn(BlockState state, BlockGetter world, BlockPos pos, SpawnPlacements.Type type, EntityType<?> entityType)
{
return state.isValidSpawn(world, pos, entityType);
}
/**
* Returns the position that the sleeper is moved to upon
* waking up, or respawning at the bed.
*
* @param state The current state
* @param world The current world
* @param pos Block position in world
* @param orientation The direction the entity is facing while getting into bed.
* @param sleeper The sleeper or camera entity, null in some cases.
* @return The spawn position
* @deprecated use {@link #getRespawnPosition(BlockState, EntityType, IWorldReader, BlockPos, float, LivingEntity)}
*/
@Deprecated
default Optional<Vector3d> getBedSpawnPosition(EntityType<?> entityType, BlockState state, IWorldReader world, BlockPos pos, float orientation, @Nullable LivingEntity sleeper)
{
if (world instanceof World)
{
return BedBlock.findStandUpPosition(entityType, world, pos, orientation);
}
return Optional.empty();
}
/**
* Called when a user either starts or stops sleeping in the bed.
* @param state
*
* @param state
* @param world The current world
* @param pos Block position in world
* @param sleeper The sleeper or camera entity, null in some cases.
* @param occupied True if we are occupying the bed, or false if they are stopping use of the bed
*/
default void setBedOccupied(BlockState state, World world, BlockPos pos, LivingEntity sleeper, boolean occupied)
default void setBedOccupied(BlockState state, Level world, BlockPos pos, LivingEntity sleeper, boolean occupied)
{
world.setBlock(pos, state.setValue(BedBlock.OCCUPIED, occupied), 3);
}
@@ -311,52 +267,9 @@ public interface IForgeBlock
* @param pos Block position in world
* @return Bed direction
*/
default Direction getBedDirection(BlockState state, IWorldReader world, BlockPos pos)
default Direction getBedDirection(BlockState state, LevelReader world, BlockPos pos)
{
return state.getValue(HorizontalBlock.FACING);
}
/**
* Determines this block should be treated as an air block
* by the rest of the code. This method is primarily
* useful for creating pure logic-blocks that will be invisible
* to the player and otherwise interact as air would.
*
* @param state The current state
* @param world The current world
* @param pos Block position in world
* @return True if the block considered air
*/
default boolean isAir(BlockState state, IBlockReader world, BlockPos pos)
{
return state.getMaterial() == Material.AIR;
}
/**
* Used during tree growth to determine if newly generated leaves can replace this block.
*
* @param state The current state
* @param world The current world
* @param pos Block position in world
* @return true if this block can be replaced by growing leaves.
*/
default boolean canBeReplacedByLeaves(BlockState state, IWorldReader world, BlockPos pos)
{
return isAir(state, world, pos) || state.is(BlockTags.LEAVES);
}
/**
* Used during tree growth to determine if newly generated logs can replace this block.
*
* @param state The current state
* @param world The current world
* @param pos Block position in world
* @return true if this block can be replaced by growing leaves.
*/
default boolean canBeReplacedByLogs(BlockState state, IWorldReader world, BlockPos pos)
{
return (isAir(state, world, pos) || state.is(BlockTags.LEAVES)) || this == Blocks.GRASS_BLOCK || state.is(Tags.Blocks.DIRT)
|| getBlock().is(BlockTags.LOGS) || getBlock().is(BlockTags.SAPLINGS) || this == Blocks.VINE;
return state.getValue(HorizontalDirectionalBlock.FACING);
}
/**
@@ -367,24 +280,9 @@ public interface IForgeBlock
* @param explosion The explosion
* @return The amount of the explosion absorbed.
*/
default float getExplosionResistance(BlockState state, IBlockReader world, BlockPos pos, Explosion explosion)
default float getExplosionResistance(BlockState state, BlockGetter world, BlockPos pos, Explosion explosion)
{
return this.getBlock().getExplosionResistance();
}
/**
* Determine if this block can make a redstone connection on the side provided,
* Useful to control which sides are inputs and outputs for redstone wires.
*
* @param state The current state
* @param world The current world
* @param pos Block position in world
* @param side The side that is trying to make the connection, CAN BE NULL
* @return True to make the connection
*/
default boolean canConnectRedstone(BlockState state, IBlockReader world, BlockPos pos, @Nullable Direction side)
{
return state.isSignalSource() && side != null;
return self().getExplosionResistance();
}
/**
@@ -394,9 +292,9 @@ public interface IForgeBlock
* @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 getPickBlock(BlockState state, RayTraceResult target, IBlockReader world, BlockPos pos, PlayerEntity player)
default ItemStack getPickBlock(BlockState state, HitResult target, BlockGetter world, BlockPos pos, Player player)
{
return this.getBlock().getCloneItemStack(world, pos, state);
return self().getCloneItemStack(world, pos, state);
}
/**
@@ -411,14 +309,14 @@ public interface IForgeBlock
* @param numberOfParticles That vanilla world have spawned
* @return True to prevent vanilla landing particles from spawning
*/
default boolean addLandingEffects(BlockState state1, ServerWorld worldserver, BlockPos pos, BlockState state2, LivingEntity entity, int numberOfParticles)
default boolean addLandingEffects(BlockState state1, ServerLevel worldserver, BlockPos pos, BlockState state2, LivingEntity entity, int numberOfParticles)
{
return false;
}
/**
* Allows a block to override the standard vanilla running particles.
* This is called from {@link Entity#handleRunningEffect} and is called both,
* This is called from Entity.spawnSprintParticle and is called both,
* Client and server side, it's up to the implementor to client check / server check.
* By default vanilla spawns particles only on the client and the server methods no-op.
*
@@ -428,42 +326,7 @@ public interface IForgeBlock
* @param entity The entity running on the block.
* @return True to prevent vanilla running particles from spawning.
*/
default boolean addRunningEffects(BlockState state, World world, BlockPos pos, Entity entity)
{
return false;
}
/**
* Spawn a digging particle effect in the world, this is a wrapper
* around EffectRenderer.addBlockHitEffects to allow the block more
* control over the particles. Useful when you have entirely different
* texture sheets for different sides/locations in the world.
*
* @param state The current state
* @param world The current world
* @param target The target the player is looking at {x/y/z/side/sub}
* @param manager A reference to the current particle manager.
* @return True to prevent vanilla digging particles form spawning.
*/
@OnlyIn(Dist.CLIENT)
default boolean addHitEffects(BlockState state, World world, RayTraceResult target, ParticleManager manager)
{
return false;
}
/**
* Spawn particles for when the block is destroyed. Due to the nature
* of how this is invoked, the x/y/z locations are not always guaranteed
* to host your block. So be sure to do proper sanity checks before assuming
* that the location is this block.
*
* @param world The current world
* @param pos Position to spawn the particle
* @param manager A reference to the current particle manager.
* @return True to prevent vanilla break particles from spawning.
*/
@OnlyIn(Dist.CLIENT)
default boolean addDestroyEffects(BlockState state, World world, BlockPos pos, ParticleManager manager)
default boolean addRunningEffects(BlockState state, Level world, BlockPos pos, Entity entity)
{
return false;
}
@@ -486,28 +349,7 @@ public interface IForgeBlock
* @param plantable The plant that wants to check
* @return True to allow the plant to be planted/stay.
*/
boolean canSustainPlant(BlockState state, IBlockReader world, BlockPos pos, Direction facing, IPlantable plantable);
/**
* Called when a plant grows on this block, only implemented for saplings using the WorldGen*Trees classes right now.
* Modder may implement this for custom plants.
* This does not use ForgeDirection, because large/huge trees can be located in non-representable direction,
* so the source location is specified.
* Currently this just changes the block to dirt if it was grass.
*
* Note: This happens DURING the generation, the generation may not be complete when this is called.
*
* @param state The current state
* @param world Current world
* @param pos Block position in world
* @param source Source plant's position in world
*/
@Deprecated//TODO - 1.17: Remove (unused)
default void onPlantGrow(BlockState state, IWorld world, BlockPos pos, BlockPos source)
{
if (state.is(Tags.Blocks.DIRT))
world.setBlock(pos, Blocks.DIRT.defaultBlockState(), 2);
}
boolean canSustainPlant(BlockState state, BlockGetter world, BlockPos pos, Direction facing, IPlantable plantable);
/**
* Checks if this soil is fertile, typically this means that growth rates
@@ -518,10 +360,10 @@ public interface IForgeBlock
* @param pos Block position in world
* @return True if the soil should be considered fertile.
*/
default boolean isFertile(BlockState state, IBlockReader world, BlockPos pos)
default boolean isFertile(BlockState state, BlockGetter world, BlockPos pos)
{
if (state.is(Blocks.FARMLAND))
return state.getValue(FarmlandBlock.MOISTURE) > 0;
return state.getValue(FarmBlock.MOISTURE) > 0;
return false;
}
@@ -534,7 +376,7 @@ public interface IForgeBlock
* @param conduit Conduit position in world
* @return True, to support the conduit, and make it active with this block.
*/
default boolean isConduitFrame(BlockState state, IWorldReader world, BlockPos pos, BlockPos conduit)
default boolean isConduitFrame(BlockState state, LevelReader world, BlockPos pos, BlockPos conduit)
{
return state.getBlock() == Blocks.PRISMARINE ||
state.getBlock() == Blocks.PRISMARINE_BRICKS ||
@@ -550,7 +392,7 @@ public interface IForgeBlock
* @param pos Block position in world
* @return True, to support being part of a nether portal frame, false otherwise.
*/
default boolean isPortalFrame(BlockState state, IBlockReader world, BlockPos pos)
default boolean isPortalFrame(BlockState state, BlockGetter world, BlockPos pos)
{
return state.is(Blocks.OBSIDIAN);
}
@@ -564,12 +406,12 @@ public interface IForgeBlock
* @param fortune
* @return Amount of XP from breaking this block.
*/
default int getExpDrop(BlockState state, IWorldReader world, BlockPos pos, int fortune, int silktouch)
default int getExpDrop(BlockState state, LevelReader world, BlockPos pos, int fortune, int silktouch)
{
return 0;
}
default BlockState rotate(BlockState state, IWorld world, BlockPos pos, Rotation direction)
default BlockState rotate(BlockState state, LevelAccessor world, BlockPos pos, Rotation direction)
{
return state.rotate(direction);
}
@@ -580,7 +422,7 @@ public interface IForgeBlock
* @param pos Block position in world
* @return The amount of enchanting power this block produces.
*/
default float getEnchantPowerBonus(BlockState state, IWorldReader world, BlockPos pos)
default float getEnchantPowerBonus(BlockState state, LevelReader world, BlockPos pos)
{
return state.is(Blocks.BOOKSHELF) ? 1: 0;
}
@@ -591,19 +433,7 @@ public interface IForgeBlock
* @param pos Block position in world
* @param neighbor Block position of neighbor
*/
default void onNeighborChange(BlockState state, IWorldReader world, BlockPos pos, BlockPos neighbor){}
/**
* Called on an Observer block whenever an update for an Observer is received.
*
* @param observerState The Observer block's state.
* @param world The current world.
* @param observerPos The Observer block's position.
* @param changedBlock The updated block.
* @param changedBlockPos The updated block's position.
*/
@Deprecated//TODO - 1.17: Remove (unused)
default void observedNeighborChange(BlockState observerState, World world, BlockPos observerPos, Block changedBlock, BlockPos changedBlockPos){}
default void onNeighborChange(BlockState state, LevelReader world, BlockPos pos, BlockPos neighbor){}
/**
* Called to determine whether to allow the a block to handle its own indirect power rather than using the default rules.
@@ -612,7 +442,7 @@ public interface IForgeBlock
* @param side The INPUT side of the block to be powered - ie the opposite of this block's output side
* @return Whether Block#isProvidingWeakPower should be called when determining indirect power
*/
default boolean shouldCheckWeakPower(BlockState state, IWorldReader world, BlockPos pos, Direction side)
default boolean shouldCheckWeakPower(BlockState state, LevelReader world, BlockPos pos, Direction side)
{
return state.isRedstoneConductor(world, pos);
}
@@ -626,7 +456,7 @@ public interface IForgeBlock
* @param pos Block position in world
* @return true To be notified of changes
*/
default boolean getWeakChanges(BlockState state, IWorldReader world, BlockPos pos)
default boolean getWeakChanges(BlockState state, LevelReader world, BlockPos pos)
{
return false;
}
@@ -651,7 +481,7 @@ public interface IForgeBlock
*/
default boolean isToolEffective(BlockState state, ToolType tool)
{
if (tool == ToolType.PICKAXE && (this.getBlock() == Blocks.REDSTONE_ORE || this.getBlock() == Blocks.REDSTONE_LAMP || this.getBlock() == Blocks.OBSIDIAN))
if (tool == ToolType.PICKAXE && (self() == Blocks.REDSTONE_ORE || self() == Blocks.REDSTONE_LAMP || self() == Blocks.OBSIDIAN))
return false;
return tool == getHarvestTool(state);
}
@@ -664,9 +494,9 @@ public interface IForgeBlock
* @param entity The entity that is breaking/stepping on/placing/hitting/falling on this block, or null if no entity is in this context
* @return A SoundType to use
*/
default SoundType getSoundType(BlockState state, IWorldReader world, BlockPos pos, @Nullable Entity entity)
default SoundType getSoundType(BlockState state, LevelReader world, BlockPos pos, @Nullable Entity entity)
{
return this.getBlock().getSoundType(state);
return self().getSoundType(state);
}
/**
@@ -677,50 +507,13 @@ public interface IForgeBlock
* @return A float RGB [0.0, 1.0] array to be averaged with a beacon's existing beam color, or null to do nothing to the beam
*/
@Nullable
default float[] getBeaconColorMultiplier(BlockState state, IWorldReader world, BlockPos pos, BlockPos beaconPos)
default float[] getBeaconColorMultiplier(BlockState state, LevelReader world, BlockPos pos, BlockPos beaconPos)
{
if (getBlock() instanceof IBeaconBeamColorProvider)
return ((IBeaconBeamColorProvider)getBlock()).getColor().getTextureDiffuseColors();
if (self() instanceof BeaconBeamBlock)
return ((BeaconBeamBlock) self()).getColor().getTextureDiffuseColors();
return null;
}
/**
* Use this to change the fog color used when the entity is "inside" a material.
* Vec3d is used here as "r/g/b" 0 - 1 values.
*
* @param world The world.
* @param pos The position at the entity viewport.
* @param state The state at the entity viewport.
* @param entity the entity
* @param originalColor The current fog color, You are not expected to use this, Return as the default if applicable.
* @return The new fog color.
*/
@OnlyIn(Dist.CLIENT)
default Vector3d getFogColor(BlockState state, IWorldReader world, BlockPos pos, Entity entity, Vector3d originalColor, float partialTicks)
{
if (state.getMaterial() == Material.WATER)
{
float f12 = 0.0F;
if (entity instanceof LivingEntity)
{
LivingEntity ent = (LivingEntity)entity;
f12 = (float) EnchantmentHelper.getRespiration(ent) * 0.2F;
if (ent.hasEffect(Effects.WATER_BREATHING))
{
f12 = f12 * 0.3F + 0.6F;
}
}
return new Vector3d(0.02F + f12, 0.02F + f12, 0.2F + f12);
}
else if (state.getMaterial() == Material.LAVA)
{
return new Vector3d(0.6F, 0.1F, 0.0F);
}
return originalColor;
}
/**
* Used to determine the state 'viewed' by an entity (see
* {@link ActiveRenderInfo#getBlockStateAtEntityViewpoint(World, Entity, float)}).
@@ -732,7 +525,7 @@ public interface IForgeBlock
* @param viewpoint the viewpoint
* @return the block state that should be 'seen'
*/
default BlockState getStateAtViewpoint(BlockState state, IBlockReader world, BlockPos pos, Vector3d viewpoint)
default BlockState getStateAtViewpoint(BlockState state, BlockGetter world, BlockPos pos, Vec3 viewpoint)
{
return state;
}
@@ -743,9 +536,9 @@ public interface IForgeBlock
* @return the PathNodeType
*/
@Nullable
default PathNodeType getAiPathNodeType(BlockState state, IBlockReader world, BlockPos pos, @Nullable MobEntity entity)
default BlockPathTypes getAiPathNodeType(BlockState state, BlockGetter world, BlockPos pos, @Nullable Mob entity)
{
return state.getBlock() == Blocks.LAVA ? PathNodeType.LAVA : state.isBurning(world, pos) ? PathNodeType.DAMAGE_FIRE : null;
return state.getBlock() == Blocks.LAVA ? BlockPathTypes.LAVA : state.isBurning(world, pos) ? BlockPathTypes.DAMAGE_FIRE : null;
}
/**
@@ -789,7 +582,7 @@ public interface IForgeBlock
* @param face The face that the fire is coming from
* @return A number ranging from 0 to 300 relating used to determine if the block will be consumed by fire
*/
default int getFlammability(BlockState state, IBlockReader world, BlockPos pos, Direction face)
default int getFlammability(BlockState state, BlockGetter world, BlockPos pos, Direction face)
{
return ((FireBlock)Blocks.FIRE).getBurnOdd(state);
}
@@ -804,7 +597,7 @@ public interface IForgeBlock
* @param face The face that the fire is coming from
* @return True if the face can be on fire, false otherwise.
*/
default boolean isFlammable(BlockState state, IBlockReader world, BlockPos pos, Direction face)
default boolean isFlammable(BlockState state, BlockGetter world, BlockPos pos, Direction face)
{
return state.getFlammability(world, pos, face) > 0;
}
@@ -818,7 +611,7 @@ public interface IForgeBlock
* @param face The face that the fire is coming from
* @param igniter The entity that lit the fire
*/
default void catchFire(BlockState state, World world, BlockPos pos, @Nullable Direction face, @Nullable LivingEntity igniter) {}
default void catchFire(BlockState state, Level world, BlockPos pos, @Nullable Direction face, @Nullable LivingEntity igniter) {}
/**
* Called when fire is updating on a neighbor block.
@@ -830,7 +623,7 @@ public interface IForgeBlock
* @param face The face that the fire is coming from
* @return A number that is used to determine the speed of fire growth around the block
*/
default int getFireSpreadSpeed(BlockState state, IBlockReader world, BlockPos pos, Direction face)
default int getFireSpreadSpeed(BlockState state, BlockGetter world, BlockPos pos, Direction face)
{
return ((FireBlock)Blocks.FIRE).getFlameOdds(state);
}
@@ -846,7 +639,7 @@ public interface IForgeBlock
* @param side The face that the fire is coming from
* @return True if this block sustains fire, meaning it will never go out.
*/
default boolean isFireSource(BlockState state, IWorldReader world, BlockPos pos, Direction side)
default boolean isFireSource(BlockState state, LevelReader world, BlockPos pos, Direction side)
{
return state.is(world.dimensionType().infiniburn());
}
@@ -859,16 +652,16 @@ public interface IForgeBlock
* @param pos Block position in world
* @return True to allow the ender dragon to destroy this block
*/
default boolean canEntityDestroy(BlockState state, IBlockReader world, BlockPos pos, Entity entity)
default boolean canEntityDestroy(BlockState state, BlockGetter world, BlockPos pos, Entity entity)
{
if (entity instanceof EnderDragonEntity)
if (entity instanceof EnderDragon)
{
return !BlockTags.DRAGON_IMMUNE.contains(this.getBlock());
return !BlockTags.DRAGON_IMMUNE.contains(this.self());
}
else if ((entity instanceof WitherEntity) ||
(entity instanceof WitherSkullEntity))
else if ((entity instanceof WitherBoss) ||
(entity instanceof WitherSkull))
{
return state.isAir(world, pos) || WitherEntity.canDestroy(state);
return state.isAir() || WitherBoss.canDestroy(state);
}
return true;
@@ -877,7 +670,7 @@ public interface IForgeBlock
/**
* Determines if this block should drop loot when exploded.
*/
default boolean canDropFromExplosion(BlockState state, IBlockReader world, BlockPos pos, Explosion explosion)
default boolean canDropFromExplosion(BlockState state, BlockGetter world, BlockPos pos, Explosion explosion)
{
return state.getBlock().dropFromExplosion(explosion);
}
@@ -897,19 +690,19 @@ public interface IForgeBlock
* @param pos Block position in world
* @param explosion The explosion instance affecting the block
*/
default void onBlockExploded(BlockState state, World world, BlockPos pos, Explosion explosion)
default void onBlockExploded(BlockState state, Level world, BlockPos pos, Explosion explosion)
{
world.setBlock(pos, Blocks.AIR.defaultBlockState(), 3);
getBlock().wasExploded(world, pos, explosion);
self().wasExploded(world, pos, explosion);
}
/**
* Determines if this block's collision box should be treated as though it can extend above its block space.
* Use this to replicate fence and wall behavior.
*/
default boolean collisionExtendsVertically(BlockState state, IBlockReader world, BlockPos pos, Entity collidingEntity)
default boolean collisionExtendsVertically(BlockState state, BlockGetter world, BlockPos pos, Entity collidingEntity)
{
return getBlock().is(BlockTags.FENCES) || getBlock().is(BlockTags.WALLS) || getBlock() instanceof FenceGateBlock;
return state.is(BlockTags.FENCES) || state.is(BlockTags.WALLS) || self() instanceof FenceGateBlock;
}
/**
@@ -921,9 +714,9 @@ public interface IForgeBlock
* @param fluidState The state of the fluid
* @return Whether the fluid overlay texture should be used
*/
default boolean shouldDisplayFluidOverlay(BlockState state, IBlockDisplayReader world, BlockPos pos, FluidState fluidState)
default boolean shouldDisplayFluidOverlay(BlockState state, BlockAndTintGetter world, BlockPos pos, FluidState fluidState)
{
return state.getBlock() instanceof BreakableBlock || state.getBlock() instanceof LeavesBlock;
return state.getBlock() instanceof HalfTransparentBlock || state.getBlock() instanceof LeavesBlock;
}
/**
@@ -939,10 +732,10 @@ public interface IForgeBlock
* @return The resulting state after the action has been performed
*/
@Nullable
default BlockState getToolModifiedState(BlockState state, World world, BlockPos pos, PlayerEntity player, ItemStack stack, ToolType toolType)
default BlockState getToolModifiedState(BlockState state, Level world, BlockPos pos, Player player, ItemStack stack, ToolType toolType)
{
if (toolType == ToolType.AXE) return AxeItem.getAxeStrippingState(state);
else if(toolType == ToolType.HOE) return HoeItem.getHoeTillingState(state);
// else if(toolType == ToolType.HOE) return HoeItem.getHoeTillingState(state); //TODO HoeItem bork
else return toolType == ToolType.SHOVEL ? ShovelItem.getShovelPathingState(state) : null;
}
@@ -955,7 +748,7 @@ public interface IForgeBlock
* @param entity The entity on the scaffolding
* @return True if the block should act like scaffolding
*/
default boolean isScaffolding(BlockState state, IWorldReader world, BlockPos pos, LivingEntity entity)
default boolean isScaffolding(BlockState state, LevelReader world, BlockPos pos, LivingEntity entity)
{
return state.is(Blocks.SCAFFOLDING);
}
@@ -21,44 +21,35 @@ package net.minecraftforge.common.extensions;
import javax.annotation.Nonnull;
import net.minecraft.block.Block;
import net.minecraft.block.BlockState;
import net.minecraft.block.Blocks;
import net.minecraft.nbt.CompoundNBT;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.util.math.AxisAlignedBB;
import net.minecraft.util.math.BlockPos;
import net.minecraft.util.math.shapes.VoxelShape;
import net.minecraft.world.World;
import net.minecraftforge.api.distmarker.Dist;
import net.minecraftforge.api.distmarker.OnlyIn;
import net.minecraft.world.level.block.Block;
import net.minecraft.world.level.block.state.BlockState;
import net.minecraft.world.level.block.Blocks;
import net.minecraft.nbt.CompoundTag;
import net.minecraft.world.level.block.entity.BlockEntity;
import net.minecraft.world.phys.AABB;
import net.minecraft.core.BlockPos;
import net.minecraft.world.phys.shapes.VoxelShape;
import net.minecraft.world.level.Level;
import net.minecraftforge.client.model.ModelDataManager;
import net.minecraftforge.client.model.data.EmptyModelData;
import net.minecraftforge.client.model.data.IModelData;
import net.minecraftforge.common.capabilities.ICapabilitySerializable;
public interface IForgeTileEntity extends ICapabilitySerializable<CompoundNBT>
public interface IForgeBlockEntity extends ICapabilitySerializable<CompoundTag>
{
default TileEntity getTileEntity() { return (TileEntity) this; }
private BlockEntity self() { return (BlockEntity) this; }
@Override
default void deserializeNBT(CompoundNBT nbt)
default void deserializeNBT(CompoundTag nbt)
{
//TODO re-evaluate
deserializeNBT(null, nbt);
}
// @Override TODO re-evaluate
default void deserializeNBT(BlockState state, CompoundNBT nbt)
{
getTileEntity().load(state, nbt);
self().load(nbt);
}
@Override
default CompoundNBT serializeNBT()
default CompoundTag serializeNBT()
{
CompoundNBT ret = new CompoundNBT();
getTileEntity().save(ret);
CompoundTag ret = new CompoundTag();
self().save(ret);
return ret;
}
@@ -71,7 +62,7 @@ public interface IForgeTileEntity extends ICapabilitySerializable<CompoundNBT>
* @param net The NetworkManager the packet originated from
* @param pkt The data packet
*/
default void onDataPacket(net.minecraft.network.NetworkManager net, net.minecraft.network.play.server.SUpdateTileEntityPacket pkt){ }
default void onDataPacket(net.minecraft.network.Connection net, net.minecraft.network.protocol.game.ClientboundBlockEntityDataPacket pkt){ }
/**
* Called when the chunk's TE update tag, gotten from {@link #getUpdateTag()}, is received on the client.
@@ -80,9 +71,9 @@ public interface IForgeTileEntity extends ICapabilitySerializable<CompoundNBT>
*
* @param tag The {@link NBTTagCompound} sent from {@link #getUpdateTag()}
*/
default void handleUpdateTag(BlockState state, CompoundNBT tag)
default void handleUpdateTag(CompoundTag tag)
{
getTileEntity().load(state, tag);
self().load(tag);
}
/**
@@ -91,7 +82,7 @@ public interface IForgeTileEntity extends ICapabilitySerializable<CompoundNBT>
*
* @return A compound tag for custom data
*/
CompoundNBT getTileData();
CompoundTag getTileData();
default void onChunkUnloaded(){}
@@ -107,7 +98,7 @@ public interface IForgeTileEntity extends ICapabilitySerializable<CompoundNBT>
/**
* Sometimes default render bounding box: infinite in scope. Used to control rendering on {@link TileEntitySpecialRenderer}.
*/
public static final AxisAlignedBB INFINITE_EXTENT_AABB = new net.minecraft.util.math.AxisAlignedBB(Double.NEGATIVE_INFINITY, Double.NEGATIVE_INFINITY, Double.NEGATIVE_INFINITY, Double.POSITIVE_INFINITY, Double.POSITIVE_INFINITY, Double.POSITIVE_INFINITY);
public static final AABB INFINITE_EXTENT_AABB = new net.minecraft.world.phys.AABB(Double.NEGATIVE_INFINITY, Double.NEGATIVE_INFINITY, Double.NEGATIVE_INFINITY, Double.POSITIVE_INFINITY, Double.POSITIVE_INFINITY, Double.POSITIVE_INFINITY);
/**
* Return an {@link AxisAlignedBB} that controls the visible scope of a {@link TileEntitySpecialRenderer} associated with this {@link TileEntity}
@@ -116,20 +107,19 @@ public interface IForgeTileEntity extends ICapabilitySerializable<CompoundNBT>
*
* @return an appropriately size {@link AxisAlignedBB} for the {@link TileEntity}
*/
@OnlyIn(Dist.CLIENT)
default AxisAlignedBB getRenderBoundingBox()
default AABB getRenderBoundingBox()
{
AxisAlignedBB bb = INFINITE_EXTENT_AABB;
BlockState state = getTileEntity().getBlockState();
AABB bb = INFINITE_EXTENT_AABB;
BlockState state = self().getBlockState();
Block block = state.getBlock();
BlockPos pos = getTileEntity().getBlockPos();
BlockPos pos = self().getBlockPos();
if (block == Blocks.ENCHANTING_TABLE)
{
bb = new AxisAlignedBB(pos, pos.offset(1, 1, 1));
bb = new AABB(pos, pos.offset(1, 1, 1));
}
else if (block == Blocks.CHEST || block == Blocks.TRAPPED_CHEST)
{
bb = new AxisAlignedBB(pos.offset(-1, 0, -1), pos.offset(2, 2, 2));
bb = new AABB(pos.offset(-1, 0, -1), pos.offset(2, 2, 2));
}
else if (block == Blocks.STRUCTURE_BLOCK)
{
@@ -137,10 +127,10 @@ public interface IForgeTileEntity extends ICapabilitySerializable<CompoundNBT>
}
else if (block != null && block != Blocks.BEACON)
{
AxisAlignedBB cbb = null;
AABB cbb = null;
try
{
VoxelShape collisionShape = state.getCollisionShape(getTileEntity().getLevel(), pos);
VoxelShape collisionShape = state.getCollisionShape(self().getLevel(), pos);
if (!collisionShape.isEmpty())
{
cbb = collisionShape.bounds().move(pos);
@@ -154,7 +144,7 @@ public interface IForgeTileEntity extends ICapabilitySerializable<CompoundNBT>
// So, once again in the long line of US having to accommodate BUKKIT breaking things,
// here it is, assume that the TE is only 1 cubic block. Problem with this is that it may
// cause the TileEntity renderer to error further down the line! But alas, nothing we can do.
cbb = new net.minecraft.util.math.AxisAlignedBB(pos.offset(-1, 0, -1), pos.offset(1, 1, 1));
cbb = new net.minecraft.world.phys.AABB(pos.offset(-1, 0, -1), pos.offset(1, 1, 1));
}
if (cbb != null) bb = cbb;
}
@@ -167,8 +157,8 @@ public interface IForgeTileEntity extends ICapabilitySerializable<CompoundNBT>
*/
default void requestModelDataUpdate()
{
TileEntity te = getTileEntity();
World world = te.getLevel();
BlockEntity te = self();
Level world = te.getLevel();
if (world != null && world.isClientSide)
{
ModelDataManager.requestModelDataRefresh(te);
@@ -22,32 +22,36 @@ package net.minecraftforge.common.extensions;
import java.util.Optional;
import javax.annotation.Nullable;
import net.minecraft.block.*;
import net.minecraft.client.particle.ParticleManager;
import net.minecraft.entity.Entity;
import net.minecraft.entity.MobEntity;
import net.minecraft.entity.LivingEntity;
import net.minecraft.entity.EntitySpawnPlacementRegistry.PlacementType;
import net.minecraft.entity.EntityType;
import net.minecraft.entity.player.PlayerEntity;
import net.minecraft.fluid.FluidState;
import net.minecraft.item.ItemStack;
import net.minecraft.pathfinding.PathNodeType;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.util.*;
import net.minecraft.util.math.BlockPos;
import net.minecraft.util.math.RayTraceResult;
import net.minecraft.util.math.vector.Vector3d;
import net.minecraft.world.*;
import net.minecraft.world.server.ServerWorld;
import net.minecraftforge.api.distmarker.Dist;
import net.minecraftforge.api.distmarker.OnlyIn;
import net.minecraft.world.entity.Entity;
import net.minecraft.world.entity.Mob;
import net.minecraft.world.entity.LivingEntity;
import net.minecraft.world.entity.SpawnPlacements.Type;
import net.minecraft.world.entity.EntityType;
import net.minecraft.world.entity.player.Player;
import net.minecraft.world.level.material.FluidState;
import net.minecraft.world.item.ItemStack;
import net.minecraft.world.level.pathfinder.BlockPathTypes;
import net.minecraft.core.BlockPos;
import net.minecraft.world.phys.HitResult;
import net.minecraft.world.phys.Vec3;
import net.minecraft.server.level.ServerLevel;
import net.minecraftforge.common.IPlantable;
import net.minecraftforge.common.ToolType;
import net.minecraft.core.Direction;
import net.minecraft.world.level.BlockAndTintGetter;
import net.minecraft.world.level.BlockGetter;
import net.minecraft.world.level.Explosion;
import net.minecraft.world.level.Level;
import net.minecraft.world.level.LevelAccessor;
import net.minecraft.world.level.LevelReader;
import net.minecraft.world.level.block.Rotation;
import net.minecraft.world.level.block.SoundType;
import net.minecraft.world.level.block.state.BlockState;
public interface IForgeBlockState
{
default BlockState getBlockState()
private BlockState self()
{
return (BlockState)this;
}
@@ -66,17 +70,17 @@ public interface IForgeBlockState
* @param entity the entity in question
* @return the factor by which the entity's motion should be multiplied
*/
default float getSlipperiness(IWorldReader world, BlockPos pos, @Nullable Entity entity)
default float getFriction(LevelReader world, BlockPos pos, @Nullable Entity entity)
{
return getBlockState().getBlock().getSlipperiness(getBlockState(), world, pos, entity);
return self().getBlock().getFriction(self(), world, pos, entity);
}
/**
* Get a light value for this block, taking into account the given state and coordinates, normal ranges are between 0 and 15
*/
default int getLightValue(IBlockReader world, BlockPos pos)
default int getLightEmission(BlockGetter world, BlockPos pos)
{
return getBlockState().getBlock().getLightValue(getBlockState(), world, pos);
return self().getBlock().getLightEmission(self(), world, pos);
}
/**
@@ -87,37 +91,9 @@ public interface IForgeBlockState
* @param entity The entity trying to use the ladder, CAN be null.
* @return True if the block should act like a ladder
*/
default boolean isLadder(IWorldReader world, BlockPos pos, LivingEntity entity)
default boolean isLadder(LevelReader world, BlockPos pos, LivingEntity entity)
{
return getBlockState().getBlock().isLadder(getBlockState(), world, pos, entity);
}
/**
* Called throughout the code as a replacement for block instanceof BlockContainer
* Moving this to the Block base class allows for mods that wish to extend vanilla
* blocks, and also want to have a tile entity on that block, may.
*
* Return true from this function to specify this block has a tile entity.
*
* @return True if block has a tile entity, false otherwise
*/
default boolean hasTileEntity()
{
return getBlockState().getBlock().hasTileEntity(getBlockState());
}
/**
* Called throughout the code as a replacement for ITileEntityProvider.createNewTileEntity
* Return the same thing you would from that function.
* This will fall back to ITileEntityProvider.createNewTileEntity(World) if this block is a ITileEntityProvider
*
* @param world The world to create the TE in
* @return A instance of a class extending TileEntity
*/
@Nullable
default TileEntity createTileEntity(IBlockReader world)
{
return getBlockState().getBlock().createTileEntity(getBlockState(), world);
return self().getBlock().isLadder(self(), world, pos, entity);
}
/**
@@ -128,9 +104,9 @@ public interface IForgeBlockState
* @param player The player damaging the block
* @return True to spawn the drops
*/
default boolean canHarvestBlock(IBlockReader world, BlockPos pos, PlayerEntity player)
default boolean canHarvestBlock(BlockGetter world, BlockPos pos, Player player)
{
return getBlockState().getBlock().canHarvestBlock(getBlockState(), world, pos, player);
return self().getBlock().canHarvestBlock(self(), world, pos, player);
}
/**
@@ -152,9 +128,9 @@ public interface IForgeBlockState
* @param fluid The current fluid and block state for the position in the world.
* @return True if the block is actually destroyed.
*/
default boolean removedByPlayer(World world, BlockPos pos, PlayerEntity player, boolean willHarvest, FluidState fluid)
default boolean removedByPlayer(Level world, BlockPos pos, Player player, boolean willHarvest, FluidState fluid)
{
return getBlockState().getBlock().removedByPlayer(getBlockState(), world, pos, player, willHarvest, fluid);
return self().getBlock().removedByPlayer(self(), world, pos, player, willHarvest, fluid);
}
/**
@@ -167,9 +143,9 @@ public interface IForgeBlockState
* @param sleeper The sleeper or camera entity, null in some cases.
* @return True to treat this as a bed
*/
default boolean isBed(IBlockReader world, BlockPos pos, @Nullable LivingEntity sleeper)
default boolean isBed(BlockGetter world, BlockPos pos, @Nullable LivingEntity sleeper)
{
return getBlockState().getBlock().isBed(getBlockState(), world, pos, sleeper);
return self().getBlock().isBed(self(), world, pos, sleeper);
}
/**
@@ -181,40 +157,25 @@ public interface IForgeBlockState
* @param type The Mob Category Type
* @return True to allow a mob of the specified category to spawn, false to prevent it.
*/
default boolean canCreatureSpawn(IWorldReader world, BlockPos pos, PlacementType type, EntityType<?> entityType)
default boolean canCreatureSpawn(LevelReader world, BlockPos pos, Type type, EntityType<?> entityType)
{
return getBlockState().getBlock().canCreatureSpawn(getBlockState(), world, pos, type, entityType);
}
/**
* Returns the position that the sleeper is moved to upon
* waking up, or respawning at the bed.
*
* @param world The current world
* @param pos Block position in world
* @param orientation The direction the entity is facing while getting into bed.
* @param sleeper The sleeper or camera entity, null in some cases.
* @return The spawn position
* @deprecated use {@link #getRespawnPosition(EntityType, IWorldReader, BlockPos, float, LivingEntity)}
*/
@Deprecated
default Optional<Vector3d> getBedSpawnPosition(EntityType<?> type, IWorldReader world, BlockPos pos, float orientation, @Nullable LivingEntity sleeper)
{
return getBlockState().getBlock().getBedSpawnPosition(type, getBlockState(), world, pos, orientation, sleeper);
return self().getBlock().canCreatureSpawn(self(), world, pos, type, entityType);
}
/**
* Returns the position that the entity is moved to upon
* respawning at this block.
*
* @param type The entity type used when checking if a dismount blockstate is dangerous. Currently always PLAYER.
* @param world The current world
* @param pos Block position in world
* @param orientation The angle the entity had when setting the respawn point
* @param entity The entity respawning, often null
* @return The spawn position or the empty optional if respawning here is not possible
*/
default Optional<Vector3d> getRespawnPosition(EntityType<?> type, IWorldReader world, BlockPos pos, float orientation, @Nullable LivingEntity entity)
default Optional<Vec3> getRespawnPosition(EntityType<?> type, LevelReader world, BlockPos pos, float orientation, @Nullable LivingEntity entity)
{
return getBlockState().getBlock().getRespawnPosition(getBlockState(), type, world, pos, orientation, entity);
return self().getBlock().getRespawnPosition(self(), type, world, pos, orientation, entity);
}
/**
@@ -225,9 +186,9 @@ public interface IForgeBlockState
* @param sleeper The sleeper or camera entity, null in some cases.
* @param occupied True if we are occupying the bed, or false if they are stopping use of the bed
*/
default void setBedOccupied(World world, BlockPos pos, LivingEntity sleeper, boolean occupied)
default void setBedOccupied(Level world, BlockPos pos, LivingEntity sleeper, boolean occupied)
{
getBlockState().getBlock().setBedOccupied(getBlockState(), world, pos, sleeper, occupied);
self().getBlock().setBedOccupied(self(), world, pos, sleeper, occupied);
}
/**
@@ -238,53 +199,9 @@ public interface IForgeBlockState
* @param pos Block position in world
* @return Bed direction
*/
default Direction getBedDirection(IWorldReader world, BlockPos pos)
default Direction getBedDirection(LevelReader world, BlockPos pos)
{
return getBlockState().getBlock().getBedDirection(getBlockState(), world, pos);
}
/**
* Determines this block should be treated as an air block
* by the rest of the code. This method is primarily
* useful for creating pure logic-blocks that will be invisible
* to the player and otherwise interact as air would.
*
* @param world The current world
* @param pos Block position in world
* @return True if the block considered air
* @deprecated TODO: Remove in 1.17, in favor of state only version. This is a old hook from before
* block states were unlimited and people used TileEntities. If you still use the location
* information in your TileEntity please explain why and how you can't use BlockState only version
* here: https://github.com/MinecraftForge/MinecraftForge/issues/7409
*/
@Deprecated
default boolean isAir(IBlockReader world, BlockPos pos)
{
return getBlockState().getBlock().isAir(getBlockState(), world, pos);
}
/**
* Used during tree growth to determine if newly generated leaves can replace this block.
*
* @param world The current world
* @param pos Block position in world
* @return true if this block can be replaced by growing leaves.
*/
default boolean canBeReplacedByLeaves(IWorldReader world, BlockPos pos)
{
return getBlockState().getBlock().canBeReplacedByLeaves(getBlockState(), world, pos);
}
/**
* Used during tree growth to determine if newly generated logs can replace this block.
*
* @param world The current world
* @param pos Block position in world
* @return true if this block can be replaced by growing leaves.
*/
default boolean canBeReplacedByLogs(IWorldReader world, BlockPos pos)
{
return getBlockState().getBlock().canBeReplacedByLogs(getBlockState(), world, pos);
return self().getBlock().getBedDirection(self(), world, pos);
}
/**
@@ -295,23 +212,9 @@ public interface IForgeBlockState
* @param explosion The explosion
* @return The amount of the explosion absorbed.
*/
default float getExplosionResistance(IBlockReader world, BlockPos pos, Explosion explosion)
default float getExplosionResistance(BlockGetter world, BlockPos pos, Explosion explosion)
{
return getBlockState().getBlock().getExplosionResistance(getBlockState(), world, pos, explosion);
}
/**
* Determine if this block can make a redstone connection on the side provided,
* Useful to control which sides are inputs and outputs for redstone wires.
*
* @param world The current world
* @param pos Block position in world
* @param side The side that is trying to make the connection, CAN BE NULL
* @return True to make the connection
*/
default boolean canConnectRedstone(IBlockReader world, BlockPos pos, @Nullable Direction side)
{
return getBlockState().getBlock().canConnectRedstone(getBlockState(), world, pos, side);
return self().getBlock().getExplosionResistance(self(), world, pos, explosion);
}
/**
@@ -321,9 +224,9 @@ public interface IForgeBlockState
* @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 getPickBlock(RayTraceResult target, IBlockReader world, BlockPos pos, PlayerEntity player)
default ItemStack getPickBlock(HitResult target, BlockGetter world, BlockPos pos, Player player)
{
return getBlockState().getBlock().getPickBlock(getBlockState(), target, world, pos, player);
return self().getBlock().getPickBlock(self(), target, world, pos, player);
}
/**
@@ -338,9 +241,9 @@ public interface IForgeBlockState
* @param numberOfParticles That vanilla world have spawned
* @return True to prevent vanilla landing particles from spawning
*/
default boolean addLandingEffects(ServerWorld worldserver, BlockPos pos, BlockState state2, LivingEntity entity, int numberOfParticles)
default boolean addLandingEffects(ServerLevel worldserver, BlockPos pos, BlockState state2, LivingEntity entity, int numberOfParticles)
{
return getBlockState().getBlock().addLandingEffects(getBlockState(), worldserver, pos, state2, entity, numberOfParticles);
return self().getBlock().addLandingEffects(self(), worldserver, pos, state2, entity, numberOfParticles);
}
/**
* Allows a block to override the standard vanilla running particles.
@@ -353,43 +256,9 @@ public interface IForgeBlockState
* @param entity The entity running on the block.
* @return True to prevent vanilla running particles from spawning.
*/
default boolean addRunningEffects(World world, BlockPos pos, Entity entity)
default boolean addRunningEffects(Level world, BlockPos pos, Entity entity)
{
return getBlockState().getBlock().addRunningEffects(getBlockState(), world, pos, entity);
}
/**
* Spawn a digging particle effect in the world, this is a wrapper
* around EffectRenderer.addBlockHitEffects to allow the block more
* control over the particles. Useful when you have entirely different
* texture sheets for different sides/locations in the world.
*
* @param world The current world
* @param target The target the player is looking at {x/y/z/side/sub}
* @param manager A reference to the current particle manager.
* @return True to prevent vanilla digging particles form spawning.
*/
@OnlyIn(Dist.CLIENT)
default boolean addHitEffects(World world, RayTraceResult target, ParticleManager manager)
{
return getBlockState().getBlock().addHitEffects(getBlockState(), world, target, manager);
}
/**
* Spawn particles for when the block is destroyed. Due to the nature
* of how this is invoked, the x/y/z locations are not always guaranteed
* to host your block. So be sure to do proper sanity checks before assuming
* that the location is this block.
*
* @param world The current world
* @param pos Position to spawn the particle
* @param manager A reference to the current particle manager.
* @return True to prevent vanilla break particles from spawning.
*/
@OnlyIn(Dist.CLIENT)
default boolean addDestroyEffects(World world, BlockPos pos, ParticleManager manager)
{
return getBlockState().getBlock().addDestroyEffects(getBlockState(), world, pos, manager);
return self().getBlock().addRunningEffects(self(), world, pos, entity);
}
/**
@@ -408,9 +277,9 @@ public interface IForgeBlockState
* @param plantable The plant that wants to check
* @return True to allow the plant to be planted/stay.
*/
default boolean canSustainPlant(IBlockReader world, BlockPos pos, Direction facing, IPlantable plantable)
default boolean canSustainPlant(BlockGetter world, BlockPos pos, Direction facing, IPlantable plantable)
{
return getBlockState().getBlock().canSustainPlant(getBlockState(), world, pos, facing, plantable);
return self().getBlock().canSustainPlant(self(), world, pos, facing, plantable);
}
/**
@@ -422,9 +291,9 @@ public interface IForgeBlockState
* @param pos Block position in world
* @return True if the soil should be considered fertile.
*/
default boolean isFertile(IBlockReader world, BlockPos pos)
default boolean isFertile(BlockGetter world, BlockPos pos)
{
return getBlockState().getBlock().isFertile(getBlockState(), world, pos);
return self().getBlock().isFertile(self(), world, pos);
}
/**
@@ -435,9 +304,9 @@ public interface IForgeBlockState
* @param conduit Conduit position in world
* @return True, to support the conduit, and make it active with this block.
*/
default boolean isConduitFrame(IWorldReader world, BlockPos pos, BlockPos conduit)
default boolean isConduitFrame(LevelReader world, BlockPos pos, BlockPos conduit)
{
return getBlockState().getBlock().isConduitFrame(getBlockState(), world, pos, conduit);
return self().getBlock().isConduitFrame(self(), world, pos, conduit);
}
/**
@@ -447,9 +316,9 @@ public interface IForgeBlockState
* @param pos Block position in world
* @return True, to support being part of a nether portal frame, false otherwise.
*/
default boolean isPortalFrame(IBlockReader world, BlockPos pos)
default boolean isPortalFrame(BlockGetter world, BlockPos pos)
{
return getBlockState().getBlock().isPortalFrame(getBlockState(), world, pos);
return self().getBlock().isPortalFrame(self(), world, pos);
}
/**
@@ -460,14 +329,14 @@ public interface IForgeBlockState
* @param fortune
* @return Amount of XP from breaking this block.
*/
default int getExpDrop(IWorldReader world, BlockPos pos, int fortune, int silktouch)
default int getExpDrop(LevelReader world, BlockPos pos, int fortune, int silktouch)
{
return getBlockState().getBlock().getExpDrop(getBlockState(), world, pos, fortune, silktouch);
return self().getBlock().getExpDrop(self(), world, pos, fortune, silktouch);
}
default BlockState rotate(IWorld world, BlockPos pos, Rotation direction)
default BlockState rotate(LevelAccessor world, BlockPos pos, Rotation direction)
{
return getBlockState().getBlock().rotate(getBlockState(), world, pos, direction);
return self().getBlock().rotate(self(), world, pos, direction);
}
/**
@@ -476,9 +345,9 @@ public interface IForgeBlockState
* @param pos Block position in world
* @return The amount of enchanting power this block produces.
*/
default float getEnchantPowerBonus(IWorldReader world, BlockPos pos)
default float getEnchantPowerBonus(LevelReader world, BlockPos pos)
{
return getBlockState().getBlock().getEnchantPowerBonus(getBlockState(), world, pos);
return self().getBlock().getEnchantPowerBonus(self(), world, pos);
}
/**
@@ -487,23 +356,9 @@ public interface IForgeBlockState
* @param pos Block position in world
* @param neighbor Block position of neighbor
*/
default void onNeighborChange(IWorldReader world, BlockPos pos, BlockPos neighbor)
default void onNeighborChange(LevelReader world, BlockPos pos, BlockPos neighbor)
{
getBlockState().getBlock().onNeighborChange(getBlockState(), world, pos, neighbor);
}
/**
* Called on an Observer block whenever an update for an Observer is received.
*
* @param world The current world.
* @param pos The Observer block's position.
* @param changed The updated block.
* @param changedPos The updated block's position.
*/
@Deprecated//TODO - 1.17: Remove (unused)
default void observedNeighborChange(World world, BlockPos pos, Block changed, BlockPos changedPos)
{
getBlockState().getBlock().observedNeighborChange(getBlockState(), world, pos, changed, changedPos);
self().getBlock().onNeighborChange(self(), world, pos, neighbor);
}
/**
@@ -513,9 +368,9 @@ public interface IForgeBlockState
* @param side The INPUT side of the block to be powered - ie the opposite of this block's output side
* @return Whether Block#isProvidingWeakPower should be called when determining indirect power
*/
default boolean shouldCheckWeakPower(IWorldReader world, BlockPos pos, Direction side)
default boolean shouldCheckWeakPower(LevelReader world, BlockPos pos, Direction side)
{
return getBlockState().getBlock().shouldCheckWeakPower(getBlockState(), world, pos, side);
return self().getBlock().shouldCheckWeakPower(self(), world, pos, side);
}
/**
@@ -527,9 +382,9 @@ public interface IForgeBlockState
* @param pos Block position in world
* @return true To be notified of changes
*/
default boolean getWeakChanges(IWorldReader world, BlockPos pos)
default boolean getWeakChanges(LevelReader world, BlockPos pos)
{
return getBlockState().getBlock().getWeakChanges(getBlockState(), world, pos);
return self().getBlock().getWeakChanges(self(), world, pos);
}
/**
@@ -538,12 +393,12 @@ public interface IForgeBlockState
*/
default ToolType getHarvestTool()
{
return getBlockState().getBlock().getHarvestTool(getBlockState());
return self().getBlock().getHarvestTool(self());
}
default int getHarvestLevel()
{
return getBlockState().getBlock().getHarvestLevel(getBlockState());
return self().getBlock().getHarvestLevel(self());
}
/**
@@ -552,7 +407,7 @@ public interface IForgeBlockState
*/
default boolean isToolEffective(ToolType tool)
{
return getBlockState().getBlock().isToolEffective(getBlockState(), tool);
return self().getBlock().isToolEffective(self(), tool);
}
/**
@@ -562,9 +417,9 @@ public interface IForgeBlockState
* @param entity The entity that is breaking/stepping on/placing/hitting/falling on this block, or null if no entity is in this context
* @return A SoundType to use
*/
default SoundType getSoundType(IWorldReader world, BlockPos pos, @Nullable Entity entity)
default SoundType getSoundType(LevelReader world, BlockPos pos, @Nullable Entity entity)
{
return getBlockState().getBlock().getSoundType(getBlockState(), world, pos, entity);
return self().getBlock().getSoundType(self(), world, pos, entity);
}
/**
@@ -574,30 +429,14 @@ public interface IForgeBlockState
* @return A float RGB [0.0, 1.0] array to be averaged with a beacon's existing beam color, or null to do nothing to the beam
*/
@Nullable
default float[] getBeaconColorMultiplier(IWorldReader world, BlockPos pos, BlockPos beacon)
default float[] getBeaconColorMultiplier(LevelReader world, BlockPos pos, BlockPos beacon)
{
return getBlockState().getBlock().getBeaconColorMultiplier(getBlockState(), world, pos, beacon);
}
/**
* Use this to change the fog color used when the entity is "inside" a material.
* Vec3d is used here as "r/g/b" 0 - 1 values.
*
* @param world The world.
* @param pos The position at the entity viewport.
* @param entity the entity
* @param originalColor The current fog color, You are not expected to use this, Return as the default if applicable.
* @return The new fog color.
*/
@OnlyIn(Dist.CLIENT)
default Vector3d getFogColor(IWorldReader world, BlockPos pos, Entity entity, Vector3d originalColor, float partialTicks)
{
return getBlockState().getBlock().getFogColor(getBlockState(), world, pos, entity, originalColor, partialTicks);
return self().getBlock().getBeaconColorMultiplier(self(), world, pos, beacon);
}
/**
* Used to determine the state 'viewed' by an entity (see
* {@link ActiveRenderInfo#getBlockStateAtEntityViewpoint(World, Entity, float)}).
* {@link net.minecraft.client.Camera#getBlockAtCamera()}).
* Can be used by fluid blocks to determine if the viewpoint is within the fluid or not.
*
* @param world the world
@@ -605,9 +444,9 @@ public interface IForgeBlockState
* @param viewpoint the viewpoint
* @return the block state that should be 'seen'
*/
default BlockState getStateAtViewpoint(IBlockReader world, BlockPos pos, Vector3d viewpoint)
default BlockState getStateAtViewpoint(BlockGetter world, BlockPos pos, Vec3 viewpoint)
{
return getBlockState().getBlock().getStateAtViewpoint(getBlockState(), world, pos, viewpoint);
return self().getBlock().getStateAtViewpoint(self(), world, pos, viewpoint);
}
/**
@@ -615,7 +454,7 @@ public interface IForgeBlockState
*/
default boolean isSlimeBlock()
{
return getBlockState().getBlock().isSlimeBlock(getBlockState());
return self().getBlock().isSlimeBlock(self());
}
/**
@@ -623,7 +462,7 @@ public interface IForgeBlockState
*/
default boolean isStickyBlock()
{
return getBlockState().getBlock().isStickyBlock(getBlockState());
return self().getBlock().isStickyBlock(self());
}
/**
@@ -633,7 +472,7 @@ public interface IForgeBlockState
*/
default boolean canStickTo(BlockState other)
{
return getBlockState().getBlock().canStickTo(getBlockState(), other);
return self().getBlock().canStickTo(self(), other);
}
/**
@@ -645,9 +484,9 @@ public interface IForgeBlockState
* @param face The face that the fire is coming from
* @return A number ranging from 0 to 300 relating used to determine if the block will be consumed by fire
*/
default int getFlammability(IBlockReader world, BlockPos pos, Direction face)
default int getFlammability(BlockGetter world, BlockPos pos, Direction face)
{
return getBlockState().getBlock().getFlammability(getBlockState(), world, pos, face);
return self().getBlock().getFlammability(self(), world, pos, face);
}
/**
@@ -658,9 +497,9 @@ public interface IForgeBlockState
* @param face The face that the fire is coming from
* @return True if the face can be on fire, false otherwise.
*/
default boolean isFlammable(IBlockReader world, BlockPos pos, Direction face)
default boolean isFlammable(BlockGetter world, BlockPos pos, Direction face)
{
return getBlockState().getBlock().isFlammable(getBlockState(), world, pos, face);
return self().getBlock().isFlammable(self(), world, pos, face);
}
/**
@@ -671,9 +510,9 @@ public interface IForgeBlockState
* @param face The face that the fire is coming from
* @param igniter The entity that lit the fire
*/
default void catchFire(World world, BlockPos pos, @Nullable Direction face, @Nullable LivingEntity igniter)
default void catchFire(Level world, BlockPos pos, @Nullable Direction face, @Nullable LivingEntity igniter)
{
getBlockState().getBlock().catchFire(getBlockState(), world, pos, face, igniter);
self().getBlock().catchFire(self(), world, pos, face, igniter);
}
/**
@@ -685,9 +524,9 @@ public interface IForgeBlockState
* @param face The face that the fire is coming from
* @return A number that is used to determine the speed of fire growth around the block
*/
default int getFireSpreadSpeed(IBlockReader world, BlockPos pos, Direction face)
default int getFireSpreadSpeed(BlockGetter world, BlockPos pos, Direction face)
{
return getBlockState().getBlock().getFireSpreadSpeed(getBlockState(), world, pos, face);
return self().getBlock().getFireSpreadSpeed(self(), world, pos, face);
}
/**
@@ -700,9 +539,9 @@ public interface IForgeBlockState
* @param side The face that the fire is coming from
* @return True if this block sustains fire, meaning it will never go out.
*/
default boolean isFireSource(IWorldReader world, BlockPos pos, Direction side)
default boolean isFireSource(LevelReader world, BlockPos pos, Direction side)
{
return getBlockState().getBlock().isFireSource(getBlockState(), world, pos, side);
return self().getBlock().isFireSource(self(), world, pos, side);
}
/**
@@ -712,9 +551,9 @@ public interface IForgeBlockState
* @param pos Block position in world
* @return True to allow the ender dragon to destroy this block
*/
default boolean canEntityDestroy(IBlockReader world, BlockPos pos, Entity entity)
default boolean canEntityDestroy(BlockGetter world, BlockPos pos, Entity entity)
{
return getBlockState().getBlock().canEntityDestroy(getBlockState(), world, pos, entity);
return self().getBlock().canEntityDestroy(self(), world, pos, entity);
}
/**
@@ -725,9 +564,9 @@ public interface IForgeBlockState
* @param pos Block position in world
* @return True if the block should deal damage
*/
default boolean isBurning(IBlockReader world, BlockPos pos)
default boolean isBurning(BlockGetter world, BlockPos pos)
{
return getBlockState().getBlock().isBurning(getBlockState(), world, pos);
return self().getBlock().isBurning(self(), world, pos);
}
/**
@@ -736,7 +575,7 @@ public interface IForgeBlockState
* @return the PathNodeType
*/
@Nullable
default PathNodeType getAiPathNodeType(IBlockReader world, BlockPos pos)
default BlockPathTypes getAiPathNodeType(BlockGetter world, BlockPos pos)
{
return getAiPathNodeType(world, pos, null);
}
@@ -747,17 +586,17 @@ public interface IForgeBlockState
* @return the PathNodeType
*/
@Nullable
default PathNodeType getAiPathNodeType(IBlockReader world, BlockPos pos, @Nullable MobEntity entity)
default BlockPathTypes getAiPathNodeType(BlockGetter world, BlockPos pos, @Nullable Mob entity)
{
return getBlockState().getBlock().getAiPathNodeType(getBlockState(), world, pos, entity);
return self().getBlock().getAiPathNodeType(self(), world, pos, entity);
}
/**
* Determines if this block should drop loot when exploded.
*/
default boolean canDropFromExplosion(IBlockReader world, BlockPos pos, Explosion explosion)
default boolean canDropFromExplosion(BlockGetter world, BlockPos pos, Explosion explosion)
{
return getBlockState().getBlock().canDropFromExplosion(getBlockState(), world, pos, explosion);
return self().getBlock().canDropFromExplosion(self(), world, pos, explosion);
}
/**
@@ -769,18 +608,18 @@ public interface IForgeBlockState
* @param pos Block position in world
* @param explosion The explosion instance affecting the block
*/
default void onBlockExploded(World world, BlockPos pos, Explosion explosion)
default void onBlockExploded(Level world, BlockPos pos, Explosion explosion)
{
getBlockState().getBlock().onBlockExploded(getBlockState(), world, pos, explosion);
self().getBlock().onBlockExploded(self(), world, pos, explosion);
}
/**
* Determines if this block's collision box should be treated as though it can extend above its block space.
* This can be used to replicate fence and wall behavior.
*/
default boolean collisionExtendsVertically(IBlockReader world, BlockPos pos, Entity collidingEntity)
default boolean collisionExtendsVertically(BlockGetter world, BlockPos pos, Entity collidingEntity)
{
return getBlockState().getBlock().collisionExtendsVertically(getBlockState(), world, pos, collidingEntity);
return self().getBlock().collisionExtendsVertically(self(), world, pos, collidingEntity);
}
/**
@@ -791,9 +630,9 @@ public interface IForgeBlockState
* @param fluidState The state of the fluid
* @return Whether the fluid overlay texture should be used
*/
default boolean shouldDisplayFluidOverlay(IBlockDisplayReader world, BlockPos pos, FluidState fluidState)
default boolean shouldDisplayFluidOverlay(BlockAndTintGetter world, BlockPos pos, FluidState fluidState)
{
return getBlockState().getBlock().shouldDisplayFluidOverlay(getBlockState(), world, pos, fluidState);
return self().getBlock().shouldDisplayFluidOverlay(self(), world, pos, fluidState);
}
/**
@@ -809,10 +648,10 @@ public interface IForgeBlockState
* @return The resulting state after the action has been performed
*/
@Nullable
default BlockState getToolModifiedState(World world, BlockPos pos, PlayerEntity player, ItemStack stack, ToolType toolType)
default BlockState getToolModifiedState(Level world, BlockPos pos, Player player, ItemStack stack, ToolType toolType)
{
BlockState eventState = net.minecraftforge.event.ForgeEventFactory.onToolUse(getBlockState(), world, pos, player, stack, toolType);
return eventState != getBlockState() ? eventState : getBlockState().getBlock().getToolModifiedState(getBlockState(), world, pos, player, stack, toolType);
BlockState eventState = net.minecraftforge.event.ForgeEventFactory.onToolUse(self(), world, pos, player, stack, toolType);
return eventState != self() ? eventState : self().getBlock().getToolModifiedState(self(), world, pos, player, stack, toolType);
}
/**
@@ -823,6 +662,6 @@ public interface IForgeBlockState
*/
default boolean isScaffolding(LivingEntity entity)
{
return getBlockState().getBlock().isScaffolding(getBlockState(), entity.level, entity.blockPosition(), entity);
return self().getBlock().isScaffolding(self(), entity.level, entity.blockPosition(), entity);
}
}
@@ -19,17 +19,18 @@
package net.minecraftforge.common.extensions;
import net.minecraft.entity.player.PlayerInventory;
import net.minecraft.inventory.container.Container;
import net.minecraft.inventory.container.ContainerType;
import net.minecraft.network.PacketBuffer;
import net.minecraft.world.entity.player.Inventory;
import net.minecraft.world.inventory.AbstractContainerMenu;
import net.minecraft.world.inventory.MenuType;
import net.minecraft.network.FriendlyByteBuf;
import net.minecraftforge.fmllegacy.network.IContainerFactory;
public interface IForgeContainerType<T>
{
static <T extends Container> ContainerType<T> create(net.minecraftforge.fml.network.IContainerFactory<T> factory)
static <T extends AbstractContainerMenu> MenuType<T> create(IContainerFactory<T> factory)
{
return new ContainerType<>(factory);
return new MenuType<>(factory);
}
T create(int windowId, PlayerInventory playerInv, PacketBuffer extraData);
T create(int windowId, Inventory playerInv, FriendlyByteBuf extraData);
}
@@ -1,111 +0,0 @@
/*
* Minecraft Forge
* Copyright (c) 2016-2021.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation version 2.1
* of the License.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
package net.minecraftforge.common.extensions;
import java.util.ArrayList;
import java.util.List;
import com.mojang.blaze3d.matrix.MatrixStack;
import net.minecraft.client.gui.AbstractGui;
import net.minecraft.client.gui.DisplayEffectsScreen;
import net.minecraft.item.ItemStack;
import net.minecraft.item.Items;
import net.minecraft.potion.Effect;
import net.minecraft.potion.EffectInstance;
import net.minecraftforge.api.distmarker.Dist;
import net.minecraftforge.api.distmarker.OnlyIn;
public interface IForgeEffect {
default Effect getEffect() {
return (Effect)this;
}
/**
* If the Potion effect should be displayed in the players inventory
* @param effect the active PotionEffect
* @return true to display it (default), false to hide it.
*/
default boolean shouldRender(EffectInstance effect) { return true; }
/**
* If the standard PotionEffect text (name and duration) should be drawn when this potion is active.
* @param effect the active PotionEffect
* @return true to draw the standard text
*/
default boolean shouldRenderInvText(EffectInstance effect) { return true; }
/**
* If the Potion effect should be displayed in the player's ingame HUD
* @param effect the active PotionEffect
* @return true to display it (default), false to hide it.
*/
default boolean shouldRenderHUD(EffectInstance effect) { return true; }
/**
* Called to draw the this Potion onto the player's inventory when it's active.
* This can be used to e.g. render Potion icons from your own texture.
*
* @param effect the active PotionEffect
* @param gui the gui instance
* @param mStack The MatrixStack
* @param x the x coordinate
* @param y the y coordinate
* @param z the z level
*/
@OnlyIn(Dist.CLIENT)
default void renderInventoryEffect(EffectInstance effect, DisplayEffectsScreen<?> gui, MatrixStack mStack, int x, int y, float z) { }
/**
* Called to draw the this Potion onto the player's ingame HUD when it's active.
* This can be used to e.g. render Potion icons from your own texture.
* @param effect the active PotionEffect
* @param gui the gui instance
* @param mStack The MatrixStack
* @param x the x coordinate
* @param y the y coordinate
* @param z the z level
* @param alpha the alpha value, blinks when the potion is about to run out
*/
@OnlyIn(Dist.CLIENT)
default void renderHUDEffect(EffectInstance effect, AbstractGui gui, MatrixStack mStack, int x, int y, float z, float alpha) { }
/**
* Get a fresh list of items that can cure this Potion.
* All new PotionEffects created from this Potion will call this to initialize the default curative items
* @see PotionEffect#getCurativeItems
* @return A list of items that can cure this Potion
*/
default List<ItemStack> getCurativeItems() {
ArrayList<ItemStack> ret = new ArrayList<ItemStack>();
ret.add(new ItemStack(Items.MILK_BUCKET));
return ret;
}
/**
* Used for determining {@code PotionEffect} sort order in GUIs.
* Defaults to the {@code PotionEffect}'s liquid color.
* @param potionEffect the {@code PotionEffect} instance containing the potion
* @return a value used to sort {@code PotionEffect}s in GUIs
*/
default int getGuiSortColor(EffectInstance potionEffect) {
return getEffect().getColor();
}
}
@@ -1,133 +0,0 @@
/*
* Minecraft Forge
* Copyright (c) 2016-2021.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation version 2.1
* of the License.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
package net.minecraftforge.common.extensions;
import java.util.List;
import com.mojang.blaze3d.matrix.MatrixStack;
import net.minecraft.client.gui.AbstractGui;
import net.minecraft.client.gui.DisplayEffectsScreen;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.CompoundNBT;
import net.minecraft.nbt.ListNBT;
import net.minecraft.potion.EffectInstance;
import net.minecraft.potion.Potion;
import net.minecraftforge.api.distmarker.Dist;
import net.minecraftforge.api.distmarker.OnlyIn;
public interface IForgeEffectInstance {
default EffectInstance getEffectInstance() {
return (EffectInstance)this;
}
/**
* If the Potion effect should be displayed in the players inventory
* @return true to display it (default), false to hide it.
*/
default boolean shouldRender() {
return getEffectInstance().getEffect().shouldRender(getEffectInstance());
}
/**
* If the standard PotionEffect text (name and duration) should be drawn when this potion is active.
* @return true to draw the standard text
*/
default boolean shouldRenderInvText() {
return getEffectInstance().getEffect().shouldRenderInvText(getEffectInstance());
}
/**
* If the Potion effect should be displayed in the player's ingame HUD
* @return true to display it (default), false to hide it.
*/
default boolean shouldRenderHUD() {
return getEffectInstance().getEffect().shouldRenderHUD(getEffectInstance());
}
/**
* Called to draw the this Potion onto the player's inventory when it's active.
* This can be used to e.g. render Potion icons from your own texture.
*
* @param gui the gui instance
* @param mStack The MatrixStack
* @param x the x coordinate
* @param y the y coordinate
* @param z the z level
*/
@OnlyIn(Dist.CLIENT)
default void renderInventoryEffect(DisplayEffectsScreen<?> gui, MatrixStack mStack, int x, int y, float z) {
getEffectInstance().getEffect().renderInventoryEffect(getEffectInstance(), gui, mStack, x, y, z);
}
/**
* Called to draw the this Potion onto the player's ingame HUD when it's active.
* This can be used to e.g. render Potion icons from your own texture.
*
* @param gui the gui instance
* @param mStack The MatrixStack
* @param x the x coordinate
* @param y the y coordinate
* @param z the z level
* @param alpha the alpha value, blinks when the potion is about to run out
*/
@OnlyIn(Dist.CLIENT)
default void renderHUDEffect(AbstractGui gui, MatrixStack mStack, int x, int y, float z, float alpha) {
getEffectInstance().getEffect().renderHUDEffect(getEffectInstance(), gui, mStack, x, y, z, alpha);
}
/***
* Returns a list of curative items for the potion effect
* By default, this list is initialized using {@link Potion#getCurativeItems}
*
* @return The list (ItemStack) of curative items for the potion effect
*/
List<ItemStack> getCurativeItems();
/***
* Checks the given ItemStack to see if it is in the list of curative items for the potion effect
* @param stack The ItemStack being checked against the list of curative items for this PotionEffect
* @return true if the given ItemStack is in the list of curative items for this PotionEffect, false otherwise
*/
default boolean isCurativeItem(ItemStack stack) {
return this.getCurativeItems().stream().anyMatch(e -> e.sameItem(stack));
}
/***
* Sets the list of curative items for this potion effect, overwriting any already present
* @param curativeItems The list of ItemStacks being set to the potion effect
*/
void setCurativeItems(List<ItemStack> curativeItems);
/***
* Adds the given stack to the list of curative items for this PotionEffect
* @param stack The ItemStack being added to the curative item list
*/
default void addCurativeItem(ItemStack stack) {
if (!this.isCurativeItem(stack))
this.getCurativeItems().add(stack);
}
default void writeCurativeItems(CompoundNBT nbt) {
ListNBT list = new ListNBT();
getCurativeItems().forEach(s -> list.add(s.save(new CompoundNBT())));
nbt.put("CurativeItems", list);
}
}
@@ -20,47 +20,37 @@
package net.minecraftforge.common.extensions;
import java.util.Collection;
import java.util.Collections;
import javax.annotation.Nullable;
import net.minecraft.block.BlockState;
import net.minecraft.entity.Entity;
import net.minecraft.entity.item.LeashKnotEntity;
import net.minecraft.entity.LivingEntity;
import net.minecraft.entity.EntityClassification;
import net.minecraft.entity.item.ArmorStandEntity;
import net.minecraft.entity.item.BoatEntity;
import net.minecraft.entity.item.EnderCrystalEntity;
import net.minecraft.entity.item.ItemEntity;
import net.minecraft.entity.item.ItemFrameEntity;
import net.minecraft.entity.item.minecart.AbstractMinecartEntity;
import net.minecraft.entity.item.PaintingEntity;
import net.minecraft.item.Items;
import net.minecraft.item.SpawnEggItem;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.CompoundNBT;
import net.minecraft.util.math.BlockPos;
import net.minecraft.util.math.RayTraceResult;
import net.minecraft.world.level.block.state.BlockState;
import net.minecraft.world.entity.Entity;
import net.minecraft.world.entity.MobCategory;
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;
import net.minecraft.world.phys.HitResult;
import net.minecraftforge.common.capabilities.ICapabilitySerializable;
import net.minecraftforge.entity.PartEntity;
public interface IForgeEntity extends ICapabilitySerializable<CompoundNBT>
public interface IForgeEntity extends ICapabilitySerializable<CompoundTag>
{
default Entity getEntity() { return (Entity) this; }
private Entity self() { return (Entity) this; }
default void deserializeNBT(CompoundNBT nbt)
default void deserializeNBT(CompoundTag nbt)
{
getEntity().load(nbt);
self().load(nbt);
}
default CompoundNBT serializeNBT()
default CompoundTag serializeNBT()
{
CompoundNBT ret = new CompoundNBT();
String id = getEntity().getEncodeId();
CompoundTag ret = new CompoundTag();
String id = self().getEncodeId();
if (id != null)
{
ret.putString("id", getEntity().getEncodeId());
ret.putString("id", self().getEncodeId());
}
return getEntity().saveWithoutId(ret);
return self().saveWithoutId(ret);
}
boolean canUpdate();
@@ -76,7 +66,7 @@ public interface IForgeEntity extends ICapabilitySerializable<CompoundNBT>
* It will be written, and read from disc, so it persists over world saves.
* @return A NBTTagCompound
*/
CompoundNBT getPersistentData();
CompoundTag getPersistentData();
/**
* Used in model rendering to determine if the entity riding this entity should be in the 'sitting' position.
@@ -93,34 +83,17 @@ public interface IForgeEntity extends ICapabilitySerializable<CompoundNBT>
* @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(RayTraceResult target)
default ItemStack getPickedResult(HitResult target)
{
if (this instanceof PaintingEntity)
return new ItemStack(Items.PAINTING);
else if (this instanceof LeashKnotEntity)
return new ItemStack(Items.LEAD);
else if (this instanceof ItemFrameEntity)
{
ItemStack held = ((ItemFrameEntity)this).getItem();
if (held.isEmpty())
return new ItemStack(Items.ITEM_FRAME);
ItemStack result = self().getPickResult();
if (result == null) {
SpawnEggItem egg = SpawnEggItem.byId(self().getType());
if (egg != null)
result = new ItemStack(egg);
else
return held.copy();
result = ItemStack.EMPTY;
}
else if (this instanceof AbstractMinecartEntity)
return ((AbstractMinecartEntity)this).getCartItem();
else if (this instanceof BoatEntity)
return new ItemStack(((BoatEntity)this).getDropItem());
else if (this instanceof ArmorStandEntity)
return new ItemStack(Items.ARMOR_STAND);
else if (this instanceof EnderCrystalEntity)
return new ItemStack(Items.END_CRYSTAL);
else
{
SpawnEggItem egg = SpawnEggItem.byId(getEntity().getType());
if (egg != null) return new ItemStack(egg);
}
return ItemStack.EMPTY;
return result;
}
/**
@@ -142,7 +115,7 @@ public interface IForgeEntity extends ICapabilitySerializable<CompoundNBT>
*/
default boolean canBeRiddenInWater(Entity rider)
{
return getEntity().rideableUnderWater();
return self().rideableUnderWater();
}
/**
@@ -159,9 +132,9 @@ public interface IForgeEntity extends ICapabilitySerializable<CompoundNBT>
* @param forSpawnCount If this is being invoked to check spawn count caps.
* @return If the creature is of the type provided
*/
default EntityClassification getClassification(boolean forSpawnCount)
default MobCategory getClassification(boolean forSpawnCount)
{
return getEntity().getType().getCategory();
return self().getType().getCategory();
}
/**
@@ -23,26 +23,21 @@ import java.util.Set;
import javax.annotation.Nullable;
import net.minecraft.block.material.Material;
import net.minecraft.entity.Entity;
import net.minecraft.fluid.Fluid;
import net.minecraft.fluid.FluidState;
import net.minecraft.tags.Tag;
import net.minecraft.util.ResourceLocation;
import net.minecraft.util.math.AxisAlignedBB;
import net.minecraft.util.math.BlockPos;
import net.minecraft.world.Explosion;
import net.minecraft.world.IBlockReader;
import net.minecraft.world.IWorldReader;
import net.minecraft.world.level.material.Material;
import net.minecraft.world.entity.Entity;
import net.minecraft.world.level.material.Fluid;
import net.minecraft.world.level.material.FluidState;
import net.minecraft.tags.SetTag;
import net.minecraft.resources.ResourceLocation;
import net.minecraft.world.phys.AABB;
import net.minecraft.core.BlockPos;
import net.minecraft.world.level.Explosion;
import net.minecraft.world.level.BlockGetter;
import net.minecraft.world.level.LevelReader;
import net.minecraftforge.fluids.FluidAttributes;
public interface IForgeFluid
{
default Fluid getFluid()
{
return (Fluid) this;
}
/**
* Called when the entity is inside this block, may be used to determined if the entity can breathing,
* display material overlays, or if the entity can swim inside a block.
@@ -54,7 +49,7 @@ public interface IForgeFluid
* @param tag Fluid category
* @param testingHead when true, its testing the entities head for vision, breathing ect... otherwise its testing the body, for swimming and movement adjustment.
*/
default boolean isEntityInside(FluidState state, IWorldReader world, BlockPos pos, Entity entity, double yToTest, Tag<Fluid> tag, boolean testingHead)
default boolean isEntityInside(FluidState state, LevelReader world, BlockPos pos, Entity entity, double yToTest, SetTag<Fluid> tag, boolean testingHead)
{
return state.is(tag) && yToTest < (double)(pos.getY() + state.getHeight(world, pos) + 0.11111111F);
}
@@ -70,7 +65,7 @@ public interface IForgeFluid
* @return null for default behavior, true if the box is within the material, false if it was not.
*/
@Nullable
default Boolean isAABBInsideMaterial(FluidState state, IWorldReader world, BlockPos pos, AxisAlignedBB boundingBox, Material materialIn)
default Boolean isAABBInsideMaterial(FluidState state, LevelReader world, BlockPos pos, AABB boundingBox, Material materialIn)
{
return null;
}
@@ -84,7 +79,7 @@ public interface IForgeFluid
* @return null for default behavior, true if the box is within the material, false if it was not.
*/
@Nullable
default Boolean isAABBInsideLiquid(FluidState state, IWorldReader world, BlockPos pos, AxisAlignedBB boundingBox)
default Boolean isAABBInsideLiquid(FluidState state, LevelReader world, BlockPos pos, AABB boundingBox)
{
return null;
}
@@ -98,7 +93,7 @@ public interface IForgeFluid
* @return The amount of the explosion absorbed.
*/
@SuppressWarnings("deprecation")
default float getExplosionResistance(FluidState state, IBlockReader world, BlockPos pos, Explosion explosion)
default float getExplosionResistance(FluidState state, BlockGetter world, BlockPos pos, Explosion explosion)
{
return state.getExplosionResistance();
}
@@ -19,21 +19,18 @@
package net.minecraftforge.common.extensions;
import javax.annotation.Nullable;
import net.minecraft.client.renderer.model.IBakedModel;
import net.minecraft.entity.Entity;
import net.minecraft.fluid.Fluid;
import net.minecraft.fluid.FluidState;
import net.minecraft.tags.Tag;
import net.minecraft.util.math.BlockPos;
import net.minecraft.world.Explosion;
import net.minecraft.world.IBlockReader;
import net.minecraft.world.IWorldReader;
import net.minecraft.world.entity.Entity;
import net.minecraft.world.level.material.Fluid;
import net.minecraft.world.level.material.FluidState;
import net.minecraft.tags.SetTag;
import net.minecraft.core.BlockPos;
import net.minecraft.world.level.Explosion;
import net.minecraft.world.level.BlockGetter;
import net.minecraft.world.level.LevelReader;
public interface IForgeFluidState
{
default FluidState getFluidState()
private FluidState self()
{
return (FluidState)this;
}
@@ -49,10 +46,10 @@ public interface IForgeFluidState
* @param tag to test for.
* @param testingHead when true, its testing the entities head for vision, breathing ect... otherwise its testing the body, for swimming and movement adjustment.
*/
default boolean isEntityInside(IWorldReader world, BlockPos pos, Entity entity, double yToTest, Tag<Fluid> tag, boolean testingHead)
default boolean isEntityInside(LevelReader world, BlockPos pos, Entity entity, double yToTest, SetTag<Fluid> tag, boolean testingHead)
{
// return ifluidstate.isTagged(p_213290_1_) && d0 < (double)((float)blockpos.getY() + ifluidstate.getActualHeight(this.world, blockpos) + 0.11111111F);
return getFluidState().getType().isEntityInside(getFluidState(), world, pos, entity, yToTest, tag, testingHead);
return self().getType().isEntityInside(self(), world, pos, entity, yToTest, tag, testingHead);
}
@@ -65,9 +62,9 @@ public interface IForgeFluidState
* @param explosion The explosion
* @return The amount of the explosion absorbed.
*/
default float getExplosionResistance(IBlockReader world, BlockPos pos, Explosion explosion)
default float getExplosionResistance(BlockGetter world, BlockPos pos, Explosion explosion)
{
return getFluidState().getType().getExplosionResistance(getFluidState(), world, pos, explosion);
return self().getType().getExplosionResistance(self(), world, pos, explosion);
}
/**
@@ -20,8 +20,8 @@
package net.minecraftforge.common.extensions;
import com.google.common.base.Preconditions;
import net.minecraft.network.PacketBuffer;
import net.minecraft.util.ResourceLocation;
import net.minecraft.network.FriendlyByteBuf;
import net.minecraft.resources.ResourceLocation;
import net.minecraftforge.fluids.FluidStack;
import net.minecraftforge.registries.ForgeRegistry;
import net.minecraftforge.registries.IForgeRegistry;
@@ -34,12 +34,13 @@ import java.util.Objects;
/**
* Extension-Interface providing methods for writing registry-id's instead of their registry-names.
*/
public interface IForgePacketBuffer
public interface IForgeFriendlyByteBuf
{
default PacketBuffer getBuffer()
private FriendlyByteBuf self()
{
return (PacketBuffer) this;
return (FriendlyByteBuf) this;
}
/**
* Writes the given entries integer id to the buffer. Notice however that this will only write the id of the given entry and will not check whether it actually exists
* in the given registry. Therefore no safety checks can be performed whilst reading it and if the entry is not in the registry a default value will be written.
@@ -51,7 +52,7 @@ public interface IForgePacketBuffer
{
ForgeRegistry<T> forgeRegistry = (ForgeRegistry<T>) registry;
int id = forgeRegistry.getID(entry);
getBuffer().writeVarInt(id);
self().writeVarInt(id);
}
/**
@@ -64,7 +65,7 @@ public interface IForgePacketBuffer
{
ForgeRegistry<?> forgeRegistry = (ForgeRegistry<?>) registry;
int id = forgeRegistry.getID(entryKey);
getBuffer().writeVarInt(id);
self().writeVarInt(id);
}
/**
@@ -75,7 +76,7 @@ public interface IForgePacketBuffer
default <T extends IForgeRegistryEntry<T>> T readRegistryIdUnsafe(@Nonnull IForgeRegistry<T> registry)
{
ForgeRegistry<T> forgeRegistry = (ForgeRegistry<T>) registry;
int id = getBuffer().readVarInt();
int id = self().readVarInt();
return forgeRegistry.getValue(id);
}
@@ -97,8 +98,8 @@ public interface IForgePacketBuffer
ResourceLocation name = retrievedRegistry.getRegistryName();
Preconditions.checkArgument(retrievedRegistry.containsValue(entry),"Cannot find %s in %s",entry.getRegistryName()!=null?entry.getRegistryName():entry,name);
ForgeRegistry<T> reg = (ForgeRegistry<T>)retrievedRegistry;
getBuffer().writeResourceLocation(name); //TODO change to writing a varInt once registries use id's
getBuffer().writeVarInt(reg.getID(entry));
self().writeResourceLocation(name); //TODO change to writing a varInt once registries use id's
self().writeVarInt(reg.getID(entry));
}
/**
@@ -109,9 +110,9 @@ public interface IForgePacketBuffer
*/
default <T extends IForgeRegistryEntry<T>> T readRegistryId()
{
ResourceLocation location = getBuffer().readResourceLocation(); //TODO change to reading a varInt once registries use id's
ResourceLocation location = self().readResourceLocation(); //TODO change to reading a varInt once registries use id's
ForgeRegistry<T> registry = RegistryManager.ACTIVE.getRegistry(location);
return registry.getValue(getBuffer().readVarInt());
return registry.getValue(self().readVarInt());
}
/**
@@ -137,10 +138,10 @@ public interface IForgePacketBuffer
default void writeFluidStack(FluidStack stack)
{
if (stack.isEmpty()) {
getBuffer().writeBoolean(false);
self().writeBoolean(false);
} else {
getBuffer().writeBoolean(true);
stack.writeToPacket(getBuffer());
self().writeBoolean(true);
stack.writeToPacket(self());
}
}
@@ -149,6 +150,6 @@ public interface IForgePacketBuffer
*/
default FluidStack readFluidStack()
{
return !getBuffer().readBoolean() ? FluidStack.EMPTY : FluidStack.readFromPacket(getBuffer());
return !self().readBoolean() ? FluidStack.EMPTY : FluidStack.readFromPacket(self());
}
}
@@ -26,45 +26,40 @@ import javax.annotation.Nullable;
import com.google.common.collect.Multimap;
import net.minecraft.block.BlockState;
import net.minecraft.block.Blocks;
import net.minecraft.client.renderer.entity.model.BipedModel;
import net.minecraft.client.renderer.tileentity.ItemStackTileEntityRenderer;
import net.minecraft.entity.Entity;
import net.minecraft.entity.MobEntity;
import net.minecraft.entity.LivingEntity;
import net.minecraft.entity.ai.attributes.Attribute;
import net.minecraft.entity.ai.attributes.AttributeModifier;
import net.minecraft.entity.item.ItemEntity;
import net.minecraft.entity.monster.EndermanEntity;
import net.minecraft.entity.monster.piglin.PiglinTasks;
import net.minecraft.entity.player.PlayerEntity;
import net.minecraft.item.ArmorItem;
import net.minecraft.item.ArmorMaterial;
import net.minecraft.item.Items;
import net.minecraft.inventory.EquipmentSlotType;
import net.minecraft.item.Item;
import net.minecraft.item.AxeItem;
import net.minecraft.item.ItemGroup;
import net.minecraft.item.ItemStack;
import net.minecraft.item.ItemUseContext;
import net.minecraft.item.crafting.IRecipeType;
import net.minecraft.nbt.CompoundNBT;
import net.minecraft.util.ActionResultType;
import net.minecraft.util.ResourceLocation;
import net.minecraft.util.math.BlockPos;
import net.minecraft.util.math.MathHelper;
import net.minecraft.util.text.ITextComponent;
import net.minecraft.world.World;
import net.minecraftforge.api.distmarker.Dist;
import net.minecraftforge.api.distmarker.OnlyIn;
import net.minecraft.world.level.block.state.BlockState;
import net.minecraft.world.level.block.Blocks;
import net.minecraft.world.entity.Entity;
import net.minecraft.world.entity.Mob;
import net.minecraft.world.entity.LivingEntity;
import net.minecraft.world.entity.ai.attributes.Attribute;
import net.minecraft.world.entity.ai.attributes.AttributeModifier;
import net.minecraft.world.entity.item.ItemEntity;
import net.minecraft.world.entity.monster.EnderMan;
import net.minecraft.world.entity.monster.piglin.PiglinAi;
import net.minecraft.world.entity.player.Player;
import net.minecraft.world.item.ArmorItem;
import net.minecraft.world.item.ArmorMaterials;
import net.minecraft.world.item.Items;
import net.minecraft.world.entity.EquipmentSlot;
import net.minecraft.world.item.Item;
import net.minecraft.world.item.AxeItem;
import net.minecraft.world.item.CreativeModeTab;
import net.minecraft.world.item.ItemStack;
import net.minecraft.world.item.context.UseOnContext;
import net.minecraft.world.item.crafting.RecipeType;
import net.minecraft.nbt.CompoundTag;
import net.minecraft.world.InteractionResult;
import net.minecraft.resources.ResourceLocation;
import net.minecraft.core.BlockPos;
import net.minecraft.util.Mth;
import net.minecraft.network.chat.Component;
import net.minecraft.world.level.Level;
import net.minecraftforge.common.ToolType;
// TODO review most of the methods in this "patch"
public interface IForgeItem
{
// Helpers for accessing Item data
default Item getItem()
private Item self()
{
return (Item) this;
}
@@ -73,9 +68,9 @@ public interface IForgeItem
* ItemStack sensitive version of getItemAttributeModifiers
*/
@SuppressWarnings("deprecation")
default Multimap<Attribute, AttributeModifier> getAttributeModifiers(EquipmentSlotType slot, ItemStack stack)
default Multimap<Attribute, AttributeModifier> getAttributeModifiers(EquipmentSlot slot, ItemStack stack)
{
return getItem().getDefaultAttributeModifiers(slot);
return self().getDefaultAttributeModifiers(slot);
}
/**
@@ -86,7 +81,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, PlayerEntity player)
default boolean onDroppedByPlayer(ItemStack item, Player player)
{
return true;
}
@@ -100,7 +95,7 @@ public interface IForgeItem
* @param displayName the name that will be displayed unless it is changed in
* this method.
*/
default ITextComponent getHighlightTip(ItemStack item, ITextComponent displayName)
default Component getHighlightTip(ItemStack item, Component displayName)
{
return displayName;
}
@@ -110,9 +105,9 @@ public interface IForgeItem
*
* @return Return PASS to allow vanilla handling, any other to skip normal code.
*/
default ActionResultType onItemUseFirst(ItemStack stack, ItemUseContext context)
default InteractionResult onItemUseFirst(ItemStack stack, UseOnContext context)
{
return ActionResultType.PASS;
return InteractionResult.PASS;
}
/**
@@ -122,7 +117,7 @@ public interface IForgeItem
*/
default boolean isPiglinCurrency(ItemStack stack)
{
return stack.getItem() == PiglinTasks.BARTERING_ITEM;
return stack.getItem() == PiglinAi.BARTERING_ITEM;
}
/**
@@ -135,7 +130,7 @@ public interface IForgeItem
*/
default boolean makesPiglinsNeutral(ItemStack stack, LivingEntity wearer)
{
return stack.getItem() instanceof ArmorItem && ((ArmorItem) stack.getItem()).getMaterial() == ArmorMaterial.GOLD;
return stack.getItem() instanceof ArmorItem && ((ArmorItem) stack.getItem()).getMaterial() == ArmorMaterials.GOLD;
}
/**
@@ -171,7 +166,7 @@ public interface IForgeItem
* @return The NBT tag
*/
@Nullable
default CompoundNBT getShareTag(ItemStack stack)
default CompoundTag getShareTag(ItemStack stack)
{
return stack.getTag();
}
@@ -183,7 +178,7 @@ public interface IForgeItem
* @param stack The stack that received NBT
* @param nbt Received NBT, can be null
*/
default void readShareTag(ItemStack stack, @Nullable CompoundNBT nbt)
default void readShareTag(ItemStack stack, @Nullable CompoundTag nbt)
{
stack.setTag(nbt);
}
@@ -199,7 +194,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, PlayerEntity player)
default boolean onBlockStartBreak(ItemStack itemstack, BlockPos pos, Player player)
{
return false;
}
@@ -226,7 +221,7 @@ public interface IForgeItem
* @param entity The entity being attacked
* @return True to cancel the rest of the interaction.
*/
default boolean onLeftClickEntity(ItemStack stack, PlayerEntity player, Entity entity)
default boolean onLeftClickEntity(ItemStack stack, Player player, Entity entity)
{
return false;
}
@@ -245,7 +240,7 @@ public interface IForgeItem
{
return ItemStack.EMPTY;
}
return new ItemStack(getItem().getCraftingRemainingItem());
return new ItemStack(self().getCraftingRemainingItem());
}
/**
@@ -257,7 +252,7 @@ public interface IForgeItem
@SuppressWarnings("deprecation")
default boolean hasContainerItem(ItemStack stack)
{
return getItem().hasCraftingRemainingItem();
return self().hasCraftingRemainingItem();
}
/**
@@ -268,7 +263,7 @@ public interface IForgeItem
* @param world The world the entity is in
* @return The normal lifespan in ticks.
*/
default int getEntityLifespan(ItemStack itemStack, World world)
default int getEntityLifespan(ItemStack itemStack, Level world)
{
return 6000;
}
@@ -300,7 +295,7 @@ public interface IForgeItem
* @return A new Entity object to spawn or null
*/
@Nullable
default Entity createEntity(World world, Entity location, ItemStack itemstack)
default Entity createEntity(Level world, Entity location, ItemStack itemstack)
{
return null;
}
@@ -325,9 +320,9 @@ public interface IForgeItem
*
* @return A list of all tabs that this item could possibly be one.
*/
default java.util.Collection<ItemGroup> getCreativeTabs()
default java.util.Collection<CreativeModeTab> getCreativeTabs()
{
return java.util.Collections.singletonList(getItem().getItemCategory());
return java.util.Collections.singletonList(self().getItemCategory());
}
/**
@@ -353,7 +348,7 @@ public interface IForgeItem
* @param player The Player that is wielding the item
* @return
*/
default boolean doesSneakBypassUse(ItemStack stack, net.minecraft.world.IWorldReader world, BlockPos pos, PlayerEntity player)
default boolean doesSneakBypassUse(ItemStack stack, net.minecraft.world.level.LevelReader world, BlockPos pos, Player player)
{
return false;
}
@@ -361,7 +356,7 @@ public interface IForgeItem
/**
* Called to tick armor in the armor slot. Override to do something
*/
default void onArmorTick(ItemStack stack, World world, PlayerEntity player)
default void onArmorTick(ItemStack stack, Level world, Player player)
{
}
@@ -374,9 +369,9 @@ 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, EquipmentSlotType armorType, Entity entity)
default boolean canEquip(ItemStack stack, EquipmentSlot armorType, Entity entity)
{
return MobEntity.getEquipmentSlotForItem(stack) == armorType;
return Mob.getEquipmentSlotForItem(stack) == armorType;
}
/**
@@ -390,7 +385,7 @@ public interface IForgeItem
* decide
*/
@Nullable
default EquipmentSlotType getEquipmentSlot(ItemStack stack)
default EquipmentSlot getEquipmentSlot(ItemStack stack)
{
return null;
}
@@ -421,37 +416,7 @@ public interface IForgeItem
* @return Path of texture to bind, or null to use default
*/
@Nullable
default String getArmorTexture(ItemStack stack, Entity entity, EquipmentSlotType slot, String type)
{
return null;
}
/**
* Returns the font renderer used to render tooltips and overlays for this item.
* Returning null will use the standard font renderer.
*
* @param stack The current item stack
* @return A instance of FontRenderer or null to use default
*/
@OnlyIn(Dist.CLIENT)
@Nullable
default net.minecraft.client.gui.FontRenderer getFontRenderer(ItemStack stack)
{
return null;
}
/**
* Override this method to have an item handle its own armor rendering.
*
* @param entityLiving The entity wearing the armor
* @param itemStack The itemStack to render the model of
* @param armorSlot The slot the armor is in
* @param _default Original armor model. Will have attributes set.
* @return A ModelBiped to render instead of the default
*/
@OnlyIn(Dist.CLIENT)
@Nullable
default <A extends BipedModel<?>> A getArmorModel(LivingEntity entityLiving, ItemStack itemStack, EquipmentSlotType armorSlot, A _default)
default String getArmorTexture(ItemStack stack, Entity entity, EquipmentSlot slot, String type)
{
return null;
}
@@ -467,21 +432,6 @@ public interface IForgeItem
return false;
}
/**
* Called when the client starts rendering the HUD, for whatever item the player
* currently has as a helmet. This is where pumpkins would render there overlay.
*
* @param stack The ItemStack that is equipped
* @param player Reference to the current client entity
* @param resolution Resolution information about the current viewport and
* configured GUI Scale
* @param partialTicks Partial ticks for the renderer, useful for interpolation
*/
@OnlyIn(Dist.CLIENT)
default void renderHelmetOverlay(ItemStack stack, PlayerEntity player, int width, int height, float partialTicks)
{
}
/**
* Return the itemDamage represented by this ItemStack. Defaults to the Damage
* entry in the stack NBT, but can be overridden here for other sources.
@@ -529,7 +479,7 @@ public interface IForgeItem
*/
default int getRGBDurabilityForDisplay(ItemStack stack)
{
return MathHelper.hsvToRgb(Math.max(0.0F, (float) (1.0F - getDurabilityForDisplay(stack))) / 3.0F, 1.0F, 1.0F);
return Mth.hsvToRgb(Math.max(0.0F, (float) (1.0F - getDurabilityForDisplay(stack))) / 3.0F, 1.0F, 1.0F);
}
/**
@@ -542,7 +492,7 @@ public interface IForgeItem
@SuppressWarnings("deprecation")
default int getMaxDamage(ItemStack stack)
{
return getItem().getMaxDamage();
return self().getMaxDamage();
}
/**
@@ -578,7 +528,7 @@ public interface IForgeItem
*/
default boolean canHarvestBlock(ItemStack stack, BlockState state)
{
return getItem().isCorrectToolForDrops(state);
return self().isCorrectToolForDrops(state);
}
/**
@@ -591,7 +541,7 @@ public interface IForgeItem
@SuppressWarnings("deprecation")
default int getItemStackLimit(ItemStack stack)
{
return getItem().getMaxStackSize();
return self().getMaxStackSize();
}
Set<ToolType> getToolTypes(ItemStack stack);
@@ -606,7 +556,7 @@ public interface IForgeItem
* @param blockState The block to harvest
* @return Harvest level, or -1 if not the specified tool type.
*/
int getHarvestLevel(ItemStack stack, ToolType tool, @Nullable PlayerEntity player, @Nullable BlockState blockState);
int getHarvestLevel(ItemStack stack, ToolType tool, @Nullable Player player, @Nullable BlockState blockState);
/**
* ItemStack sensitive version of getItemEnchantability
@@ -616,7 +566,7 @@ public interface IForgeItem
*/
default int getItemEnchantability(ItemStack stack)
{
return getItem().getEnchantmentValue();
return self().getEnchantmentValue();
}
/**
@@ -632,7 +582,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, net.minecraft.enchantment.Enchantment enchantment)
default boolean canApplyAtEnchantingTable(ItemStack stack, net.minecraft.world.item.enchantment.Enchantment enchantment)
{
return enchantment.category.canEnchant(stack.getItem());
}
@@ -716,7 +666,7 @@ public interface IForgeItem
* capabilities for the life of this item.
*/
@Nullable
default net.minecraftforge.common.capabilities.ICapabilityProvider initCapabilities(ItemStack stack, @Nullable CompoundNBT nbt)
default net.minecraftforge.common.capabilities.ICapabilityProvider initCapabilities(ItemStack stack, @Nullable CompoundTag nbt)
{
return null;
}
@@ -760,13 +710,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 IRecipeType<?> recipeType)
{
return getBurnTime(itemStack);
}
@Deprecated // use variant with IRecipeType
default int getBurnTime(ItemStack stack)
default int getBurnTime(ItemStack itemStack, @Nullable RecipeType<?> recipeType)
{
return -1;
}
@@ -779,17 +723,10 @@ public interface IForgeItem
* @param world the world the horse is in
* @param horse the horse wearing this armor
*/
default void onHorseArmorTick(ItemStack stack, World world, MobEntity horse)
default void onHorseArmorTick(ItemStack stack, Level world, Mob horse)
{
}
/**
* @return This Item's renderer, or the default instance if it does not have
* one.
*/
@OnlyIn(Dist.CLIENT)
ItemStackTileEntityRenderer getItemStackTileEntityRenderer();
/**
* Retrieves a list of tags names this is known to be associated with.
* This should be used in favor of TagCollection.getOwningTags, as this caches the result and automatically updates when the TagCollection changes.
@@ -818,7 +755,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, PlayerEntity player, EndermanEntity endermanEntity)
default boolean isEnderMask(ItemStack stack, Player player, EnderMan endermanEntity)
{
return stack.getItem() == Blocks.CARVED_PUMPKIN.asItem();
}
@@ -861,6 +798,6 @@ public interface IForgeItem
*/
default boolean isDamageable(ItemStack stack)
{
return this.getItem().canBeDepleted();
return self().canBeDepleted();
}
}
@@ -23,37 +23,36 @@ import java.util.Set;
import javax.annotation.Nullable;
import net.minecraft.entity.monster.EndermanEntity;
import net.minecraft.item.crafting.IRecipeType;
import net.minecraft.util.CachedBlockInfo;
import net.minecraft.block.BlockState;
import net.minecraft.enchantment.Enchantment;
import net.minecraft.entity.Entity;
import net.minecraft.entity.MobEntity;
import net.minecraft.entity.LivingEntity;
import net.minecraft.entity.item.ItemEntity;
import net.minecraft.entity.player.PlayerEntity;
import net.minecraft.inventory.EquipmentSlotType;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraft.item.ItemUseContext;
import net.minecraft.nbt.CompoundNBT;
import net.minecraft.world.entity.monster.EnderMan;
import net.minecraft.world.item.crafting.RecipeType;
import net.minecraft.world.level.block.state.pattern.BlockInWorld;
import net.minecraft.world.level.block.state.BlockState;
import net.minecraft.world.item.enchantment.Enchantment;
import net.minecraft.world.entity.Entity;
import net.minecraft.world.entity.Mob;
import net.minecraft.world.entity.LivingEntity;
import net.minecraft.world.entity.item.ItemEntity;
import net.minecraft.world.entity.player.Player;
import net.minecraft.world.entity.EquipmentSlot;
import net.minecraft.world.item.Item;
import net.minecraft.world.item.ItemStack;
import net.minecraft.world.item.context.UseOnContext;
import net.minecraft.nbt.CompoundTag;
import net.minecraft.stats.Stats;
import net.minecraft.util.ActionResultType;
import net.minecraft.util.math.BlockPos;
import net.minecraft.util.text.IFormattableTextComponent;
import net.minecraft.util.text.ITextComponent;
import net.minecraft.world.World;
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.ToolType;
import net.minecraftforge.common.capabilities.ICapabilitySerializable;
/*
* Extension added to ItemStack that bounces to ItemSack sensitive Item methods. Typically this is just for convince.
*/
public interface IForgeItemStack extends ICapabilitySerializable<CompoundNBT>
public interface IForgeItemStack extends ICapabilitySerializable<CompoundTag>
{
// Helpers for accessing Item data
default ItemStack getStack()
private ItemStack self()
{
return (ItemStack)this;
}
@@ -66,7 +65,7 @@ public interface IForgeItemStack extends ICapabilitySerializable<CompoundNBT>
*/
default ItemStack getContainerItem()
{
return getStack().getItem().getContainerItem(getStack());
return self().getItem().getContainerItem(self());
}
/**
@@ -76,7 +75,7 @@ public interface IForgeItemStack extends ICapabilitySerializable<CompoundNBT>
*/
default boolean hasContainerItem()
{
return getStack().getItem().hasContainerItem(getStack());
return self().getItem().hasContainerItem(self());
}
/**
@@ -84,15 +83,9 @@ public interface IForgeItemStack extends ICapabilitySerializable<CompoundNBT>
* it not act as a fuel. Return -1 to let the default vanilla logic
* decide.
*/
default int getBurnTime(@Nullable IRecipeType<?> recipeType)
default int getBurnTime(@Nullable RecipeType<?> recipeType)
{
return getStack().getItem().getBurnTime(getStack(), recipeType);
}
@Deprecated // use variant with IRecipeType
default int getBurnTime()
{
return getBurnTime(null);
return self().getItem().getBurnTime(self(), recipeType);
}
/**
@@ -104,26 +97,26 @@ public interface IForgeItemStack extends ICapabilitySerializable<CompoundNBT>
* @param state The block to harvest
* @return Harvest level, or -1 if not the specified tool type.
*/
default int getHarvestLevel(ToolType tool, @Nullable PlayerEntity player, @Nullable BlockState state)
default int getHarvestLevel(ToolType tool, @Nullable Player player, @Nullable BlockState state)
{
return getStack().getItem().getHarvestLevel(getStack(), tool, player, state);
return self().getItem().getHarvestLevel(self(), tool, player, state);
}
default Set<ToolType> getToolTypes() {
return getStack().getItem().getToolTypes(getStack());
return self().getItem().getToolTypes(self());
}
default ActionResultType onItemUseFirst(ItemUseContext context)
default InteractionResult onItemUseFirst(UseOnContext context)
{
PlayerEntity entityplayer = context.getPlayer();
Player entityplayer = context.getPlayer();
BlockPos blockpos = context.getClickedPos();
CachedBlockInfo blockworldstate = new CachedBlockInfo(context.getLevel(), blockpos, false);
if (entityplayer != null && !entityplayer.abilities.mayBuild && !getStack().hasAdventureModePlaceTagForBlock(context.getLevel().getTagManager(), blockworldstate)) {
return ActionResultType.PASS;
BlockInWorld blockworldstate = new BlockInWorld(context.getLevel(), blockpos, false);
if (entityplayer != null && !entityplayer.getAbilities().mayBuild && !self().hasAdventureModePlaceTagForBlock(context.getLevel().getTagManager(), blockworldstate)) {
return InteractionResult.PASS;
} else {
Item item = getStack().getItem();
ActionResultType enumactionresult = item.onItemUseFirst(getStack(), context);
if (entityplayer != null && enumactionresult == ActionResultType.SUCCESS) {
Item item = self().getItem();
InteractionResult enumactionresult = item.onItemUseFirst(self(), context);
if (entityplayer != null && enumactionresult == InteractionResult.SUCCESS) {
entityplayer.awardStat(Stats.ITEM_USED.get(item));
}
@@ -131,10 +124,10 @@ public interface IForgeItemStack extends ICapabilitySerializable<CompoundNBT>
}
}
default CompoundNBT serializeNBT()
default CompoundTag serializeNBT()
{
CompoundNBT ret = new CompoundNBT();
getStack().save(ret);
CompoundTag ret = new CompoundTag();
self().save(ret);
return ret;
}
/**
@@ -147,9 +140,9 @@ public interface IForgeItemStack extends ICapabilitySerializable<CompoundNBT>
* @param player The Player that is wielding the item
* @return True to prevent harvesting, false to continue as normal
*/
default boolean onBlockStartBreak(BlockPos pos, PlayerEntity player)
default boolean onBlockStartBreak(BlockPos pos, Player player)
{
return !getStack().isEmpty() && getStack().getItem().onBlockStartBreak(getStack(), pos, player);
return !self().isEmpty() && self().getItem().onBlockStartBreak(self(), pos, player);
}
/**
@@ -161,7 +154,7 @@ public interface IForgeItemStack extends ICapabilitySerializable<CompoundNBT>
*/
default boolean shouldCauseBlockBreakReset(ItemStack newStack)
{
return getStack().getItem().shouldCauseBlockBreakReset(getStack(), newStack);
return self().getItem().shouldCauseBlockBreakReset(self(), newStack);
}
/**
@@ -178,7 +171,7 @@ public interface IForgeItemStack extends ICapabilitySerializable<CompoundNBT>
*/
default boolean canApplyAtEnchantingTable(Enchantment enchantment)
{
return getStack().getItem().canApplyAtEnchantingTable(getStack(), enchantment);
return self().getItem().canApplyAtEnchantingTable(self(), enchantment);
}
/**
@@ -188,7 +181,7 @@ public interface IForgeItemStack extends ICapabilitySerializable<CompoundNBT>
*/
default int getItemEnchantability()
{
return getStack().getItem().getItemEnchantability(getStack());
return self().getItem().getItemEnchantability(self());
}
/**
@@ -201,9 +194,9 @@ public interface IForgeItemStack extends ICapabilitySerializable<CompoundNBT>
* decide
*/
@Nullable
default EquipmentSlotType getEquipmentSlot()
default EquipmentSlot getEquipmentSlot()
{
return getStack().getItem().getEquipmentSlot(getStack());
return self().getItem().getEquipmentSlot(self());
}
/**
@@ -216,7 +209,7 @@ public interface IForgeItemStack extends ICapabilitySerializable<CompoundNBT>
*/
default boolean canDisableShield(ItemStack shield, LivingEntity entity, LivingEntity attacker)
{
return getStack().getItem().canDisableShield(getStack(), shield, entity, attacker);
return self().getItem().canDisableShield(self(), shield, entity, attacker);
}
/**
@@ -227,7 +220,7 @@ public interface IForgeItemStack extends ICapabilitySerializable<CompoundNBT>
*/
default boolean isShield(@Nullable LivingEntity entity)
{
return getStack().getItem().isShield(getStack(), entity);
return self().getItem().isShield(self(), entity);
}
/**
@@ -238,7 +231,7 @@ public interface IForgeItemStack extends ICapabilitySerializable<CompoundNBT>
*/
default boolean onEntitySwing(LivingEntity entity)
{
return getStack().getItem().onEntitySwing(getStack(), entity);
return self().getItem().onEntitySwing(self(), entity);
}
/**
@@ -250,7 +243,7 @@ public interface IForgeItemStack extends ICapabilitySerializable<CompoundNBT>
*/
default void onUsingTick(LivingEntity player, int count)
{
getStack().getItem().onUsingTick(getStack(), player, count);
self().getItem().onUsingTick(self(), player, count);
}
/**
@@ -260,9 +253,9 @@ public interface IForgeItemStack extends ICapabilitySerializable<CompoundNBT>
* @param world The world the entity is in
* @return The normal lifespan in ticks.
*/
default int getEntityLifespan(World world)
default int getEntityLifespan(Level world)
{
return getStack().getItem().getEntityLifespan(getStack(), world);
return self().getItem().getEntityLifespan(self(), world);
}
/**
@@ -275,7 +268,7 @@ public interface IForgeItemStack extends ICapabilitySerializable<CompoundNBT>
*/
default boolean onEntityItemUpdate(ItemEntity entity)
{
return getStack().getItem().onEntityItemUpdate(getStack(), entity);
return self().getItem().onEntityItemUpdate(self(), entity);
}
/**
@@ -284,15 +277,15 @@ public interface IForgeItemStack extends ICapabilitySerializable<CompoundNBT>
*/
default float getXpRepairRatio()
{
return getStack().getItem().getXpRepairRatio(getStack());
return self().getItem().getXpRepairRatio(self());
}
/**
* Called to tick armor in the armor slot. Override to do something
*/
default void onArmorTick(World world, PlayerEntity player)
default void onArmorTick(Level world, Player player)
{
getStack().getItem().onArmorTick(getStack(), world, player);
self().getItem().onArmorTick(self(), world, player);
}
/**
@@ -302,9 +295,9 @@ public interface IForgeItemStack extends ICapabilitySerializable<CompoundNBT>
* @param world the world the horse is in
* @param horse the horse wearing this armor
*/
default void onHorseArmorTick(World world, MobEntity horse)
default void onHorseArmorTick(Level world, Mob horse)
{
getStack().getItem().onHorseArmorTick(getStack(), world, horse);
self().getItem().onHorseArmorTick(self(), world, horse);
}
/**
@@ -315,9 +308,9 @@ public interface IForgeItemStack extends ICapabilitySerializable<CompoundNBT>
* @param entity The entity trying to equip the armor
* @return True if the given ItemStack can be inserted in the slot
*/
default boolean canEquip(EquipmentSlotType armorType, Entity entity)
default boolean canEquip(EquipmentSlot armorType, Entity entity)
{
return getStack().getItem().canEquip(getStack(), armorType, entity);
return self().getItem().canEquip(self(), armorType, entity);
}
/**
@@ -328,7 +321,7 @@ public interface IForgeItemStack extends ICapabilitySerializable<CompoundNBT>
*/
default boolean isBookEnchantable(ItemStack book)
{
return getStack().getItem().isBookEnchantable(getStack(), book);
return self().getItem().isBookEnchantable(self(), book);
}
@@ -339,9 +332,9 @@ public interface IForgeItemStack extends ICapabilitySerializable<CompoundNBT>
*
* @param player The player that dropped the item
*/
default boolean onDroppedByPlayer(PlayerEntity player)
default boolean onDroppedByPlayer(Player player)
{
return getStack().getItem().onDroppedByPlayer(getStack(), player);
return self().getItem().onDroppedByPlayer(self(), player);
}
/**
@@ -352,9 +345,9 @@ public interface IForgeItemStack extends ICapabilitySerializable<CompoundNBT>
* @param displayName the name that will be displayed unless it is changed in
* this method.
*/
default ITextComponent getHighlightTip(ITextComponent displayName)
default Component getHighlightTip(Component displayName)
{
return getStack().getItem().getHighlightTip(getStack(), displayName);
return self().getItem().getHighlightTip(self(), displayName);
}
/**
@@ -371,9 +364,9 @@ public interface IForgeItemStack extends ICapabilitySerializable<CompoundNBT>
* @return The NBT tag
*/
@Nullable
default CompoundNBT getShareTag()
default CompoundTag getShareTag()
{
return getStack().getItem().getShareTag(getStack());
return self().getItem().getShareTag(self());
}
/**
@@ -382,9 +375,9 @@ public interface IForgeItemStack extends ICapabilitySerializable<CompoundNBT>
*
* @param nbt Received NBT, can be null
*/
default void readShareTag(@Nullable CompoundNBT nbt)
default void readShareTag(@Nullable CompoundTag nbt)
{
getStack().getItem().readShareTag(getStack(), nbt);
self().getItem().readShareTag(self(), nbt);
}
/**
@@ -396,9 +389,9 @@ public interface IForgeItemStack extends ICapabilitySerializable<CompoundNBT>
* @param player The Player that is wielding the item
* @return
*/
default boolean doesSneakBypassUse(net.minecraft.world.IWorldReader world, BlockPos pos, PlayerEntity player)
default boolean doesSneakBypassUse(net.minecraft.world.level.LevelReader world, BlockPos pos, Player player)
{
return getStack().isEmpty() || getStack().getItem().doesSneakBypassUse(getStack(), world, pos, player);
return self().isEmpty() || self().getItem().doesSneakBypassUse(self(), world, pos, player);
}
/**
@@ -408,8 +401,8 @@ public interface IForgeItemStack extends ICapabilitySerializable<CompoundNBT>
*/
default boolean areShareTagsEqual(ItemStack other)
{
CompoundNBT shareTagA = getStack().getShareTag();
CompoundNBT shareTagB = other.getShareTag();
CompoundTag shareTagA = self().getShareTag();
CompoundTag shareTagB = other.getShareTag();
if (shareTagA == null)
return shareTagB == null;
else
@@ -425,11 +418,11 @@ public interface IForgeItemStack extends ICapabilitySerializable<CompoundNBT>
*/
default boolean equals(ItemStack other, boolean limitTags)
{
if (getStack().isEmpty())
if (self().isEmpty())
return other.isEmpty();
else
return !other.isEmpty() && getStack().getCount() == other.getCount() && getStack().getItem() == other.getItem() &&
(limitTags ? getStack().areShareTagsEqual(other) : ItemStack.tagMatches(getStack(), other));
return !other.isEmpty() && self().getCount() == other.getCount() && self().getItem() == other.getItem() &&
(limitTags ? self().areShareTagsEqual(other) : ItemStack.tagMatches(self(), other));
}
/**
@@ -439,7 +432,7 @@ public interface IForgeItemStack extends ICapabilitySerializable<CompoundNBT>
*/
default boolean isRepairable()
{
return getStack().getItem().isRepairable(getStack());
return self().getItem().isRepairable(self());
}
/**
@@ -449,7 +442,7 @@ public interface IForgeItemStack extends ICapabilitySerializable<CompoundNBT>
*/
default boolean isPiglinCurrency()
{
return getStack().getItem().isPiglinCurrency(getStack());
return self().getItem().isPiglinCurrency(self());
}
/**
@@ -462,7 +455,7 @@ public interface IForgeItemStack extends ICapabilitySerializable<CompoundNBT>
*/
default boolean makesPiglinsNeutral(LivingEntity wearer)
{
return getStack().getItem().makesPiglinsNeutral(getStack(), wearer);
return self().getItem().makesPiglinsNeutral(self(), wearer);
}
/**
@@ -472,9 +465,9 @@ public interface IForgeItemStack extends ICapabilitySerializable<CompoundNBT>
* @param endermanEntity The enderman that the player look
* @return true if this Item can be used.
*/
default boolean isEnderMask(PlayerEntity player, EndermanEntity endermanEntity)
default boolean isEnderMask(Player player, EnderMan endermanEntity)
{
return getStack().getItem().isEnderMask(getStack(), player, endermanEntity);
return self().getItem().isEnderMask(self(), player, endermanEntity);
}
/**
@@ -486,7 +479,7 @@ public interface IForgeItemStack extends ICapabilitySerializable<CompoundNBT>
*/
default boolean canElytraFly(LivingEntity entity)
{
return getStack().getItem().canElytraFly(getStack(), entity);
return self().getItem().canElytraFly(self(), entity);
}
/**
@@ -502,6 +495,6 @@ public interface IForgeItemStack extends ICapabilitySerializable<CompoundNBT>
*/
default boolean elytraFlightTick(LivingEntity entity, int flightTicks)
{
return getStack().getItem().elytraFlightTick(getStack(), entity, flightTicks);
return self().getItem().elytraFlightTick(self(), entity, flightTicks);
}
}
@@ -21,7 +21,7 @@ package net.minecraftforge.common.extensions;
import net.minecraftforge.common.capabilities.ICapabilityProvider;
public interface IForgeWorld extends ICapabilityProvider
public interface IForgeLevel extends ICapabilityProvider
{
/**
* The maximum radius to scan for entities when trying to check bounding boxes. Vanilla's default is
@@ -21,7 +21,7 @@ package net.minecraftforge.common.extensions;
import net.minecraftforge.common.capabilities.ICapabilityProvider;
public interface IForgeChunk extends ICapabilityProvider
public interface IForgeLevelChunk extends ICapabilityProvider
{
}
@@ -0,0 +1,57 @@
/*
* Minecraft Forge
* Copyright (c) 2016-2021.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation version 2.1
* of the License.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
package net.minecraftforge.common.extensions;
import java.util.ArrayList;
import java.util.List;
import net.minecraft.world.item.ItemStack;
import net.minecraft.world.item.Items;
import net.minecraft.world.effect.MobEffect;
import net.minecraft.world.effect.MobEffectInstance;
public interface IForgeMobEffect
{
private MobEffect self() {
return (MobEffect)this;
}
/**
* Get a fresh list of items that can cure this Potion.
* All new PotionEffects created from this Potion will call this to initialize the default curative items
* @see PotionEffect#getCurativeItems
* @return A list of items that can cure this Potion
*/
default List<ItemStack> getCurativeItems() {
ArrayList<ItemStack> ret = new ArrayList<ItemStack>();
ret.add(new ItemStack(Items.MILK_BUCKET));
return ret;
}
/**
* Used for determining {@code PotionEffect} sort order in GUIs.
* Defaults to the {@code PotionEffect}'s liquid color.
* @param potionEffect the {@code PotionEffect} instance containing the potion
* @return a value used to sort {@code PotionEffect}s in GUIs
*/
default int getGuiSortColor(MobEffectInstance potionEffect) {
return self().getColor();
}
}
@@ -0,0 +1,69 @@
/*
* Minecraft Forge
* Copyright (c) 2016-2021.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation version 2.1
* of the License.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
package net.minecraftforge.common.extensions;
import java.util.List;
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
{
/***
* Returns a list of curative items for the potion effect
* By default, this list is initialized using {@link Potion#getCurativeItems}
*
* @return The list (ItemStack) of curative items for the potion effect
*/
List<ItemStack> getCurativeItems();
/***
* Checks the given ItemStack to see if it is in the list of curative items for the potion effect
* @param stack The ItemStack being checked against the list of curative items for this PotionEffect
* @return true if the given ItemStack is in the list of curative items for this PotionEffect, false otherwise
*/
default boolean isCurativeItem(ItemStack stack) {
return this.getCurativeItems().stream().anyMatch(e -> e.sameItem(stack));
}
/***
* Sets the list of curative items for this potion effect, overwriting any already present
* @param curativeItems The list of ItemStacks being set to the potion effect
*/
void setCurativeItems(List<ItemStack> curativeItems);
/***
* Adds the given stack to the list of curative items for this PotionEffect
* @param stack The ItemStack being added to the curative item list
*/
default void addCurativeItem(ItemStack stack) {
if (!this.isCurativeItem(stack))
this.getCurativeItems().add(stack);
}
default void writeCurativeItems(CompoundTag nbt) {
ListTag list = new ListTag();
getCurativeItems().forEach(s -> list.add(s.save(new CompoundTag())));
nbt.put("CurativeItems", list);
}
}
@@ -19,7 +19,7 @@
package net.minecraftforge.common.extensions;
public interface IForgeResourcePack
public interface IForgePackResources
{
default boolean isHidden()
{
@@ -21,15 +21,16 @@ package net.minecraftforge.common.extensions;
import java.util.Collections;
import java.util.List;
import net.minecraft.entity.EntityClassification;
import net.minecraft.world.biome.MobSpawnInfo;
import net.minecraft.world.gen.feature.structure.Structure;
import net.minecraft.util.random.WeightedRandomList;
import net.minecraft.world.entity.MobCategory;
import net.minecraft.world.level.biome.MobSpawnSettings;
import net.minecraft.world.level.levelgen.feature.StructureFeature;
public interface IForgeStructure
public interface IForgeStructureFeature
{
default Structure<?> getStructure()
private StructureFeature<?> self()
{
return (Structure<?>) this;
return (StructureFeature<?>) this;
}
/**
@@ -37,7 +38,7 @@ public interface IForgeStructure
*
* @apiNote Implement this over {@link Structure#getSpawnList()}
*/
default List<MobSpawnInfo.Spawners> getDefaultSpawnList()
default List<MobSpawnSettings.SpawnerData> getDefaultSpawnList()
{
return Collections.emptyList();
}
@@ -47,7 +48,7 @@ public interface IForgeStructure
*
* @apiNote Implement this over {@link Structure#getCreatureSpawnList()}
*/
default List<MobSpawnInfo.Spawners> getDefaultCreatureSpawnList()
default List<MobSpawnSettings.SpawnerData> getDefaultCreatureSpawnList()
{
return Collections.emptyList();
}
@@ -60,7 +61,7 @@ public interface IForgeStructure
default boolean getDefaultRestrictsSpawnsToInside()
{
//The Pillager Outpost and Ocean Monument check the full structure by default instead of limiting themselves to being within the structure's bounds
return getStructure() != Structure.PILLAGER_OUTPOST && getStructure() != Structure.OCEAN_MONUMENT;
return self() != StructureFeature.PILLAGER_OUTPOST && self() != StructureFeature.OCEAN_MONUMENT;
}
/**
@@ -69,5 +70,5 @@ public interface IForgeStructure
* @apiNote This method is marked as final in {@link Structure} so as to not be overridden by modders and breaking support for
* {@link net.minecraftforge.event.world.StructureSpawnListGatherEvent}.
*/
List<MobSpawnInfo.Spawners> getSpawnList(EntityClassification classification);
WeightedRandomList<MobSpawnSettings.SpawnerData> getSpawnList(MobCategory classification);
}
@@ -0,0 +1,69 @@
/*
* Minecraft Forge
* Copyright (c) 2016-2021.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation version 2.1
* of the License.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
package net.minecraftforge.common.extensions;
import net.minecraft.data.tags.TagsProvider;
import net.minecraft.tags.Tag;
import net.minecraft.resources.ResourceKey;
import net.minecraft.resources.ResourceLocation;
//TODO, Tag removal support.
public interface IForgeTagAppender<T>
{
private TagsProvider.TagAppender<T> self() {
return (TagsProvider.TagAppender<T>) this;
}
@SuppressWarnings("unchecked")
default TagsProvider.TagAppender<T> addTags(Tag.Named<T>... values) {
TagsProvider.TagAppender<T> builder = self();
for (Tag.Named<T> value : values) {
builder.addTag(value);
}
return builder;
}
default TagsProvider.TagAppender<T> add(ResourceKey<T>... keys) {
TagsProvider.TagAppender<T> builder = self();
for (ResourceKey<T> key : keys) {
builder.getInternalBuilder().addElement(key.location(), self().getModID());
}
return builder;
}
default TagsProvider.TagAppender<T> replace() {
return replace(true);
}
default TagsProvider.TagAppender<T> replace(boolean value) {
self().getInternalBuilder().replace(value);
return self();
}
default TagsProvider.TagAppender<T> addOptional(final ResourceLocation location)
{
return self().add(new Tag.OptionalElementEntry(location));
}
default TagsProvider.TagAppender<T> addOptionalTag(final ResourceLocation location)
{
return self().add(new Tag.OptionalTagEntry(location));
}
}
@@ -1,70 +0,0 @@
/*
* Minecraft Forge
* Copyright (c) 2016-2021.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation version 2.1
* of the License.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
package net.minecraftforge.common.extensions;
import net.minecraft.data.TagsProvider;
import net.minecraft.tags.ITag;
import net.minecraft.util.RegistryKey;
import net.minecraft.util.ResourceLocation;
//TODO, Tag removal support.
public interface IForgeTagBuilder<T>
{
default TagsProvider.Builder<T> getBuilder() {
return (TagsProvider.Builder<T>) this;
}
@SuppressWarnings("unchecked")
default TagsProvider.Builder<T> addTags(ITag.INamedTag<T>... values) {
TagsProvider.Builder<T> builder = getBuilder();
for (ITag.INamedTag<T> value : values) {
builder.addTag(value);
}
return builder;
}
default TagsProvider.Builder<T> add(RegistryKey<T>... keys) {
TagsProvider.Builder<T> builder = getBuilder();
for (RegistryKey<T> key : keys) {
builder.getInternalBuilder().addElement(key.location(), getBuilder().getModID());
}
return builder;
}
default TagsProvider.Builder<T> replace() {
return replace(true);
}
default TagsProvider.Builder<T> replace(boolean value) {
getBuilder().getInternalBuilder().replace(value);
return getBuilder();
}
default TagsProvider.Builder<T> addOptional(final ResourceLocation location)
{
return getBuilder().add(new ITag.OptionalItemEntry(location));
}
default TagsProvider.Builder<T> addOptionalTag(final ResourceLocation location)
{
return getBuilder().add(new ITag.OptionalTagEntry(location));
}
}
@@ -20,42 +20,42 @@
package net.minecraftforge.common.extensions;
import java.util.Map;
import net.minecraft.tags.ITagCollection;
import net.minecraft.util.ResourceLocation;
import net.minecraft.tags.TagCollection;
import net.minecraft.resources.ResourceLocation;
import net.minecraftforge.common.ForgeTagHandler;
import net.minecraftforge.registries.IForgeRegistry;
import net.minecraftforge.registries.IForgeRegistryEntry;
public interface IForgeTagCollectionSupplier
public interface IForgeTagContainer
{
/**
* Gets the tag map of registry names to tag collections for the various custom tag types.
*
* @apiNote Prefer using one of the getCustomTypeCollection methods
*/
default Map<ResourceLocation, ITagCollection<?>> getCustomTagTypes()
default Map<ResourceLocation, TagCollection<?>> getCustomTagTypes()
{
return ForgeTagHandler.getCustomTagTypes();
}
/**
* Gets the {@link ITagCollection} for a forge registry with the given name, or throws an exception if the registry doesn't support custom tag types.
* Gets the {@link TagCollection} for a forge registry with the given name, or throws an exception if the registry doesn't support custom tag types.
* @param regName Name of the forge registry
* @return The tag collection
*/
default ITagCollection<?> getCustomTypeCollection(ResourceLocation regName)
default TagCollection<?> getCustomTypeCollection(ResourceLocation regName)
{
if (!ForgeTagHandler.getCustomTagTypeNames().contains(regName)) throw new IllegalArgumentException("Registry " + regName + ", does not support custom tag types");
return getCustomTagTypes().get(regName);
}
/**
* Gets the {@link ITagCollection} for a forge registry, or throws an exception if the registry doesn't support custom tag types.
* Gets the {@link TagCollection} for a forge registry, or throws an exception if the registry doesn't support custom tag types.
* @param reg Forge registry
* @return The tag collection
*/
default <T extends IForgeRegistryEntry<T>> ITagCollection<T> getCustomTypeCollection(IForgeRegistry<T> reg)
default <T extends IForgeRegistryEntry<T>> TagCollection<T> getCustomTypeCollection(IForgeRegistry<T> reg)
{
return (ITagCollection<T>) getCustomTypeCollection(reg.getRegistryName());
return (TagCollection<T>) getCustomTypeCollection(reg.getRegistryName());
}
}
@@ -1,27 +0,0 @@
/*
* Minecraft Forge
* Copyright (c) 2016-2021.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation version 2.1
* of the License.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
package net.minecraftforge.common.extensions;
import net.minecraft.world.server.ServerWorld;
public interface IForgeWorldServer extends IForgeWorld
{
default ServerWorld getWorldServer() { return (ServerWorld) this; }
}
@@ -21,9 +21,9 @@ package net.minecraftforge.common.loot;
import com.google.gson.JsonObject;
import net.minecraft.loot.ConditionArraySerializer;
import net.minecraft.loot.conditions.ILootCondition;
import net.minecraft.util.ResourceLocation;
import net.minecraft.advancements.critereon.SerializationContext;
import net.minecraft.world.level.storage.loot.predicates.LootItemCondition;
import net.minecraft.resources.ResourceLocation;
import net.minecraftforge.registries.GameData;
import net.minecraftforge.registries.IForgeRegistryEntry;
@@ -63,7 +63,7 @@ public abstract class GlobalLootModifierSerializer<T extends IGlobalLootModifier
* @param json The full json object (including ILootConditions)
* @param conditionsIn An already deserialized list of ILootConditions
*/
public abstract T read(ResourceLocation location, JsonObject object, ILootCondition[] ailootcondition);
public abstract T read(ResourceLocation location, JsonObject object, LootItemCondition[] ailootcondition);
/**
* Write the serializer to json.
@@ -77,9 +77,9 @@ public abstract class GlobalLootModifierSerializer<T extends IGlobalLootModifier
* Helper to create the json object from the conditions.
* Add any extra properties to the returned json.
*/
public JsonObject makeConditions(ILootCondition[] conditions) {
public JsonObject makeConditions(LootItemCondition[] conditions) {
JsonObject json = new JsonObject();
json.add("conditions", ConditionArraySerializer.INSTANCE.serializeConditions(conditions));
json.add("conditions", SerializationContext.INSTANCE.serializeConditions(conditions));
return json;
}
@@ -23,8 +23,8 @@ import java.util.List;
import javax.annotation.Nonnull;
import net.minecraft.item.ItemStack;
import net.minecraft.loot.LootContext;
import net.minecraft.world.item.ItemStack;
import net.minecraft.world.level.storage.loot.LootContext;
/**
* Implementation that defines what a global loot modifier must implement in order to be functional.
@@ -24,10 +24,10 @@ import java.util.function.Predicate;
import javax.annotation.Nonnull;
import net.minecraft.item.ItemStack;
import net.minecraft.loot.LootContext;
import net.minecraft.loot.conditions.ILootCondition;
import net.minecraft.loot.conditions.LootConditionManager;
import net.minecraft.world.item.ItemStack;
import net.minecraft.world.level.storage.loot.LootContext;
import net.minecraft.world.level.storage.loot.predicates.LootItemCondition;
import net.minecraft.world.level.storage.loot.predicates.LootItemConditions;
/**
* A base implementation of a Global Loot Modifier for modders to extend.
@@ -35,16 +35,16 @@ import net.minecraft.loot.conditions.LootConditionManager;
* implementation that takes care of Forge registry things.
*/
public abstract class LootModifier implements IGlobalLootModifier {
protected final ILootCondition[] conditions;
protected final LootItemCondition[] conditions;
private final Predicate<LootContext> combinedConditions;
/**
* Constructs a LootModifier.
* @param conditionsIn the ILootConditions that need to be matched before the loot is modified.
*/
protected LootModifier(ILootCondition[] conditionsIn) {
protected LootModifier(LootItemCondition[] conditionsIn) {
this.conditions = conditionsIn;
this.combinedConditions = LootConditionManager.andConditions(conditionsIn);
this.combinedConditions = LootItemConditions.andConditions(conditionsIn);
}
@Nonnull
@@ -30,8 +30,8 @@ import java.util.ArrayList;
import java.util.Collection;
import java.util.Map;
import net.minecraft.loot.LootSerializers;
import net.minecraft.loot.conditions.ILootCondition;
import net.minecraft.world.level.storage.loot.Deserializers;
import net.minecraft.world.level.storage.loot.predicates.LootItemCondition;
import org.apache.commons.io.IOUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
@@ -43,17 +43,17 @@ import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import net.minecraft.client.resources.JsonReloadListener;
import net.minecraft.profiler.IProfiler;
import net.minecraft.resources.IResource;
import net.minecraft.resources.IResourceManager;
import net.minecraft.util.JSONUtils;
import net.minecraft.util.ResourceLocation;
import net.minecraft.server.packs.resources.SimpleJsonResourceReloadListener;
import net.minecraft.util.profiling.ProfilerFiller;
import net.minecraft.server.packs.resources.Resource;
import net.minecraft.server.packs.resources.ResourceManager;
import net.minecraft.util.GsonHelper;
import net.minecraft.resources.ResourceLocation;
import net.minecraftforge.registries.ForgeRegistries;
public class LootModifierManager extends JsonReloadListener {
public class LootModifierManager extends SimpleJsonResourceReloadListener {
public static final Logger LOGGER = LogManager.getLogger();
private static final Gson GSON_INSTANCE = LootSerializers.createFunctionSerializer().create();
private static final Gson GSON_INSTANCE = Deserializers.createFunctionSerializer().create();
private Map<ResourceLocation, IGlobalLootModifier> registeredLootModifiers = ImmutableMap.of();
private static final String folder = "loot_modifiers";
@@ -63,7 +63,7 @@ public class LootModifierManager extends JsonReloadListener {
}
@Override
protected void apply(Map<ResourceLocation, JsonElement> resourceList, IResourceManager resourceManagerIn, IProfiler profilerIn) {
protected void apply(Map<ResourceLocation, JsonElement> resourceList, ResourceManager resourceManagerIn, ProfilerFiller profilerIn) {
Builder<ResourceLocation, IGlobalLootModifier> builder = ImmutableMap.builder();
//old way (for reference)
/*Map<IGlobalLootModifier, ResourceLocation> toLocation = new HashMap<IGlobalLootModifier, ResourceLocation>();
@@ -84,11 +84,11 @@ public class LootModifierManager extends JsonReloadListener {
ResourceLocation resourcelocation = new ResourceLocation("forge","loot_modifiers/global_loot_modifiers.json");
try {
//read in all data files from forge:loot_modifiers/global_loot_modifiers in order to do layering
for(IResource iresource : resourceManagerIn.getResources(resourcelocation)) {
for(Resource iresource : resourceManagerIn.getResources(resourcelocation)) {
try ( InputStream inputstream = iresource.getInputStream();
Reader reader = new BufferedReader(new InputStreamReader(inputstream, StandardCharsets.UTF_8));
) {
JsonObject jsonobject = JSONUtils.fromJson(GSON_INSTANCE, reader, JsonObject.class);
JsonObject jsonobject = GsonHelper.fromJson(GSON_INSTANCE, reader, JsonObject.class);
boolean replace = jsonobject.get("replace").getAsBoolean();
if(replace) finalLocations.clear();
JsonArray entryList = jsonobject.get("entries").getAsJsonArray();
@@ -126,14 +126,14 @@ public class LootModifierManager extends JsonReloadListener {
private IGlobalLootModifier deserializeModifier(ResourceLocation location, JsonElement element) {
if (!element.isJsonObject()) return null;
JsonObject object = element.getAsJsonObject();
ILootCondition[] lootConditions = GSON_INSTANCE.fromJson(object.get("conditions"), ILootCondition[].class);
LootItemCondition[] lootConditions = GSON_INSTANCE.fromJson(object.get("conditions"), LootItemCondition[].class);
// For backward compatibility with the initial implementation, fall back to using the location as the type.
// TODO: Remove fallback in 1.16
ResourceLocation serializer = location;
if (object.has("type"))
{
serializer = new ResourceLocation(JSONUtils.getAsString(object, "type"));
serializer = new ResourceLocation(GsonHelper.getAsString(object, "type"));
}
return ForgeRegistries.LOOT_MODIFIER_SERIALIZERS.getValue(serializer).read(location, object, lootConditions);
@@ -22,17 +22,17 @@ package net.minecraftforge.common.loot;
import com.google.gson.JsonDeserializationContext;
import com.google.gson.JsonObject;
import com.google.gson.JsonSerializationContext;
import net.minecraft.loot.ILootSerializer;
import net.minecraft.loot.LootConditionType;
import net.minecraft.loot.LootContext;
import net.minecraft.loot.conditions.ILootCondition;
import net.minecraft.util.JSONUtils;
import net.minecraft.util.ResourceLocation;
import net.minecraft.world.level.storage.loot.Serializer;
import net.minecraft.world.level.storage.loot.predicates.LootItemConditionType;
import net.minecraft.world.level.storage.loot.LootContext;
import net.minecraft.world.level.storage.loot.predicates.LootItemCondition;
import net.minecraft.util.GsonHelper;
import net.minecraft.resources.ResourceLocation;
public class LootTableIdCondition implements ILootCondition
public class LootTableIdCondition implements LootItemCondition
{
// TODO Forge Registry at some point?
public static final LootConditionType LOOT_TABLE_ID = new LootConditionType(new LootTableIdCondition.Serializer());
public static final LootItemConditionType LOOT_TABLE_ID = new LootItemConditionType(new LootTableIdCondition.Serializer());
public static final ResourceLocation UNKNOWN_LOOT_TABLE = new ResourceLocation("forge", "unknown_loot_table");
private final ResourceLocation targetLootTableId;
@@ -43,7 +43,7 @@ public class LootTableIdCondition implements ILootCondition
}
@Override
public LootConditionType getType()
public LootItemConditionType getType()
{
return LOOT_TABLE_ID;
}
@@ -59,7 +59,7 @@ public class LootTableIdCondition implements ILootCondition
return new Builder(targetLootTableId);
}
public static class Builder implements ILootCondition.IBuilder
public static class Builder implements LootItemCondition.Builder
{
private final ResourceLocation targetLootTableId;
@@ -70,13 +70,13 @@ public class LootTableIdCondition implements ILootCondition
}
@Override
public ILootCondition build()
public LootItemCondition build()
{
return new LootTableIdCondition(this.targetLootTableId);
}
}
public static class Serializer implements ILootSerializer<LootTableIdCondition>
public static class Serializer implements net.minecraft.world.level.storage.loot.Serializer<LootTableIdCondition>
{
@Override
public void serialize(JsonObject object, LootTableIdCondition instance, JsonSerializationContext ctx)
@@ -87,7 +87,7 @@ public class LootTableIdCondition implements ILootCondition
@Override
public LootTableIdCondition deserialize(JsonObject object, JsonDeserializationContext ctx)
{
return new LootTableIdCondition(new ResourceLocation(JSONUtils.getAsString(object, "loot_table_id")));
return new LootTableIdCondition(new ResourceLocation(GsonHelper.getAsString(object, "loot_table_id")));
}
}
}
@@ -23,22 +23,27 @@ import java.lang.reflect.Type;
import java.util.Map;
import com.google.gson.*;
import net.minecraft.util.math.MathHelper;
import net.minecraft.util.Mth;
import net.minecraft.client.renderer.model.ItemTransformVec3f;
import net.minecraft.util.math.vector.*;
import net.minecraft.client.renderer.block.model.ItemTransform;
import net.minecraftforge.api.distmarker.Dist;
import net.minecraftforge.api.distmarker.OnlyIn;
import com.mojang.math.Matrix4f;
import com.mojang.math.Quaternion;
import com.mojang.math.Transformation;
import com.mojang.math.Vector3f;
import com.mojang.math.Vector4f;
public final class TransformationHelper
{
@Deprecated
@OnlyIn(Dist.CLIENT)
public static TransformationMatrix toTransformation(ItemTransformVec3f transform)
public static Transformation toTransformation(ItemTransform transform)
{
if (transform.equals(ItemTransformVec3f.NO_TRANSFORM)) return TransformationMatrix.identity();
if (transform.equals(ItemTransform.NO_TRANSFORM)) return Transformation.identity();
return new TransformationMatrix(transform.translation, quatFromXYZ(transform.rotation, true), transform.scale, null);
return new Transformation(transform.translation, quatFromXYZ(transform.rotation, true), transform.scale, null);
}
public static Quaternion quatFromXYZ(Vector3f xyz, boolean degrees)
@@ -83,19 +88,19 @@ public final class TransformationHelper
// If the inputs are too close for comfort, linearly interpolate
// and normalize the result.
if (dot > THRESHOLD) {
float x = MathHelper.lerp(t, v0.i(), v1.i());
float y = MathHelper.lerp(t, v0.j(), v1.j());
float z = MathHelper.lerp(t, v0.k(), v1.k());
float w = MathHelper.lerp(t, v0.r(), v1.r());
float x = Mth.lerp(t, v0.i(), v1.i());
float y = Mth.lerp(t, v0.j(), v1.j());
float z = Mth.lerp(t, v0.k(), v1.k());
float w = Mth.lerp(t, v0.r(), v1.r());
return new Quaternion(x,y,z,w);
}
// Since dot is in range [0, DOT_THRESHOLD], acos is safe
float angle01 = (float)Math.acos(dot);
float angle0t = angle01*t;
float sin0t = MathHelper.sin(angle0t);
float sin01 = MathHelper.sin(angle01);
float sin1t = MathHelper.sin(angle01 - angle0t);
float sin0t = Mth.sin(angle0t);
float sin01 = Mth.sin(angle01);
float sin1t = Mth.sin(angle01 - angle0t);
float s1 = sin0t / sin01;
float s0 = sin1t / sin01;
@@ -108,39 +113,39 @@ public final class TransformationHelper
);
}
public static TransformationMatrix slerp(TransformationMatrix one, TransformationMatrix that, float progress)
public static Transformation slerp(Transformation one, Transformation that, float progress)
{
return new TransformationMatrix(
return new Transformation(
lerp(one.getTranslation(), that.getTranslation(), progress),
slerp(one.getLeftRotation(), that.getLeftRotation(), progress),
lerp(one.getScale(), that.getScale(), progress),
slerp(one.getRightRot(), that.getRightRot(), progress)
slerp(one.getRightRotation(), that.getRightRotation(), progress)
);
}
public static boolean epsilonEquals(Vector4f v1, Vector4f v2, float epsilon)
{
return MathHelper.abs(v1.x()-v2.x()) < epsilon &&
MathHelper.abs(v1.y()-v2.y()) < epsilon &&
MathHelper.abs(v1.z()-v2.z()) < epsilon &&
MathHelper.abs(v1.w()-v2.w()) < epsilon;
return Mth.abs(v1.x()-v2.x()) < epsilon &&
Mth.abs(v1.y()-v2.y()) < epsilon &&
Mth.abs(v1.z()-v2.z()) < epsilon &&
Mth.abs(v1.w()-v2.w()) < epsilon;
}
public static class Deserializer implements JsonDeserializer<TransformationMatrix>
public static class Deserializer implements JsonDeserializer<Transformation>
{
private static final Vector3f ORIGIN_CORNER = new Vector3f();
private static final Vector3f ORIGIN_OPPOSING_CORNER = new Vector3f(1f, 1f, 1f);
private static final Vector3f ORIGIN_CENTER = new Vector3f(.5f, .5f, .5f);
@Override
public TransformationMatrix deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException
public Transformation deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException
{
if (json.isJsonPrimitive() && json.getAsJsonPrimitive().isString())
{
String transform = json.getAsString();
if(transform.equals("identity"))
{
return TransformationMatrix.identity();
return Transformation.identity();
}
else
{
@@ -150,15 +155,15 @@ public final class TransformationHelper
if (json.isJsonArray())
{
// direct matrix array
return new TransformationMatrix(parseMatrix(json));
return new Transformation(parseMatrix(json));
}
if (!json.isJsonObject()) throw new JsonParseException("TRSR: expected array or object, got: " + json);
JsonObject obj = json.getAsJsonObject();
TransformationMatrix ret;
Transformation ret;
if (obj.has("matrix"))
{
// matrix as a sole key
ret = new TransformationMatrix(parseMatrix(obj.get("matrix")));
ret = new Transformation(parseMatrix(obj.get("matrix")));
obj.remove("matrix");
if (obj.entrySet().size() != 0)
{
@@ -214,7 +219,7 @@ public final class TransformationHelper
obj.remove("origin");
}
if (!obj.entrySet().isEmpty()) throw new JsonParseException("TRSR: can either have single 'matrix' key, or a combination of 'translation', 'rotation', 'scale', 'post-rotation', 'origin'");
TransformationMatrix matrix = new TransformationMatrix(translation, leftRot, scale, rightRot);
Transformation matrix = new Transformation(translation, leftRot, scale, rightRot);
// Use a different origin if needed.
if (!ORIGIN_CENTER.equals(origin))
@@ -36,10 +36,10 @@ import com.google.gson.annotations.SerializedName;
import com.google.gson.reflect.TypeToken;
import com.google.gson.stream.JsonReader;
import com.google.gson.stream.JsonWriter;
import net.minecraft.client.renderer.model.IModelTransform;
import net.minecraft.resources.IResource;
import net.minecraft.resources.IResourceManager;
import net.minecraft.util.ResourceLocation;
import net.minecraft.client.resources.model.ModelState;
import net.minecraft.server.packs.resources.Resource;
import net.minecraft.server.packs.resources.ResourceManager;
import net.minecraft.resources.ResourceLocation;
import net.minecraftforge.api.distmarker.Dist;
import net.minecraftforge.api.distmarker.OnlyIn;
import net.minecraftforge.common.animation.Event;
@@ -77,13 +77,13 @@ public final class AnimationStateMachine implements IAnimationStateMachine
private transient IClip currentState;
private transient float lastPollTime;
private static final LoadingCache<Triple<? extends IClip, Float, Float>, Pair<IModelTransform, Iterable<Event>>> clipCache = CacheBuilder.newBuilder()
private static final LoadingCache<Triple<? extends IClip, Float, Float>, Pair<ModelState, Iterable<Event>>> clipCache = CacheBuilder.newBuilder()
.maximumSize(100)
.expireAfterWrite(100, TimeUnit.MILLISECONDS)
.build(new CacheLoader<Triple<? extends IClip, Float, Float>, Pair<IModelTransform, Iterable<Event>>>()
.build(new CacheLoader<Triple<? extends IClip, Float, Float>, Pair<ModelState, Iterable<Event>>>()
{
@Override
public Pair<IModelTransform, Iterable<Event>> load(Triple<? extends IClip, Float, Float> key) throws Exception
public Pair<ModelState, Iterable<Event>> load(Triple<? extends IClip, Float, Float> key) throws Exception
{
return Clips.apply(key.getLeft(), key.getMiddle(), key.getRight());
}
@@ -132,13 +132,13 @@ public final class AnimationStateMachine implements IAnimationStateMachine
}
@Override
public Pair<IModelTransform, Iterable<Event>> apply(float time)
public Pair<ModelState, Iterable<Event>> apply(float time)
{
if(lastPollTime == Float.NEGATIVE_INFINITY)
{
lastPollTime = time;
}
Pair<IModelTransform, Iterable<Event>> pair = clipCache.getUnchecked(Triple.of(currentState, lastPollTime, time));
Pair<ModelState, Iterable<Event>> pair = clipCache.getUnchecked(Triple.of(currentState, lastPollTime, time));
lastPollTime = time;
boolean shouldFilter = false;
if(shouldHandleSpecialEvents)
@@ -206,9 +206,9 @@ public final class AnimationStateMachine implements IAnimationStateMachine
* Load a new instance if AnimationStateMachine at specified location, with specified custom parameters.
*/
@OnlyIn(Dist.CLIENT)
public static IAnimationStateMachine load(IResourceManager manager, ResourceLocation location, ImmutableMap<String, ITimeValue> customParameters)
public static IAnimationStateMachine load(ResourceManager manager, ResourceLocation location, ImmutableMap<String, ITimeValue> customParameters)
{
try (IResource resource = manager.getResource(location))
try (Resource resource = manager.getResource(location))
{
ClipResolver clipResolver = new ClipResolver();
ParameterResolver parameterResolver = new ParameterResolver(customParameters);
@@ -19,8 +19,8 @@
package net.minecraftforge.common.model.animation;
import net.minecraft.nbt.INBT;
import net.minecraft.util.Direction;
import net.minecraft.nbt.Tag;
import net.minecraft.core.Direction;
import net.minecraftforge.common.capabilities.Capability;
import net.minecraftforge.common.capabilities.CapabilityInject;
import net.minecraftforge.common.capabilities.CapabilityManager;
@@ -37,17 +37,7 @@ public class CapabilityAnimation
public static void register()
{
CapabilityManager.INSTANCE.register(IAnimationStateMachine.class, new Capability.IStorage<IAnimationStateMachine>()
{
@Override
public INBT writeNBT(Capability<IAnimationStateMachine> capability, IAnimationStateMachine instance, Direction side)
{
return null;
}
@Override
public void readNBT(Capability<IAnimationStateMachine> capability, IAnimationStateMachine instance, Direction side, INBT nbt) {}
}, AnimationStateMachine::getMissing);
CapabilityManager.INSTANCE.register(IAnimationStateMachine.class);
}
public static class DefaultItemAnimationCapabilityProvider implements ICapabilityProvider
Loaded 100 of 1990 files, more files were not shown because too many files have changed in this diff. Show more