Skip to content

Commit

Permalink
Allow client-optional components
Browse files Browse the repository at this point in the history
  • Loading branch information
Pyrofab committed Apr 15, 2024
1 parent a3223e0 commit 9481cba
Show file tree
Hide file tree
Showing 24 changed files with 127 additions and 70 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -31,13 +31,15 @@
import net.minecraft.network.codec.PacketCodecs;
import net.minecraft.network.packet.CustomPayload;
import net.minecraft.server.network.ServerPlayerEntity;
import net.minecraft.text.Text;
import net.minecraft.util.Identifier;
import org.jetbrains.annotations.ApiStatus;
import org.jetbrains.annotations.Contract;
import org.jetbrains.annotations.Nullable;
import org.ladysnake.cca.api.v3.component.sync.AutoSyncedComponent;
import org.ladysnake.cca.api.v3.component.sync.ComponentPacketWriter;
import org.ladysnake.cca.api.v3.component.sync.PlayerSyncPredicate;
import org.ladysnake.cca.internal.base.ComponentsInternals;
import org.ladysnake.cca.internal.base.asm.CcaBootstrap;

import java.util.NoSuchElementException;
Expand Down Expand Up @@ -209,10 +211,17 @@ public void syncWith(ServerPlayerEntity player, ComponentProvider provider, Comp
if (predicate.shouldSyncWith(player)) {
RegistryByteBuf buf = new RegistryByteBuf(Unpooled.buffer(), player.getServerWorld().getRegistryManager());
writer.writeSyncPacket(buf, player);
CustomPayload payload = provider.toComponentPacket(this, buf);
CustomPayload payload = provider.toComponentPacket(this, !predicate.isSyncOptional(), buf);

if (payload != null) {
ServerPlayNetworking.getSender(player).sendPacket(payload, PacketCallbacks.always(buf::release));
if (ServerPlayNetworking.canSend(player, payload.getId())) {
ServerPlayNetworking.getSender(player).sendPacket(payload, PacketCallbacks.always(buf::release));
} else {
if (!predicate.isSyncOptional()) {
player.networkHandler.disconnect(Text.literal("This server requires Cardinal Components API (unhandled packet: " + payload.getId().id() + ")" + ComponentsInternals.getClientOptionalModAdvice()));
}
buf.release();
}
} else {
buf.release();
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -26,11 +26,11 @@
import net.minecraft.network.RegistryByteBuf;
import net.minecraft.network.packet.CustomPayload;
import net.minecraft.server.network.ServerPlayerEntity;
import org.jetbrains.annotations.Nullable;
import org.ladysnake.cca.api.v3.component.sync.AutoSyncedComponent;
import org.ladysnake.cca.api.v3.component.sync.PlayerSyncPredicate;
import org.ladysnake.cca.internal.base.ComponentUpdatePayload;

import javax.annotation.Nullable;
import java.util.List;

/**
Expand Down Expand Up @@ -64,13 +64,14 @@ default Iterable<ServerPlayerEntity> getRecipientsForComponentSync() {
*
* <p>It is the responsibility of the caller to {@link ByteBuf#release() release} the buffer after this method returns.
*
* @param key the key describing the component being synchronized
* @param data the component's raw sync data
* @param key the key describing the component being synchronized
* @param required {@code true} if attempting to sync a component key unknown to the client should disconnect it
* @param data the component's raw sync data
* @return a {@link ComponentUpdatePayload} that has all the information required to perform the component sync
* @since 6.0.0
*/
@Nullable
default <C extends AutoSyncedComponent> CustomPayload toComponentPacket(ComponentKey<? super C> key, RegistryByteBuf data) {
default <C extends AutoSyncedComponent> CustomPayload toComponentPacket(ComponentKey<? super C> key, boolean required, RegistryByteBuf data) {
return null;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,14 @@ public interface PlayerSyncPredicate {
@Contract(pure = true)
boolean shouldSyncWith(ServerPlayerEntity player);

/**
* If this method returns {@code true} and a client cannot handle a sync packet, the sync will be skipped.
* Otherwise, a sync update will disconnect the client.
*/
default boolean isSyncOptional() {
return false;
}

static PlayerSyncPredicate all() {
return p -> true;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -24,25 +24,27 @@

import net.fabricmc.fabric.api.client.networking.v1.ClientPlayNetworking;
import net.minecraft.network.packet.CustomPayload;
import net.minecraft.text.Text;
import org.ladysnake.cca.api.v3.component.Component;
import org.ladysnake.cca.api.v3.component.sync.AutoSyncedComponent;

import java.util.Optional;
import java.util.function.BiFunction;

public final class CcaClientInternals {
public static <T extends org.ladysnake.cca.internal.base.ComponentUpdatePayload<?>> void registerComponentSync(CustomPayload.Id<T> packetId, BiFunction<T, ClientPlayNetworking.Context, Optional<? extends Component>> getter) {
public static <T extends ComponentUpdatePayload<?>> void registerComponentSync(CustomPayload.Id<T> packetId, BiFunction<T, ClientPlayNetworking.Context, Optional<? extends Component>> getter) {
ClientPlayNetworking.registerGlobalReceiver(packetId, (payload, ctx) -> {
try {
getter.apply(payload, ctx).ifPresent(c -> {
if (c instanceof AutoSyncedComponent synced) {
synced.applySyncPacket(payload.buf());
}
});
} catch (UnknownComponentException e) {
ctx.player().networkHandler.onDisconnected(Text.literal(e.getMessage() + "\n(you are probably missing a mod installed on the server)" + ComponentsInternals.getClientOptionalModAdvice()));
} finally {
payload.buf().release();
}
});
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -25,13 +25,19 @@
import net.fabricmc.fabric.api.networking.v1.PayloadTypeRegistry;
import net.minecraft.network.RegistryByteBuf;
import net.minecraft.network.codec.PacketCodec;
import net.minecraft.network.codec.PacketCodecs;
import net.minecraft.network.packet.CustomPayload;
import net.minecraft.util.Identifier;
import org.ladysnake.cca.api.v3.component.ComponentKey;
import org.ladysnake.cca.api.v3.component.ComponentRegistry;

import java.util.Optional;

public record ComponentUpdatePayload<T>(
Id<ComponentUpdatePayload<T>> id,
T targetData,
ComponentKey<?> componentKey,
boolean required,
Identifier componentKeyId,
RegistryByteBuf buf
) implements CustomPayload {
public static <T> CustomPayload.Id<ComponentUpdatePayload<T>> id(String path) {
Expand All @@ -43,15 +49,24 @@ public static <T> void register(Id<ComponentUpdatePayload<T>> id, PacketCodec<?
}

public static <T> PacketCodec<RegistryByteBuf, ComponentUpdatePayload<T>> codec(Id<ComponentUpdatePayload<T>> id, PacketCodec<? super RegistryByteBuf, T> targetDataCodec) {
return org.ladysnake.cca.internal.base.MorePacketCodecs.tuple(
return PacketCodec.tuple(
PacketCodec.unit(id), ComponentUpdatePayload::id,
targetDataCodec, ComponentUpdatePayload::targetData,
ComponentKey.PACKET_CODEC, ComponentUpdatePayload::componentKey,
org.ladysnake.cca.internal.base.MorePacketCodecs.REG_BYTE_BUF, ComponentUpdatePayload::buf,
PacketCodecs.BOOL, ComponentUpdatePayload::required,
Identifier.PACKET_CODEC, ComponentUpdatePayload::componentKeyId,
MorePacketCodecs.REG_BYTE_BUF, ComponentUpdatePayload::buf,
ComponentUpdatePayload::new
);
}

public Optional<ComponentKey<?>> componentKey() {
ComponentKey<?> key = ComponentRegistry.get(this.componentKeyId());
if (key == null && this.required()) {
throw new UnknownComponentException("Unknown component " + this.componentKeyId());
}
return Optional.ofNullable(key);
}

@Override
public Id<? extends CustomPayload> getId() {
return id;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@
import net.minecraft.util.Identifier;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.jetbrains.annotations.NotNull;
import org.ladysnake.cca.api.v3.component.ComponentRegistry;
import org.ladysnake.cca.internal.base.asm.StaticComponentLoadingException;

Expand Down Expand Up @@ -93,4 +94,8 @@ public static void logDeserializationWarnings(Collection<String> missedKeyIds) {
}
}
}

public static @NotNull String getClientOptionalModAdvice() {
return FabricLoader.getInstance().isDevelopmentEnvironment() ? "\n§eDEV ADVICE: If your mod is supposed to be client-optional, try overriding isSyncOptional() in your component." : "";
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,6 @@
*/
package org.ladysnake.cca.internal.base;

import com.mojang.datafixers.util.Function4;
import com.mojang.datafixers.util.Unit;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
Expand All @@ -31,8 +30,6 @@
import net.minecraft.network.codec.PacketCodec;
import net.minecraft.util.math.ChunkPos;

import java.util.function.Function;

public final class MorePacketCodecs {
public static final PacketCodec<ByteBuf, Unit> EMPTY = PacketCodec.unit(Unit.INSTANCE);

Expand All @@ -59,35 +56,4 @@ public final class MorePacketCodecs {
PacketByteBuf::writeChunkPos,
PacketByteBuf::readChunkPos
);

/**
* {@return a codec for encoding three values}
*/
public static <B, C, T1, T2, T3, T4> PacketCodec<B, C> tuple(
PacketCodec<? super B, T1> codec1,
Function<C, T1> from1,
PacketCodec<? super B, T2> codec2,
Function<C, T2> from2,
PacketCodec<? super B, T3> codec3,
Function<C, T3> from3,
PacketCodec<? super B, T4> codec4,
Function<C, T4> from4,
Function4<T1, T2, T3, T4, C> to
) {
return PacketCodec.ofStatic(
(buf, value) -> {
codec1.encode(buf, from1.apply(value));
codec2.encode(buf, from2.apply(value));
codec3.encode(buf, from3.apply(value));
codec4.encode(buf, from4.apply(value));
},
(buf) -> {
T1 object2 = codec1.decode(buf);
T2 object3 = codec2.decode(buf);
T3 object4 = codec3.decode(buf);
T4 object5 = codec4.decode(buf);
return to.apply(object2, object3, object4, object5);
}
);
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
/*
* Cardinal-Components-API
* Copyright (C) 2019-2024 Ladysnake
*
* 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 org.ladysnake.cca.internal.base;

public class UnknownComponentException extends RuntimeException {
public UnknownComponentException(String message) {
super(message);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -31,11 +31,11 @@ public class CcaBlockClient {
public static void initClient() {
if (FabricLoader.getInstance().isModLoaded("fabric-networking-api-v1")) {
CcaClientInternals.registerComponentSync(CardinalComponentsBlock.PACKET_ID,
(payload, ctx) -> payload.componentKey().maybeGet(payload.targetData().beType().get(
(payload, ctx) -> payload.componentKey().flatMap(key -> key.maybeGet(payload.targetData().beType().get(
ctx.client().world,
payload.targetData().bePos()
))
);
));
}
if (FabricLoader.getInstance().isModLoaded("fabric-lifecycle-events-v1")) {
ClientBlockEntityEvents.BLOCK_ENTITY_LOAD.register((be, world) -> ((ComponentProvider) be).getComponentContainer().onServerLoad());
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -101,11 +101,12 @@ public Iterable<ServerPlayerEntity> getRecipientsForComponentSync() {
}

@Override
public <C extends AutoSyncedComponent> ComponentUpdatePayload<?> toComponentPacket(ComponentKey<? super C> key, RegistryByteBuf data) {
public <C extends AutoSyncedComponent> ComponentUpdatePayload<?> toComponentPacket(ComponentKey<? super C> key, boolean required, RegistryByteBuf data) {
return new ComponentUpdatePayload<>(
CardinalComponentsBlock.PACKET_ID,
new BlockEntityAddress(this.getType(), this.getPos()),
key,
required,
key.getId(),
data
);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -34,11 +34,11 @@ public static void initClient() {
if (FabricLoader.getInstance().isModLoaded("fabric-networking-api-v1")) {
CcaClientInternals.registerComponentSync(
CardinalComponentsChunk.PACKET_ID,
(payload, ctx) -> payload.componentKey().maybeGet(Objects.requireNonNull(ctx.client().world).getChunk(
(payload, ctx) -> payload.componentKey().flatMap(key -> key.maybeGet(Objects.requireNonNull(ctx.client().world).getChunk(
payload.targetData().x,
payload.targetData().z
))
);
));
}
if (FabricLoader.getInstance().isModLoaded("fabric-lifecycle-events-v1")) {
ClientChunkEvents.CHUNK_LOAD.register((world, chunk) -> ((ComponentProvider) chunk).getComponentContainer().onServerLoad());
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -69,11 +69,12 @@ public Iterable<ServerPlayerEntity> getRecipientsForComponentSync() {
}

@Override
public @javax.annotation.Nullable <C extends AutoSyncedComponent> ComponentUpdatePayload<?> toComponentPacket(ComponentKey<? super C> key, RegistryByteBuf data) {
public @Nullable <C extends AutoSyncedComponent> ComponentUpdatePayload<?> toComponentPacket(ComponentKey<? super C> key, boolean required, RegistryByteBuf data) {
return new ComponentUpdatePayload<>(
CardinalComponentsChunk.PACKET_ID,
this.getPos(),
key,
required,
key.getId(),
data
);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,9 @@ public static void initClient() {
if (FabricLoader.getInstance().isModLoaded("fabric-networking-api-v1")) {
CcaClientInternals.registerComponentSync(
CardinalComponentsEntity.PACKET_ID,
(payload, ctx) -> payload.componentKey().maybeGet(Objects.requireNonNull(ctx.client().world).getEntityById(payload.targetData()))
(payload, ctx) -> payload.componentKey().flatMap(
key -> key.maybeGet(Objects.requireNonNull(ctx.client().world).getEntityById(payload.targetData()))
)
);
}
if (FabricLoader.getInstance().isModLoaded("fabric-lifecycle-events-v1")) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -93,11 +93,12 @@ public Iterable<ServerPlayerEntity> getRecipientsForComponentSync() {
}

@Override
public <C extends AutoSyncedComponent> ComponentUpdatePayload<?> toComponentPacket(ComponentKey<? super C> key, RegistryByteBuf data) {
public <C extends AutoSyncedComponent> ComponentUpdatePayload<?> toComponentPacket(ComponentKey<? super C> key, boolean required, RegistryByteBuf data) {
return new ComponentUpdatePayload<>(
CardinalComponentsEntity.PACKET_ID,
this.getId(),
key,
required,
key.getId(),
data
);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,7 @@ public interface ItemComponentInitializer extends ComponentRegistrationInitializ
* Called to register component migrations from CCA to {@link net.minecraft.component.DataComponentType}.
*
* @param registry an {@link ItemComponentMigrationRegistry} for component migrations
* @since 7.0.0
*/
void registerItemComponentMigrations(ItemComponentMigrationRegistry registry);
}
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,9 @@ public static void initClient() {
if (FabricLoader.getInstance().isModLoaded("fabric-networking-api-v1")) {
CcaClientInternals.registerComponentSync(
CardinalComponentsLevel.PACKET_ID,
(payload, ctx) -> payload.componentKey().maybeGet(Objects.requireNonNull(ctx.client().world).getLevelProperties())
(payload, ctx) -> payload.componentKey().flatMap(
key -> key.maybeGet(Objects.requireNonNull(ctx.client().world).getLevelProperties())
)
);
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -87,11 +87,12 @@ public Iterable<ServerPlayerEntity> getRecipientsForComponentSync() {
}

@Override
public <C extends AutoSyncedComponent> ComponentUpdatePayload<?> toComponentPacket(ComponentKey<? super C> key, RegistryByteBuf data) {
public <C extends AutoSyncedComponent> ComponentUpdatePayload<?> toComponentPacket(ComponentKey<? super C> key, boolean required, RegistryByteBuf data) {
return new ComponentUpdatePayload<>(
CardinalComponentsLevel.PACKET_ID,
Unit.INSTANCE,
key,
required,
key.getId(),
data
);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -32,11 +32,13 @@ public static void initClient() {
if (FabricLoader.getInstance().isModLoaded("fabric-networking-api-v1")) {
CcaClientInternals.registerComponentSync(
CardinalComponentsScoreboard.TEAM_PACKET_ID,
(payload, ctx) -> payload.componentKey().maybeGet(Objects.requireNonNull(ctx.client().world).getScoreboard().getTeam(payload.targetData()))
);
(payload, ctx) -> payload.componentKey().flatMap(key -> key.maybeGet(Objects.requireNonNull(ctx.client().world).getScoreboard().getTeam(payload.targetData()))
));
CcaClientInternals.registerComponentSync(
CardinalComponentsScoreboard.SCOREBOARD_PACKET_ID,
(payload, ctx) -> payload.componentKey().maybeGet(Objects.requireNonNull(ctx.client().world).getScoreboard())
(payload, ctx) -> payload.componentKey().flatMap(
key -> key.maybeGet(Objects.requireNonNull(ctx.client().world).getScoreboard())
)
);
}
}
Expand Down
Loading

0 comments on commit 9481cba

Please sign in to comment.