Revive custom ingredient types.

This commit is contained in:
LexManos committed 2023-10-06 21:14:04 -07:00
1 parent 587b684035
commit 5b0abf97c8
47 files changed
+1891 -1353

No files matched your search

@@ -5,128 +5,25 @@
package net.minecraftforge.common.crafting;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParseException;
import com.google.gson.JsonSyntaxException;
import com.mojang.brigadier.exceptions.CommandSyntaxException;
import com.mojang.serialization.Codec;
import com.mojang.serialization.JsonOps;
import net.minecraft.world.item.Item;
import net.minecraft.world.item.ItemStack;
import net.minecraft.world.item.Items;
import net.minecraftforge.common.crafting.conditions.ICondition;
import net.minecraft.nbt.TagParser;
import net.minecraft.Util;
import net.minecraft.nbt.CompoundTag;
import net.minecraft.util.GsonHelper;
import net.minecraft.resources.ResourceLocation;
import net.minecraftforge.registries.ForgeRegistries;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.apache.logging.log4j.Marker;
import org.apache.logging.log4j.MarkerManager;
public class CraftingHelper {
@SuppressWarnings("unused")
private static final Logger LOGGER = LogManager.getLogger();
@SuppressWarnings("unused")
private static final Marker CRAFTHELPER = MarkerManager.getMarker("CRAFTHELPER");
private static Gson GSON = new GsonBuilder().setPrettyPrinting().disableHtmlEscaping().create();
/* TODO: Custom Ingredients
private static final BiMap<ResourceLocation, IIngredientSerializer<?>> ingredients = HashBiMap.create();
public static <T extends Ingredient> IIngredientSerializer<T> register(ResourceLocation key, IIngredientSerializer<T> serializer) {
if (ingredients.containsKey(key))
throw new IllegalStateException("Duplicate recipe ingredient serializer: " + key);
if (ingredients.containsValue(serializer))
throw new IllegalStateException("Duplicate recipe ingredient serializer: " + key + " " + serializer);
ingredients.put(key, serializer);
return serializer;
}
@Nullable
public static ResourceLocation getID(IIngredientSerializer<?> serializer) {
return ingredients.inverse().get(serializer);
}
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();
ResourceLocation key = ingredients.inverse().get(serializer);
if (key == null)
throw new IllegalArgumentException("Tried to serialize unregistered Ingredient: " + ingredient + " " + serializer);
if (serializer != VanillaIngredientSerializer.INSTANCE) {
buffer.writeVarInt(-1); //Marker to know there is a custom ingredient
buffer.writeResourceLocation(key);
}
serializer.write(buffer, ingredient);
}
public static Ingredient getIngredient(ResourceLocation type, FriendlyByteBuf buffer) {
IIngredientSerializer<?> serializer = ingredients.get(type);
if (serializer == null)
throw new IllegalArgumentException("Can not deserialize unknown Ingredient type: " + type);
return serializer.parse(buffer);
}
public static Ingredient getIngredient(JsonElement json, boolean allowEmpty) {
if (json == null || json.isJsonNull())
throw new JsonSyntaxException("Json cannot be null");
if (json.isJsonArray()) {
List<Ingredient> ingredients = Lists.newArrayList();
List<Ingredient> vanilla = Lists.newArrayList();
json.getAsJsonArray().forEach((ele) -> {
Ingredient ing = CraftingHelper.getIngredient(ele, allowEmpty);
if (ing.getClass() == Ingredient.class) //Vanilla, Due to how we read it splits each itemstack, so we pull out to re-merge later
vanilla.add(ing);
else
ingredients.add(ing);
});
if (!vanilla.isEmpty())
ingredients.add(Ingredient.merge(vanilla));
if (ingredients.size() == 0) {
if (allowEmpty)
return Ingredient.EMPTY;
throw new JsonSyntaxException("Item array cannot be empty, at least one item must be defined");
}
if (ingredients.size() == 1)
return ingredients.get(0);
return new CompoundIngredient(ingredients);
}
if (!json.isJsonObject())
throw new JsonSyntaxException("Expcted ingredient to be a object or array of objects");
JsonObject obj = (JsonObject)json;
String type = GsonHelper.getAsString(obj, "type", "minecraft:item");
if (type.isEmpty())
throw new JsonSyntaxException("Ingredient type can not be an empty string");
IIngredientSerializer<?> serializer = ingredients.get(new ResourceLocation(type));
if (serializer == null)
throw new JsonSyntaxException("Unknown ingredient type: " + type);
return serializer.parse(obj);
}
*/
public static ItemStack getItemStack(JsonObject json, boolean readNBT) {
return getItemStack(json, readNBT, false);
@@ -1,178 +0,0 @@
/*
* Copyright (c) Forge Development LLC and contributors
* SPDX-License-Identifier: LGPL-2.1-only
*/
package net.minecraftforge.common.crafting;
/*
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
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.network.FriendlyByteBuf;
import net.minecraft.util.GsonHelper;
import net.minecraft.world.entity.player.StackedContents;
import net.minecraft.world.item.ItemStack;
import net.minecraft.world.item.crafting.Ingredient;
import org.jetbrains.annotations.Nullable;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.stream.IntStream;
import java.util.stream.Stream;
/** Ingredient that matches if all child ingredients match * /
public class IntersectionIngredient extends AbstractIngredient
{
private final List<Ingredient> children;
private final boolean isSimple;
private ItemStack[] intersectedMatchingStacks = null;
private IntList packedMatchingStacks = null;
protected IntersectionIngredient(List<Ingredient> children)
{
if (children.size() < 2)
throw new IllegalArgumentException("Cannot create an IntersectionIngredient with one or no children");
this.children = Collections.unmodifiableList(children);
this.isSimple = children.stream().allMatch(Ingredient::isSimple);
}
/**
* Gets an intersection ingredient
* @param ingredients List of ingredients to match
* @return Ingredient that only matches if all the passed ingredients match
* /
public static Ingredient of(Ingredient... ingredients)
{
if (ingredients.length == 0)
throw new IllegalArgumentException("Cannot create an IntersectionIngredient with no children, use Ingredient.of() to create an empty ingredient");
if (ingredients.length == 1)
return ingredients[0];
return new IntersectionIngredient(Arrays.asList(ingredients));
}
@Override
public boolean test(@Nullable ItemStack stack)
{
if (stack == null || stack.isEmpty())
return false;
for (Ingredient ingredient : children)
if (!ingredient.test(stack))
return false;
return true;
}
@Override
public ItemStack[] getItems()
{
if (this.intersectedMatchingStacks == null)
{
this.intersectedMatchingStacks = Arrays
.stream(children.get(0).getItems())
.filter(stack ->
{
// the first ingredient is treated as a base, filtered by the second onwards
for (int i = 1; i < children.size(); i++)
if (!children.get(i).test(stack))
return false;
return true;
})
.toArray(ItemStack[]::new);
}
return intersectedMatchingStacks;
}
@Override
public boolean isEmpty()
{
return children.stream().anyMatch(Ingredient::isEmpty);
}
@Override
public boolean isSimple()
{
return isSimple;
}
@Override
protected void invalidate()
{
super.invalidate();
this.intersectedMatchingStacks = null;
this.packedMatchingStacks = null;
}
@Override
public IntList getStackingIds()
{
if (this.packedMatchingStacks == null || checkInvalidation())
{
markValid();
ItemStack[] matchingStacks = getItems();
this.packedMatchingStacks = new IntArrayList(matchingStacks.length);
for(ItemStack stack : matchingStacks)
this.packedMatchingStacks.add(StackedContents.getStackingIndex(stack));
this.packedMatchingStacks.sort(IntComparators.NATURAL_COMPARATOR);
}
return packedMatchingStacks;
}
@Override
public JsonElement toJson()
{
JsonObject json = new JsonObject();
json.addProperty("type", CraftingHelper.getID(Serializer.INSTANCE).toString());
JsonArray array = new JsonArray();
for (Ingredient ingredient : children)
array.add(ingredient.toJson());
json.add("children", array);
return json;
}
@Override
public IIngredientSerializer<IntersectionIngredient> getSerializer()
{
return Serializer.INSTANCE;
}
public static class Serializer implements IIngredientSerializer<IntersectionIngredient>
{
public static final IIngredientSerializer<IntersectionIngredient> INSTANCE = new Serializer();
@Override
public IntersectionIngredient parse(JsonObject json)
{
JsonArray children = GsonHelper.getAsJsonArray(json, "children");
if (children.size() < 2)
throw new JsonSyntaxException("Must have at least two children for an intersection ingredient");
return new IntersectionIngredient(
IntStream.range(0, children.size())
.mapToObj(i -> Ingredient.fromJson(children.get(i), false))
.toList()
);
}
@Override
public IntersectionIngredient parse(FriendlyByteBuf buffer)
{
return new IntersectionIngredient(Stream.generate(() -> Ingredient.fromNetwork(buffer)).limit(buffer.readVarInt()).toList());
}
@Override
public void write(FriendlyByteBuf buffer, IntersectionIngredient intersection)
{
buffer.writeVarInt(intersection.children.size());
for (Ingredient ingredient : intersection.children)
ingredient.toNetwork(buffer);
}
}
}
*/
@@ -1,157 +0,0 @@
/*
* Copyright (c) Forge Development LLC and contributors
* SPDX-License-Identifier: LGPL-2.1-only
*/
package net.minecraftforge.common.crafting;
/*
import com.google.common.collect.ImmutableSet;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonSyntaxException;
import net.minecraft.advancements.critereon.NbtPredicate;
import net.minecraft.nbt.CompoundTag;
import net.minecraft.network.FriendlyByteBuf;
import net.minecraft.util.GsonHelper;
import net.minecraft.world.item.Item;
import net.minecraft.world.item.ItemStack;
import net.minecraft.world.item.crafting.Ingredient;
import net.minecraft.world.level.ItemLike;
import net.minecraftforge.registries.ForgeRegistries;
import org.jetbrains.annotations.Nullable;
import java.util.Arrays;
import java.util.Collections;
import java.util.Objects;
import java.util.Set;
import java.util.stream.Collectors;
import java.util.stream.Stream;
/** Ingredient that matches the given items, performing a partial NBT match. Use {@link StrictNBTIngredient} if you want exact match on NBT * /
public class PartialNBTIngredient extends AbstractIngredient
{
private final Set<Item> items;
private final CompoundTag nbt;
private final NbtPredicate predicate;
protected PartialNBTIngredient(Set<Item> items, CompoundTag nbt)
{
super(items.stream().map(item ->
{
ItemStack stack = new ItemStack(item);
// copy NBT to prevent the stack from modifying the original, as capabilities or vanilla item durability will modify the tag
stack.setTag(nbt.copy());
return new Ingredient.ItemValue(stack);
}));
if (items.isEmpty())
{
throw new IllegalArgumentException("Cannot create a PartialNBTIngredient with no items");
}
this.items = Collections.unmodifiableSet(items);
this.nbt = nbt;
this.predicate = new NbtPredicate(nbt);
}
/** Creates a new ingredient matching any item from the list, containing the given NBT * /
public static PartialNBTIngredient of(CompoundTag nbt, ItemLike... items)
{
return new PartialNBTIngredient(Arrays.stream(items).map(ItemLike::asItem).collect(Collectors.toSet()), nbt);
}
/** Creates a new ingredient matching the given item, containing the given NBT * /
public static PartialNBTIngredient of(ItemLike item, CompoundTag nbt)
{
return new PartialNBTIngredient(Set.of(item.asItem()), nbt);
}
@Override
public boolean test(@Nullable ItemStack input)
{
if (input == null)
return false;
return items.contains(input.getItem()) && predicate.matches(input.getShareTag());
}
@Override
public boolean isSimple()
{
return false;
}
@Override
public IIngredientSerializer<? extends Ingredient> getSerializer()
{
return Serializer.INSTANCE;
}
@Override
public JsonElement toJson()
{
JsonObject json = new JsonObject();
json.addProperty("type", CraftingHelper.getID(Serializer.INSTANCE).toString());
if (items.size() == 1)
{
json.addProperty("item", ForgeRegistries.ITEMS.getKey(items.iterator().next()).toString());
}
else
{
JsonArray items = new JsonArray();
// ensure the order of items in the set is deterministic when saved to JSON
this.items.stream().map(ForgeRegistries.ITEMS::getKey).sorted().forEach(name -> items.add(name.toString()));
json.add("items", items);
}
json.addProperty("nbt", nbt.toString());
return json;
}
public static class Serializer implements IIngredientSerializer<PartialNBTIngredient>
{
public static final Serializer INSTANCE = new Serializer();
@Override
public PartialNBTIngredient parse(JsonObject json)
{
// parse items
Set<Item> items;
if (json.has("item"))
items = Set.of(CraftingHelper.getItem(GsonHelper.getAsString(json, "item"), true));
else if (json.has("items"))
{
ImmutableSet.Builder<Item> builder = ImmutableSet.builder();
JsonArray itemArray = GsonHelper.getAsJsonArray(json, "items");
for (int i = 0; i < itemArray.size(); i++)
{
builder.add(CraftingHelper.getItem(GsonHelper.convertToString(itemArray.get(i), "items[" + i + ']'), true));
}
items = builder.build();
}
else
throw new JsonSyntaxException("Must set either 'item' or 'items'");
// parse NBT
if (!json.has("nbt"))
throw new JsonSyntaxException("Missing nbt, expected to find a String or JsonObject");
CompoundTag nbt = CraftingHelper.getNBT(json.get("nbt"));
return new PartialNBTIngredient(items, nbt);
}
@Override
public PartialNBTIngredient parse(FriendlyByteBuf buffer)
{
Set<Item> items = Stream.generate(() -> buffer.readRegistryIdUnsafe(ForgeRegistries.ITEMS)).limit(buffer.readVarInt()).collect(Collectors.toSet());
CompoundTag nbt = buffer.readNbt();
return new PartialNBTIngredient(items, Objects.requireNonNull(nbt));
}
@Override
public void write(FriendlyByteBuf buffer, PartialNBTIngredient ingredient)
{
buffer.writeVarInt(ingredient.items.size());
for (Item item : ingredient.items)
buffer.writeRegistryIdUnsafe(ForgeRegistries.ITEMS, item);
buffer.writeNbt(ingredient.nbt);
}
}
}
*/
@@ -0,0 +1,81 @@
/*
* Copyright (c) Forge Development LLC and contributors
* SPDX-License-Identifier: LGPL-2.1-only
*/
package net.minecraftforge.common.crafting.ingredients;
import net.minecraft.network.FriendlyByteBuf;
import net.minecraft.tags.TagKey;
import net.minecraft.world.item.Item;
import net.minecraft.world.item.ItemStack;
import net.minecraft.world.item.crafting.Ingredient;
import net.minecraft.world.level.ItemLike;
import java.util.stream.Stream;
/**
* Extension of {@link Ingredient} which makes most methods custom ingredients need to implement abstract, and removes the static constructors
* Mods are encouraged to extend this class for their custom ingredients
*/
public abstract class AbstractIngredient extends Ingredient {
/** Empty constructor, for the sake of dynamic ingredients */
protected AbstractIngredient() {
super(Stream.of());
}
/** Value constructor, for ingredients that have some vanilla representation */
protected AbstractIngredient(Stream<? extends Value> values) {
super(values);
}
@Override
public abstract boolean isSimple();
@Override
public abstract IIngredientSerializer<? extends Ingredient> serializer();
/* Hide vanilla ingredient static constructors to reduce errors with constructing custom ingredients */
/** @deprecated use {@link Ingredient#fromValues(Stream)} */
@Deprecated
public static Ingredient fromValues(Stream<? extends Ingredient.Value> values) {
throw new UnsupportedOperationException("Use Ingredient.fromValues()");
}
/** @deprecated use {@link Ingredient#of()} */
@Deprecated
public static Ingredient of() {
throw new UnsupportedOperationException("Use Ingredient.of()");
}
/** @deprecated use {@link Ingredient#of(ItemLike...)} (Stream)} */
@Deprecated
public static Ingredient of(ItemLike... items) {
throw new UnsupportedOperationException("Use Ingredient.of()");
}
/** @deprecated use {@link Ingredient#of(ItemStack...)} (Stream)} */
@Deprecated
public static Ingredient of(ItemStack... stacks) {
throw new UnsupportedOperationException("Use Ingredient.of()");
}
/** @deprecated use {@link Ingredient#of(Stream)} (Stream)} */
@Deprecated
public static Ingredient of(Stream<ItemStack> stacks) {
throw new UnsupportedOperationException("Use Ingredient.of()");
}
/** @deprecated use {@link Ingredient#of(TagKey)} (Stream)} */
@Deprecated
public static Ingredient of(TagKey<Item> tag) {
throw new UnsupportedOperationException("Use Ingredient.of()");
}
/** @deprecated use {@link Ingredient#fromNetwork(FriendlyByteBuf)} */
@Deprecated
public static Ingredient fromNetwork(FriendlyByteBuf buffer) {
throw new UnsupportedOperationException("Use Ingredient.fromNetwork()");
}
}
@@ -3,20 +3,15 @@
* SPDX-License-Identifier: LGPL-2.1-only
*/
package net.minecraftforge.common.crafting;
/*
package net.minecraftforge.common.crafting.ingredients;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import com.google.common.collect.Lists;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonSyntaxException;
import com.mojang.serialization.Codec;
import com.mojang.serialization.codecs.RecordCodecBuilder;
import it.unimi.dsi.fastutil.ints.IntArrayList;
import it.unimi.dsi.fastutil.ints.IntComparators;
@@ -28,45 +23,27 @@ import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
/** Ingredient that matches if any of the child ingredients match */
/*
public class CompoundIngredient extends Ingredient {
public class CompoundIngredient extends AbstractIngredient {
public static Ingredient of(Ingredient... children) {
if (children.length == 0)
throw new IllegalArgumentException("Cannot create a compound ingredient with no children, use Ingredient.of() to create an empty ingredient");
if (children.length == 1)
return children[0];
return new CompoundIngredient(Arrays.asList(children));
}
private List<Ingredient> children;
private ItemStack[] stacks;
private IntList itemIds;
private final boolean isSimple;
protected CompoundIngredient(List<Ingredient> children)
{
private CompoundIngredient(List<Ingredient> children) {
this.children = Collections.unmodifiableList(children);
this.isSimple = children.stream().allMatch(Ingredient::isSimple);
}
/** Creates a compound ingredient from the given list of ingredients */
/*
public static Ingredient of(Ingredient... children)
{
// if 0 or 1 ingredient, can save effort
if (children.length == 0)
throw new IllegalArgumentException("Cannot create a compound ingredient with no children, use Ingredient.of() to create an empty ingredient");
if (children.length == 1)
return children[0];
// need to merge vanilla ingredients, as otherwise the JSON produced by this ingredient could be invalid
List<Ingredient> vanillaIngredients = new ArrayList<>();
List<Ingredient> allIngredients = new ArrayList<>();
for (Ingredient child : children) {
if (child.getSerializer() == VanillaIngredientSerializer.INSTANCE)
vanillaIngredients.add(child);
else
allIngredients.add(child);
}
if (!vanillaIngredients.isEmpty())
allIngredients.add(merge(vanillaIngredients));
if (allIngredients.size() == 1)
return allIngredients.get(0);
return new CompoundIngredient(allIngredients);
}
@Override
@NotNull
public ItemStack[] getItems() {
@@ -110,14 +87,42 @@ public class CompoundIngredient extends Ingredient {
return isSimple;
}
@NotNull
public Collection<Ingredient> getChildren() {
return this.children;
}
@Override
public boolean isEmpty() {
return children.stream().allMatch(Ingredient::isEmpty);
}
@Override
public IIngredientSerializer<? extends Ingredient> serializer() {
return SERIALIZER;
}
public static final Codec<CompoundIngredient> CODEC = RecordCodecBuilder.create(builder ->
builder.group(
Ingredient.CODEC_NONEMPTY.listOf().fieldOf("children").forGetter(i -> i.children)
).apply(builder, CompoundIngredient::new)
);
public static final IIngredientSerializer<CompoundIngredient> SERIALIZER = new IIngredientSerializer<>() {
@Override
public Codec<CompoundIngredient> codec() {
return CODEC;
}
@Override
public void write(FriendlyByteBuf buffer, CompoundIngredient value) {
buffer.writeVarInt(value.children.size());
for (var child : value.children)
child.toNetwork(buffer);
}
@Override
public CompoundIngredient read(FriendlyByteBuf buffer) {
int size = buffer.readVarInt();
var children = new ArrayList<Ingredient>(size);
for (int x = 0; x < size; x++)
children.add(Ingredient.fromNetwork(buffer));
return new CompoundIngredient(children);
}
};
}
*/
@@ -3,10 +3,11 @@
* SPDX-License-Identifier: LGPL-2.1-only
*/
package net.minecraftforge.common.crafting;
/*
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
package net.minecraftforge.common.crafting.ingredients;
import com.mojang.serialization.Codec;
import com.mojang.serialization.codecs.RecordCodecBuilder;
import it.unimi.dsi.fastutil.ints.IntArrayList;
import it.unimi.dsi.fastutil.ints.IntComparators;
import it.unimi.dsi.fastutil.ints.IntList;
@@ -18,42 +19,37 @@ import org.jetbrains.annotations.Nullable;
import java.util.Arrays;
/** Ingredient that matches everything from the first ingredient that is not included in the second ingredient * /
public class DifferenceIngredient extends AbstractIngredient
{
/** Ingredient that matches everything from the first ingredient that is not included in the second ingredient */
public class DifferenceIngredient extends AbstractIngredient {
/**
* Gets the difference from the two ingredients
* @param base Ingredient the item must match
* @param subtracted Ingredient the item must not match
* @return Ingredient that matches anything in {@code base} that is not in {@code subtracted}
*/
public static DifferenceIngredient of(Ingredient base, Ingredient subtracted) {
return new DifferenceIngredient(base, subtracted);
}
private final Ingredient base;
private final Ingredient subtracted;
private ItemStack[] filteredMatchingStacks;
private IntList packedMatchingStacks;
protected DifferenceIngredient(Ingredient base, Ingredient subtracted)
{
private DifferenceIngredient(Ingredient base, Ingredient subtracted) {
this.base = base;
this.subtracted = subtracted;
}
/**
* Gets the difference from the two ingredients
* @param base Ingredient the item must match
* @param subtracted Ingredient the item must not match
* @return Ingredient that {@code base} anything in base that is not in {@code subtracted}
* /
public static DifferenceIngredient of(Ingredient base, Ingredient subtracted)
{
return new DifferenceIngredient(base, subtracted);
}
@Override
public boolean test(@Nullable ItemStack stack)
{
public boolean test(@Nullable ItemStack stack) {
if (stack == null || stack.isEmpty())
return false;
return base.test(stack) && !subtracted.test(stack);
}
@Override
public ItemStack[] getItems()
{
public ItemStack[] getItems() {
if (this.filteredMatchingStacks == null)
this.filteredMatchingStacks = Arrays.stream(base.getItems())
.filter(stack -> !subtracted.test(stack))
@@ -62,34 +58,29 @@ public class DifferenceIngredient extends AbstractIngredient
}
@Override
public boolean isEmpty()
{
public boolean isEmpty() {
return base.isEmpty();
}
@Override
public boolean isSimple()
{
public boolean isSimple() {
return base.isSimple() && subtracted.isSimple();
}
@Override
protected void invalidate()
{
protected void invalidate() {
super.invalidate();
this.filteredMatchingStacks = null;
this.packedMatchingStacks = null;
}
@Override
public IntList getStackingIds()
{
if (this.packedMatchingStacks == null || checkInvalidation())
{
public IntList getStackingIds() {
if (this.packedMatchingStacks == null || checkInvalidation()) {
markValid();
ItemStack[] matchingStacks = getItems();
var matchingStacks = getItems();
this.packedMatchingStacks = new IntArrayList(matchingStacks.length);
for (ItemStack stack : matchingStacks)
for (var stack : matchingStacks)
this.packedMatchingStacks.add(StackedContents.getStackingIndex(stack));
this.packedMatchingStacks.sort(IntComparators.NATURAL_COMPARATOR);
@@ -98,46 +89,34 @@ public class DifferenceIngredient extends AbstractIngredient
}
@Override
public JsonElement toJson(boolean allowEmpty)
{
JsonObject json = new JsonObject();
json.addProperty("type", CraftingHelper.getID(Serializer.INSTANCE).toString());
json.add("base", base.toJson(allowEmpty));
json.add("subtracted", subtracted.toJson(allowEmpty));
return json;
public IIngredientSerializer<DifferenceIngredient> serializer() {
return SERIALIZER;
}
@Override
public IIngredientSerializer<DifferenceIngredient> getSerializer()
{
return Serializer.INSTANCE;
}
public static class Serializer implements IIngredientSerializer<DifferenceIngredient> {
public static final IIngredientSerializer<DifferenceIngredient> INSTANCE = new Serializer();
public static final Codec<DifferenceIngredient> CODEC = RecordCodecBuilder.create(builder ->
builder.group(
Ingredient.CODEC.fieldOf("base").forGetter(i -> i.base),
Ingredient.CODEC.fieldOf("subtracted").forGetter(i -> i.subtracted)
).apply(builder, DifferenceIngredient::new)
);
public static final IIngredientSerializer<DifferenceIngredient> SERIALIZER = new IIngredientSerializer<>() {
@Override
public DifferenceIngredient parse(JsonObject json)
{
Ingredient base = Ingredient.fromJson(json.get("base"), false);
Ingredient without = Ingredient.fromJson(json.get("subtracted"), false);
return new DifferenceIngredient(base, without);
public Codec<? extends DifferenceIngredient> codec() {
return CODEC;
}
@Override
public DifferenceIngredient parse(FriendlyByteBuf buffer)
{
public DifferenceIngredient read(FriendlyByteBuf buffer) {
Ingredient base = Ingredient.fromNetwork(buffer);
Ingredient without = Ingredient.fromNetwork(buffer);
return new DifferenceIngredient(base, without);
}
@Override
public void write(FriendlyByteBuf buffer, DifferenceIngredient ingredient)
{
public void write(FriendlyByteBuf buffer, DifferenceIngredient ingredient) {
ingredient.base.toNetwork(buffer);
ingredient.subtracted.toNetwork(buffer);
}
}
};
}
*/
@@ -0,0 +1,43 @@
/*
* Copyright (c) Forge Development LLC and contributors
* SPDX-License-Identifier: LGPL-2.1-only
*/
package net.minecraftforge.common.crafting.ingredients;
import java.util.Arrays;
import net.minecraft.tags.TagKey;
import net.minecraft.world.item.Item;
import net.minecraft.world.item.ItemStack;
import net.minecraft.world.item.crafting.Ingredient;
public interface IIngredientBuilder {
default PartialNBTIngredient.Builder partialNbt() {
return PartialNBTIngredient.builder();
}
default Ingredient strictNbt(ItemStack value) {
return StrictNBTIngredient.of(value);
}
default Ingredient compound(Ingredient... values) {
return CompoundIngredient.of(values);
}
default Ingredient intersection(@SuppressWarnings("rawtypes") TagKey... values) {
return intersection(Arrays.stream(values).map(Ingredient::of).toArray(Ingredient[]::new));
}
default Ingredient intersection(Ingredient... values) {
return IntersectionIngredient.of(values);
}
default Ingredient difference(TagKey<Item> base, TagKey<Item> subtracted) {
return difference(Ingredient.of(base), Ingredient.of(subtracted));
}
default Ingredient difference(Ingredient base, Ingredient subtracted) {
return DifferenceIngredient.of(base, subtracted);
}
}
@@ -0,0 +1,34 @@
/*
* Copyright (c) Forge Development LLC and contributors
* SPDX-License-Identifier: LGPL-2.1-only
*/
package net.minecraftforge.common.crafting.ingredients;
import com.mojang.serialization.Codec;
import net.minecraft.world.item.crafting.Ingredient;
import net.minecraft.network.FriendlyByteBuf;
public interface IIngredientSerializer<T extends Ingredient> {
Codec<? extends T> codec();
void write(FriendlyByteBuf buffer, T value);
T read(FriendlyByteBuf buffer);
IIngredientSerializer<Ingredient> VANILLA = new IIngredientSerializer<>() {
@Override
public Codec<? extends Ingredient> codec() {
return Ingredient.VANILLA_CODEC;
}
@Override
public void write(FriendlyByteBuf buffer, Ingredient value) {
value.toNetwork(buffer);
}
@Override
public Ingredient read(FriendlyByteBuf buffer) {
return Ingredient.fromNetwork(buffer);
}
};
}
@@ -0,0 +1,139 @@
/*
* Copyright (c) Forge Development LLC and contributors
* SPDX-License-Identifier: LGPL-2.1-only
*/
package net.minecraftforge.common.crafting.ingredients;
import com.mojang.serialization.Codec;
import com.mojang.serialization.codecs.RecordCodecBuilder;
import it.unimi.dsi.fastutil.ints.IntArrayList;
import it.unimi.dsi.fastutil.ints.IntComparators;
import it.unimi.dsi.fastutil.ints.IntList;
import net.minecraft.network.FriendlyByteBuf;
import net.minecraft.world.entity.player.StackedContents;
import net.minecraft.world.item.ItemStack;
import net.minecraft.world.item.crafting.Ingredient;
import org.jetbrains.annotations.Nullable;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
/** Ingredient that matches if all child ingredients match */
public class IntersectionIngredient extends AbstractIngredient {
/**
* Gets an intersection ingredient
* @param ingredients List of ingredients to match
* @return Ingredient that only matches if all the passed ingredients match
*/
public static Ingredient of(Ingredient... ingredients) {
if (ingredients.length == 0)
throw new IllegalArgumentException("Cannot create an IntersectionIngredient with no children, use Ingredient.of() to create an empty ingredient");
if (ingredients.length == 1)
return ingredients[0];
return new IntersectionIngredient(Arrays.asList(ingredients));
}
private final List<Ingredient> children;
private final boolean isSimple;
private ItemStack[] intersectedMatchingStacks = null;
private IntList packedMatchingStacks = null;
private IntersectionIngredient(List<Ingredient> children) {
if (children.size() < 2)
throw new IllegalArgumentException("Cannot create an IntersectionIngredient with one or no children");
this.children = Collections.unmodifiableList(children);
this.isSimple = children.stream().allMatch(Ingredient::isSimple);
}
@Override
public boolean test(@Nullable ItemStack stack) {
if (stack == null || stack.isEmpty())
return false;
for (Ingredient ingredient : children)
if (!ingredient.test(stack))
return false;
return true;
}
@Override
public ItemStack[] getItems() {
if (this.intersectedMatchingStacks == null) {
this.intersectedMatchingStacks = Arrays
.stream(children.get(0).getItems())
.filter(stack -> {
// the first ingredient is treated as a base, filtered by the second onwards
for (int i = 1; i < children.size(); i++)
if (!children.get(i).test(stack))
return false;
return true;
})
.toArray(ItemStack[]::new);
}
return intersectedMatchingStacks;
}
@Override
public boolean isEmpty() {
return children.stream().anyMatch(Ingredient::isEmpty);
}
@Override
public boolean isSimple() {
return isSimple;
}
@Override
protected void invalidate() {
super.invalidate();
this.intersectedMatchingStacks = null;
this.packedMatchingStacks = null;
}
@Override
public IntList getStackingIds() {
if (this.packedMatchingStacks == null || checkInvalidation()) {
markValid();
var matchingStacks = getItems();
this.packedMatchingStacks = new IntArrayList(matchingStacks.length);
for (var stack : matchingStacks)
this.packedMatchingStacks.add(StackedContents.getStackingIndex(stack));
this.packedMatchingStacks.sort(IntComparators.NATURAL_COMPARATOR);
}
return packedMatchingStacks;
}
@Override
public IIngredientSerializer<IntersectionIngredient> serializer() {
return SERIALIZER;
}
public static final Codec<IntersectionIngredient> CODEC = RecordCodecBuilder.create(builder ->
builder.group(
Ingredient.CODEC.listOf().fieldOf("children").forGetter(i -> i.children)
)
.apply(builder, IntersectionIngredient::new)
);
public static final IIngredientSerializer<IntersectionIngredient> SERIALIZER = new IIngredientSerializer<>() {
@Override
public Codec<? extends IntersectionIngredient> codec() {
return CODEC;
}
@Override
public IntersectionIngredient read(FriendlyByteBuf buffer) {
return new IntersectionIngredient(buffer.readList(Ingredient::fromNetwork));
}
@Override
public void write(FriendlyByteBuf buffer, IntersectionIngredient value) {
buffer.writeCollection(value.children, (b, i) -> i.toNetwork(b));
}
};
}
@@ -0,0 +1,139 @@
/*
* Copyright (c) Forge Development LLC and contributors
* SPDX-License-Identifier: LGPL-2.1-only
*/
package net.minecraftforge.common.crafting.ingredients;
import com.mojang.serialization.Codec;
import com.mojang.serialization.codecs.RecordCodecBuilder;
import net.minecraft.advancements.critereon.NbtPredicate;
import net.minecraft.nbt.CompoundTag;
import net.minecraft.nbt.TagParser;
import net.minecraft.network.FriendlyByteBuf;
import net.minecraft.world.item.Item;
import net.minecraft.world.item.ItemStack;
import net.minecraft.world.item.crafting.Ingredient;
import net.minecraft.world.level.ItemLike;
import net.minecraftforge.registries.ForgeRegistries;
import org.jetbrains.annotations.Nullable;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Objects;
/** Ingredient that matches the given items, performing a partial NBT match. Use {@link StrictNBTIngredient} if you want exact match on NBT */
public class PartialNBTIngredient extends AbstractIngredient {
public static Builder builder() {
return new Builder();
}
private final List<Item> items;
private final CompoundTag nbt;
private final NbtPredicate predicate;
private PartialNBTIngredient(List<Item> items, CompoundTag nbt) {
super(items.stream().map(item -> {
var stack = new ItemStack(item);
// copy NBT to prevent the stack from modifying the original, as capabilities or vanilla item durability will modify the tag
stack.setTag(nbt.copy());
return new Ingredient.ItemValue(stack);
}));
if (items.isEmpty())
throw new IllegalArgumentException("Cannot create a PartialNBTIngredient with no items");
this.items = Collections.unmodifiableList(items);
this.nbt = nbt;
this.predicate = new NbtPredicate(nbt);
}
/** Creates a new ingredient matching any item from the list, containing the given NBT */
public static PartialNBTIngredient of(CompoundTag nbt, ItemLike... items) {
return new PartialNBTIngredient(Arrays.stream(items).map(ItemLike::asItem).toList(), nbt);
}
/** Creates a new ingredient matching the given item, containing the given NBT */
public static PartialNBTIngredient of(ItemLike item, CompoundTag nbt) {
return new PartialNBTIngredient(List.of(item.asItem()), nbt);
}
@Override
public boolean test(@Nullable ItemStack input) {
if (input == null)
return false;
return items.contains(input.getItem()) && predicate.matches(input.getShareTag());
}
@Override
public boolean isSimple() {
return false;
}
@Override
public IIngredientSerializer<? extends Ingredient> serializer() {
return SERIALIZER;
}
public static final Codec<PartialNBTIngredient> CODEC = RecordCodecBuilder.create(builder ->
builder.group(
ForgeRegistries.ITEMS.getCodec().listOf().fieldOf("items").forGetter(i -> i.items),
TagParser.AS_CODEC.fieldOf("nbt").forGetter(i -> i.nbt)
).apply(builder, PartialNBTIngredient::new)
);
public static final IIngredientSerializer<PartialNBTIngredient> SERIALIZER = new IIngredientSerializer<>() {
@Override
public Codec<? extends PartialNBTIngredient> codec() {
return CODEC;
}
@Override
public PartialNBTIngredient read(FriendlyByteBuf buffer) {
var items = buffer.readList(b -> b.readRegistryIdUnsafe(ForgeRegistries.ITEMS));
var nbt = buffer.readNbt();
return new PartialNBTIngredient(items, Objects.requireNonNull(nbt));
}
@Override
public void write(FriendlyByteBuf buffer, PartialNBTIngredient value) {
buffer.writeCollection(value.items, (b, item) -> b.writeRegistryIdUnsafe(ForgeRegistries.ITEMS, item));
buffer.writeNbt(value.nbt);
}
};
public static class Builder {
private List<ItemLike> items = new ArrayList<>();
private CompoundTag nbt;
public Builder nbt(CompoundTag value) {
if (this.nbt != null)
throw new IllegalStateException("NBT Tag already set");
this.nbt = value;
return this;
}
public Builder item(ItemLike item) {
this.items.add(item);
return this;
}
public Builder items(ItemLike... values) {
for (var item : values)
this.items.add(item);
return this;
}
public PartialNBTIngredient build() {
if (nbt == null)
throw new IllegalStateException("NBT Data not set");
if (items.isEmpty())
throw new IllegalStateException("No items added");
return PartialNBTIngredient.of(nbt, items.stream().toArray(ItemLike[]::new));
}
}
}
@@ -3,10 +3,11 @@
* SPDX-License-Identifier: LGPL-2.1-only
*/
package net.minecraftforge.common.crafting;
package net.minecraftforge.common.crafting.ingredients;
import java.util.stream.Stream;
import net.minecraft.network.FriendlyByteBuf;
import net.minecraft.world.item.ItemStack;
import net.minecraft.world.item.crafting.Ingredient;
import org.jetbrains.annotations.Nullable;
@@ -15,22 +16,17 @@ import com.mojang.serialization.Codec;
import com.mojang.serialization.codecs.RecordCodecBuilder;
/** Ingredient that matches the given stack, performing an exact NBT match. Use {@link PartialNBTIngredient} if you need partial match. */
public class StrictNBTIngredient extends Ingredient {
public static final Codec<StrictNBTIngredient> CODEC = RecordCodecBuilder.create(b -> b.group(
ItemStack.CODEC.fieldOf("stack").forGetter(i -> i.stack)
).apply(b, StrictNBTIngredient::new));
private final ItemStack stack;
protected StrictNBTIngredient(ItemStack stack) {
super(Stream.of(new Ingredient.ItemValue(stack)));
this.stack = stack;
}
/** Creates a new ingredient matching the given stack and tag */
public class StrictNBTIngredient extends AbstractIngredient {
public static StrictNBTIngredient of(ItemStack stack) {
return new StrictNBTIngredient(stack);
}
private final ItemStack stack;
private StrictNBTIngredient(ItemStack stack) {
super(Stream.of(new Ingredient.ItemValue(stack)));
this.stack = stack;
}
@Override
public boolean test(@Nullable ItemStack input) {
if (input == null)
@@ -43,4 +39,30 @@ public class StrictNBTIngredient extends Ingredient {
public boolean isSimple() {
return false;
}
@Override
public IIngredientSerializer<? extends Ingredient> serializer() {
return SERIALIZER;
}
public static final Codec<StrictNBTIngredient> CODEC = RecordCodecBuilder.create(b -> b.group(
ItemStack.CODEC.fieldOf("stack").forGetter(i -> i.stack)
).apply(b, StrictNBTIngredient::new));
public static final IIngredientSerializer<StrictNBTIngredient> SERIALIZER = new IIngredientSerializer<>() {
@Override
public Codec<? extends StrictNBTIngredient> codec() {
return CODEC;
}
@Override
public void write(FriendlyByteBuf buffer, StrictNBTIngredient value) {
buffer.writeItem(value.stack);
}
@Override
public StrictNBTIngredient read(FriendlyByteBuf buffer) {
return new StrictNBTIngredient(buffer.readItem());
}
};
}