aboutsummaryrefslogtreecommitdiff
path: root/runtime/src/main/java/me/shedaniel/rei/impl/common/transfer/InputSlotCrafter.java
blob: f79bb65bcf73f24a880e4c4bd52fc76f3c47cfed (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
/*
 * This file is licensed under the MIT License, part of Roughly Enough Items.
 * Copyright (c) 2018, 2019, 2020, 2021, 2022, 2023 shedaniel
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */

package me.shedaniel.rei.impl.common.transfer;

import me.shedaniel.rei.api.common.entry.InputIngredient;
import me.shedaniel.rei.api.common.transfer.ItemRecipeFinder;
import me.shedaniel.rei.api.common.transfer.info.stack.SlotAccessor;
import net.minecraft.core.component.DataComponents;
import net.minecraft.server.level.ServerPlayer;
import net.minecraft.world.Container;
import net.minecraft.world.inventory.AbstractContainerMenu;
import net.minecraft.world.item.ItemStack;
import org.jetbrains.annotations.Nullable;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

public abstract class InputSlotCrafter<T extends AbstractContainerMenu, C extends Container> {
    protected T container;
    private Iterable<SlotAccessor> inputStacks;
    private Iterable<SlotAccessor> inventoryStacks;
    protected ServerPlayer player;
    
    protected InputSlotCrafter(T container) {
        this.container = container;
    }
    
    public void fillInputSlots(ServerPlayer player, boolean hasShift) {
        this.player = player;
        this.inventoryStacks = this.getInventorySlots();
        this.inputStacks = this.getInputSlots();
        
        // Return the already placed items on the grid
        this.cleanInputs();
        
        ItemRecipeFinder recipeFinder = new ItemRecipeFinder();
        this.populateRecipeFinder(recipeFinder);
        List<List<ItemStack>> ingredients = new ArrayList<>();
        for (InputIngredient<ItemStack> itemStacks : this.getInputs()) {
            ingredients.add(itemStacks.get());
        }
        
        if (recipeFinder.findRecipe(ingredients, 1, null)) {
            this.fillInputSlots(recipeFinder, ingredients, hasShift);
        } else {
            this.cleanInputs();
            this.markDirty();
            throw new NotEnoughMaterialsException();
        }
        
        this.markDirty();
    }
    
    protected abstract Iterable<SlotAccessor> getInputSlots();
    
    protected abstract Iterable<SlotAccessor> getInventorySlots();
    
    protected abstract List<InputIngredient<ItemStack>> getInputs();
    
    protected abstract void populateRecipeFinder(ItemRecipeFinder recipeFinder);
    
    protected abstract void markDirty();
    
    public void alignRecipeToGrid(Iterable<SlotAccessor> inputStacks, Iterator<ItemStack> recipeItems, int craftsAmount) {
        for (SlotAccessor inputStack : inputStacks) {
            if (!recipeItems.hasNext()) {
                return;
            }
            
            this.acceptAlignedInput(recipeItems.next(), inputStack, craftsAmount);
        }
    }
    
    public void acceptAlignedInput(ItemStack toBeTakenStack, SlotAccessor inputStack, int craftsAmount) {
        if (!toBeTakenStack.isEmpty()) {
            for (int i = 0; i < craftsAmount; ++i) {
                this.fillInputSlot(inputStack, toBeTakenStack);
            }
        }
    }
    
    protected void fillInputSlot(SlotAccessor slot, ItemStack toBeTakenStack) {
        SlotAccessor takenSlot = this.takeInventoryStack(toBeTakenStack);
        if (takenSlot != null) {
            ItemStack takenStack = takenSlot.getItemStack().copy();
            if (!takenStack.isEmpty()) {
                if (takenStack.getCount() > 1) {
                    takenSlot.takeStack(1);
                } else {
                    takenSlot.setItemStack(ItemStack.EMPTY);
                }
                
                takenStack.setCount(1);
                if (!slot.canPlace(takenStack)) {
                    return;
                }
                
                if (slot.getItemStack().isEmpty()) {
                    slot.setItemStack(takenStack);
                } else {
                    slot.getItemStack().grow(1);
                }
            }
        }
    }
    
    protected void fillInputSlots(ItemRecipeFinder recipeFinder, List<List<ItemStack>> ingredients, boolean hasShift) {
        int recipeCrafts = recipeFinder.countRecipeCrafts(ingredients, Integer.MAX_VALUE, null);
        int amountToFill = hasShift ? recipeCrafts : 1;
        List<ItemStack> recipeItems = new ArrayList<>();
        if (recipeFinder.findRecipe(ingredients, amountToFill, recipeItems::add)) {
            int finalCraftsAmount = amountToFill;
            
            for (ItemStack itemId : recipeItems) {
                // Fix issue with empty item id (grid slot) [shift-click issue]
                if (itemId.isEmpty()) {
                    continue;
                }
                finalCraftsAmount = Math.min(finalCraftsAmount, itemId.getMaxStackSize());
            }
            
            recipeItems.clear();
            
            if (recipeFinder.findRecipe(ingredients, finalCraftsAmount, recipeItems::add)) {
                this.cleanInputs();
                this.alignRecipeToGrid(inputStacks, recipeItems.iterator(), finalCraftsAmount);
            }
        }
    }
    
    protected abstract void cleanInputs();
    
    @Nullable
    public SlotAccessor takeInventoryStack(ItemStack itemStack) {
        boolean rejectedModification = false;
        for (SlotAccessor inventoryStack : inventoryStacks) {
            ItemStack itemStack1 = inventoryStack.getItemStack();
            if (!itemStack1.isEmpty() && areItemsEqual(itemStack, itemStack1) && !itemStack1.isDamaged() && !itemStack1.isEnchanted() && !itemStack1.has(DataComponents.CUSTOM_NAME)) {
                if (!inventoryStack.allowModification(player)) {
                    rejectedModification = true;
                } else {
                    return inventoryStack;
                }
            }
        }
        
        if (rejectedModification) {
            throw new IllegalStateException("Unable to take item from inventory due to slot not allowing modification! Item requested: " + itemStack);
        }
        
        return null;
    }
    
    private static boolean areItemsEqual(ItemStack stack1, ItemStack stack2) {
        return ItemStack.isSameItemSameComponents(stack1, stack2);
    }
    
    public static class NotEnoughMaterialsException extends RuntimeException {
    }
}