Skip to content

Commit

Permalink
Is this even right?
Browse files Browse the repository at this point in the history
  • Loading branch information
DrexHD authored and modmuss50 committed Jan 21, 2024
1 parent 85601af commit a0fcc00
Show file tree
Hide file tree
Showing 14 changed files with 163 additions and 45 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,9 @@
import java.util.HashMap;
import java.util.Map;

import net.minecraft.client.MinecraftClient;
import net.minecraft.network.codec.RegistryByteBuf;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

Expand Down Expand Up @@ -63,13 +66,15 @@ public <C extends ScreenHandler> void registerFactory(Identifier identifier, Con
}

public static void init() {
ClientPlayNetworking.registerGlobalReceiver(ContainerProviderImpl.OPEN_CONTAINER, (client, handler, buf, responseSender) -> {
Identifier identifier = buf.readIdentifier();
int syncId = buf.readUnsignedByte();
ClientPlayNetworking.registerGlobalReceiver(ContainerProviderImpl.ContainerOpenPayload.ID, (payload, player, responseSender) -> {
Identifier identifier = payload.identifier();
int syncId = payload.syncId();
RegistryByteBuf buf = payload.registryByteBuf();

// Retain the buf since we must open the screen handler with it's extra modded data on the client thread
buf.retain();

MinecraftClient client = MinecraftClient.getInstance();
client.execute(() -> {
try {
ContainerFactory<HandledScreen> factory = FACTORIES.get(identifier);
Expand All @@ -79,7 +84,7 @@ public static void init() {
return;
}

ClientPlayerEntity player = client.player;
// ClientPlayerEntity player = client.player;
HandledScreen<?> gui = factory.create(syncId, identifier, player, buf);

player.currentScreenHandler = gui.getScreenHandler();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@

import net.minecraft.entity.player.PlayerEntity;
import net.minecraft.network.PacketByteBuf;
import net.minecraft.network.codec.RegistryByteBuf;
import net.minecraft.screen.ScreenHandler;
import net.minecraft.server.network.ServerPlayerEntity;
import net.minecraft.util.Identifier;
Expand Down Expand Up @@ -48,7 +49,7 @@ public interface ContainerProviderRegistry {
* @param player the player that should open the container
* @param writer a PacketByteBuf where data can be written to, this data is then accessible by the container factory when creating the container or the gui
*/
void openContainer(Identifier identifier, ServerPlayerEntity player, Consumer<PacketByteBuf> writer);
void openContainer(Identifier identifier, ServerPlayerEntity player, Consumer<RegistryByteBuf> writer);

/**
* Open a modded container. This should be called on the server side - it has no effect on the client side.
Expand All @@ -57,5 +58,5 @@ public interface ContainerProviderRegistry {
* @param player the player that should open the container
* @param writer a PacketByteBuf where data can be written to, this data is then accessible by the container factory when creating the container or the gui
*/
void openContainer(Identifier identifier, PlayerEntity player, Consumer<PacketByteBuf> writer);
void openContainer(Identifier identifier, PlayerEntity player, Consumer<RegistryByteBuf> writer);
}
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,15 @@
import java.util.function.Consumer;

import io.netty.buffer.Unpooled;

import net.fabricmc.fabric.api.networking.v1.PayloadTypeRegistry;
import net.fabricmc.fabric.impl.networking.CommonVersionPayload;

import net.minecraft.network.NetworkSide;
import net.minecraft.network.codec.PacketCodec;
import net.minecraft.network.codec.RegistryByteBuf;
import net.minecraft.network.packet.CustomPayload;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

Expand All @@ -36,12 +45,15 @@
import net.fabricmc.fabric.mixin.container.ServerPlayerEntityAccessor;

public class ContainerProviderImpl implements ContainerProviderRegistry {
public static final Identifier OPEN_CONTAINER = new Identifier("fabric", "container/open");

private static final Logger LOGGER = LoggerFactory.getLogger(ContainerProviderImpl.class);

private static final Map<Identifier, ContainerFactory<ScreenHandler>> FACTORIES = new HashMap<>();

public static void init() {
PayloadTypeRegistry.play(NetworkSide.SERVERBOUND).register(ContainerOpenPayload.ID, ContainerOpenPayload.CODEC);
}

@Override
public void registerFactory(Identifier identifier, ContainerFactory<ScreenHandler> factory) {
if (FACTORIES.containsKey(identifier)) {
Expand All @@ -52,7 +64,7 @@ public void registerFactory(Identifier identifier, ContainerFactory<ScreenHandle
}

@Override
public void openContainer(Identifier identifier, PlayerEntity player, Consumer<PacketByteBuf> writer) {
public void openContainer(Identifier identifier, PlayerEntity player, Consumer<RegistryByteBuf> writer) {
if (!(player instanceof ServerPlayerEntity)) {
LOGGER.warn("Please only use ContainerProviderRegistry.openContainer() with server-sided player entities!");
return;
Expand All @@ -64,7 +76,7 @@ public void openContainer(Identifier identifier, PlayerEntity player, Consumer<P
private boolean emittedNoSyncHookWarning = false;

@Override
public void openContainer(Identifier identifier, ServerPlayerEntity player, Consumer<PacketByteBuf> writer) {
public void openContainer(Identifier identifier, ServerPlayerEntity player, Consumer<RegistryByteBuf> writer) {
int syncId;

if (player instanceof ServerPlayerEntitySyncHook) {
Expand All @@ -82,16 +94,10 @@ public void openContainer(Identifier identifier, ServerPlayerEntity player, Cons
throw new RuntimeException("Neither ServerPlayerEntitySyncHook nor Accessor present! This should not happen!");
}

PacketByteBuf buf = new PacketByteBuf(Unpooled.buffer());
buf.writeIdentifier(identifier);
buf.writeByte(syncId);

RegistryByteBuf buf = new RegistryByteBuf(Unpooled.buffer(), player.server.getRegistryManager());
writer.accept(buf);
player.networkHandler.sendPacket(ServerPlayNetworking.createS2CPacket(OPEN_CONTAINER, buf));

PacketByteBuf clonedBuf = new PacketByteBuf(buf.duplicate());
clonedBuf.readIdentifier();
clonedBuf.readUnsignedByte();
player.networkHandler.sendPacket(ServerPlayNetworking.createS2CPacket(new ContainerOpenPayload(identifier, syncId, buf)));

ScreenHandler screenHandler = createContainer(syncId, identifier, player, clonedBuf);

Expand All @@ -114,4 +120,24 @@ public <C extends ScreenHandler> C createContainer(int syncId, Identifier identi
//noinspection unchecked
return (C) factory.create(syncId, identifier, player, buf);
}

public record ContainerOpenPayload(Identifier identifier, int syncId, RegistryByteBuf registryByteBuf) implements CustomPayload {
public static final PacketCodec<RegistryByteBuf, ContainerOpenPayload> CODEC = CustomPayload.codecOf(ContainerOpenPayload::write, ContainerOpenPayload::new);
public static final CustomPayload.Id<ContainerOpenPayload> ID = CustomPayload.id("fabric:container/open");

private ContainerOpenPayload(RegistryByteBuf buf) {
this(buf.readIdentifier(), buf.readByte(), buf);
}

private void write(RegistryByteBuf buf) {
buf.writeIdentifier(this.identifier);
buf.writeByte(this.syncId);
registryByteBuf.getBytes(registryByteBuf.readerIndex(), buf);
}

@Override
public Id<? extends CustomPayload> getId() {
return ID;
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,9 @@
"fabric-containers-v0.accurate.mixins.json"
],
"entrypoints": {
"main": [
"net.fabricmc.fabric.impl.container.ContainerProviderImpl::init"
],
"client": [
"net.fabricmc.fabric.impl.client.container.ScreenProviderRegistryImpl::init"
]
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,6 @@
import net.minecraft.network.ClientConnection;
import net.minecraft.network.NetworkSide;
import net.minecraft.network.PacketCallbacks;
import net.minecraft.network.listener.PacketListener;
import net.minecraft.network.packet.Packet;
import net.minecraft.server.network.ConnectedClientData;
import net.minecraft.server.network.ServerPlayNetworkHandler;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,6 @@

import org.jetbrains.annotations.Nullable;

import net.minecraft.network.PacketByteBuf;
import net.minecraft.network.listener.ClientCommonPacketListener;
import net.minecraft.network.packet.Packet;
import net.minecraft.server.MinecraftServer;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -33,8 +33,13 @@
import com.mojang.brigadier.tree.ArgumentCommandNode;
import com.mojang.brigadier.tree.LiteralCommandNode;

import net.fabricmc.fabric.api.networking.v1.PayloadTypeRegistry;

import net.minecraft.command.CommandSource;
import net.minecraft.command.EntitySelector;
import net.minecraft.network.NetworkSide;
import net.minecraft.network.codec.RegistryByteBuf;
import net.minecraft.network.packet.CustomPayload;
import net.minecraft.server.command.ServerCommandSource;
import net.minecraft.server.network.ServerPlayerEntity;
import net.minecraft.text.Text;
Expand Down Expand Up @@ -101,13 +106,17 @@ private static int registerChannel(CommandContext<ServerCommandSource> context,
throw new SimpleCommandExceptionType(Text.literal(String.format("Cannot register channel %s twice for server player", channel))).create();
}

ServerPlayNetworking.registerReceiver(executor.networkHandler, channel, (server, player, handler, buf, sender) -> {
System.out.printf("Received packet on channel %s%n", channel);
});

context.getSource().sendFeedback(() -> Text.literal(String.format("Registered channel %s for %s", channel, executor.getDisplayName())), false);
CustomPayload.Type<RegistryByteBuf, ? extends CustomPayload> payloadType = PayloadTypeRegistry.play(NetworkSide.SERVERBOUND).get(channel);
if (payloadType != null) {

return 1;
ServerPlayNetworking.registerReceiver(executor.networkHandler, payloadType.id(), (payload, player, sender) -> {
System.out.printf("Received packet on channel %s%n", payloadType.id().id());
});
context.getSource().sendFeedback(() -> Text.literal(String.format("Registered channel %s for %s", channel, executor.getDisplayName())), false);
return 1;
} else {
throw new SimpleCommandExceptionType(Text.literal("Unknown channel id")).create();
}
}

private static int unregisterChannel(CommandContext<ServerCommandSource> context, ServerPlayerEntity player) throws CommandSyntaxException {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,13 @@

package net.fabricmc.fabric.test.networking.keybindreciever;

import net.fabricmc.fabric.api.networking.v1.PayloadTypeRegistry;

import net.minecraft.network.NetworkSide;
import net.minecraft.network.PacketByteBuf;
import net.minecraft.network.codec.PacketCodec;
import net.minecraft.network.codec.RegistryByteBuf;
import net.minecraft.network.packet.CustomPayload;
import net.minecraft.server.MinecraftServer;
import net.minecraft.server.network.ServerPlayNetworkHandler;
import net.minecraft.server.network.ServerPlayerEntity;
Expand All @@ -35,12 +41,24 @@
public final class NetworkingKeybindPacketTest implements ModInitializer {
public static final Identifier KEYBINDING_PACKET_ID = NetworkingTestmods.id("keybind_press_test");

private static void receive(MinecraftServer server, ServerPlayerEntity player, ServerPlayNetworkHandler handler, PacketByteBuf buf, PacketSender responseSender) {
server.execute(() -> player.sendMessage(Text.literal("So you pressed ").append(Text.keybind("fabric-networking-api-v1-testmod-keybind").styled(style -> style.withFormatting(Formatting.BLUE))), false));
private static void receive(KeybindPayload payload, ServerPlayerEntity player, PacketSender responseSender) {
player.server.execute(() -> player.sendMessage(Text.literal("So you pressed ").append(Text.keybind("fabric-networking-api-v1-testmod-keybind").styled(style -> style.withFormatting(Formatting.BLUE))), false));
}

@Override
public void onInitialize() {
ServerPlayConnectionEvents.INIT.register((handler, server) -> ServerPlayNetworking.registerReceiver(handler, KEYBINDING_PACKET_ID, NetworkingKeybindPacketTest::receive));
PayloadTypeRegistry.play(NetworkSide.SERVERBOUND).register(KeybindPayload.ID, KeybindPayload.CODEC);
ServerPlayConnectionEvents.INIT.register((handler, server) -> ServerPlayNetworking.registerReceiver(handler, KeybindPayload.ID, NetworkingKeybindPacketTest::receive));
}

private record KeybindPayload() implements CustomPayload {
public static final CustomPayload.Id<KeybindPayload> ID = new CustomPayload.Id<>(KEYBINDING_PACKET_ID);
public static final PacketCodec<RegistryByteBuf, KeybindPayload> CODEC = CustomPayload.codecOf((value, buf) -> {}, buf -> new KeybindPayload());

@Override
public Id<? extends CustomPayload> getId() {
return ID;
}
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,9 @@
import com.mojang.brigadier.CommandDispatcher;
import com.mojang.brigadier.arguments.StringArgumentType;

import net.fabricmc.fabric.api.networking.v1.PayloadTypeRegistry;

import net.minecraft.network.NetworkSide;
import net.minecraft.network.PacketByteBuf;
import net.minecraft.network.codec.PacketCodec;
import net.minecraft.network.codec.RegistryByteBuf;
Expand Down Expand Up @@ -59,8 +62,8 @@ private static void sendToUnknownChannel(ServerPlayerEntity player) {
for (int i = 0; i < 20; i++) {
buf.writeUuid(UUID.randomUUID());
}

ServerPlayNetworking.getSender(player).sendPacket(UNKNOWN_TEST_CHANNEL, buf);
// TODO 1.20.5
// ServerPlayNetworking.getSender(player).sendPacket(UNKNOWN_TEST_CHANNEL, buf);
}

public static void registerCommand(CommandDispatcher<ServerCommandSource> dispatcher) {
Expand Down Expand Up @@ -92,8 +95,9 @@ public static void registerCommand(CommandDispatcher<ServerCommandSource> dispat
.then(literal("repeat").executes(ctx -> {
PacketByteBuf buf = PacketByteBufs.create();
buf.writeText(Text.literal("repeat"));
ServerPlayNetworking.send(ctx.getSource().getPlayer(), TEST_CHANNEL, buf);
ServerPlayNetworking.send(ctx.getSource().getPlayer(), TEST_CHANNEL, buf);
// TODO 1.20.5
// ServerPlayNetworking.send(ctx.getSource().getPlayer(), TEST_CHANNEL, buf);
// ServerPlayNetworking.send(ctx.getSource().getPlayer(), TEST_CHANNEL, buf);
return Command.SINGLE_SUCCESS;
}))
.then(literal("bundled").executes(ctx -> {
Expand All @@ -114,6 +118,7 @@ public static void registerCommand(CommandDispatcher<ServerCommandSource> dispat
public void onInitialize() {
NetworkingTestmods.LOGGER.info("Hello from networking user!");

PayloadTypeRegistry.play(NetworkSide.SERVERBOUND).register(OverlayPacket.ID, OverlayPacket.CODEC);
CommandRegistrationCallback.EVENT.register((dispatcher, registryAccess, environment) -> {
NetworkingPlayPacketTest.registerCommand(dispatcher);
});
Expand Down Expand Up @@ -146,7 +151,7 @@ public void write(PacketByteBuf buf) {

@Override
public Id<? extends CustomPayload> getId() {
return null;
return ID;
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -37,12 +37,13 @@ public final class NetworkingPlayPacketClientTest implements ClientModInitialize

@Override
public void onInitializeClient() {
ClientPlayConnectionEvents.INIT.register((handler, client) -> ClientPlayNetworking.registerReceiver(NetworkingPlayPacketTest.OverlayPacket.PACKET_TYPE, this));
ClientPlayConnectionEvents.INIT.register((handler, client) -> ClientPlayNetworking.registerReceiver(NetworkingPlayPacketTest.OverlayPacket.ID, this));

ClientCommandRegistrationCallback.EVENT.register((dispatcher, dedicated) -> dispatcher.register(
ClientCommandManager.literal("clientnetworktestcommand")
.then(ClientCommandManager.literal("unknown").executes(context -> {
ClientPlayNetworking.send(UNKNOWN_TEST_CHANNEL, PacketByteBufs.create());
// TODO 1.20.5
// ClientPlayNetworking.send(UNKNOWN_TEST_CHANNEL, PacketByteBufs.create());
return Command.SINGLE_SUCCESS;
}
))));
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -46,8 +46,8 @@ public class CustomIngredientImpl extends Ingredient {

public static final Codec<CustomIngredientSerializer<?>> CODEC = Identifier.CODEC.flatXmap(identifier ->
Optional.ofNullable(REGISTERED_SERIALIZERS.get(identifier))
.map(DataResult::success)
.orElseGet(() -> DataResult.error(() -> "Unknown custom ingredient serializer: " + identifier)),
.map(DataResult::success)
.orElseGet(() -> DataResult.error(() -> "Unknown custom ingredient serializer: " + identifier)),
serializer -> DataResult.success(serializer.getIdentifier())
);

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,13 @@

package net.fabricmc.fabric.impl.registry.sync;

import net.fabricmc.fabric.api.networking.v1.PayloadTypeRegistry;

import net.minecraft.network.NetworkSide;
import net.minecraft.network.PacketByteBuf;
import net.minecraft.network.codec.PacketCodec;
import net.minecraft.network.codec.RegistryByteBuf;
import net.minecraft.network.packet.CustomPayload;
import net.minecraft.registry.Registries;
import net.minecraft.util.Identifier;

Expand All @@ -30,8 +37,9 @@ public class FabricRegistryInit implements ModInitializer {

@Override
public void onInitialize() {
PayloadTypeRegistry.configuration(NetworkSide.SERVERBOUND).register(SyncCompletePayload.ID, SyncCompletePayload.CODEC);
ServerConfigurationConnectionEvents.BEFORE_CONFIGURE.register(RegistrySyncManager::configureClient);
ServerConfigurationNetworking.registerGlobalReceiver(SYNC_COMPLETE_ID, (server, handler, buf, responseSender) -> {
ServerConfigurationNetworking.registerGlobalReceiver(SyncCompletePayload.ID, (payload, handler, responseSender) -> {
handler.completeTask(RegistrySyncManager.SyncConfigurationTask.KEY);
});

Expand Down Expand Up @@ -194,4 +202,14 @@ public void onInitialize() {
RegistryAttributeHolder.get(Registries.GAME_EVENT)
.addAttribute(RegistryAttribute.SYNCED);
}

private record SyncCompletePayload() implements CustomPayload {
public static final CustomPayload.Id<SyncCompletePayload> ID = new CustomPayload.Id<>(SYNC_COMPLETE_ID);
public static final PacketCodec<PacketByteBuf, SyncCompletePayload> CODEC = CustomPayload.codecOf((value, buf) -> {}, buf -> new SyncCompletePayload());

@Override
public Id<? extends CustomPayload> getId() {
return ID;
}
}
}
Loading

0 comments on commit a0fcc00

Please sign in to comment.