PhysicalConnectivity/src/main/kotlin/net/shadowfacts/phycon/network/DeviceBlockEntity.kt

67 lines
1.6 KiB
Kotlin

package net.shadowfacts.phycon.network
import net.minecraft.block.entity.BlockEntity
import net.minecraft.block.entity.BlockEntityType
import net.minecraft.nbt.CompoundTag
import net.minecraft.util.Tickable
import net.shadowfacts.phycon.api.PacketSink
import net.shadowfacts.phycon.api.packet.Packet
import net.shadowfacts.phycon.api.util.MACAddress
import java.util.*
/**
* @author shadowfacts
*/
abstract class DeviceBlockEntity(type: BlockEntityType<*>): BlockEntity(type), Tickable, PacketSink {
var macAddress = MACAddress.random()
protected set
private val sendQueue = LinkedList<Packet>()
override fun handle(packet: Packet) {
if (acceptsPacket(packet)) {
handlePacket(packet)
}
}
abstract fun handlePacket(packet: Packet)
fun acceptsPacket(packet: Packet): Boolean {
return when (packet.destination.type) {
MACAddress.Type.BROADCAST -> true
MACAddress.Type.UNICAST -> macAddress == packet.destination
MACAddress.Type.MULTICAST -> acceptsMulticastPacket(packet)
}
}
fun acceptsMulticastPacket(packet: Packet): Boolean {
return false
}
fun enqueue(packet: Packet) {
sendQueue.add(packet)
}
override fun tick() {
if (sendQueue.isNotEmpty()) {
val packet = sendQueue.pop()
val destinations = NetworkUtil.findDestinations(world!!, pos)
destinations.forEach {
it.handle(packet)
}
}
}
override fun toTag(tag: CompoundTag): CompoundTag {
tag.putLong("MACAddress", macAddress.address)
return super.toTag(tag)
}
override fun fromTag(tag: CompoundTag) {
super.fromTag(tag)
macAddress = MACAddress(tag.getLong("MACAddress"))
}
}