summaryrefslogtreecommitdiff
path: root/Net.cs
blob: b99a0f62e1664d5012722b5c85236f691de93dcc (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
using System.Buffers.Binary;
using LiteNetLib.Utils;

namespace OnekoOnline.Net;

public static class NetExtensions
{
    public static void Put(this NetDataWriter writer, PacketInfo info)
    {
        writer.Put(info.Serialize());
    }

    public static PacketInfo GetPacketInfo(this NetDataReader reader)
    {
        return PacketInfo.Deserialize(reader.GetBytesSegment(PacketInfo.SizeOf));
    }

    public static PacketInfo PeekPacketInfo(this NetDataReader reader)
    {
        if (reader.AvailableBytes < PacketInfo.SizeOf) return PacketInfo.InvalidPacket;
        return PacketInfo.Deserialize(reader.RawData.AsSpan(0, PacketInfo.SizeOf));
    }

    public static void ResetWithInfo(this NetDataWriter writer, PacketInfo info)
    {
        writer.Reset();
        writer.Put(info);
    }

    public static void ResetWithInfo(this NetDataWriter writer, PacketInfo info, int size)
    {
        writer.Reset(size+PacketInfo.SizeOf);
        writer.Put(info);
    }
}

public enum PacketType : byte
{
    MousePosition,
    OnekoState,
    OnekoSpritesheet,
    Username,
    UserId,
    Disconnect,
    Invalid
}

public struct PacketInfo
{
    public readonly PacketType Type;
    public readonly int FromId;
    public const int SizeOf = sizeof(int) + 1;
    public readonly bool IsValid => Type != PacketType.Invalid;

    public static readonly PacketInfo InvalidPacket = new(PacketType.Invalid, -1);

    public PacketInfo(PacketType type, int id)
    {
        Type = type;
        FromId = id;
    }

    public readonly void Serialize(Span<byte> span)
    {
        span[0] = (byte)Type;
        BinaryPrimitives.WriteInt32LittleEndian(span[1..], FromId);
    }

    public readonly byte[] Serialize()
    {
        byte[] bytes = new byte[SizeOf];
        Serialize(bytes);
        return bytes;
    }

    public static PacketInfo Deserialize(ReadOnlySpan<byte> span)
    {
        PacketType type = (PacketType)span[0];
        int id = BinaryPrimitives.ReadInt32LittleEndian(span[1..]);
        return new PacketInfo(type, id);
    }
}

class User(int id)
{
    public readonly int Id = id;

    //Oneko Stuff
    public byte[]? SpriteSheet;
    public string? Username;

    public bool ExchangedData => SpriteSheet != null && Username != null;
}