PhysicalConnectivity/src/main/kotlin/net/shadowfacts/phycon/networking/C2SConfigureDevice.kt

50 lines
1.7 KiB
Kotlin

package net.shadowfacts.phycon.networking
import net.fabricmc.fabric.api.networking.v1.PacketByteBufs
import net.fabricmc.fabric.api.networking.v1.PacketSender
import net.minecraft.block.entity.BlockEntity
import net.minecraft.nbt.NbtCompound
import net.minecraft.network.Packet
import net.minecraft.network.PacketByteBuf
import net.minecraft.server.MinecraftServer
import net.minecraft.server.network.ServerPlayNetworkHandler
import net.minecraft.server.network.ServerPlayerEntity
import net.minecraft.util.Identifier
import net.shadowfacts.phycon.PhysicalConnectivity
import net.shadowfacts.phycon.util.ClientConfigurableDevice
/**
* @author shadowfacts
*/
object C2SConfigureDevice: ServerReceiver {
override val CHANNEL = Identifier(PhysicalConnectivity.MODID, "configure_device")
operator fun <T> invoke(be: T): Packet<*> where T: BlockEntity, T: ClientConfigurableDevice {
val buf = PacketByteBufs.create()
buf.writeIdentifier(be.world!!.registryKey.value)
buf.writeBlockPos(be.pos)
val tag = NbtCompound()
be.writeDeviceConfiguration(tag)
buf.writeNbt(tag)
return createPacket(buf)
}
override fun receive(server: MinecraftServer, player: ServerPlayerEntity, handler: ServerPlayNetworkHandler, buf: PacketByteBuf, responseSender: PacketSender) {
val dimID = buf.readIdentifier()
val pos = buf.readBlockPos()
val tag = buf.readNbt() ?: return
server.execute {
// todo: check if the player is close enough
val world = player.world
if (world.registryKey.value != dimID) return@execute
val be = world.getBlockEntity(pos) ?: return@execute
val device = be as? ClientConfigurableDevice ?: return@execute
device.loadDeviceConfiguration(tag)
be.markDirty()
}
}
}