Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[1.21.4] Recipe priority system for solving overlaps in recipe ingredients and patterns. #1855

Open
wants to merge 4 commits into
base: 1.21.x
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,14 @@
);
List<RecipeHolder<?>> list = new ArrayList<>(sortedmap.size());
sortedmap.forEach((p_379232_, p_379233_) -> {
@@ -93,6 +_,7 @@
.stream()
.map(p_380840_ -> new RecipeManager.IngredientCollector(p_380840_.getKey(), p_380840_.getValue()))
.toList();
+ this.recipes.order(); // Neo: order recipes by priority.
this.recipes
.values()
.forEach(
@@ -260,6 +_,11 @@
return p_380850_ -> p_380850_.getType() == p_381108_ && p_380850_ instanceof SingleItemRecipe singleitemrecipe
? Optional.of(singleitemrecipe.input())
Expand Down
46 changes: 46 additions & 0 deletions patches/net/minecraft/world/item/crafting/RecipeMap.java.patch
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
--- a/net/minecraft/world/item/crafting/RecipeMap.java
+++ b/net/minecraft/world/item/crafting/RecipeMap.java
@@ -13,24 +_,41 @@

public class RecipeMap {
public static final RecipeMap EMPTY = new RecipeMap(ImmutableMultimap.of(), Map.of());
- private final Multimap<RecipeType<?>, RecipeHolder<?>> byType;
+ private Multimap<RecipeType<?>, RecipeHolder<?>> byType;
private final Map<ResourceKey<Recipe<?>>, RecipeHolder<?>> byKey;
+ private final Multimap<Integer, com.mojang.datafixers.util.Pair<RecipeType<?>, RecipeHolder<?>>> priorities;

private RecipeMap(Multimap<RecipeType<?>, RecipeHolder<?>> p_379497_, Map<ResourceKey<Recipe<?>>, RecipeHolder<?>> p_380280_) {
+ this(p_379497_, p_380280_, com.google.common.collect.ImmutableSetMultimap.of());
+ }
+
+ private RecipeMap(Multimap<RecipeType<?>, RecipeHolder<?>> p_379497_, Map<ResourceKey<Recipe<?>>, RecipeHolder<?>> p_380280_, Multimap<Integer, com.mojang.datafixers.util.Pair<RecipeType<?>, RecipeHolder<?>>> priorities) {
this.byType = p_379497_;
this.byKey = p_380280_;
+ this.priorities = priorities;
}

public static RecipeMap create(Iterable<RecipeHolder<?>> p_379481_) {
Builder<RecipeType<?>, RecipeHolder<?>> builder = ImmutableMultimap.builder();
com.google.common.collect.ImmutableMap.Builder<ResourceKey<Recipe<?>>, RecipeHolder<?>> builder1 = ImmutableMap.builder();
+ com.google.common.collect.SetMultimap<Integer, com.mojang.datafixers.util.Pair<RecipeType<?>, RecipeHolder<?>>> priorityBuilder = com.google.common.collect.MultimapBuilder.treeKeys().hashSetValues().build();
+ Map<ResourceKey<Recipe<?>>, Integer> recipePriorities = net.neoforged.neoforge.common.NeoForgeEventHandler.getRecipePriorityManager().getRecipePriorities(); // Neo: get overriding recipe priorities

for (RecipeHolder<?> recipeholder : p_379481_) {
+ int priority = recipePriorities.getOrDefault(recipeholder.id(), 0);
+
builder.put(recipeholder.value().getType(), recipeholder);
builder1.put(recipeholder.id(), recipeholder);
+ priorityBuilder.put(priority, com.mojang.datafixers.util.Pair.of(recipeholder.value().getType(), recipeholder));
}

- return new RecipeMap(builder.build(), builder1.build());
+ return new RecipeMap(builder.build(), builder1.build(), com.google.common.collect.ImmutableSetMultimap.copyOf(priorityBuilder));
+ }
+
+ public void order() {
bconlon1 marked this conversation as resolved.
Show resolved Hide resolved
+ com.google.common.collect.LinkedListMultimap<RecipeType<?>, RecipeHolder<?>> finalBuilder = com.google.common.collect.LinkedListMultimap.create();
+ com.google.common.collect.Lists.reverse(new java.util.ArrayList<>(this.priorities.entries())).forEach((e) -> finalBuilder.put(e.getValue().getFirst(), e.getValue().getSecond()));
+ this.byType = ImmutableMultimap.copyOf(finalBuilder);
}

public <I extends RecipeInput, T extends Recipe<I>> Collection<RecipeHolder<T>> byType(RecipeType<T> p_379772_) {
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@
import net.neoforged.bus.api.EventPriority;
import net.neoforged.bus.api.SubscribeEvent;
import net.neoforged.fml.LogicalSide;
import net.neoforged.neoforge.common.crafting.RecipePriorityManager;
import net.neoforged.neoforge.common.loot.LootModifierManager;
import net.neoforged.neoforge.common.util.FakePlayerFactory;
import net.neoforged.neoforge.common.util.LogicalSidedProvider;
Expand Down Expand Up @@ -147,12 +148,15 @@ public void onCommandsRegister(RegisterCommandsEvent event) {
}

private static LootModifierManager INSTANCE;
private static RecipePriorityManager RECIPE_PRIORITY;
private static DataMapLoader DATA_MAPS;

@SubscribeEvent
public void onResourceReload(AddReloadListenerEvent event) {
INSTANCE = new LootModifierManager();
RECIPE_PRIORITY = new RecipePriorityManager();
event.addListener(INSTANCE);
event.addListener(RECIPE_PRIORITY);
event.addListener(DATA_MAPS = new DataMapLoader(event.getConditionContext(), event.getRegistryAccess()));
}

Expand All @@ -162,6 +166,12 @@ static LootModifierManager getLootModifierManager() {
return INSTANCE;
}

public static RecipePriorityManager getRecipePriorityManager() {
if (RECIPE_PRIORITY == null)
throw new IllegalStateException("Can not retrieve RecipePriorityManager until resources have loaded once.");
return RECIPE_PRIORITY;
}

@SubscribeEvent
public void resourceReloadListeners(AddReloadListenerEvent event) {
event.addListener(CreativeModeTabRegistry.getReloadListener());
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,98 @@
/*
* Copyright (c) NeoForged and contributors
* SPDX-License-Identifier: LGPL-2.1-only
*/

package net.neoforged.neoforge.common.crafting;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import it.unimi.dsi.fastutil.objects.Object2IntMap;
import it.unimi.dsi.fastutil.objects.Object2IntMaps;
import it.unimi.dsi.fastutil.objects.Object2IntOpenHashMap;
import java.io.IOException;
import java.io.Reader;
import java.util.Map;
import java.util.Optional;
import net.minecraft.core.registries.Registries;
import net.minecraft.resources.FileToIdConverter;
import net.minecraft.resources.ResourceKey;
import net.minecraft.resources.ResourceLocation;
import net.minecraft.server.packs.resources.Resource;
import net.minecraft.server.packs.resources.ResourceManager;
import net.minecraft.server.packs.resources.SimpleJsonResourceReloadListener;
import net.minecraft.util.ExtraCodecs;
import net.minecraft.util.GsonHelper;
import net.minecraft.util.profiling.ProfilerFiller;
import net.minecraft.world.item.crafting.Recipe;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

public class RecipePriorityManager extends SimpleJsonResourceReloadListener<JsonElement> {
private static final Gson GSON = new GsonBuilder().setPrettyPrinting().disableHtmlEscaping().create();
public static final Logger LOGGER = LogManager.getLogger();

private Object2IntMap<ResourceKey<Recipe<?>>> recipePriorities = Object2IntMaps.emptyMap();
private static final String folder = "recipe_priorities";

public RecipePriorityManager() {
super(ExtraCodecs.JSON, FileToIdConverter.json(folder));
}

@Override
protected Map<ResourceLocation, JsonElement> prepare(ResourceManager resourceManager, ProfilerFiller profilerFiller) {
Map<ResourceLocation, JsonElement> map = super.prepare(resourceManager, profilerFiller);
for (String namespace : resourceManager.getNamespaces()) {
ResourceLocation resourceLocation = ResourceLocation.fromNamespaceAndPath(namespace, "recipe_priorities/recipe_priorities.json");
Optional<Resource> resource = resourceManager.getResource(resourceLocation);
if (resource.isPresent()) {
try (Reader reader = resource.get().openAsReader()) {
JsonObject jsonobject = GsonHelper.fromJson(GSON, reader, JsonObject.class);
boolean replace = GsonHelper.getAsBoolean(jsonobject, "replace", false);
if (replace)
map.clear();
JsonObject entries = GsonHelper.getAsJsonObject(jsonobject, "entries");
for (String entry : entries.keySet()) {
ResourceLocation loc = ResourceLocation.tryParse(entry);
map.remove(loc); //remove and re-add if needed, to update the ordering.
map.put(loc, entries.get(entry));
}
} catch (RuntimeException | IOException ioexception) {
LOGGER.error("Couldn't read recipe priority list {} in data pack {}", resourceLocation, resource.get().sourcePackId(), ioexception);
}
}
}
return map;
}

@Override
protected void apply(Map<ResourceLocation, JsonElement> resourceList, ResourceManager resourceManagerIn, ProfilerFiller profilerIn) {
Object2IntMap<ResourceKey<Recipe<?>>> builder = new Object2IntOpenHashMap<>();
for (Map.Entry<ResourceLocation, JsonElement> entry : resourceList.entrySet()) {
JsonElement json = entry.getValue();
if (json instanceof JsonObject jsonObject) {
JsonElement entries = jsonObject.get("entries");
if (entries instanceof JsonObject entriesObject) {
for (var priorityEntry : entriesObject.entrySet()) {
ResourceLocation location = ResourceLocation.tryParse(priorityEntry.getKey());
int priority = priorityEntry.getValue().getAsInt();
if (location != null) {
builder.put(ResourceKey.create(Registries.RECIPE, location), priority);
}
}
}
}
}
this.recipePriorities = Object2IntMaps.unmodifiable(builder);
LOGGER.info("Loaded {} recipe priority overrides", this.recipePriorities.size());
}

/**
* An immutable map of the registered recipe priorities in layered order.
*/
public Object2IntMap<ResourceKey<Recipe<?>>> getRecipePriorities() {
return this.recipePriorities;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,86 @@
/*
* Copyright (c) NeoForged and contributors
* SPDX-License-Identifier: LGPL-2.1-only
*/

package net.neoforged.neoforge.common.data;

import com.google.common.collect.ImmutableList;
import com.google.gson.JsonObject;
import java.nio.file.Path;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
import net.minecraft.core.HolderLookup;
import net.minecraft.data.CachedOutput;
import net.minecraft.data.DataProvider;
import net.minecraft.data.PackOutput;
import net.minecraft.resources.ResourceLocation;

public abstract class RecipePrioritiesProvider implements DataProvider {
private final PackOutput output;
private final CompletableFuture<HolderLookup.Provider> registriesLookup;
protected HolderLookup.Provider registries;
private final String modid;
private final Map<ResourceLocation, Integer> toSerialize = new HashMap<>();
private boolean replace = false;

public RecipePrioritiesProvider(PackOutput output, CompletableFuture<HolderLookup.Provider> registries, String modid) {
this.output = output;
this.registriesLookup = registries;
this.modid = modid;
}

/**
* Sets the "replace" key in recipe_priorities to true.
*/
protected void replacing() {
this.replace = true;
}

/**
* Call {@link #add} here, which will pass in the necessary information to write the jsons.
*/
protected abstract void start();

@Override
public final CompletableFuture<?> run(CachedOutput cache) {
return this.registriesLookup.thenCompose(registries -> this.run(cache, registries));
}

protected CompletableFuture<?> run(CachedOutput cache, HolderLookup.Provider registries) {
this.registries = registries;
start();

Path path = this.output.getOutputFolder(PackOutput.Target.DATA_PACK).resolve(this.modid).resolve("recipe_priorities").resolve("recipe_priorities.json");

JsonObject entries = new JsonObject();
toSerialize.forEach((key, value) -> entries.addProperty(key.toString(), value));

JsonObject json = new JsonObject();
json.addProperty("replace", this.replace);
json.add("entries", entries);

ImmutableList.Builder<CompletableFuture<?>> futuresBuilder = new ImmutableList.Builder<>();
futuresBuilder.add(DataProvider.saveStable(cache, json, path));

return CompletableFuture.allOf(futuresBuilder.build().toArray(CompletableFuture[]::new));
}

public void add(ResourceLocation recipe, Integer priority) {
this.toSerialize.put(recipe, priority);
}

public void add(String recipe, Integer priority) {
add(ResourceLocation.fromNamespaceAndPath(this.modid, recipe), priority);
}

public void add(String id, String location, Integer priority) {
add(ResourceLocation.fromNamespaceAndPath(id, location), priority);
}

@Override
public String getName() {
return "Recipe Priorities : " + modid;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
{
"parent": "minecraft:recipes/root",
"criteria": {
"has_cherry_planks": {
"conditions": {
"items": [
{
"items": "minecraft:cherry_planks"
}
]
},
"trigger": "minecraft:inventory_changed"
},
"has_the_recipe": {
"conditions": {
"recipe": "neotests_recipe_priorities:higher_priority_test"
},
"trigger": "minecraft:recipe_unlocked"
}
},
"requirements": [
[
"has_the_recipe",
"has_cherry_planks"
]
],
"rewards": {
"recipes": [
"neotests_recipe_priorities:higher_priority_test"
]
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
{
"type": "minecraft:crafting_shaped",
"category": "misc",
"group": "bed",
"key": {
"#": "minecraft:yellow_wool",
"X": "minecraft:cherry_planks"
},
"pattern": [
"###",
"XXX"
],
"result": {
"count": 1,
"id": "minecraft:redstone_block"
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
{
"entries": {
"neotests_recipe_priorities:higher_priority_test": 1
},
"replace": false
}
Loading
Loading