|
| 1 | +package org.embeddedt.modernfix.searchtree; |
| 2 | + |
| 3 | +import it.unimi.dsi.fastutil.objects.Object2ObjectOpenHashMap; |
| 4 | +import net.minecraft.client.gui.screens.recipebook.RecipeCollection; |
| 5 | +import net.minecraft.client.searchtree.SearchTree; |
| 6 | +import net.minecraft.world.item.Item; |
| 7 | +import net.minecraft.world.item.ItemStack; |
| 8 | + |
| 9 | +import java.util.ArrayList; |
| 10 | +import java.util.Collections; |
| 11 | +import java.util.List; |
| 12 | +import java.util.Map; |
| 13 | +import java.util.stream.Collectors; |
| 14 | + |
| 15 | +public class RecipeBookSearchTree extends DummySearchTree<RecipeCollection> { |
| 16 | + private final SearchTree<ItemStack> stackCollector; |
| 17 | + private Map<Item, List<RecipeCollection>> collectionsByItem = null; |
| 18 | + private final List<RecipeCollection> allCollections = new ArrayList<>(); |
| 19 | + |
| 20 | + public RecipeBookSearchTree(SearchTree<ItemStack> stackCollector) { |
| 21 | + this.stackCollector = stackCollector; |
| 22 | + } |
| 23 | + |
| 24 | + private Map<Item, List<RecipeCollection>> populateCollectionMap() { |
| 25 | + Map<Item, List<RecipeCollection>> collections = this.collectionsByItem; |
| 26 | + if(collections == null) { |
| 27 | + collections = new Object2ObjectOpenHashMap<>(); |
| 28 | + Map<Item, List<RecipeCollection>> finalCollection = collections; |
| 29 | + for(RecipeCollection collection : allCollections) { |
| 30 | + collection.getRecipes().stream().map(recipe -> recipe.getResultItem().getItem()).distinct().forEach(item -> { |
| 31 | + finalCollection.computeIfAbsent(item, k -> new ArrayList<>()).add(collection); |
| 32 | + }); |
| 33 | + } |
| 34 | + this.collectionsByItem = collections; |
| 35 | + } |
| 36 | + return collections; |
| 37 | + } |
| 38 | + |
| 39 | + @Override |
| 40 | + public void add(RecipeCollection pObj) { |
| 41 | + this.allCollections.add(pObj); |
| 42 | + } |
| 43 | + |
| 44 | + @Override |
| 45 | + public void clear() { |
| 46 | + this.allCollections.clear(); |
| 47 | + } |
| 48 | + |
| 49 | + @Override |
| 50 | + public void refresh() { |
| 51 | + this.collectionsByItem = null; |
| 52 | + } |
| 53 | + |
| 54 | + @Override |
| 55 | + public List<RecipeCollection> search(String pSearchText) { |
| 56 | + // Avoid constructing the recipe collection map until the first real search |
| 57 | + if(pSearchText.trim().length() == 0) { |
| 58 | + return this.allCollections; |
| 59 | + } |
| 60 | + List<ItemStack> stacks = stackCollector.search(pSearchText); |
| 61 | + Map<Item, List<RecipeCollection>> collections = this.populateCollectionMap(); |
| 62 | + return stacks.stream().map(ItemStack::getItem).distinct().flatMap(item -> collections.getOrDefault(item, Collections.emptyList()).stream()).collect(Collectors.toList()); |
| 63 | + } |
| 64 | +} |
0 commit comments