Skip to content

CSharpGodotTools/PacketGen

Repository files navigation

PacketGen

.NET Build & Test GitHub stars GitHub forks License Last commit Contributors Watchers Discord

Source generator for the netcode packet scripts in https://github.com/CSharpGodotTools/Template


Input:

public partial class CPacketPlayerInfo : ClientPacket
{
    public string Username { get; set; }
    public Vector2 Position { get; set; }
}

Output:

public partial class CPacketPlayerInfo
{
    public override void Write(PacketWriter writer)
    {
        writer.Write(Username);
        writer.Write(Position);
    }

    public override void Read(PacketReader reader)
    {
        Username = reader.ReadString();
        Position = reader.ReadVector2();
    }
}

Input:

public class TestPacket : ClientPacket {}

[PacketRegistry(typeof(ushort))]
public partial class PacketRegistry
{
}

Output:

public partial class PacketRegistry
{
    public static readonly Dictionary<Type, PacketInfo<ClientPacket>> ClientPacketInfo;
    public static readonly Dictionary<ushort, Type> ClientPacketTypes;
    public static readonly Dictionary<Type, PacketInfo<ServerPacket>> ServerPacketInfo;
    public static readonly Dictionary<ushort, Type> ServerPacketTypes;

    static PacketRegistry()
    {
        ClientPacketInfo = new Dictionary<Type, PacketInfo<ClientPacket>>()
        {
            
            {
                typeof(TestPacket),
                new PacketInfo<ClientPacket>
                {
                    Opcode = 0,
                    Instance = new TestPacket()
                }
            }
        };

        ClientPacketTypes = ClientPacketInfo.ToDictionary(kvp => kvp.Value.Opcode, kvp => kvp.Key);

        ServerPacketInfo = new Dictionary<Type, PacketInfo<ServerPacket>>()
        {
            
        };

        ServerPacketTypes = ServerPacketInfo.ToDictionary(kvp => kvp.Value.Opcode, kvp => kvp.Key);
    }
}

public sealed class PacketInfo<T>
{
    public ushort Opcode;
    public T Instance;
}

Installing as Local NuGet Package

Copy the .nupkg from bin\Debug to main project.

Add a file named NuGet.config to the main projects root folder with the following contents:

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <packageSources>
    <add key="LocalNugets" value="Framework/Libraries" />
    <add key="nuget.org" value="https://api.nuget.org/v3/index.json" />
  </packageSources>
</configuration>

The name for the key LocalNugets can be changed to anything you'd like. Change the Framework/Libraries path to point to the .nupkg package file.

Add the following to the main projects .csproj file:

<PackageReference Include="PacketGen" Version="*" />

Replace * with the explicit latest version or keep it as is.

Contributing

All files are generated to PacketGen.Tests\bin\Debug\net10.0\_Generated.

All tests are in PacketGen.Tests\Tests.

All generators are in PacketGen\Generators.