allow crafters to work with the crafting module

closes #212
This commit is contained in:
Ell 2024-10-25 18:44:25 +02:00
parent a410e9cb29
commit f976936427
9 changed files with 137 additions and 37 deletions

View file

@ -48,4 +48,7 @@ public interface IModule {
ItemFilter getItemFilter(ItemStack module, PipeBlockEntity tile); ItemFilter getItemFilter(ItemStack module, PipeBlockEntity tile);
DirectionSelector getDirectionSelector(ItemStack module, PipeBlockEntity tile); DirectionSelector getDirectionSelector(ItemStack module, PipeBlockEntity tile);
ItemStack store(ItemStack module, PipeBlockEntity tile, ItemStack stack, Direction direction);
} }

View file

@ -108,4 +108,9 @@ public abstract class ModuleItem extends Item implements IModule {
return null; return null;
} }
@Override
public ItemStack store(ItemStack module, PipeBlockEntity tile, ItemStack stack, Direction direction) {
return stack;
}
} }

View file

@ -202,13 +202,7 @@ public class PipeItem implements IPipeItem {
protected ItemStack store(PipeBlockEntity currPipe) { protected ItemStack store(PipeBlockEntity currPipe) {
var dir = Utility.getDirectionFromOffset(this.destInventory, this.getDestPipe()); var dir = Utility.getDirectionFromOffset(this.destInventory, this.getDestPipe());
var connectable = currPipe.getPipeConnectable(dir); return currPipe.store(this.stack, dir);
if (connectable != null)
return connectable.insertItem(currPipe.getBlockPos(), dir, this.stack, false);
var handler = currPipe.getItemHandler(dir);
if (handler != null)
return ItemHandlerHelper.insertItemStacked(handler, this.stack, false);
return this.stack;
} }
protected PipeBlockEntity getNextTile(PipeBlockEntity currPipe, boolean progress) { protected PipeBlockEntity getNextTile(PipeBlockEntity currPipe, boolean progress) {

View file

@ -6,6 +6,7 @@ import de.ellpeck.prettypipes.items.IModule;
import de.ellpeck.prettypipes.misc.ItemFilter.IFilteredContainer; import de.ellpeck.prettypipes.misc.ItemFilter.IFilteredContainer;
import de.ellpeck.prettypipes.pipe.PipeBlockEntity; import de.ellpeck.prettypipes.pipe.PipeBlockEntity;
import de.ellpeck.prettypipes.pipe.containers.AbstractPipeContainer; import de.ellpeck.prettypipes.pipe.containers.AbstractPipeContainer;
import de.ellpeck.prettypipes.pipe.modules.craft.CraftingModuleContainer;
import de.ellpeck.prettypipes.pipe.modules.modifier.FilterModifierModuleContainer; import de.ellpeck.prettypipes.pipe.modules.modifier.FilterModifierModuleContainer;
import de.ellpeck.prettypipes.pipe.modules.modifier.FilterModifierModuleItem; import de.ellpeck.prettypipes.pipe.modules.modifier.FilterModifierModuleItem;
import de.ellpeck.prettypipes.pipe.modules.stacksize.StackSizeModuleItem; import de.ellpeck.prettypipes.pipe.modules.stacksize.StackSizeModuleItem;
@ -94,6 +95,18 @@ public record PacketButton(BlockPos pos, int result, List<Integer> data) impleme
if (player.containerMenu instanceof IFilteredContainer filtered) if (player.containerMenu instanceof IFilteredContainer filtered)
filtered.getFilter().onButtonPacket(filtered, data.getFirst()); filtered.getFilter().onButtonPacket(filtered, data.getFirst());
}), }),
ENSURE_ITEM_ORDER_BUTTON((pos, data, player) -> {
if (player.containerMenu instanceof CraftingModuleContainer container) {
container.ensureItemOrder = !container.ensureItemOrder;
container.modified = true;
}
}),
INSERT_SINGLES_BUTTON((pos, data, player) -> {
if (player.containerMenu instanceof CraftingModuleContainer container) {
container.insertSingles = !container.insertSingles;
container.modified = true;
}
}),
STACK_SIZE_MODULE_BUTTON((pos, data, player) -> { STACK_SIZE_MODULE_BUTTON((pos, data, player) -> {
var container = (AbstractPipeContainer<?>) player.containerMenu; var container = (AbstractPipeContainer<?>) player.containerMenu;
var moduleData = container.moduleStack.getOrDefault(StackSizeModuleItem.Data.TYPE, StackSizeModuleItem.Data.DEFAULT); var moduleData = container.moduleStack.getOrDefault(StackSizeModuleItem.Data.TYPE, StackSizeModuleItem.Data.DEFAULT);

View file

@ -4,7 +4,6 @@ import de.ellpeck.prettypipes.PrettyPipes;
import de.ellpeck.prettypipes.Registry; import de.ellpeck.prettypipes.Registry;
import de.ellpeck.prettypipes.Utility; import de.ellpeck.prettypipes.Utility;
import de.ellpeck.prettypipes.items.IModule; import de.ellpeck.prettypipes.items.IModule;
import de.ellpeck.prettypipes.misc.EquatableItemStack;
import de.ellpeck.prettypipes.misc.ItemFilter; import de.ellpeck.prettypipes.misc.ItemFilter;
import de.ellpeck.prettypipes.network.NetworkLock; import de.ellpeck.prettypipes.network.NetworkLock;
import de.ellpeck.prettypipes.network.PipeNetwork; import de.ellpeck.prettypipes.network.PipeNetwork;
@ -39,6 +38,7 @@ import net.neoforged.neoforge.capabilities.BlockCapability;
import net.neoforged.neoforge.capabilities.Capabilities; import net.neoforged.neoforge.capabilities.Capabilities;
import net.neoforged.neoforge.common.util.Lazy; import net.neoforged.neoforge.common.util.Lazy;
import net.neoforged.neoforge.items.IItemHandler; import net.neoforged.neoforge.items.IItemHandler;
import net.neoforged.neoforge.items.ItemHandlerHelper;
import net.neoforged.neoforge.items.ItemStackHandler; import net.neoforged.neoforge.items.ItemStackHandler;
import org.apache.commons.lang3.tuple.Pair; import org.apache.commons.lang3.tuple.Pair;
import org.apache.commons.lang3.tuple.Triple; import org.apache.commons.lang3.tuple.Triple;
@ -72,7 +72,7 @@ public class PipeBlockEntity extends BlockEntity implements MenuProvider, IPipeC
} }
}; };
// crafting module slot, ingredient request network lock // crafting module slot, ingredient request network lock
public final Queue<Pair<Integer, NetworkLock>> craftIngredientRequests = new LinkedList<>(); public final List<Pair<Integer, NetworkLock>> craftIngredientRequests = new ArrayList<>();
// crafting module slot, destination pipe for the result, result item // crafting module slot, destination pipe for the result, result item
public final List<Triple<Integer, BlockPos, ItemStack>> craftResultRequests = new ArrayList<>(); public final List<Triple<Integer, BlockPos, ItemStack>> craftResultRequests = new ArrayList<>();
public PressurizerBlockEntity pressurizer; public PressurizerBlockEntity pressurizer;
@ -416,6 +416,23 @@ public class PipeBlockEntity extends BlockEntity implements MenuProvider, IPipeC
}).filter(Objects::nonNull).collect(Collectors.toList()); }).filter(Objects::nonNull).collect(Collectors.toList());
} }
public ItemStack store(ItemStack stack, Direction direction) {
var modules = this.streamModules().iterator();
while (modules.hasNext()) {
var module = modules.next();
stack = module.getRight().store(module.getLeft(), this, stack, direction);
if (stack.isEmpty())
return stack;
}
var connectable = this.getPipeConnectable(direction);
if (connectable != null)
return connectable.insertItem(this.getBlockPos(), direction, stack, false);
var handler = this.getItemHandler(direction);
if (handler != null)
return ItemHandlerHelper.insertItemStacked(handler, stack, false);
return stack;
}
@Override @Override
public Component getDisplayName() { public Component getDisplayName() {
return Component.translatable("container." + PrettyPipes.ID + ".pipe"); return Component.translatable("container." + PrettyPipes.ID + ".pipe");

View file

@ -6,12 +6,17 @@ import de.ellpeck.prettypipes.pipe.containers.AbstractPipeContainer;
import net.minecraft.core.BlockPos; import net.minecraft.core.BlockPos;
import net.minecraft.world.entity.player.Player; import net.minecraft.world.entity.player.Player;
import net.minecraft.world.inventory.MenuType; import net.minecraft.world.inventory.MenuType;
import net.minecraft.world.item.ItemStack;
import net.neoforged.neoforge.items.ItemStackHandler; import net.neoforged.neoforge.items.ItemStackHandler;
import net.neoforged.neoforge.items.SlotItemHandler;
import org.jetbrains.annotations.NotNull;
public class CraftingModuleContainer extends AbstractPipeContainer<CraftingModuleItem> { public class CraftingModuleContainer extends AbstractPipeContainer<CraftingModuleItem> {
public ItemStackHandler input; public ItemStackHandler input;
public ItemStackHandler output; public ItemStackHandler output;
public boolean ensureItemOrder;
public boolean insertSingles;
public boolean modified; public boolean modified;
public CraftingModuleContainer(MenuType<?> type, int id, Player player, BlockPos pos, int moduleIndex) { public CraftingModuleContainer(MenuType<?> type, int id, Player player, BlockPos pos, int moduleIndex) {
@ -21,6 +26,9 @@ public class CraftingModuleContainer extends AbstractPipeContainer<CraftingModul
@Override @Override
protected void addSlots() { protected void addSlots() {
var contents = this.moduleStack.get(CraftingModuleItem.Contents.TYPE); var contents = this.moduleStack.get(CraftingModuleItem.Contents.TYPE);
this.ensureItemOrder = contents.ensureItemOrder();
this.insertSingles = contents.insertSingles();
this.input = Utility.copy(contents.input()); this.input = Utility.copy(contents.input());
for (var i = 0; i < this.input.getSlots(); i++) { for (var i = 0; i < this.input.getSlots(); i++) {
this.addSlot(new FilterSlot(this.input, i, (176 - this.input.getSlots() * 18) / 2 + 1 + i % 9 * 18, 17 + 32 + i / 9 * 18, false) { this.addSlot(new FilterSlot(this.input, i, (176 - this.input.getSlots() * 18) / 2 + 1 + i % 9 * 18, 17 + 32 + i / 9 * 18, false) {
@ -49,7 +57,7 @@ public class CraftingModuleContainer extends AbstractPipeContainer<CraftingModul
public void removed(Player playerIn) { public void removed(Player playerIn) {
super.removed(playerIn); super.removed(playerIn);
if (this.modified) { if (this.modified) {
this.moduleStack.set(CraftingModuleItem.Contents.TYPE, new CraftingModuleItem.Contents(this.input, this.output)); this.moduleStack.set(CraftingModuleItem.Contents.TYPE, new CraftingModuleItem.Contents(this.input, this.output, this.ensureItemOrder, this.insertSingles));
this.tile.setChanged(); this.tile.setChanged();
} }
} }

View file

@ -1,10 +1,18 @@
package de.ellpeck.prettypipes.pipe.modules.craft; package de.ellpeck.prettypipes.pipe.modules.craft;
import de.ellpeck.prettypipes.PrettyPipes;
import de.ellpeck.prettypipes.packets.PacketButton;
import de.ellpeck.prettypipes.pipe.containers.AbstractPipeGui; import de.ellpeck.prettypipes.pipe.containers.AbstractPipeGui;
import net.minecraft.ChatFormatting;
import net.minecraft.client.gui.GuiGraphics; import net.minecraft.client.gui.GuiGraphics;
import net.minecraft.client.gui.components.Button;
import net.minecraft.client.gui.components.Tooltip;
import net.minecraft.network.chat.Component; import net.minecraft.network.chat.Component;
import net.minecraft.world.entity.player.Inventory; import net.minecraft.world.entity.player.Inventory;
import java.util.List;
import java.util.function.Supplier;
public class CraftingModuleGui extends AbstractPipeGui<CraftingModuleContainer> { public class CraftingModuleGui extends AbstractPipeGui<CraftingModuleContainer> {
public CraftingModuleGui(CraftingModuleContainer screenContainer, Inventory inv, Component titleIn) { public CraftingModuleGui(CraftingModuleContainer screenContainer, Inventory inv, Component titleIn) {
@ -16,4 +24,23 @@ public class CraftingModuleGui extends AbstractPipeGui<CraftingModuleContainer>
super.renderBg(graphics, partialTicks, mouseX, mouseY); super.renderBg(graphics, partialTicks, mouseX, mouseY);
graphics.blit(AbstractPipeGui.TEXTURE, this.leftPos + 176 / 2 - 16 / 2, this.topPos + 32 + 18 * 2, 176, 80, 16, 16); graphics.blit(AbstractPipeGui.TEXTURE, this.leftPos + 176 / 2 - 16 / 2, this.topPos + 32 + 18 * 2, 176, 80, 16, 16);
} }
@Override
protected void init() {
super.init();
var cacheText = (Supplier<String>) () -> "info." + PrettyPipes.ID + ".ensure_item_order_" + (this.menu.ensureItemOrder ? "on" : "off");
this.addRenderableWidget(Button.builder(Component.translatable(cacheText.get()), button -> {
PacketButton.sendAndExecute(this.menu.tile.getBlockPos(), PacketButton.ButtonResult.ENSURE_ITEM_ORDER_BUTTON, List.of());
button.setMessage(Component.translatable(cacheText.get()));
}).bounds(this.leftPos + this.imageWidth - 7 - 20, this.topPos + 17 + 32 + 18 * 2 + 2, 20, 20).tooltip(
Tooltip.create(Component.translatable("info." + PrettyPipes.ID + ".ensure_item_order.description").withStyle(ChatFormatting.GRAY))).build());
var singleText = (Supplier<String>) () -> "info." + PrettyPipes.ID + ".insert_singles_" + (this.menu.insertSingles ? "on" : "off");
this.addRenderableWidget(Button.builder(Component.translatable(singleText.get()), button -> {
PacketButton.sendAndExecute(this.menu.tile.getBlockPos(), PacketButton.ButtonResult.INSERT_SINGLES_BUTTON, List.of());
button.setMessage(Component.translatable(singleText.get()));
}).bounds(this.leftPos + this.imageWidth - 7 - 20 - 22, this.topPos + 17 + 32 + 18 * 2 + 2, 20, 20).tooltip(
Tooltip.create(Component.translatable("info." + PrettyPipes.ID + ".insert_singles.description").withStyle(ChatFormatting.GRAY))).build());
}
} }

View file

@ -23,13 +23,12 @@ import net.minecraft.world.entity.player.Inventory;
import net.minecraft.world.entity.player.Player; import net.minecraft.world.entity.player.Player;
import net.minecraft.world.item.ItemStack; import net.minecraft.world.item.ItemStack;
import net.neoforged.neoforge.items.IItemHandler; import net.neoforged.neoforge.items.IItemHandler;
import net.neoforged.neoforge.items.ItemHandlerHelper;
import net.neoforged.neoforge.items.ItemStackHandler; import net.neoforged.neoforge.items.ItemStackHandler;
import org.apache.commons.lang3.tuple.Pair; import org.apache.commons.lang3.tuple.Pair;
import org.apache.commons.lang3.tuple.Triple; import org.apache.commons.lang3.tuple.Triple;
import java.util.ArrayList; import java.util.*;
import java.util.List;
import java.util.Stack;
import java.util.function.Consumer; import java.util.function.Consumer;
public class CraftingModuleItem extends ModuleItem { public class CraftingModuleItem extends ModuleItem {
@ -37,7 +36,7 @@ public class CraftingModuleItem extends ModuleItem {
private final int speed; private final int speed;
public CraftingModuleItem(String name, ModuleTier tier) { public CraftingModuleItem(String name, ModuleTier tier) {
super(name, new Properties().component(Contents.TYPE, new Contents(new ItemStackHandler(tier.forTier(1, 4, 9)), new ItemStackHandler(tier.forTier(1, 2, 4))))); super(name, new Properties().component(Contents.TYPE, new Contents(new ItemStackHandler(tier.forTier(1, 4, 9)), new ItemStackHandler(tier.forTier(1, 2, 4)), false, false)));
this.speed = tier.forTier(20, 10, 5); this.speed = tier.forTier(20, 10, 5);
} }
@ -75,23 +74,29 @@ public class CraftingModuleItem extends ModuleItem {
// process crafting ingredient requests // process crafting ingredient requests
if (!tile.craftIngredientRequests.isEmpty()) { if (!tile.craftIngredientRequests.isEmpty()) {
network.startProfile("crafting_ingredients"); network.startProfile("crafting_ingredients");
var request = tile.craftIngredientRequests.peek(); var request = tile.craftIngredientRequests.getFirst();
if (request.getLeft() == slot) { if (request.getLeft() == slot) {
var lock = request.getRight(); var lock = request.getRight();
var equalityTypes = ItemFilter.getEqualityTypes(tile); var equalityTypes = ItemFilter.getEqualityTypes(tile);
var dest = tile.getAvailableDestination(Direction.values(), lock.stack, true, true); var dest = tile.getAvailableDestination(Direction.values(), lock.stack, true, true);
if (dest != null) { if (dest != null) {
var requestRemain = network.requestExistingItem(lock.location, tile.getBlockPos(), dest.getLeft(), lock, dest.getRight(), equalityTypes); var ensureItemOrder = module.get(Contents.TYPE).ensureItemOrder;
network.resolveNetworkLock(lock); // if we're ensuring the correct item order and the item is already on the way, don't do anything yet
tile.craftIngredientRequests.remove(); if (!ensureItemOrder || network.getPipeItemsOnTheWay(dest.getLeft()).findAny().isEmpty()) {
var requestRemain = network.requestExistingItem(lock.location, tile.getBlockPos(), dest.getLeft(), lock, dest.getRight(), equalityTypes);
network.resolveNetworkLock(lock);
tile.craftIngredientRequests.remove(request);
// if we couldn't fit all items into the destination, create another request for the rest // if we couldn't fit all items into the destination, create another request for the rest
var remain = lock.stack.copy(); var remain = lock.stack.copy();
remain.shrink(dest.getRight().getCount() - requestRemain.getCount()); remain.shrink(dest.getRight().getCount() - requestRemain.getCount());
if (!remain.isEmpty()) { if (!remain.isEmpty()) {
var remainRequest = new NetworkLock(lock.location, remain); var remainRequest = new NetworkLock(lock.location, remain);
tile.craftIngredientRequests.add(Pair.of(slot, remainRequest)); // if we're ensuring item order, we need to insert the remaining request at the start so that it gets processed first
network.createNetworkLock(remainRequest); var index = ensureItemOrder ? 0 : tile.craftResultRequests.size();
tile.craftIngredientRequests.add(index, Pair.of(slot, remainRequest));
network.createNetworkLock(remainRequest);
}
} }
} }
} }
@ -181,16 +186,20 @@ public class CraftingModuleItem extends ModuleItem {
var craftableCrafts = Mth.ceil(craftableAmount / (float) resultAmount); var craftableCrafts = Mth.ceil(craftableAmount / (float) resultAmount);
var toCraft = Math.min(craftableCrafts, requiredCrafts); var toCraft = Math.min(craftableCrafts, requiredCrafts);
var input = module.get(Contents.TYPE).input; var contents = module.get(Contents.TYPE);
for (var i = 0; i < input.getSlots(); i++) { // if we're ensuring item order, all items for a single recipe should be sent in order first before starting on the next one!
var in = input.getStackInSlot(i); for (var c = contents.ensureItemOrder ? toCraft : 1; c > 0; c--) {
if (in.isEmpty()) for (var i = 0; i < contents.input.getSlots(); i++) {
continue; var in = contents.input.getStackInSlot(i);
var copy = in.copy(); if (in.isEmpty())
copy.setCount(in.getCount() * toCraft); continue;
var ret = ItemTerminalBlockEntity.requestItemLater(tile.getLevel(), tile.getBlockPos(), items, unavailableConsumer, copy, CraftingModuleItem.addDependency(dependencyChain, module), equalityTypes); var copy = in.copy();
for (var lock : ret.getLeft()) if (!contents.ensureItemOrder)
tile.craftIngredientRequests.add(Pair.of(slot, lock)); copy.setCount(in.getCount() * toCraft);
var ret = ItemTerminalBlockEntity.requestItemLater(tile.getLevel(), tile.getBlockPos(), items, unavailableConsumer, copy, CraftingModuleItem.addDependency(dependencyChain, module), equalityTypes);
for (var lock : ret.getLeft())
tile.craftIngredientRequests.add(Pair.of(slot, lock));
}
} }
var remain = stack.copy(); var remain = stack.copy();
@ -203,6 +212,22 @@ public class CraftingModuleItem extends ModuleItem {
return remain; return remain;
} }
@Override
public ItemStack store(ItemStack module, PipeBlockEntity tile, ItemStack stack, Direction direction) {
if (module.get(Contents.TYPE).insertSingles) {
var handler = tile.getItemHandler(direction);
if (handler != null) {
while (!stack.isEmpty()) {
var remain = ItemHandlerHelper.insertItem(handler, stack.copyWithCount(1), false);
if (!remain.isEmpty())
break;
stack.shrink(1);
}
}
}
return stack;
}
private int getResultAmountPerCraft(ItemStack module, ItemStack stack, ItemEquality... equalityTypes) { private int getResultAmountPerCraft(ItemStack module, ItemStack stack, ItemEquality... equalityTypes) {
var output = module.get(Contents.TYPE).output; var output = module.get(Contents.TYPE).output;
var resultAmount = 0; var resultAmount = 0;
@ -220,11 +245,13 @@ public class CraftingModuleItem extends ModuleItem {
return deps; return deps;
} }
public record Contents(ItemStackHandler input, ItemStackHandler output) { public record Contents(ItemStackHandler input, ItemStackHandler output, boolean ensureItemOrder, boolean insertSingles) {
public static final Codec<Contents> CODEC = RecordCodecBuilder.create(i -> i.group( public static final Codec<Contents> CODEC = RecordCodecBuilder.create(i -> i.group(
Utility.ITEM_STACK_HANDLER_CODEC.fieldOf("input").forGetter(d -> d.input), Utility.ITEM_STACK_HANDLER_CODEC.fieldOf("input").forGetter(d -> d.input),
Utility.ITEM_STACK_HANDLER_CODEC.fieldOf("output").forGetter(d -> d.output) Utility.ITEM_STACK_HANDLER_CODEC.fieldOf("output").forGetter(d -> d.output),
Codec.BOOL.optionalFieldOf("ensure_item_order", false).forGetter(d -> d.ensureItemOrder),
Codec.BOOL.optionalFieldOf("insert_singles", false).forGetter(d -> d.insertSingles)
).apply(i, Contents::new)); ).apply(i, Contents::new));
public static final DataComponentType<Contents> TYPE = DataComponentType.<Contents>builder().persistent(Contents.CODEC).cacheEncoding().build(); public static final DataComponentType<Contents> TYPE = DataComponentType.<Contents>builder().persistent(Contents.CODEC).cacheEncoding().build();

View file

@ -66,6 +66,12 @@
"info.prettypipes.blacklist": "\u00A74D", "info.prettypipes.blacklist": "\u00A74D",
"info.prettypipes.whitelist.description": "Items in filter slots are allowed", "info.prettypipes.whitelist.description": "Items in filter slots are allowed",
"info.prettypipes.blacklist.description": "Items in filter slots are disallowed", "info.prettypipes.blacklist.description": "Items in filter slots are disallowed",
"info.prettypipes.insert_singles_on": "\u00A72S",
"info.prettypipes.insert_singles_off": "\u00A74\u00A7mS",
"info.prettypipes.insert_singles.description": "Whether items should be inserted one at a time, rather than as a stack\nRecommended for use with the Crafter",
"info.prettypipes.ensure_item_order_on": "\u00A72O",
"info.prettypipes.ensure_item_order_off": "\u00A74\u00A7mO",
"info.prettypipes.ensure_item_order.description": "Whether the module should wait for items to be inserted in the order they appear in the input slots\nRecommended for use with the Crafter",
"info.prettypipes.shift": "Hold Shift for info", "info.prettypipes.shift": "Hold Shift for info",
"info.prettypipes.populate": "P", "info.prettypipes.populate": "P",
"info.prettypipes.populate.description": "Populate filter slots with items from adjacent inventories", "info.prettypipes.populate.description": "Populate filter slots with items from adjacent inventories",