GodotTicTacToe/scripts/net/packethandling/Serializable.cs

61 lines
1.7 KiB
C#

using Godot;
namespace Network.PacketHandling {
public abstract class Serializable : Reference {
public SerializableMetadata Metadata;
public Serializable() {
Metadata = new SerializableMetadata(Protocol.GetPacketTypeIDFor(this));
}
public void Serialize(PacketBuffer packetBuffer) {
Metadata.Serialize(packetBuffer);
WriteContents(packetBuffer);
}
public void Deserialize(PacketBuffer packetBuffer) {
if (!Metadata.Deserialized) {
Metadata.Deserialize(packetBuffer);
}
ReadContents(packetBuffer);
}
public void DeserializeWithMetadata(SerializableMetadata metadata, PacketBuffer packetBuffer) {
Metadata = metadata;
Deserialize(packetBuffer);
}
public abstract void WriteContents(PacketBuffer packetBuffer);
public abstract void ReadContents(PacketBuffer packetBuffer);
}
public class SerializableMetadata : Reference {
public int PacketType;
public bool Reliable;
public int ID;
public bool Deserialized = false;
public SerializableMetadata(int packetType) {
PacketType = packetType;
}
public void Serialize(PacketBuffer packetBuffer) {
packetBuffer.Write(PacketType);
packetBuffer.Write(Reliable);
packetBuffer.Write(ID);
}
public void Deserialize(PacketBuffer packetBuffer) {
Deserialized = true;
PacketType = packetBuffer.ReadInt();
Reliable = packetBuffer.ReadBool();
ID = packetBuffer.ReadInt();
}
}
}