Skip to content

Commit

Permalink
Bukkit.getRecipesFor is slow, so cache it
Browse files Browse the repository at this point in the history
  • Loading branch information
mcmonkey4eva committed Feb 6, 2022
1 parent 9a8c9cd commit d8660f1
Show file tree
Hide file tree
Showing 3 changed files with 14 additions and 4 deletions.
Expand Up @@ -3295,6 +3295,7 @@ else if (attribute.startsWith("unexplored_structure", 2) && attribute.hasContext
// <--[tag]
// @attribute <LocationTag.vector_length>
// @returns ElementTag(Decimal)
// @synonyms LocationTag.magnitude
// @group math
// @description
// Returns the 3D length of the vector/location.
Expand Down
Expand Up @@ -52,6 +52,7 @@ public ItemScriptHelper() {

public static void removeDenizenRecipes() {
smithingRetain.clear();
recipeCache.clear();
recipeIdToItemScript.clear();
NMSHandler.getItemHelper().clearDenizenRecipes();
}
Expand Down Expand Up @@ -488,12 +489,20 @@ else if (recipe instanceof CookingRecipe) {
return DenyCraftReason.ALLOWED;
}

public static HashMap<Material, Collection<Recipe>> recipeCache = new HashMap<>();

public static Collection<Recipe> getRecipesFor(Material item) {
return recipeCache.computeIfAbsent(item, (i) -> {
return Bukkit.getRecipesFor(new ItemStack(i));
});
}

public static boolean hasAlternateValidRecipe(Recipe recipe, ItemStack[] items) {
// Workaround for Spigot bug with the wrong recipe ID getting grabbed
if (recipe instanceof ShapedRecipe) {
ItemStack result = recipe.getResult();
if (isItemscript(result)) {
for (Recipe altRecipe : Bukkit.getRecipesFor(result)) {
for (Recipe altRecipe : getRecipesFor(result.getType())) {
if (altRecipe instanceof ShapedRecipe) {
if (shouldDenyCraft(items, altRecipe) == DenyCraftReason.ALLOWED) {
return true;
Expand Down Expand Up @@ -533,7 +542,7 @@ public void onItemCooked(BlockCookEvent event) {
return;
}
ItemStack[] stacks = new ItemStack[] { event.getSource() };
for (Recipe recipe : Bukkit.getRecipesFor(event.getResult())) {
for (Recipe recipe : getRecipesFor(event.getResult().getType())) {
if (recipe instanceof CookingRecipe && shouldDenyCraft(stacks, recipe) == DenyCraftReason.ALLOWED) {
return;
}
Expand Down
Expand Up @@ -269,8 +269,8 @@ public void version(CommandContext args, CommandSender sender) throws CommandExc
*/
@Command(
aliases = {"denizen"}, usage = "save",
desc = "Saves the current state of Denizen/saves.yml.", modifiers = {"save"},
min = 1, max = 3, permission = "denizen.basic", flags = "s")
desc = "Saves the current Denizen save data to file as needed.", modifiers = {"save"},
min = 1, max = 3, permission = "denizen.basic")
public void save(CommandContext args, CommandSender sender) throws CommandException {
DenizenCore.saveAll();
Denizen.getInstance().saveSaves(true);
Expand Down

0 comments on commit d8660f1

Please sign in to comment.