networking stuff

This commit is contained in:
Ell 2024-09-15 15:17:16 +02:00
parent 2e05cd7b70
commit bc710789c8
22 changed files with 244 additions and 391 deletions

View file

@ -47,7 +47,6 @@ import de.ellpeck.prettypipes.terminal.containers.CraftingTerminalContainer;
import de.ellpeck.prettypipes.terminal.containers.CraftingTerminalGui;
import de.ellpeck.prettypipes.terminal.containers.ItemTerminalContainer;
import de.ellpeck.prettypipes.terminal.containers.ItemTerminalGui;
import net.minecraft.client.gui.screens.MenuScreens;
import net.minecraft.client.renderer.blockentity.BlockEntityRenderers;
import net.minecraft.client.renderer.entity.EntityRenderers;
import net.minecraft.core.Direction;
@ -211,12 +210,12 @@ public final class Registry {
@SubscribeEvent
public static void registerPayloads(final RegisterPayloadHandlersEvent event) {
var registrar = event.registrar(PrettyPipes.ID);
registrar.play(PacketItemEnterPipe.ID, PacketItemEnterPipe::new, PacketItemEnterPipe::onMessage);
registrar.play(PacketButton.ID, PacketButton::new, PacketButton::onMessage);
registrar.play(PacketCraftingModuleTransfer.ID, PacketCraftingModuleTransfer::new, PacketCraftingModuleTransfer::onMessage);
registrar.play(PacketGhostSlot.ID, PacketGhostSlot::new, PacketGhostSlot::onMessage);
registrar.play(PacketNetworkItems.ID, PacketNetworkItems::new, PacketNetworkItems::onMessage);
registrar.play(PacketRequest.ID, PacketRequest::new, PacketRequest::onMessage);
registrar.playBidirectional(PacketItemEnterPipe.TYPE, PacketItemEnterPipe.CODEC, PacketItemEnterPipe::onMessage);
registrar.playBidirectional(PacketButton.TYPE, PacketButton.CODEC, PacketButton::onMessage);
registrar.playBidirectional(PacketCraftingModuleTransfer.TYPE, PacketCraftingModuleTransfer.CODEC, PacketCraftingModuleTransfer::onMessage);
registrar.playBidirectional(PacketGhostSlot.TYPE, PacketGhostSlot.CODEC, PacketGhostSlot::onMessage);
registrar.playBidirectional(PacketNetworkItems.TYPE, PacketNetworkItems.CODEC, PacketNetworkItems::onMessage);
registrar.playBidirectional(PacketRequest.TYPE, PacketRequest.CODEC, PacketRequest::onMessage);
}
private static <T extends AbstractPipeContainer<?>> MenuType<T> registerPipeContainer(RegisterEvent.RegisterHelper<MenuType<?>> helper, String name) {

View file

@ -46,7 +46,7 @@ public class CraftingTerminalTransferHandler implements IRecipeTransferHandler<C
List<PacketGhostSlot.Entry> stacks = new ArrayList<>();
var ingredients = slots.getSlotViews(RecipeIngredientRole.INPUT);
for (var entry : ingredients)
stacks.add(new PacketGhostSlot.Entry(player.level(), entry.getIngredients(VanillaTypes.ITEM_STACK).collect(Collectors.toList())));
stacks.add(PacketGhostSlot.Entry.fromStacks(player.level(), entry.getIngredients(VanillaTypes.ITEM_STACK).collect(Collectors.toList())));
PacketDistributor.sendToServer(new PacketGhostSlot(container.getTile().getBlockPos(), stacks));
return null;
}

View file

@ -13,6 +13,8 @@ import net.neoforged.api.distmarker.OnlyIn;
import net.neoforged.neoforge.client.gui.widget.ExtendedButton;
import org.apache.commons.lang3.ArrayUtils;
import java.util.List;
public class DirectionSelector {
private static final Direction[] ALL = ArrayUtils.addAll(Direction.values(), (Direction) null);
@ -33,7 +35,7 @@ public class DirectionSelector {
@OnlyIn(Dist.CLIENT)
public AbstractWidget getButton(int x, int y) {
return new ExtendedButton(x, y, 100, 20, Component.translatable("info." + PrettyPipes.ID + ".populate"), button ->
PacketButton.sendAndExecute(this.pipe.getBlockPos(), PacketButton.ButtonResult.DIRECTION_SELECTOR)) {
PacketButton.sendAndExecute(this.pipe.getBlockPos(), PacketButton.ButtonResult.DIRECTION_SELECTOR, List.of())) {
@Override
public Component getMessage() {
var pipe = DirectionSelector.this.pipe;
@ -102,4 +104,5 @@ public class DirectionSelector {
DirectionSelector getSelector();
}
}

View file

@ -54,12 +54,12 @@ public class ItemFilter extends ItemStackHandler {
if (this.canModifyWhitelist) {
var whitelistText = (Supplier<String>) () -> "info." + PrettyPipes.ID + "." + (this.isWhitelist ? "whitelist" : "blacklist");
buttons.add(Button.builder(Component.translatable(whitelistText.get()), button -> {
PacketButton.sendAndExecute(this.pipe.getBlockPos(), PacketButton.ButtonResult.FILTER_CHANGE, 0);
PacketButton.sendAndExecute(this.pipe.getBlockPos(), PacketButton.ButtonResult.FILTER_CHANGE, List.of(0));
button.setMessage(Component.translatable(whitelistText.get()));
}).bounds(x - 20, y, 20, 20).tooltip(Tooltip.create(Component.translatable(whitelistText.get() + ".description").withStyle(ChatFormatting.GRAY))).build());
}
if (this.canPopulateFromInventories) {
buttons.add(Button.builder(Component.translatable("info." + PrettyPipes.ID + ".populate"), button -> PacketButton.sendAndExecute(this.pipe.getBlockPos(), PacketButton.ButtonResult.FILTER_CHANGE, 1)).bounds(x - 42, y, 20, 20).tooltip(Tooltip.create(Component.translatable("info." + PrettyPipes.ID + ".populate.description").withStyle(ChatFormatting.GRAY))).build());
buttons.add(Button.builder(Component.translatable("info." + PrettyPipes.ID + ".populate"), button -> PacketButton.sendAndExecute(this.pipe.getBlockPos(), PacketButton.ButtonResult.FILTER_CHANGE, List.of(1))).bounds(x - 42, y, 20, 20).tooltip(Tooltip.create(Component.translatable("info." + PrettyPipes.ID + ".populate.description").withStyle(ChatFormatting.GRAY))).build());
}
return buttons;
}

View file

@ -119,8 +119,8 @@ public class PipeNetwork extends SavedData implements GraphListener<BlockPos, Ne
for (var edge : this.graph.edgeSet())
edges.add(edge.serializeNBT(provider));
nbt.put("edges", edges);
nbt.put("items", Utility.serializeAll(this.pipeItems.values()));
nbt.put("locks", Utility.serializeAll(this.networkLocks.values()));
nbt.put("items", Utility.serializeAll(provider, this.pipeItems.values()));
nbt.put("locks", Utility.serializeAll(provider, this.networkLocks.values()));
return nbt;
}
@ -201,7 +201,7 @@ public class PipeNetwork extends SavedData implements GraphListener<BlockPos, Ne
var item = itemSupplier.apply(startPipe.getItemSpeed(stack));
item.setDestination(startInventory, destInventory, path);
startPipe.addNewItem(item);
PacketDistributor.sendToPlayersTrackingChunk((ServerLevel) this.level, new ChunkPos(startPipePos), new PacketItemEnterPipe(startPipePos, item));
PacketDistributor.sendToPlayersTrackingChunk((ServerLevel) this.level, new ChunkPos(startPipePos), new PacketItemEnterPipe(startPipePos, item.serializeNBT(this.level.registryAccess())));
return true;
}

View file

@ -13,8 +13,10 @@ import de.ellpeck.prettypipes.terminal.CraftingTerminalBlockEntity;
import de.ellpeck.prettypipes.terminal.ItemTerminalBlockEntity;
import net.minecraft.client.Minecraft;
import net.minecraft.core.BlockPos;
import net.minecraft.network.FriendlyByteBuf;
import net.minecraft.network.RegistryFriendlyByteBuf;
import net.minecraft.network.chat.Component;
import net.minecraft.network.codec.ByteBufCodecs;
import net.minecraft.network.codec.StreamCodec;
import net.minecraft.network.protocol.common.custom.CustomPacketPayload;
import net.minecraft.resources.ResourceLocation;
import net.minecraft.world.MenuProvider;
@ -22,64 +24,50 @@ import net.minecraft.world.entity.player.Inventory;
import net.minecraft.world.entity.player.Player;
import net.minecraft.world.inventory.AbstractContainerMenu;
import net.neoforged.neoforge.network.PacketDistributor;
import net.neoforged.neoforge.network.handling.PlayPayloadContext;
import net.neoforged.neoforge.network.handling.IPayloadContext;
import org.apache.logging.log4j.util.TriConsumer;
import javax.annotation.Nullable;
import java.util.ArrayList;
import java.util.List;
import static de.ellpeck.prettypipes.misc.DirectionSelector.IDirectionContainer;
public class PacketButton implements CustomPacketPayload {
public record PacketButton(BlockPos pos, int result, List<Integer> data) implements CustomPacketPayload {
public static final ResourceLocation ID = new ResourceLocation(PrettyPipes.ID, "button");
public static final Type<PacketButton> TYPE = new Type<>(ResourceLocation.fromNamespaceAndPath(PrettyPipes.ID, "button"));
public static final StreamCodec<RegistryFriendlyByteBuf, PacketButton> CODEC = StreamCodec.composite(
BlockPos.STREAM_CODEC, PacketButton::pos,
ByteBufCodecs.INT, PacketButton::result,
ByteBufCodecs.collection(ArrayList::new, ByteBufCodecs.INT), PacketButton::data,
PacketButton::new);
private final BlockPos pos;
private final ButtonResult result;
private final int[] data;
public PacketButton(BlockPos pos, ButtonResult result, int... data) {
this.pos = pos;
this.result = result;
this.data = data;
}
public PacketButton(FriendlyByteBuf buf) {
this.pos = buf.readBlockPos();
this.result = ButtonResult.values()[buf.readByte()];
this.data = buf.readVarIntArray();
public PacketButton(BlockPos pos, ButtonResult result, List<Integer> data) {
this(pos, result.ordinal(), data);
}
@Override
public void write(FriendlyByteBuf buf) {
buf.writeBlockPos(this.pos);
buf.writeByte(this.result.ordinal());
buf.writeVarIntArray(this.data);
public Type<? extends CustomPacketPayload> type() {
return PacketButton.TYPE;
}
@Override
public ResourceLocation id() {
return PacketButton.ID;
public static void onMessage(PacketButton message, IPayloadContext ctx) {
var player = ctx.player();
ButtonResult.values()[message.result].action.accept(message.pos, message.data, player);
}
public static void onMessage(PacketButton message, PlayPayloadContext ctx) {
ctx.workHandler().execute(() -> {
var player = ctx.player().orElseThrow();
message.result.action.accept(message.pos, message.data, player);
});
}
public static void sendAndExecute(BlockPos pos, ButtonResult result, int... data) {
PacketDistributor.SERVER.noArg().send(new PacketButton(pos, result, data));
public static void sendAndExecute(BlockPos pos, ButtonResult result, List<Integer> data) {
PacketDistributor.sendToServer(new PacketButton(pos, result, data));
result.action.accept(pos, data, Minecraft.getInstance().player);
}
public enum ButtonResult {
PIPE_TAB((pos, data, player) -> {
var tile = Utility.getBlockEntity(PipeBlockEntity.class, player.level(), pos);
if (data[0] < 0) {
if (data.getFirst() < 0) {
player.openMenu(tile, pos);
} else {
var stack = tile.modules.getStackInSlot(data[0]);
var stack = tile.modules.getStackInSlot(data.getFirst());
player.openMenu(new MenuProvider() {
@Override
public Component getDisplayName() {
@ -89,18 +77,18 @@ public class PacketButton implements CustomPacketPayload {
@Nullable
@Override
public AbstractContainerMenu createMenu(int windowId, Inventory inv, Player player) {
return ((IModule) stack.getItem()).getContainer(stack, tile, windowId, inv, player, data[0]);
return ((IModule) stack.getItem()).getContainer(stack, tile, windowId, inv, player, data.getFirst());
}
}, buf -> {
buf.writeBlockPos(pos);
buf.writeInt(data[0]);
buf.writeInt(data.getFirst());
});
}
}),
FILTER_CHANGE((pos, data, player) -> {
if (player.containerMenu instanceof IFilteredContainer filtered)
filtered.getFilter().onButtonPacket(filtered, data[0]);
filtered.getFilter().onButtonPacket(filtered, data.getFirst());
}),
STACK_SIZE_MODULE_BUTTON((pos, data, player) -> {
var container = (AbstractPipeContainer<?>) player.containerMenu;
@ -108,11 +96,11 @@ public class PacketButton implements CustomPacketPayload {
}),
STACK_SIZE_AMOUNT((pos, data, player) -> {
var container = (AbstractPipeContainer<?>) player.containerMenu;
StackSizeModuleItem.setMaxStackSize(container.moduleStack, data[0]);
StackSizeModuleItem.setMaxStackSize(container.moduleStack, data.getFirst());
}),
CRAFT_TERMINAL_REQUEST((pos, data, player) -> {
var tile = Utility.getBlockEntity(CraftingTerminalBlockEntity.class, player.level(), pos);
tile.requestCraftingItems(player, data[0], data[1] > 0);
tile.requestCraftingItems(player, data.getFirst(), data.get(1) > 0);
}),
CANCEL_CRAFTING((pos, data, player) -> {
var tile = Utility.getBlockEntity(ItemTerminalBlockEntity.class, player.level(), pos);
@ -120,16 +108,16 @@ public class PacketButton implements CustomPacketPayload {
}),
TAG_FILTER((pos, data, player) -> {
var container = (FilterModifierModuleContainer) player.containerMenu;
FilterModifierModuleItem.setFilterTag(container.moduleStack, container.getTags().get(data[0]));
FilterModifierModuleItem.setFilterTag(container.moduleStack, container.getTags().get(data.getFirst()));
}),
DIRECTION_SELECTOR((pos, data, player) -> {
if (player.containerMenu instanceof IDirectionContainer filtered)
filtered.getSelector().onButtonPacket();
});
public final TriConsumer<BlockPos, int[], Player> action;
public final TriConsumer<BlockPos, List<Integer>, Player> action;
ButtonResult(TriConsumer<BlockPos, int[], Player> action) {
ButtonResult(TriConsumer<BlockPos, List<Integer>, Player> action) {
this.action = action;
}
}

View file

@ -2,63 +2,40 @@ package de.ellpeck.prettypipes.packets;
import de.ellpeck.prettypipes.PrettyPipes;
import de.ellpeck.prettypipes.pipe.modules.craft.CraftingModuleContainer;
import net.minecraft.network.FriendlyByteBuf;
import net.minecraft.network.RegistryFriendlyByteBuf;
import net.minecraft.network.codec.ByteBufCodecs;
import net.minecraft.network.codec.StreamCodec;
import net.minecraft.network.protocol.common.custom.CustomPacketPayload;
import net.minecraft.resources.ResourceLocation;
import net.minecraft.world.item.ItemStack;
import net.neoforged.neoforge.items.ItemHandlerHelper;
import net.neoforged.neoforge.items.ItemStackHandler;
import net.neoforged.neoforge.network.handling.PlayPayloadContext;
import net.neoforged.neoforge.network.handling.IPayloadContext;
import java.util.ArrayList;
import java.util.List;
public class PacketCraftingModuleTransfer implements CustomPacketPayload {
public record PacketCraftingModuleTransfer(List<ItemStack> inputs, List<ItemStack> outputs) implements CustomPacketPayload {
public static final ResourceLocation ID = new ResourceLocation(PrettyPipes.ID, "crafting_module_transfer");
private final List<ItemStack> inputs;
private final List<ItemStack> outputs;
public PacketCraftingModuleTransfer(List<ItemStack> inputs, List<ItemStack> outputs) {
this.inputs = inputs;
this.outputs = outputs;
}
public PacketCraftingModuleTransfer(FriendlyByteBuf buf) {
this.inputs = new ArrayList<>();
for (var i = buf.readInt(); i > 0; i--)
this.inputs.add(buf.readItem());
this.outputs = new ArrayList<>();
for (var i = buf.readInt(); i > 0; i--)
this.outputs.add(buf.readItem());
}
public static final Type<PacketCraftingModuleTransfer> TYPE = new Type<>(ResourceLocation.fromNamespaceAndPath(PrettyPipes.ID, "crafting_module_transfer"));
public static final StreamCodec<RegistryFriendlyByteBuf, PacketCraftingModuleTransfer> CODEC = StreamCodec.composite(
ByteBufCodecs.collection(ArrayList::new, ItemStack.STREAM_CODEC), PacketCraftingModuleTransfer::inputs,
ByteBufCodecs.collection(ArrayList::new, ItemStack.STREAM_CODEC), PacketCraftingModuleTransfer::outputs,
PacketCraftingModuleTransfer::new);
@Override
public void write(FriendlyByteBuf buf) {
buf.writeInt(this.inputs.size());
for (var stack : this.inputs)
buf.writeItem(stack);
buf.writeInt(this.outputs.size());
for (var stack : this.outputs)
buf.writeItem(stack);
public Type<? extends CustomPacketPayload> type() {
return PacketCraftingModuleTransfer.TYPE;
}
@Override
public ResourceLocation id() {
return PacketCraftingModuleTransfer.ID;
}
public static void onMessage(PacketCraftingModuleTransfer message, PlayPayloadContext ctx) {
ctx.workHandler().execute(() -> {
var player = ctx.player().orElseThrow();
public static void onMessage(PacketCraftingModuleTransfer message, IPayloadContext ctx) {
var player = ctx.player();
if (player.containerMenu instanceof CraftingModuleContainer container) {
PacketCraftingModuleTransfer.copy(container.input, message.inputs);
PacketCraftingModuleTransfer.copy(container.output, message.outputs);
container.modified = true;
container.broadcastChanges();
}
});
}
private static void copy(ItemStackHandler container, List<ItemStack> contents) {

View file

@ -7,7 +7,9 @@ import de.ellpeck.prettypipes.Utility;
import de.ellpeck.prettypipes.terminal.CraftingTerminalBlockEntity;
import net.minecraft.core.BlockPos;
import net.minecraft.core.registries.Registries;
import net.minecraft.network.FriendlyByteBuf;
import net.minecraft.network.RegistryFriendlyByteBuf;
import net.minecraft.network.codec.ByteBufCodecs;
import net.minecraft.network.codec.StreamCodec;
import net.minecraft.network.protocol.common.custom.CustomPacketPayload;
import net.minecraft.resources.ResourceLocation;
import net.minecraft.tags.TagKey;
@ -15,78 +17,45 @@ import net.minecraft.world.item.Item;
import net.minecraft.world.item.ItemStack;
import net.minecraft.world.item.Items;
import net.minecraft.world.level.Level;
import net.neoforged.neoforge.network.handling.PlayPayloadContext;
import net.neoforged.neoforge.network.handling.IPayloadContext;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
public class PacketGhostSlot implements CustomPacketPayload {
public record PacketGhostSlot(BlockPos pos, List<Entry> stacks) implements CustomPacketPayload {
public static final ResourceLocation ID = new ResourceLocation(PrettyPipes.ID, "ghost_slot");
private final BlockPos pos;
private final List<Entry> stacks;
public PacketGhostSlot(BlockPos pos, List<Entry> stacks) {
this.pos = pos;
this.stacks = stacks;
}
public PacketGhostSlot(FriendlyByteBuf buf) {
this.pos = buf.readBlockPos();
this.stacks = new ArrayList<>();
for (var i = buf.readInt(); i > 0; i--)
this.stacks.add(new Entry(buf));
}
public static final Type<PacketGhostSlot> TYPE = new Type<>(ResourceLocation.fromNamespaceAndPath(PrettyPipes.ID, "ghost_slot"));
public static final StreamCodec<RegistryFriendlyByteBuf, PacketGhostSlot> CODEC = StreamCodec.composite(
BlockPos.STREAM_CODEC, PacketGhostSlot::pos,
ByteBufCodecs.collection(ArrayList::new, Entry.CODEC), PacketGhostSlot::stacks,
PacketGhostSlot::new);
@Override
public void write(FriendlyByteBuf buf) {
buf.writeBlockPos(this.pos);
buf.writeInt(this.stacks.size());
for (var entry : this.stacks)
entry.write(buf);
public Type<? extends CustomPacketPayload> type() {
return PacketGhostSlot.TYPE;
}
@Override
public ResourceLocation id() {
return PacketGhostSlot.ID;
}
public static void onMessage(PacketGhostSlot message, PlayPayloadContext ctx) {
ctx.workHandler().execute(() -> {
var player = ctx.player().orElseThrow();
public static void onMessage(PacketGhostSlot message, IPayloadContext ctx) {
var player = ctx.player();
var tile = Utility.getBlockEntity(CraftingTerminalBlockEntity.class, player.level(), message.pos);
if (tile != null)
tile.setGhostItems(message.stacks);
});
}
public static class Entry {
public record Entry(List<ItemStack> stacks, TagKey<Item> tag) {
private final List<ItemStack> stacks;
private final TagKey<Item> tag;
public static final StreamCodec<RegistryFriendlyByteBuf, Entry> CODEC = StreamCodec.composite(
ByteBufCodecs.collection(ArrayList::new, ItemStack.STREAM_CODEC), Entry::stacks,
ByteBufCodecs.fromCodec(TagKey.codec(Registries.ITEM)), Entry::tag,
Entry::new);
public Entry(Level level, List<ItemStack> stacks) {
public static Entry fromStacks(Level level, List<ItemStack> stacks) {
var tag = Entry.getTagForStacks(level, stacks);
if (tag != null) {
this.stacks = null;
this.tag = tag;
return new Entry(null, tag);
} else {
this.stacks = stacks;
this.tag = null;
}
}
public Entry(FriendlyByteBuf buf) {
if (buf.readBoolean()) {
this.tag = null;
this.stacks = new ArrayList<>();
for (var i = buf.readInt(); i > 0; i--)
this.stacks.add(buf.readItem());
} else {
this.stacks = null;
this.tag = TagKey.create(Registries.ITEM, new ResourceLocation(buf.readUtf()));
return new Entry(stacks, null);
}
}
@ -98,18 +67,6 @@ public class PacketGhostSlot implements CustomPacketPayload {
.map(h -> new ItemStack(h.value())).collect(Collectors.toList());
}
public void write(FriendlyByteBuf buf) {
if (this.stacks != null) {
buf.writeBoolean(true);
buf.writeInt(this.stacks.size());
for (var stack : this.stacks)
buf.writeItem(stack);
} else {
buf.writeBoolean(false);
buf.writeUtf(this.tag.location().toString());
}
}
private static TagKey<Item> getTagForStacks(Level level, List<ItemStack> stacks) {
return level.registryAccess().registry(Registries.ITEM).orElseThrow().getTags().filter(e -> {
var tag = e.getSecond();

View file

@ -7,41 +7,27 @@ import de.ellpeck.prettypipes.pipe.PipeBlockEntity;
import net.minecraft.client.Minecraft;
import net.minecraft.core.BlockPos;
import net.minecraft.nbt.CompoundTag;
import net.minecraft.network.FriendlyByteBuf;
import net.minecraft.network.RegistryFriendlyByteBuf;
import net.minecraft.network.codec.ByteBufCodecs;
import net.minecraft.network.codec.StreamCodec;
import net.minecraft.network.protocol.common.custom.CustomPacketPayload;
import net.minecraft.resources.ResourceLocation;
import net.neoforged.neoforge.network.handling.PlayPayloadContext;
import net.neoforged.neoforge.network.handling.IPayloadContext;
public class PacketItemEnterPipe implements CustomPacketPayload {
public record PacketItemEnterPipe(BlockPos tilePos, CompoundTag item) implements CustomPacketPayload {
public static final ResourceLocation ID = new ResourceLocation(PrettyPipes.ID, "item_enter_pipe");
private final BlockPos tilePos;
private final CompoundTag item;
public PacketItemEnterPipe(BlockPos tilePos, IPipeItem item) {
this.tilePos = tilePos;
this.item = item.serializeNBT();
}
public PacketItemEnterPipe(FriendlyByteBuf buf) {
this.tilePos = buf.readBlockPos();
this.item = buf.readNbt();
}
public static final Type<PacketItemEnterPipe> TYPE = new Type<>(ResourceLocation.fromNamespaceAndPath(PrettyPipes.ID, "item_enter_pipe"));
public static final StreamCodec<RegistryFriendlyByteBuf, PacketItemEnterPipe> CODEC = StreamCodec.composite(
BlockPos.STREAM_CODEC, PacketItemEnterPipe::tilePos,
ByteBufCodecs.COMPOUND_TAG, PacketItemEnterPipe::item,
PacketItemEnterPipe::new);
@Override
public void write(FriendlyByteBuf buf) {
buf.writeBlockPos(this.tilePos);
buf.writeNbt(this.item);
public Type<? extends CustomPacketPayload> type() {
return PacketItemEnterPipe.TYPE;
}
@Override
public ResourceLocation id() {
return PacketItemEnterPipe.ID;
}
public static void onMessage(PacketItemEnterPipe message, PlayPayloadContext ctx) {
ctx.workHandler().execute(() -> {
public static void onMessage(PacketItemEnterPipe message, IPayloadContext ctx) {
var mc = Minecraft.getInstance();
if (mc.level == null)
return;
@ -49,7 +35,6 @@ public class PacketItemEnterPipe implements CustomPacketPayload {
var pipe = Utility.getBlockEntity(PipeBlockEntity.class, mc.level, message.tilePos);
if (pipe != null)
pipe.getItems().add(item);
});
}
}

View file

@ -3,76 +3,35 @@ package de.ellpeck.prettypipes.packets;
import de.ellpeck.prettypipes.PrettyPipes;
import de.ellpeck.prettypipes.terminal.containers.ItemTerminalGui;
import net.minecraft.client.Minecraft;
import net.minecraft.network.FriendlyByteBuf;
import net.minecraft.network.RegistryFriendlyByteBuf;
import net.minecraft.network.codec.ByteBufCodecs;
import net.minecraft.network.codec.StreamCodec;
import net.minecraft.network.protocol.common.custom.CustomPacketPayload;
import net.minecraft.resources.ResourceLocation;
import net.minecraft.world.item.ItemStack;
import net.neoforged.neoforge.network.handling.PlayPayloadContext;
import net.neoforged.neoforge.network.handling.IPayloadContext;
import java.util.ArrayList;
import java.util.List;
public class PacketNetworkItems implements CustomPacketPayload {
public record PacketNetworkItems(List<ItemStack> items, List<ItemStack> craftables, List<ItemStack> currentlyCrafting) implements CustomPacketPayload {
public static final ResourceLocation ID = new ResourceLocation(PrettyPipes.ID, "network_items");
private final List<ItemStack> items;
private final List<ItemStack> craftables;
private final List<ItemStack> currentlyCrafting;
public PacketNetworkItems(List<ItemStack> items, List<ItemStack> craftables, List<ItemStack> currentlyCrafting) {
this.items = items;
this.craftables = craftables;
this.currentlyCrafting = currentlyCrafting;
}
public PacketNetworkItems(FriendlyByteBuf buf) {
this.items = new ArrayList<>();
for (var i = buf.readVarInt(); i > 0; i--) {
var stack = buf.readItem();
stack.setCount(buf.readVarInt());
this.items.add(stack);
}
this.craftables = new ArrayList<>();
for (var i = buf.readVarInt(); i > 0; i--)
this.craftables.add(buf.readItem());
this.currentlyCrafting = new ArrayList<>();
for (var i = buf.readVarInt(); i > 0; i--)
this.currentlyCrafting.add(buf.readItem());
}
public static final Type<PacketNetworkItems> TYPE = new Type<>(ResourceLocation.fromNamespaceAndPath(PrettyPipes.ID, "network_items"));
public static final StreamCodec<RegistryFriendlyByteBuf, PacketNetworkItems> CODEC = StreamCodec.composite(
ByteBufCodecs.collection(ArrayList::new, ItemStack.STREAM_CODEC), PacketNetworkItems::items,
ByteBufCodecs.collection(ArrayList::new, ItemStack.STREAM_CODEC), PacketNetworkItems::craftables,
ByteBufCodecs.collection(ArrayList::new, ItemStack.STREAM_CODEC), PacketNetworkItems::currentlyCrafting,
PacketNetworkItems::new);
@Override
public void write(FriendlyByteBuf buf) {
buf.writeVarInt(this.items.size());
for (var stack : this.items) {
var copy = stack.copy();
copy.setCount(1);
buf.writeItem(copy);
buf.writeVarInt(stack.getCount());
}
buf.writeVarInt(this.craftables.size());
for (var stack : this.craftables)
buf.writeItem(stack);
buf.writeVarInt(this.currentlyCrafting.size());
for (var stack : this.currentlyCrafting)
buf.writeItem(stack);
public Type<? extends CustomPacketPayload> type() {
return PacketNetworkItems.TYPE;
}
@Override
public ResourceLocation id() {
return PacketNetworkItems.ID;
}
@SuppressWarnings("Convert2Lambda")
public static void onMessage(PacketNetworkItems message, PlayPayloadContext ctx) {
ctx.workHandler().execute(new Runnable() {
@Override
public void run() {
public static void onMessage(PacketNetworkItems message, IPayloadContext ctx) {
var mc = Minecraft.getInstance();
if (mc.screen instanceof ItemTerminalGui terminal)
terminal.updateItemList(message.items, message.craftables, message.currentlyCrafting);
}
});
}
}

View file

@ -4,59 +4,39 @@ import de.ellpeck.prettypipes.PrettyPipes;
import de.ellpeck.prettypipes.Utility;
import de.ellpeck.prettypipes.terminal.ItemTerminalBlockEntity;
import net.minecraft.core.BlockPos;
import net.minecraft.network.FriendlyByteBuf;
import net.minecraft.network.RegistryFriendlyByteBuf;
import net.minecraft.network.codec.ByteBufCodecs;
import net.minecraft.network.codec.StreamCodec;
import net.minecraft.network.protocol.common.custom.CustomPacketPayload;
import net.minecraft.resources.ResourceLocation;
import net.minecraft.world.item.ItemStack;
import net.neoforged.neoforge.network.handling.PlayPayloadContext;
import net.neoforged.neoforge.network.handling.IPayloadContext;
public class PacketRequest implements CustomPacketPayload {
public record PacketRequest(BlockPos pos, ItemStack stack, int nbtHash, int amount) implements CustomPacketPayload {
public static final ResourceLocation ID = new ResourceLocation(PrettyPipes.ID, "request");
private final BlockPos pos;
private final ItemStack stack;
private final int nbtHash;
private final int amount;
public static final Type<PacketRequest> TYPE = new Type<>(ResourceLocation.fromNamespaceAndPath(PrettyPipes.ID, "request"));
public static final StreamCodec<RegistryFriendlyByteBuf, PacketRequest> CODEC = StreamCodec.composite(
BlockPos.STREAM_CODEC, PacketRequest::pos,
ItemStack.STREAM_CODEC, PacketRequest::stack,
ByteBufCodecs.INT, PacketRequest::nbtHash,
ByteBufCodecs.INT, PacketRequest::amount,
PacketRequest::new);
public PacketRequest(BlockPos pos, ItemStack stack, int amount) {
this.pos = pos;
this.stack = stack;
this.nbtHash = stack.hasTag() ? stack.getTag().hashCode() : 0;
this.amount = amount;
}
public PacketRequest(FriendlyByteBuf buf) {
this.pos = buf.readBlockPos();
this.stack = buf.readItem();
this.nbtHash = buf.readVarInt();
this.amount = buf.readVarInt();
this(pos, stack, stack.hasTag() ? stack.getTag().hashCode() : 0, amount);
}
@Override
public void write(FriendlyByteBuf buf) {
buf.writeBlockPos(this.pos);
buf.writeItem(this.stack);
buf.writeVarInt(this.nbtHash);
buf.writeVarInt(this.amount);
public Type<? extends CustomPacketPayload> type() {
return PacketRequest.TYPE;
}
@Override
public ResourceLocation id() {
return PacketRequest.ID;
}
@SuppressWarnings("Convert2Lambda")
public static void onMessage(PacketRequest message, PlayPayloadContext ctx) {
ctx.workHandler().execute(new Runnable() {
@Override
public void run() {
var player = ctx.player().orElseThrow();
public static void onMessage(PacketRequest message, IPayloadContext ctx) {
var player = ctx.player();
var tile = Utility.getBlockEntity(ItemTerminalBlockEntity.class, player.level(), message.pos);
message.stack.setCount(message.amount);
tile.requestItem(player, message.stack, message.nbtHash);
}
});
}
}

View file

@ -5,6 +5,7 @@ import de.ellpeck.prettypipes.network.NetworkEdge;
import de.ellpeck.prettypipes.network.PipeItem;
import net.minecraft.client.renderer.MultiBufferSource;
import net.minecraft.core.BlockPos;
import net.minecraft.core.HolderLookup;
import net.minecraft.nbt.CompoundTag;
import net.minecraft.resources.ResourceLocation;
import net.minecraft.world.item.ItemStack;
@ -12,17 +13,17 @@ import net.minecraft.world.level.Level;
import net.neoforged.api.distmarker.Dist;
import net.neoforged.api.distmarker.OnlyIn;
import net.neoforged.neoforge.common.util.INBTSerializable;
import org.apache.commons.lang3.function.TriFunction;
import org.jgrapht.GraphPath;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;
import java.util.function.BiFunction;
public interface IPipeItem extends INBTSerializable<CompoundTag> {
Map<ResourceLocation, BiFunction<ResourceLocation, CompoundTag, IPipeItem>> TYPES = new HashMap<>(
Map<ResourceLocation, TriFunction<HolderLookup.Provider, ResourceLocation, CompoundTag, IPipeItem>> TYPES = new HashMap<>(
Collections.singletonMap(PipeItem.TYPE, PipeItem::new));
ItemStack getContent();
@ -44,9 +45,10 @@ public interface IPipeItem extends INBTSerializable<CompoundTag> {
@OnlyIn(Dist.CLIENT)
void render(PipeBlockEntity tile, PoseStack matrixStack, Random random, float partialTicks, int light, int overlay, MultiBufferSource source);
static IPipeItem load(CompoundTag nbt) {
var type = new ResourceLocation(nbt.getString("type"));
static IPipeItem load(HolderLookup.Provider provider, CompoundTag nbt) {
var type = ResourceLocation.parse(nbt.getString("type"));
var func = IPipeItem.TYPES.get(type);
return func != null ? func.apply(type, nbt) : null;
return func != null ? func.apply(provider, type, nbt) : null;
}
}

View file

@ -10,7 +10,7 @@ import net.minecraft.core.BlockPos;
import net.minecraft.core.Direction;
import net.minecraft.tags.FluidTags;
import net.minecraft.world.InteractionHand;
import net.minecraft.world.InteractionResult;
import net.minecraft.world.ItemInteractionResult;
import net.minecraft.world.entity.LivingEntity;
import net.minecraft.world.entity.player.Player;
import net.minecraft.world.item.ItemStack;
@ -77,12 +77,12 @@ public class PipeBlock extends BaseEntityBlock implements SimpleWaterloggedBlock
}
@Override
public InteractionResult use(BlockState state, Level worldIn, BlockPos pos, Player player, InteractionHand handIn, BlockHitResult result) {
public ItemInteractionResult useItemOn(ItemStack pStack, BlockState state, Level worldIn, BlockPos pos, Player player, InteractionHand handIn, BlockHitResult result) {
var tile = Utility.getBlockEntity(PipeBlockEntity.class, worldIn, pos);
if (tile == null)
return InteractionResult.PASS;
return ItemInteractionResult.PASS_TO_DEFAULT_BLOCK_INTERACTION;
if (!tile.canHaveModules())
return InteractionResult.PASS;
return ItemInteractionResult.PASS_TO_DEFAULT_BLOCK_INTERACTION;
var stack = player.getItemInHand(handIn);
if (stack.getItem() instanceof IModule) {
var copy = stack.copy();
@ -90,14 +90,14 @@ public class PipeBlock extends BaseEntityBlock implements SimpleWaterloggedBlock
var remain = ItemHandlerHelper.insertItem(tile.modules, copy, false);
if (remain.isEmpty()) {
stack.shrink(1);
return InteractionResult.SUCCESS;
return ItemInteractionResult.SUCCESS;
}
} else if (handIn == InteractionHand.MAIN_HAND && stack.isEmpty()) {
if (!worldIn.isClientSide)
player.openMenu(tile, pos);
return InteractionResult.SUCCESS;
return ItemInteractionResult.SUCCESS;
}
return InteractionResult.PASS;
return ItemInteractionResult.PASS_TO_DEFAULT_BLOCK_INTERACTION;
}
@Override

View file

@ -97,7 +97,7 @@ public class PipeBlockEntity extends BlockEntity implements MenuProvider, IPipeC
super.saveAdditional(compound, provider);
compound.put("modules", this.modules.serializeNBT(provider));
compound.putInt("module_drop_check", this.moduleDropCheck);
compound.put("requests", Utility.serializeAll(this.craftIngredientRequests));
compound.put("requests", Utility.serializeAll(provider, this.craftIngredientRequests));
if (this.cover != null)
compound.put("cover", NbtUtils.writeBlockState(this.cover));
var results = new ListTag();
@ -132,7 +132,7 @@ public class PipeBlockEntity extends BlockEntity implements MenuProvider, IPipeC
public CompoundTag getUpdateTag(HolderLookup.Provider provider) {
// sync pipe items on load
var nbt = this.saveWithoutMetadata(provider);
nbt.put("items", Utility.serializeAll(this.getItems()));
nbt.put("items", Utility.serializeAll(provider, this.getItems()));
return nbt;
}

View file

@ -144,7 +144,7 @@ public abstract class AbstractPipeGui<T extends AbstractPipeContainer<?>> extend
return false;
if (mouseX < this.x || mouseY < this.y || mouseX >= this.x + 28 || mouseY >= this.y + 32)
return false;
PacketDistributor.sendToServer(new PacketButton(AbstractPipeGui.this.menu.tile.getBlockPos(), PacketButton.ButtonResult.PIPE_TAB, this.index));
PacketDistributor.sendToServer(new PacketButton(AbstractPipeGui.this.menu.tile.getBlockPos(), PacketButton.ButtonResult.PIPE_TAB, List.of(this.index)));
AbstractPipeGui.this.getMinecraft().getSoundManager().play(SimpleSoundInstance.forUI(SoundEvents.UI_BUTTON_CLICK, 1));
return true;
}

View file

@ -134,7 +134,7 @@ public class FilterModifierModuleGui extends AbstractPipeGui<FilterModifierModul
return false;
if (mouseX < this.x || mouseY < this.y || mouseX >= this.x + 140 || mouseY >= this.y + 12)
return false;
PacketButton.sendAndExecute(FilterModifierModuleGui.this.menu.tile.getBlockPos(), PacketButton.ButtonResult.TAG_FILTER, FilterModifierModuleGui.this.tags.indexOf(this.tag));
PacketButton.sendAndExecute(FilterModifierModuleGui.this.menu.tile.getBlockPos(), PacketButton.ButtonResult.TAG_FILTER, List.of(FilterModifierModuleGui.this.tags.indexOf(this.tag)));
FilterModifierModuleGui.this.getMinecraft().getSoundManager().play(SimpleSoundInstance.forUI(SoundEvents.UI_BUTTON_CLICK, 1));
return true;
}

View file

@ -11,6 +11,7 @@ import net.minecraft.client.resources.language.I18n;
import net.minecraft.network.chat.Component;
import net.minecraft.world.entity.player.Inventory;
import java.util.List;
import java.util.function.Supplier;
public class StackSizeModuleGui extends AbstractPipeGui<StackSizeModuleContainer> {
@ -40,11 +41,11 @@ public class StackSizeModuleGui extends AbstractPipeGui<StackSizeModuleContainer
if (s.isEmpty())
return;
var amount = Integer.parseInt(s);
PacketButton.sendAndExecute(this.menu.tile.getBlockPos(), ButtonResult.STACK_SIZE_AMOUNT, amount);
PacketButton.sendAndExecute(this.menu.tile.getBlockPos(), ButtonResult.STACK_SIZE_AMOUNT, List.of(amount));
});
Supplier<Component> buttonText = () -> Component.translatable("info." + PrettyPipes.ID + ".limit_to_max_" + (StackSizeModuleItem.getLimitToMaxStackSize(this.menu.moduleStack) ? "on" : "off"));
this.addRenderableWidget(Button.builder(buttonText.get(), b -> {
PacketButton.sendAndExecute(this.menu.tile.getBlockPos(), ButtonResult.STACK_SIZE_MODULE_BUTTON);
PacketButton.sendAndExecute(this.menu.tile.getBlockPos(), ButtonResult.STACK_SIZE_MODULE_BUTTON, List.of());
b.setMessage(buttonText.get());
}).bounds(this.leftPos + 7, this.topPos + 17 + 32 + 10 + 22, 120, 20).build());
}
@ -55,4 +56,5 @@ public class StackSizeModuleGui extends AbstractPipeGui<StackSizeModuleContainer
graphics.drawString(this.font, I18n.get("info." + PrettyPipes.ID + ".max_stack_size") + ":", 7, 17 + 32, 4210752, false);
}
}

View file

@ -6,12 +6,11 @@ import de.ellpeck.prettypipes.Utility;
import net.minecraft.core.BlockPos;
import net.minecraft.core.registries.BuiltInRegistries;
import net.minecraft.network.chat.Component;
import net.minecraft.world.InteractionHand;
import net.minecraft.world.InteractionResult;
import net.minecraft.world.entity.player.Player;
import net.minecraft.world.item.Item;
import net.minecraft.world.item.ItemStack;
import net.minecraft.world.item.TooltipFlag;
import net.minecraft.world.level.BlockGetter;
import net.minecraft.world.level.Level;
import net.minecraft.world.level.block.BaseEntityBlock;
import net.minecraft.world.level.block.RenderShape;
@ -22,7 +21,6 @@ import net.minecraft.world.level.block.state.BlockBehaviour;
import net.minecraft.world.level.block.state.BlockState;
import net.minecraft.world.phys.BlockHitResult;
import javax.annotation.Nullable;
import java.util.List;
public class PressurizerBlock extends BaseEntityBlock {
@ -39,7 +37,7 @@ public class PressurizerBlock extends BaseEntityBlock {
}
@Override
public InteractionResult use(BlockState state, Level worldIn, BlockPos pos, Player player, InteractionHand handIn, BlockHitResult result) {
public InteractionResult useWithoutItem(BlockState state, Level worldIn, BlockPos pos, Player player, BlockHitResult result) {
var tile = Utility.getBlockEntity(PressurizerBlockEntity.class, worldIn, pos);
if (tile == null)
return InteractionResult.PASS;
@ -60,8 +58,8 @@ public class PressurizerBlock extends BaseEntityBlock {
}
@Override
public void appendHoverText(ItemStack stack, @Nullable BlockGetter worldIn, List<Component> tooltip, TooltipFlag flagIn) {
Utility.addTooltip(BuiltInRegistries.BLOCK.getKey(this).getPath(), tooltip);
public void appendHoverText(ItemStack pStack, Item.TooltipContext pContext, List<Component> pTooltipComponents, TooltipFlag pTooltipFlag) {
Utility.addTooltip(BuiltInRegistries.BLOCK.getKey(this).getPath(), pTooltipComponents);
}
@org.jetbrains.annotations.Nullable

View file

@ -13,6 +13,7 @@ import de.ellpeck.prettypipes.terminal.containers.CraftingTerminalContainer;
import net.minecraft.ChatFormatting;
import net.minecraft.core.BlockPos;
import net.minecraft.core.Direction;
import net.minecraft.core.HolderLookup;
import net.minecraft.nbt.CompoundTag;
import net.minecraft.network.chat.Component;
import net.minecraft.network.chat.Style;
@ -99,7 +100,7 @@ public class CraftingTerminalBlockEntity extends ItemTerminalBlockEntity {
if (!this.level.isClientSide) {
List<PacketGhostSlot.Entry> clients = new ArrayList<>();
for (var i = 0; i < this.ghostItems.getSlots(); i++)
clients.add(new PacketGhostSlot.Entry(this.level, Collections.singletonList(this.ghostItems.getStackInSlot(i))));
clients.add(PacketGhostSlot.Entry.fromStacks(this.level, List.of(this.ghostItems.getStackInSlot(i))));
PacketDistributor.sendToPlayersTrackingChunk((ServerLevel) this.level, new ChunkPos(this.getBlockPos()), new PacketGhostSlot(this.getBlockPos(), clients));
}
}
@ -139,15 +140,15 @@ public class CraftingTerminalBlockEntity extends ItemTerminalBlockEntity {
}
@Override
public void saveAdditional(CompoundTag compound) {
super.saveAdditional(compound);
compound.put("craft_items", this.craftItems.serializeNBT());
public void saveAdditional(CompoundTag compound, HolderLookup.Provider provider) {
super.saveAdditional(compound, provider);
compound.put("craft_items", this.craftItems.serializeNBT(provider));
}
@Override
public void load(CompoundTag compound) {
this.craftItems.deserializeNBT(compound.getCompound("craft_items"));
super.load(compound);
public void loadAdditional(CompoundTag compound, HolderLookup.Provider provider) {
this.craftItems.deserializeNBT(provider, compound.getCompound("craft_items"));
super.loadAdditional(compound, provider);
}
@Override

View file

@ -232,7 +232,7 @@ public class ItemTerminalBlockEntity extends BlockEntity implements IPipeConnect
public void saveAdditional(CompoundTag compound, HolderLookup.Provider pRegistries) {
super.saveAdditional(compound, pRegistries);
compound.put("items", this.items.serializeNBT(pRegistries));
compound.put("requests", Utility.serializeAll(this.existingRequests));
compound.put("requests", Utility.serializeAll(pRegistries, this.existingRequests));
}
@Override

View file

@ -11,6 +11,8 @@ import net.minecraft.resources.ResourceLocation;
import net.minecraft.world.entity.player.Inventory;
import net.neoforged.neoforge.network.PacketDistributor;
import java.util.Arrays;
public class CraftingTerminalGui extends ItemTerminalGui {
private static final ResourceLocation TEXTURE = ResourceLocation.fromNamespaceAndPath(PrettyPipes.ID, "textures/gui/crafting_terminal.png");
@ -28,7 +30,7 @@ public class CraftingTerminalGui extends ItemTerminalGui {
var amount = ItemTerminalGui.requestModifier();
// also allow holding backspace instead of alt for people whose alt key is inaccessible (linux?)
var force = Screen.hasAltDown() || InputConstants.isKeyDown(this.minecraft.getWindow().getWindow(), 259) ? 1 : 0;
PacketDistributor.sendToServer(new PacketButton(this.menu.tile.getBlockPos(), PacketButton.ButtonResult.CRAFT_TERMINAL_REQUEST, amount, force));
PacketDistributor.sendToServer(new PacketButton(this.menu.tile.getBlockPos(), PacketButton.ButtonResult.CRAFT_TERMINAL_REQUEST, Arrays.asList(amount, force)));
}).bounds(this.leftPos + 8, this.topPos + 100, 50, 20).build());
this.tick();
}

View file

@ -161,7 +161,7 @@ public class ItemTerminalGui extends AbstractContainerScreen<ItemTerminalContain
// and vanilla buttons are activated when the click starts, so we'll always invoke jei accidentally by default
if (button == 0 && this.cancelCraftingButton.visible && this.cancelCraftingButton.isHovered()) {
if (this.currentlyCrafting != null && !this.currentlyCrafting.isEmpty()) {
PacketDistributor.sendToServer(new PacketButton(this.menu.tile.getBlockPos(), PacketButton.ButtonResult.CANCEL_CRAFTING));
PacketDistributor.sendToServer(new PacketButton(this.menu.tile.getBlockPos(), PacketButton.ButtonResult.CANCEL_CRAFTING, List.of()));
return true;
}
}