Compare commits

...

29 Commits

Author SHA1 Message Date
edmand46 b39bd8bd0a fix: updated workflows 2024-04-14 19:23:08 +03:00
edmand46 12b80c546c fix: updated workflows 2024-04-14 19:14:57 +03:00
edmand46 5c20fbafc1 Merge pull request #15 from edmand46/feat/rooms
feat: Room List
2024-04-13 18:27:28 +03:00
edmand46 bd0c6df5ea fix: timer, providing api for listeners 2024-04-13 18:25:39 +03:00
edmand46 c4811ef052 feat(wip): list rooms 2024-04-13 17:43:23 +03:00
edmand46 d82964526c feat(wip): room list support 2024-04-13 16:17:31 +03:00
edmand46 acedaef270 ♻️ unified event api for room and entities 2024-04-07 17:15:52 +03:00
edmand46 0c4bdb83c9 added new method for RagonBuffer 2024-04-07 17:11:45 +03:00
edmand46 5a79502848 RagonStream 2024-04-06 19:11:16 +03:00
edmand46 b8fe2bb13f 🐛 wrong condition in lobby in memory on finding room by id 2024-02-04 20:06:07 +03:00
edmand46 89d130a193 🐛 fixed double call on invoke local flag in ragon property 2024-01-21 12:20:47 +03:00
edmand46 0cd912a1aa 🎨 added null checks 2024-01-13 15:15:29 +03:00
edmand46 c64cc61c78 🐛 prediction spawning for wrong connection, payload capacity 2024-01-04 23:29:35 +03:00
edmand46 2dcb047014 chore: added logging 2023-11-05 22:19:55 +03:00
edmand46 33f8bba2ed fixed: remove exception on non exists player 2023-11-05 22:08:41 +03:00
edmand46 5aa159ed2f fixed: custom property wrong size 2023-11-05 21:53:57 +03:00
edmand46 892558ab16 chore: update version 2023-10-22 21:10:31 +03:00
edmand46 f55634877a 📝 update readme.md 2023-10-21 23:10:41 +03:00
edmand46 8b3a29a750 📝 update readme.md 2023-10-21 23:09:49 +03:00
edmand46 6a50bffe1e 📝 update readme.md 2023-10-21 23:03:55 +03:00
edmand46 9144ad58ef 📝 update readme.md 2023-10-21 23:03:37 +03:00
edmand46 ee9f3fbe3a 🐛 crash on abnormal disconnecting from websocket server 2023-10-19 20:20:40 +03:00
edmand46 893c73512a feat: allow control replication via code, fix null owner on OnEntityCreated 2023-10-16 23:37:35 +03:00
edmand46 e7dd693147 🐛 Event Payload 2023-10-14 23:50:25 +03:00
edmand46 fef1007c8c 🔖 update version 2023-10-14 21:48:33 +03:00
edmand46 e33c442a18 🐛 WebSocket buffer size 2023-10-14 21:35:51 +03:00
edmand46 09b185a3ad 🐛 checking size event 2023-10-13 12:10:46 +03:00
edmand46 7d154ea4d4 🎨 cleanup 2023-10-13 11:02:56 +03:00
edmand46 d2577e5d1f remove allocation on raw data replication 2023-10-13 10:58:15 +03:00
60 changed files with 1008 additions and 280 deletions
+25
View File
@@ -0,0 +1,25 @@
**/.dockerignore
**/.env
**/.git
**/.gitignore
**/.project
**/.settings
**/.toolstarget
**/.vs
**/.vscode
**/.idea
**/*.*proj.user
**/*.dbmdl
**/*.jfm
**/azds.yaml
**/bin
**/charts
**/docker-compose*
**/Dockerfile*
**/node_modules
**/npm-debug.log
**/obj
**/secrets.dev.yaml
**/values.dev.yaml
LICENSE
README.md
+1 -1
View File
@@ -49,7 +49,7 @@ jobs:
- name: Setup dotnet
uses: actions/setup-dotnet@v1
with:
dotnet-version: 7.0.x
dotnet-version: 8.0.x
- name: Build
shell: bash
run: |
+1
View File
@@ -1,6 +1,7 @@
.DS_Store
.idea
.vs
.vscode
obj
bin
*.user
BIN
View File
Binary file not shown.

After

Width:  |  Height:  |  Size: 26 KiB

+1 -1
View File
@@ -1,5 +1,5 @@
<p align="center">
<img src="Images/ragon-logo.png" width="200" >
<img src="Images/logo.png">
</p>
## Ragon Server
+2 -2
View File
@@ -12,11 +12,11 @@
<PropertyGroup Condition=" '$(Configuration)' == 'Release' ">
<AllowUnsafeBlocks>true</AllowUnsafeBlocks>
<DebugType>none</DebugType>
<OutputPath>/Users/edmand46/RagonProjects/ragon-oss-examples/Assets/Ragon/Runtime/Plugins</OutputPath>
<OutputPath></OutputPath>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)' == 'Debug' ">
<OutputPath>/Users/edmand46/RagonProjects/ragon-oss-examples/Assets/Ragon/Plugins/</OutputPath>
<OutputPath></OutputPath>
</PropertyGroup>
<ItemGroup>
+49 -30
View File
@@ -19,20 +19,49 @@ using Ragon.Protocol;
namespace Ragon.Client
{
public sealed class RagonEntity: IDisposable
public sealed class RagonEntity : IDisposable
{
private class EventSubscription : IDisposable
{
private List<Action<RagonPlayer, IRagonEvent>> _callbacks;
private List<Action<RagonPlayer, IRagonEvent>> _localCallbacks;
private Action<RagonPlayer, IRagonEvent> _callback;
public EventSubscription(
List<Action<RagonPlayer, IRagonEvent>> callbacks,
List<Action<RagonPlayer, IRagonEvent>> localCallbacks,
Action<RagonPlayer, IRagonEvent> callback)
{
_callbacks = callbacks;
_localCallbacks = localCallbacks;
_callback = callback;
}
public void Dispose()
{
_callbacks?.Remove(_callback);
_localCallbacks?.Remove(_callback);
_callbacks = null!;
_localCallbacks = null!;
_callback = null!;
}
}
private delegate void OnEventDelegate(RagonPlayer player, RagonBuffer serializer);
private RagonClient _client;
public ushort Id { get; private set; }
public ushort Type { get; private set; }
public bool Replication { get; private set; }
public RagonAuthority Authority { get; private set; }
public RagonPlayer Owner { get; private set; }
public RagonEntityState State { get; private set; }
public bool IsStatic => SceneId > 0;
public bool IsReplicated { get; private set; }
public bool IsAttached { get; private set; }
public bool HasAuthority { get; private set; }
@@ -53,33 +82,27 @@ namespace Ragon.Client
private readonly Dictionary<int, List<Action<RagonPlayer, IRagonEvent>>> _localListeners = new Dictionary<int, List<Action<RagonPlayer, IRagonEvent>>>();
private readonly Dictionary<int, List<Action<RagonPlayer, IRagonEvent>>> _listeners = new Dictionary<int, List<Action<RagonPlayer, IRagonEvent>>>();
public RagonEntity(ushort type = 0, ushort sceneId = 0)
public RagonEntity(ushort type = 0, ushort sceneId = 0, bool replicated = true)
{
State = new RagonEntityState(this);
Type = type;
IsReplicated = replicated;
_spawnPayload = new RagonPayload(0);
_destroyPayload = new RagonPayload(0);
_sceneId = sceneId;
}
internal void Attach(RagonClient client, ushort entityId, ushort entityType, bool hasAuthority, RagonPlayer owner)
internal void Attach()
{
Type = entityType;
Id = entityId;
Owner = owner;
IsAttached = true;
Replication = true;
HasAuthority = hasAuthority;
_client = client;
Attached?.Invoke(this);
}
internal void SetReplication(bool enabled)
public void SetReplication(bool enabled)
{
Replication = enabled;
IsReplicated = enabled;
}
internal void Detach(RagonPayload payload)
@@ -103,9 +126,16 @@ namespace Ragon.Client
return payload;
}
public void AttachPayload(RagonPayload payload)
public void Prepare(RagonClient client, ushort entityId, ushort entityType, bool hasAuthority, RagonPlayer player, RagonPayload payload)
{
Type = entityType;
Id = entityId;
HasAuthority = hasAuthority;
_client = client;
_spawnPayload = payload;
Owner = player;
}
public T GetAttachPayload<T>() where T : IRagonPayload, new()
@@ -166,6 +196,7 @@ namespace Ragon.Client
listener.Invoke(_client.Room.Local, evnt);
return;
}
if (replicationMode == RagonReplicationMode.LocalAndServer)
{
var localListeners = _localListeners[eventCode];
@@ -189,11 +220,10 @@ namespace Ragon.Client
_client.Reliable.Send(sendData);
}
public Action<RagonPlayer, IRagonEvent> OnEvent<TEvent>(Action<RagonPlayer, TEvent> callback) where TEvent : IRagonEvent, new()
public IDisposable OnEvent<TEvent>(Action<RagonPlayer, TEvent> callback) where TEvent : IRagonEvent, new()
{
var t = new TEvent();
var eventCode = _client.Event.GetEventCode(t);
var action = (RagonPlayer player, IRagonEvent eventData) => callback.Invoke(player, (TEvent)eventData);
if (!_listeners.TryGetValue(eventCode, out var callbacks))
@@ -222,19 +252,7 @@ namespace Ragon.Client
});
}
return action;
}
public void OffEvent<TEvent>(Action<RagonPlayer, IRagonEvent> callback) where TEvent : IRagonEvent, new()
{
var t = new TEvent();
var eventCode = _client.Event.GetEventCode(t);
if (_listeners.TryGetValue(eventCode, out var callbacks))
callbacks.Remove(callback);
if (_localListeners.TryGetValue(eventCode, out var localCallbacks))
localCallbacks.Remove(callback);
return new EventSubscription(callbacks, localCallbacks, action);
}
internal void Write(RagonBuffer buffer)
@@ -246,7 +264,6 @@ namespace Ragon.Client
_propertiesChanged = false;
}
internal void Read(RagonBuffer buffer)
{
State.ReadState(buffer);
@@ -254,6 +271,8 @@ namespace Ragon.Client
internal void Event(ushort eventCode, RagonPlayer caller, RagonBuffer buffer)
{
if (!IsReplicated) return;
if (_events.TryGetValue(eventCode, out var evnt))
evnt?.Invoke(caller, buffer);
else
@@ -21,6 +21,8 @@ namespace Ragon.Client;
public class RagonPayload
{
public static RagonPayload Empty = new RagonPayload(0);
private readonly uint[] _data = new uint[128];
private readonly int _size = 0;
+7 -6
View File
@@ -63,7 +63,7 @@ namespace Ragon.Client
protected void InvokeChanged()
{
if (!InvokeLocal)
if (_entity.HasAuthority)
return;
Changed?.Invoke();
@@ -71,7 +71,8 @@ namespace Ragon.Client
protected void MarkAsChanged()
{
InvokeChanged();
if (InvokeLocal)
Changed?.Invoke();
if (_dirty || _entity == null)
return;
@@ -106,15 +107,15 @@ namespace Ragon.Client
{
Serialize(_propertyBuffer);
buffer.FromBuffer(_propertyBuffer, _size);
buffer.CopyFrom(_propertyBuffer, _size);
return;
}
Serialize(_propertyBuffer);
var propertySize = (ushort) _propertyBuffer.WriteOffset;
buffer.WriteUShort(propertySize);;
buffer.FromBuffer(_propertyBuffer, propertySize);
var propertySize = (ushort)_propertyBuffer.WriteOffset;
buffer.WriteUShort(propertySize);
buffer.CopyFrom(_propertyBuffer, propertySize);
}
internal void Read(RagonBuffer buffer)
@@ -51,17 +51,19 @@ internal class EntityCreateHandler : IHandler
if (player == null)
{
RagonLog.Warn($"Owner {ownerId}|{player.Name} not found in players");
_playerCache.Dump();
return;
}
var hasAuthority = _playerCache.Local.Id == player.Id;
var entity = _entityCache.TryGetEntity(attachId, entityType, 0, entityId, hasAuthority, out var hasCreated);
entity.AttachPayload(payload);
entity.Prepare(_client, entityId, entityType, hasAuthority, player, payload);
if (hasCreated)
_entityListener.OnEntityCreated(entity);
entity.Attach(_client, entityId, entityType, hasAuthority, player);
entity.Attach();
}
}
@@ -20,35 +20,37 @@ namespace Ragon.Client;
internal class EntityEventHandler : IHandler
{
private readonly RagonPlayerCache _playerCache;
private readonly RagonEntityCache _entityCache;
private readonly RagonPlayerCache _playerCache;
private readonly RagonEntityCache _entityCache;
public EntityEventHandler(
RagonPlayerCache playerCache,
RagonEntityCache entityCache
)
public EntityEventHandler(
RagonPlayerCache playerCache,
RagonEntityCache entityCache
)
{
_playerCache = playerCache;
_entityCache = entityCache;
}
public void Handle(RagonBuffer reader)
{
var eventCode = reader.ReadUShort();
var peerId = reader.ReadUShort();
var executionMode = (RagonReplicationMode)reader.ReadByte();
var entityId = reader.ReadUShort();
var player = _playerCache.GetPlayerByPeer(peerId);
if (player == null)
{
_playerCache = playerCache;
_entityCache = entityCache;
RagonLog.Error($"Player with peerId:{peerId} not found as owner of event with code:{eventCode}");
_playerCache.Dump();
return;
}
public void Handle(RagonBuffer reader)
{
var eventCode = reader.ReadUShort();
var peerId = reader.ReadUShort();
var executionMode = (RagonReplicationMode)reader.ReadByte();
var entityId = reader.ReadUShort();
if (player.IsLocal && executionMode == RagonReplicationMode.LocalAndServer)
return;
var player = _playerCache.GetPlayerByPeer(peerId);
if (player == null)
{
RagonLog.Warn($"Player not found for event {eventCode}");
return;
}
if (player.IsLocal && executionMode == RagonReplicationMode.LocalAndServer)
return;
_entityCache.OnEvent(player, entityId, eventCode, reader);
}
_entityCache.OnEvent(player, entityId, eventCode, reader);
}
}
@@ -41,6 +41,14 @@ internal class EntityOwnershipHandler: IHandler
var entities = reader.ReadUShort();
var player = _playerCache.GetPlayerByPeer(newOwnerId);
if (player == null)
{
RagonLog.Error($"Player with Id:{newOwnerId} not found in cache");
_playerCache.Dump();
return;
}
for (var i = 0; i < entities; i++)
{
var entityId = reader.ReadUShort();
@@ -19,9 +19,9 @@ using Ragon.Protocol;
namespace Ragon.Client;
public struct RagonRoomInformation
public struct RoomParameters
{
public RagonRoomInformation(string roomId, string playerId, string ownerId, ushort min, ushort max)
public RoomParameters(string roomId, string playerId, string ownerId, ushort min, ushort max)
{
RoomId = roomId;
PlayerId = playerId;
@@ -39,6 +39,8 @@ public struct RagonRoomInformation
internal class JoinSuccessHandler : IHandler
{
private readonly RagonListenerList _listenerList;
private readonly RagonPlayerCache _playerCache;
private readonly RagonEntityCache _entityCache;
@@ -67,7 +69,7 @@ internal class JoinSuccessHandler : IHandler
var sceneName = reader.ReadString();
var scene = new RagonScene(_client, _playerCache, _entityCache, sceneName);
var roomInfo = new RagonRoomInformation(roomId, localId, ownerId, min, max);
var roomInfo = new RoomParameters(roomId, localId, ownerId, min, max);
var room = new RagonRoom(_client, _entityCache, _playerCache, roomInfo, scene);
_playerCache.SetOwnerAndLocal(ownerId, localId);
@@ -19,7 +19,7 @@ using Ragon.Protocol;
namespace Ragon.Client;
internal class OwnershipRoomHandler: IHandler
internal class OwnershipRoomHandler : IHandler
{
private readonly RagonListenerList _listenerList;
private readonly RagonPlayerCache _playerCache;
@@ -39,6 +39,13 @@ internal class OwnershipRoomHandler: IHandler
{
var newOwnerId = reader.ReadUShort();
var player = _playerCache.GetPlayerByPeer(newOwnerId);
if (player == null)
{
RagonLog.Warn($"Player with peerId:{newOwnerId} not found in cache");
_playerCache.Dump();
return;
}
_playerCache.OnOwnershipChanged(newOwnerId);
_listenerList.OnOwnershipChanged(player);
@@ -45,6 +45,6 @@ internal class PlayerJoinHandler : IHandler
if (player != null)
_listenerList.OnPlayerJoined(player);
else
RagonLog.Trace($"[Joined] {playerId}");
RagonLog.Warn($"Player with Id:{playerId} not found in cache");
}
}
@@ -57,5 +57,9 @@ internal class PlayerLeftHandler : IHandler
foreach (var id in toDeleteIds)
_entityCache.OnDestroy(id, emptyPayload);
}
else
{
RagonLog.Warn($"Player with Id:{playerId} not found in cache");
}
}
}
@@ -37,6 +37,15 @@ internal class RoomDataHandler: IHandler
var rawData = reader.RawData;
var peerId = (ushort)(rawData[1] + (rawData[2] << 8));
var player = _playerCache.GetPlayerByPeer(peerId);
if (player == null)
{
RagonLog.Error($"Player with peerId:{peerId} not found");
_playerCache.Dump();
return;
}
var headerSize = 3;
var payload = new byte[rawData.Length - headerSize];
@@ -18,7 +18,7 @@ using Ragon.Protocol;
namespace Ragon.Client;
public class RoomEventHandler: IHandler
public class RoomEventHandler : IHandler
{
private readonly RagonClient _client;
private readonly RagonPlayerCache _playerCache;
@@ -41,7 +41,9 @@ public class RoomEventHandler: IHandler
var player = _playerCache.GetPlayerByPeer(peerId);
if (player == null)
{
RagonLog.Warn($"Player not found for event {eventCode}");
RagonLog.Error($"Player with peerId:{peerId} not found as owner of event with code:{eventCode}");
_playerCache.Dump();
return;
}
@@ -0,0 +1,43 @@
using Ragon.Protocol;
namespace Ragon.Client;
internal class RoomListHandler: IHandler
{
private RagonListenerList _listenerList;
private RagonSession _session;
public RoomListHandler(RagonSession session, RagonListenerList list)
{
_session = session;
_listenerList = list;
}
public void Handle(RagonBuffer reader)
{
var roomCount = reader.ReadUShort();
var roomList = new RagonRoomInformation[roomCount];
for (int i = 0; i < roomCount; i++)
{
var id = reader.ReadString();
var scene = reader.ReadString();
var maxPlayers = reader.ReadUShort();
var minPlayers = reader.ReadUShort();
var players = reader.ReadUShort();
var roomInfo = new RagonRoomInformation()
{
Id = id,
Scene = scene,
PlayerCount = players,
PlayerMax = maxPlayers,
PlayerMin = minPlayers,
Properties = new Dictionary<string, byte[]>()
};
roomList[i] = roomInfo;
}
_listenerList.OnRoomList(roomList);
}
}
@@ -45,6 +45,7 @@ internal class SnapshotHandler : IHandler
public void Handle(RagonBuffer buffer)
{
var entities = new List<RagonEntity>();
var playersCount = buffer.ReadUShort();
RagonLog.Trace("Players: " + playersCount);
for (var i = 0; i < playersCount; i++)
@@ -70,25 +71,28 @@ internal class SnapshotHandler : IHandler
var player = _playerCache.GetPlayerByPeer(ownerPeerId);
if (player == null)
{
RagonLog.Error($"Player not found with peerId: ${ownerPeerId}");
RagonLog.Error($"Player not found with peerId: {ownerPeerId}");
_playerCache.Dump();
return;
}
var hasAuthority = _playerCache.Local.Id == player.Id;
var entity = _entityCache.TryGetEntity(0, entityType, 0, entityId, hasAuthority, out _);
var payload = RagonPayload.Empty;
if (payloadSize > 0)
{
var payload = new RagonPayload(payloadSize);
payload = new RagonPayload(payloadSize);
payload.Read(buffer);
entity.AttachPayload(payload);
}
entity.Prepare(_client, entityId, entityType, hasAuthority, player, payload);
_entityListener.OnEntityCreated(entity);
entity.Read(buffer);
entity.Attach(_client, entityId, entityType, hasAuthority, player);
entities.Add(entity);
}
var staticEntities = buffer.ReadUShort();
@@ -104,15 +108,19 @@ internal class SnapshotHandler : IHandler
var player = _playerCache.GetPlayerByPeer(ownerPeerId);
if (player == null)
{
RagonLog.Error($"Player not found with peerId: ${ownerPeerId}");
RagonLog.Error($"Player not found with peerId: {ownerPeerId}");
_playerCache.Dump();
return;
}
var hasAuthority = _playerCache.Local.Id == player.Id;
var entity = _entityCache.TryGetEntity(0, entityType, staticId, entityId, hasAuthority, out _);
entity.Prepare(_client, entityId, entityType, hasAuthority, player, RagonPayload.Empty);
entity.Read(buffer);
entity.Attach(_client, entityId, entityType, hasAuthority, player);
entities.Add(entity);
}
if (_client.Status == RagonStatus.LOBBY)
@@ -121,6 +129,9 @@ internal class SnapshotHandler : IHandler
_listenerList.OnJoined();
}
foreach (var entity in entities)
entity.Attach();
_listenerList.OnSceneLoaded();
}
}
@@ -0,0 +1,6 @@
namespace Ragon.Client;
public interface IRagonRoomListListener
{
public void OnRoomListUpdate(IReadOnlyList<RagonRoomInformation> roomsInfos);
}
+44 -43
View File
@@ -29,7 +29,7 @@ namespace Ragon.Client
private RagonBuffer _writeBuffer;
private RagonRoom _room;
private RagonSession _session;
private RagonListenerList listeners;
private RagonListenerList _listeners;
private RagonPlayerCache _playerCache;
private RagonEntityCache _entityCache;
private RagonEventCache _eventCache;
@@ -48,7 +48,6 @@ namespace Ragon.Client
public NetworkStatistics Statistics => _stats;
public RagonRoom Room => _room;
internal RagonBuffer Buffer => _writeBuffer;
internal INetworkChannel Reliable => _connection.Reliable;
internal INetworkChannel Unreliable => _connection.Unreliable;
@@ -57,7 +56,7 @@ namespace Ragon.Client
public RagonClient(INetworkConnection connection, int rate)
{
listeners = new RagonListenerList(this);
_listeners = new RagonListenerList(this);
_connection = connection;
_connection.OnData += OnData;
@@ -105,24 +104,25 @@ namespace Ragon.Client
_entityCache = new RagonEntityCache(this, _playerCache, _sceneCollector);
_handlers = new IHandler[byte.MaxValue];
_handlers[(byte)RagonOperation.AUTHORIZED_SUCCESS] = new AuthorizeSuccessHandler(this, listeners);
_handlers[(byte)RagonOperation.AUTHORIZED_FAILED] = new AuthorizeFailedHandler(listeners);
_handlers[(byte)RagonOperation.JOIN_SUCCESS] = new JoinSuccessHandler(this, listeners, _playerCache, _entityCache);
_handlers[(byte)RagonOperation.JOIN_FAILED] = new JoinFailedHandler(listeners);
_handlers[(byte)RagonOperation.LEAVE_ROOM] = new LeaveRoomHandler(this, listeners, _entityCache);
_handlers[(byte)RagonOperation.OWNERSHIP_ROOM_CHANGED] = new OwnershipRoomHandler(listeners, _playerCache, _entityCache);
_handlers[(byte)RagonOperation.OWNERSHIP_ENTITY_CHANGED] = new EntityOwnershipHandler(listeners, _playerCache, _entityCache);
_handlers[(byte)RagonOperation.PLAYER_JOINED] = new PlayerJoinHandler(_playerCache, listeners);
_handlers[(byte)RagonOperation.PLAYER_LEAVED] = new PlayerLeftHandler(_entityCache, _playerCache, listeners);
_handlers[(byte)RagonOperation.LOAD_SCENE] = new SceneLoadHandler(this, listeners);
_handlers[(byte)RagonOperation.AUTHORIZED_SUCCESS] = new AuthorizeSuccessHandler(this, _listeners);
_handlers[(byte)RagonOperation.AUTHORIZED_FAILED] = new AuthorizeFailedHandler(_listeners);
_handlers[(byte)RagonOperation.JOIN_SUCCESS] = new JoinSuccessHandler(this, _listeners, _playerCache, _entityCache);
_handlers[(byte)RagonOperation.JOIN_FAILED] = new JoinFailedHandler(_listeners);
_handlers[(byte)RagonOperation.LEAVE_ROOM] = new LeaveRoomHandler(this, _listeners, _entityCache);
_handlers[(byte)RagonOperation.OWNERSHIP_ROOM_CHANGED] = new OwnershipRoomHandler(_listeners, _playerCache, _entityCache);
_handlers[(byte)RagonOperation.OWNERSHIP_ENTITY_CHANGED] = new EntityOwnershipHandler(_listeners, _playerCache, _entityCache);
_handlers[(byte)RagonOperation.PLAYER_JOINED] = new PlayerJoinHandler(_playerCache, _listeners);
_handlers[(byte)RagonOperation.PLAYER_LEAVED] = new PlayerLeftHandler(_entityCache, _playerCache, _listeners);
_handlers[(byte)RagonOperation.LOAD_SCENE] = new SceneLoadHandler(this, _listeners);
_handlers[(byte)RagonOperation.CREATE_ENTITY] = new EntityCreateHandler(this, _playerCache, _entityCache, _entityListener);
_handlers[(byte)RagonOperation.REMOVE_ENTITY] = new EntityRemoveHandler(_entityCache);
_handlers[(byte)RagonOperation.REPLICATE_ENTITY_STATE] = new StateEntityHandler(_entityCache);
_handlers[(byte)RagonOperation.REPLICATE_ENTITY_EVENT] = new EntityEventHandler(_playerCache, _entityCache);
_handlers[(byte)RagonOperation.REPLICATE_ROOM_EVENT] = new RoomEventHandler(this, _playerCache);
_handlers[(byte)RagonOperation.SNAPSHOT] = new SnapshotHandler(this, listeners, _entityCache, _playerCache, _entityListener);
_handlers[(byte)RagonOperation.SNAPSHOT] = new SnapshotHandler(this, _listeners, _entityCache, _playerCache, _entityListener);
_handlers[(byte)RagonOperation.TIMESTAMP_SYNCHRONIZATION] = new TimestampHandler(this);
_handlers[(byte)RagonOperation.REPLICATE_RAW_DATA] = new RoomDataHandler(_playerCache, listeners);
_handlers[(byte)RagonOperation.REPLICATE_RAW_DATA] = new RoomDataHandler(_playerCache, _listeners);
_handlers[(byte)RagonOperation.ROOM_LIST_UPDATED] = new RoomListHandler(_session, _listeners);
var protocolRaw = RagonVersion.Parse(protocol);
_connection.Connect(address, port, protocolRaw);
@@ -153,7 +153,7 @@ namespace Ragon.Client
_stats.Update(_connection.BytesSent, _connection.BytesReceived, _connection.Ping, dt);
}
listeners.Update();
_listeners.Update();
_connection.Update();
}
@@ -167,31 +167,32 @@ namespace Ragon.Client
_connection.Dispose();
}
public void AddListener(IRagonListener listener) => listeners.Add(listener);
public void AddListener(IRagonAuthorizationListener listener) => listeners.Add(listener);
public void AddListener(IRagonConnectionListener listener) => listeners.Add(listener);
public void AddListener(IRagonFailedListener listener) => listeners.Add(listener);
public void AddListener(IRagonJoinListener listener) => listeners.Add(listener);
public void AddListener(IRagonLeftListener listener) => listeners.Add(listener);
public void AddListener(IRagonOwnershipChangedListener listener) => listeners.Add(listener);
public void AddListener(IRagonPlayerJoinListener listener) => listeners.Add(listener);
public void AddListener(IRagonPlayerLeftListener listener) => listeners.Add(listener);
public void AddListener(IRagonSceneListener listener) => listeners.Add(listener);
public void AddListener(IRagonSceneRequestListener listener) => listeners.Add(listener);
public void AddListener(IRagonDataListener listener) => listeners.Add(listener);
public void RemoveListener(IRagonListener listener) => listeners.Remove(listener);
public void RemoveListener(IRagonAuthorizationListener listener) => listeners.Remove(listener);
public void RemoveListener(IRagonConnectionListener listener) => listeners.Remove(listener);
public void RemoveListener(IRagonFailedListener listener) => listeners.Remove(listener);
public void RemoveListener(IRagonJoinListener listener) => listeners.Remove(listener);
public void RemoveListener(IRagonLeftListener listener) => listeners.Remove(listener);
public void RemoveListener(IRagonOwnershipChangedListener listener) => listeners.Remove(listener);
public void RemoveListener(IRagonPlayerJoinListener listener) => listeners.Remove(listener);
public void RemoveListener(IRagonPlayerLeftListener listener) => listeners.Remove(listener);
public void RemoveListener(IRagonSceneListener listener) => listeners.Remove(listener);
public void RemoveListener(IRagonSceneRequestListener listener) => listeners.Remove(listener);
public void RemoveListener(IRagonDataListener listener) => listeners.Remove(listener);
public void AddListener(IRagonListener listener) => _listeners.Add(listener);
public void AddListener(IRagonAuthorizationListener listener) => _listeners.Add(listener);
public void AddListener(IRagonConnectionListener listener) => _listeners.Add(listener);
public void AddListener(IRagonFailedListener listener) => _listeners.Add(listener);
public void AddListener(IRagonJoinListener listener) => _listeners.Add(listener);
public void AddListener(IRagonLeftListener listener) => _listeners.Add(listener);
public void AddListener(IRagonOwnershipChangedListener listener) => _listeners.Add(listener);
public void AddListener(IRagonPlayerJoinListener listener) => _listeners.Add(listener);
public void AddListener(IRagonPlayerLeftListener listener) => _listeners.Add(listener);
public void AddListener(IRagonSceneListener listener) => _listeners.Add(listener);
public void AddListener(IRagonSceneRequestListener listener) => _listeners.Add(listener);
public void AddListener(IRagonDataListener listener) => _listeners.Add(listener);
public void AddListener(IRagonRoomListListener listener) => _listeners.Add(listener);
public void RemoveListener(IRagonListener listener) => _listeners.Remove(listener);
public void RemoveListener(IRagonAuthorizationListener listener) => _listeners.Remove(listener);
public void RemoveListener(IRagonConnectionListener listener) => _listeners.Remove(listener);
public void RemoveListener(IRagonFailedListener listener) => _listeners.Remove(listener);
public void RemoveListener(IRagonJoinListener listener) => _listeners.Remove(listener);
public void RemoveListener(IRagonLeftListener listener) => _listeners.Remove(listener);
public void RemoveListener(IRagonOwnershipChangedListener listener) => _listeners.Remove(listener);
public void RemoveListener(IRagonPlayerJoinListener listener) => _listeners.Remove(listener);
public void RemoveListener(IRagonPlayerLeftListener listener) => _listeners.Remove(listener);
public void RemoveListener(IRagonSceneListener listener) => _listeners.Remove(listener);
public void RemoveListener(IRagonSceneRequestListener listener) => _listeners.Remove(listener);
public void RemoveListener(IRagonDataListener listener) => _listeners.Remove(listener);
public void RemoveListener(IRagonRoomListListener listener) => _listeners.Remove(listener);
#endregion
@@ -235,7 +236,7 @@ namespace Ragon.Client
{
RagonLog.Trace("Connected");
listeners.OnConnected();
_listeners.OnConnected();
_status = RagonStatus.CONNECTED;
}
@@ -243,7 +244,7 @@ namespace Ragon.Client
{
RagonLog.Trace($"Disconnected: {reason}");
listeners.OnDisconnected(reason);
_listeners.OnDisconnected(reason);
_status = RagonStatus.DISCONNECTED;
}
+3 -7
View File
@@ -116,7 +116,7 @@ public sealed class RagonEntityCache
foreach (var ent in _entityList)
{
if (!ent.IsAttached ||
!ent.Replication ||
!ent.IsReplicated ||
!ent.PropertiesChanged) continue;
ent.Write(buffer);
@@ -186,20 +186,17 @@ public sealed class RagonEntityCache
}
}
if (_pendingEntities.TryGetValue(attachId, out var pendingEntity))
if (_pendingEntities.TryGetValue(attachId, out var pendingEntity) && hasAuthority)
{
_pendingEntities.Remove(attachId);
_entityMap.Add(entityId, pendingEntity);
if (hasAuthority)
_entityList.Add(pendingEntity);
_entityList.Add(pendingEntity);
hasCreated = false;
return pendingEntity;
}
var entity = new RagonEntity(entityType, sceneId);
_entityMap.Add(entityId, entity);
@@ -217,7 +214,6 @@ public sealed class RagonEntityCache
{
if (_entityMap.TryGetValue(entityId, out var entity))
{
_entityMap.Remove(entityId);
_entityList.Remove(entity);
+17
View File
@@ -32,6 +32,7 @@ namespace Ragon.Client
private readonly List<IRagonPlayerJoinListener> _playerJoinListeners = new();
private readonly List<IRagonPlayerLeftListener> _playerLeftListeners = new();
private readonly List<IRagonDataListener> _dataListeners = new();
private readonly List<IRagonRoomListListener> _roomListListeners = new();
private readonly List<Action> _delayedActions = new();
public RagonListenerList(RagonClient client)
@@ -131,6 +132,11 @@ namespace Ragon.Client
_playerLeftListeners.Add(listener);
}
public void Add(IRagonRoomListListener listener)
{
_roomListListeners.Add(listener);
}
public void Remove(IRagonDataListener listener)
{
_delayedActions.Add(() => _dataListeners.Remove(listener));
@@ -186,6 +192,11 @@ namespace Ragon.Client
_delayedActions.Add(() => _playerLeftListeners.Remove(listener));
}
public void Remove(IRagonRoomListListener listener)
{
_delayedActions.Add(() => _roomListListeners.Remove(listener));
}
public void OnAuthorizationSuccess(string playerId, string playerName, string payload)
{
foreach (var listener in _authorizationListeners)
@@ -263,5 +274,11 @@ namespace Ragon.Client
foreach (var listener in _dataListeners)
listener.OnData(player, data);
}
public void OnRoomList(RagonRoomInformation[] roomInfos)
{
foreach (var listListener in _roomListListeners)
listListener.OnRoomListUpdate(roomInfos);
}
}
}
+25 -2
View File
@@ -27,8 +27,21 @@ public sealed class RagonPlayerCache
public RagonPlayer Local { get; private set; }
public bool IsRoomOwner => _ownerId == _localId;
public RagonPlayer? GetPlayerById(string playerId) => _playersById[playerId];
public RagonPlayer? GetPlayerByPeer(ushort peerId) => _playersByConnection[peerId];
public RagonPlayer? GetPlayerById(string playerId)
{
if (_playersById.TryGetValue(playerId, out var player))
return player;
return null;
}
public RagonPlayer? GetPlayerByPeer(ushort peerId)
{
if (_playersByConnection.TryGetValue(peerId, out var player))
return player;
return null;
}
private string _ownerId;
private string _localId;
@@ -91,4 +104,14 @@ public sealed class RagonPlayerCache
_playersByConnection.Clear();
_playersById.Clear();
}
public void Dump()
{
RagonLog.Trace("Players: ");
RagonLog.Trace("[Connection] [ID] [Name]");
foreach (var player in _players)
{
RagonLog.Trace($"[{player.PeerId}] {player.Id} {player.Name}");
}
}
}
+35 -21
View File
@@ -20,17 +20,44 @@ namespace Ragon.Client
{
public class RagonRoom: IDisposable
{
private class EventSubscription : IDisposable
{
private List<Action<RagonPlayer, IRagonEvent>> _callbacks;
private List<Action<RagonPlayer, IRagonEvent>> _localCallbacks;
private Action<RagonPlayer, IRagonEvent> _callback;
public EventSubscription(
List<Action<RagonPlayer, IRagonEvent>> callbacks,
List<Action<RagonPlayer, IRagonEvent>> localCallbacks,
Action<RagonPlayer, IRagonEvent> callback)
{
_callbacks = callbacks;
_localCallbacks = localCallbacks;
_callback = callback;
}
public void Dispose()
{
_callbacks?.Remove(_callback);
_localCallbacks?.Remove(_callback);
_callbacks = null!;
_localCallbacks = null!;
_callback = null!;
}
}
private delegate void OnEventDelegate(RagonPlayer player, RagonBuffer serializer);
private RagonClient _client;
private RagonScene _scene;
private RagonEntityCache _entityCache;
private RagonPlayerCache _playerCache;
private RagonRoomInformation _information;
private RoomParameters _parameters;
public string Id => _information.RoomId;
public int MinPlayers => _information.Min;
public int MaxPlayers => _information.Max;
public string Id => _parameters.RoomId;
public int MinPlayers => _parameters.Min;
public int MaxPlayers => _parameters.Max;
public string Scene => _scene.Name;
public IReadOnlyList<RagonPlayer> Players => _playerCache.Players;
@@ -44,11 +71,11 @@ namespace Ragon.Client
public RagonRoom(RagonClient client,
RagonEntityCache entityCache,
RagonPlayerCache playerCache,
RagonRoomInformation information,
RoomParameters parameters,
RagonScene scene)
{
_client = client;
_information = information;
_parameters = parameters;
_entityCache = entityCache;
_playerCache = playerCache;
_scene = scene;
@@ -73,11 +100,10 @@ namespace Ragon.Client
RagonLog.Warn($"Handler event on entity {Id} with eventCode {eventCode} not defined");
}
public Action<RagonPlayer, IRagonEvent> OnEvent<TEvent>(Action<RagonPlayer, TEvent> callback) where TEvent : IRagonEvent, new()
public IDisposable OnEvent<TEvent>(Action<RagonPlayer, TEvent> callback) where TEvent : IRagonEvent, new()
{
var t = new TEvent();
var eventCode = _client.Event.GetEventCode(t);
var action = (RagonPlayer player, IRagonEvent eventData) => callback.Invoke(player, (TEvent)eventData);
if (!_listeners.TryGetValue(eventCode, out var callbacks))
@@ -106,19 +132,7 @@ namespace Ragon.Client
});
}
return action;
}
public void OffEvent<TEvent>(Action<RagonPlayer, IRagonEvent> callback) where TEvent : IRagonEvent, new()
{
var t = new TEvent();
var eventCode = _client.Event.GetEventCode(t);
if (_listeners.TryGetValue(eventCode, out var callbacks))
callbacks.Remove(callback);
if (_localListeners.TryGetValue(eventCode, out var localCallbacks))
localCallbacks.Remove(callback);
return new EventSubscription(callbacks, localCallbacks, action);
}
public void LoadScene(string sceneName) => _scene.Load(sceneName);
@@ -0,0 +1,12 @@
namespace Ragon.Client
{
public struct RagonRoomInformation
{
public string Id;
public string Scene;
public int PlayerMax;
public int PlayerMin;
public int PlayerCount;
public Dictionary<string, byte[]> Properties;
}
}
+6 -6
View File
@@ -31,11 +31,11 @@ namespace Ragon.Client
public void CreateOrJoin(string sceneName, int minPlayers, int maxPlayers)
{
var parameters = new RagonRoomParameters() {Scene = sceneName, Min = minPlayers, Max = maxPlayers};
var parameters = new RagonRoomPayload() {Scene = sceneName, Min = minPlayers, Max = maxPlayers};
CreateOrJoin(parameters);
}
public void CreateOrJoin(RagonRoomParameters parameters)
public void CreateOrJoin(RagonRoomPayload parameters)
{
_buffer.Clear();
_buffer.WriteOperation(RagonOperation.JOIN_OR_CREATE_ROOM);
@@ -48,15 +48,15 @@ namespace Ragon.Client
public void Create(string sceneName, int minPlayers, int maxPlayers)
{
Create(null, new RagonRoomParameters() {Scene = sceneName, Min = minPlayers, Max = maxPlayers});
Create(null, new RagonRoomPayload() {Scene = sceneName, Min = minPlayers, Max = maxPlayers});
}
public void Create(string roomId, string sceneNa, int minPlayers, int maxPlayers)
public void Create(string roomId, string sceneName, int minPlayers, int maxPlayers)
{
Create(roomId, new RagonRoomParameters() {Scene = sceneNa, Min = minPlayers, Max = maxPlayers});
Create(roomId, new RagonRoomPayload() {Scene = sceneName, Min = minPlayers, Max = maxPlayers});
}
public void Create(string roomId, RagonRoomParameters parameters)
public void Create(string roomId, RagonRoomPayload parameters)
{
_buffer.Clear();
_buffer.WriteOperation(RagonOperation.CREATE_ROOM);
-1
View File
@@ -6,7 +6,6 @@
<LangVersion>8</LangVersion>
<RootNamespace>Ragon.Common</RootNamespace>
<GeneratePackageOnBuild>true</GeneratePackageOnBuild>
<Version>1.2.4-rc</Version>
<Title>Ragon.Protocol</Title>
<Copyright>Eduard Kargin</Copyright>
<PackageProjectUrl>https://ragon-server.com</PackageProjectUrl>
+39 -10
View File
@@ -1,5 +1,5 @@
/*
* Copyright 2023 Eduard Kargin <kargin.eduard@gmail.com>
* Copyright 2023-2024 Eduard Kargin <kargin.eduard@gmail.com>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -75,7 +75,7 @@ namespace Ragon.Protocol
public int ReadOffset => _read;
public int WriteOffset => _write;
public int Length => ((_write - 1) >> 3) + 1;
public int Capacity => _write - _read;
public int Capacity => _write - _read - 1;
public RagonBuffer(int capacity = 128)
{
@@ -121,6 +121,21 @@ namespace Ragon.Protocol
return (RagonOperation)Read(8);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void WriteFloat(float value)
{
var bytes = BitConverter.GetBytes(value);
WriteBytes(bytes);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public float ReadFloat()
{
var bytes = ReadBytes(4);
var value = BitConverter.ToSingle(bytes, 0);
return value;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void WriteFloat(float value, float min, float max, float precision)
{
@@ -147,6 +162,23 @@ namespace Ragon.Protocol
return adjusted;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void WriteInt(int value)
{
var bytes = BitConverter.GetBytes(value);
WriteBytes(bytes);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public int ReadInt()
{
var bytes = ReadBytes(4);
var value = BitConverter.ToInt32(bytes, 0);
return value;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void WriteInt(int value, int min, int max)
{
@@ -236,9 +268,6 @@ namespace Ragon.Protocol
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void Write(uint value, int numBits = 16)
{
Debug.Assert(!(numBits < 0));
Debug.Assert(!(numBits > 32));
var currentBucketIndex = _write >> 5;
var used = _write & 0x0000001F;
var mask = (1UL << used) - 1;
@@ -284,10 +313,10 @@ namespace Ragon.Protocol
[MethodImpl(MethodImplOptions.AggressiveInlining)]
[Obsolete("Do not use this method, will be removed")]
public byte[] ReadBytes(int lenght)
public byte[] ReadBytes(int len)
{
var data = new byte[lenght];
for (int i = 0; i < lenght; i++)
var data = new byte[len];
for (int i = 0; i < len; i++)
data[i] = (byte)Read(8);
return data;
@@ -357,7 +386,7 @@ namespace Ragon.Protocol
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void FromBuffer(RagonBuffer buffer, int size)
public void CopyFrom(RagonBuffer buffer, int size)
{
WriteArray(buffer._buckets, size);
}
@@ -434,7 +463,7 @@ namespace Ragon.Protocol
public void ToArray(byte[] outData)
{
Debug.Assert(outData.Length >= Length);
Write(1, 1);
var bucketsCount = (_write >> 5) + 1;
var length = Length;
+1
View File
@@ -44,5 +44,6 @@ namespace Ragon.Protocol
TRANSFER_ROOM_OWNERSHIP = 23,
TRANSFER_ENTITY_OWNERSHIP = 24,
TIMESTAMP_SYNCHRONIZATION = 25,
ROOM_LIST_UPDATED = 26,
}
}
@@ -17,7 +17,7 @@
namespace Ragon.Protocol
{
public class RagonRoomParameters: IRagonSerializable
public class RagonRoomPayload: IRagonSerializable
{
public string Scene { get; set; }
public int Min { get; set; }
+309
View File
@@ -0,0 +1,309 @@
using System;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Text;
namespace Ragon.Protocol
{
[StructLayout(LayoutKind.Explicit)]
internal struct ValueConverter
{
[FieldOffset(0)] public int Int;
[FieldOffset(0)] public float Float;
[FieldOffset(0)] public long Long;
[FieldOffset(0)] public byte Byte0;
[FieldOffset(1)] public byte Byte1;
[FieldOffset(2)] public byte Byte2;
[FieldOffset(3)] public byte Byte3;
[FieldOffset(4)] public byte Byte4;
[FieldOffset(5)] public byte Byte5;
[FieldOffset(6)] public byte Byte6;
[FieldOffset(7)] public byte Byte7;
}
public class RagonStream
{
private byte[] _data;
private int _offset;
private int _size;
public int Lenght => _offset;
public int Size => _size - _offset;
public RagonStream(int capacity = 256)
{
_data = new byte[capacity];
_offset = 0;
_size = 0;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void Reset()
{
_size = _offset;
_offset = 0;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void AddOffset(int offset)
{
_offset += offset;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public int WriteByte(byte value)
{
ResizeIfNeed(1);
_data[_offset] = value;
_offset += 1;
return 1;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public byte ReadByte()
{
var value = _data[_offset];
_offset += 1;
return value;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public int WriteBool(bool value)
{
ResizeIfNeed(1);
_data[_offset] = value ? (byte)1 : (byte)0;
_offset += 1;
return 1;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public bool ReadBool()
{
var value = _data[_offset];
_offset += 1;
return value == 1;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public int WriteInt(int value)
{
ResizeIfNeed(4);
var converter = new ValueConverter() { Int = value };
_data[_offset] = converter.Byte0;
_data[_offset + 1] = converter.Byte1;
_data[_offset + 2] = converter.Byte2;
_data[_offset + 3] = converter.Byte3;
_offset += 4;
return 4;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public int WriteInt(int value, int offset)
{
ResizeIfNeed(4);
var converter = new ValueConverter() { Int = value };
_data[offset] = converter.Byte0;
_data[offset + 1] = converter.Byte1;
_data[offset + 2] = converter.Byte2;
_data[offset + 3] = converter.Byte3;
return 4;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public int ReadInt()
{
var converter = new ValueConverter
{ Byte0 = _data[_offset], Byte1 = _data[_offset + 1], Byte2 = _data[_offset + 2], Byte3 = _data[_offset + 3] };
_offset += 4;
return converter.Int;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void WriteLong(long value)
{
ResizeIfNeed(8);
WriteLong(value, _offset);
_offset += 8;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public int WriteLong(long value, int offset)
{
var converter = new ValueConverter() { Long = value };
_data[offset] = converter.Byte0;
_data[offset + 1] = converter.Byte1;
_data[offset + 2] = converter.Byte2;
_data[offset + 3] = converter.Byte3;
_data[offset + 4] = converter.Byte4;
_data[offset + 5] = converter.Byte5;
_data[offset + 6] = converter.Byte6;
_data[offset + 7] = converter.Byte7;
return 8;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public long ReadLong()
{
var converter = new ValueConverter
{
Byte0 = _data[_offset],
Byte1 = _data[_offset + 1],
Byte2 = _data[_offset + 2],
Byte3 = _data[_offset + 3],
Byte4 = _data[_offset + 4],
Byte5 = _data[_offset + 5],
Byte6 = _data[_offset + 6],
Byte7 = _data[_offset + 7],
};
_offset += 8;
return converter.Long;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public int WriteFloat(float value)
{
var converter = new ValueConverter() { Float = value };
WriteInt(converter.Int);
return 4;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public float ReadFloat()
{
var rawValue = ReadInt();
var converter = new ValueConverter() { Int = rawValue };
var value = converter.Float;
return value;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public int WriteString(string value)
{
var rawData = Encoding.UTF8.GetBytes(value);
var len = rawData.Length;
ResizeIfNeed(2 + len);
WriteUShort((ushort)len);
Buffer.BlockCopy(rawData, 0, _data, _offset, len);
_offset += len;
return len + 2;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public string ReadString()
{
var len = ReadUShort();
var rawData = new byte[len];
Buffer.BlockCopy(_data, _offset, rawData, 0, len);
var str = Encoding.UTF8.GetString(rawData);
_offset += len;
return str;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public byte[] ReadBinary(int len)
{
if (len >= _data.Length)
return Array.Empty<byte>();
var payload = new byte[len];
Buffer.BlockCopy(_data, _offset, payload, 0, len);
_offset += len;
return payload;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void WriteBinary(byte[] payload)
{
ResizeIfNeed(payload.Length);
Array.Copy(payload, 0, _data, _offset, payload.Length);
_offset += payload.Length;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void WriteOperation(RagonOperation operation)
{
ResizeIfNeed(1);
_data[_offset] = (byte)operation;
_offset += 1;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public RagonOperation ReadOperation()
{
var op = (RagonOperation)_data[_offset];
_offset += 1;
return op;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void WriteUShort(ushort value)
{
ResizeIfNeed(2);
_data[_offset] = (byte)(value & 0x00FF);
_data[_offset + 1] = (byte)((value & 0xFF00) >> 8);
_offset += 2;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void WriteUShort(ushort value, int offset)
{
ResizeIfNeed(2);
_data[offset] = (byte)(value & 0x00FF);
_data[offset + 1] = (byte)((value & 0xFF00) >> 8);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public ushort ReadUShort()
{
var value = (ushort)(_data[_offset] + (_data[_offset + 1] << 8));
_offset += 2;
return value;
}
public void Clear()
{
_offset = 0;
_size = 0;
}
public void FromArray(byte[] data)
{
Clear();
ResizeIfNeed(data.Length);
Buffer.BlockCopy(data, 0, _data, 0, data.Length);
_size = data.Length;
}
public byte[] ToArray()
{
var bytes = new byte[_offset];
Buffer.BlockCopy(_data, 0, bytes, 0, _offset);
return bytes;
}
private void ResizeIfNeed(int lenght)
{
if (_offset + lenght < _data.Length)
return;
var newData = new byte[_data.Length * 4 + lenght];
Buffer.BlockCopy(_data, 0, newData, 0, _data.Length);
_data = newData;
}
}
}
+1 -1
View File
@@ -3,7 +3,7 @@
<PropertyGroup>
<OutputType>Exe</OutputType>
<RootNamespace>Ragon.Relay</RootNamespace>
<TargetFramework>net7.0</TargetFramework>
<TargetFramework>net8.0</TargetFramework>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)' == 'Release' ">
+6
View File
@@ -1,5 +1,6 @@
using System;
using Newtonsoft.Json;
using Ragon.Server;
using Ragon.Server.Plugin;
namespace Ragon.Relay;
@@ -21,4 +22,9 @@ public class RelayServerPlugin: BaseServerPlugin
return true;
}
public override IRoomPlugin CreateRoomPlugin(RoomInformation information)
{
return new RelayRoomPlugin();
}
}
@@ -47,22 +47,32 @@ public class WebSocketServer : INetworkServer
{
while (!cancellationToken.IsCancellationRequested)
{
var context = await _httpListener.GetContextAsync();
if (!context.Request.IsWebSocketRequest)
WebSocketConnection connection = null!;
try
{
context.Response.StatusCode = 200;
context.Response.ContentLength64 = 0;
context.Response.Close();
continue;
var context = await _httpListener.GetContextAsync();
if (!context.Request.IsWebSocketRequest)
{
context.Response.StatusCode = 200;
context.Response.ContentLength64 = 0;
context.Response.Close();
continue;
}
var webSocketContext = await context.AcceptWebSocketAsync(null);
var webSocket = webSocketContext.WebSocket;
var peerId = _sequencer.Pop();
connection = new WebSocketConnection(webSocket, peerId);
}
catch (Exception ex)
{
_logger.Warn(ex);
continue;
}
var webSocketContext = await context.AcceptWebSocketAsync(null);
var webSocket = webSocketContext.WebSocket;
_connections[connection.Id] = connection;
var peerId = _sequencer.Pop();
var connection = new WebSocketConnection(webSocket, peerId);
_connections[peerId] = connection;
StartListen(connection, cancellationToken);
}
}
@@ -75,6 +85,7 @@ public class WebSocketServer : INetworkServer
var webSocket = connection.Socket;
var bytes = new byte[2048];
var buffer = new Memory<byte>(bytes);
while (
webSocket.State == WebSocketState.Open ||
!cancellationToken.IsCancellationRequested)
@@ -84,7 +95,7 @@ public class WebSocketServer : INetworkServer
var result = await webSocket.ReceiveAsync(buffer, cancellationToken);
if (result.Count > 0)
{
var payload = buffer.Slice(0, buffer.Length);
var payload = buffer.Slice(0, result.Count);
_networkListener.OnData(connection, NetworkChannel.RELIABLE, payload.ToArray());
}
}
@@ -96,6 +107,7 @@ public class WebSocketServer : INetworkServer
_sequencer.Push(connection.Id);
_activeConnections.Remove(connection);
_networkListener.OnDisconnected(connection);
}
+1 -1
View File
@@ -5,7 +5,7 @@
<Nullable>enable</Nullable>
<RootNamespace>Ragon.Core</RootNamespace>
<GeneratePackageOnBuild>true</GeneratePackageOnBuild>
<Version>1.2.4-rc</Version>
<Version>1.3.1</Version>
<Title>Ragon.Server</Title>
<Copyright>Eduard Kargin</Copyright>
<PackageProjectUrl>https://ragon-server.com</PackageProjectUrl>
@@ -14,7 +14,6 @@
* limitations under the License.
*/
using Ragon.Protocol;
namespace Ragon.Server.Entity;
@@ -54,6 +54,13 @@ public class RagonProperty : RagonPayload
public void Write(RagonBuffer buffer)
{
if (IsFixed)
{
buffer.WriteArray(_data, Size);
return;
}
buffer.Write((ushort) Size);
buffer.WriteArray(_data, Size);
}
+2 -2
View File
@@ -39,13 +39,13 @@ public class RagonEvent
public void Read(RagonBuffer buffer)
{
_size = buffer.Capacity - 1;
_size = buffer.Capacity;
buffer.ReadArray(_data, _size);
}
public void Write(RagonBuffer buffer)
{
if (_size == 0) return;
if (_size <= 0) return;
buffer.WriteArray(_data, _size);
}
}
@@ -26,7 +26,7 @@ namespace Ragon.Server.Handler;
public sealed class RoomCreateOperation : BaseOperation
{
private readonly RagonRoomParameters _roomParameters = new();
private readonly RagonRoomPayload _roomPayload = new();
private readonly Logger _logger = LogManager.GetCurrentClassLogger();
private readonly IServerPlugin _serverPlugin;
private readonly RagonWebHookPlugin _ragonWebHookPlugin;
@@ -65,13 +65,13 @@ public sealed class RoomCreateOperation : BaseOperation
}
}
_roomParameters.Deserialize(Reader);
_roomPayload.Deserialize(Reader);
var information = new RoomInformation()
{
Scene = _roomParameters.Scene,
Max = _roomParameters.Max,
Min = _roomParameters.Min,
Scene = _roomPayload.Scene,
Max = _roomPayload.Max,
Min = _roomPayload.Min,
};
var lobbyPlayer = context.LobbyPlayer;
@@ -80,6 +80,9 @@ public sealed class RoomCreateOperation : BaseOperation
var roomPlugin = _serverPlugin.CreateRoomPlugin(information);
var room = new RagonRoom(roomId, information, roomPlugin);
if (!roomPlugin.OnPlayerJoined(roomPlayer))
return;
roomPlayer.OnAttached(room);
context.Scheduler.Run(room);
@@ -32,18 +32,17 @@ public sealed class RoomDataOperation : BaseOperation
var room = context.Room;
var data = Reader.RawData;
Writer.Clear();
Writer.WriteOperation(RagonOperation.REPLICATE_RAW_DATA);
Writer.WriteUShort(player.Connection.Id);
var playerData = Writer.ToArray();
var payloadData = data;
var size = playerData.Length + payloadData.Length;
var dataSize = data.Length - 1;
var headerSize = 3;
var size = headerSize + dataSize;
var sendData = new byte[size];
var peerId = player.Connection.Id;
Array.Copy(playerData, 0, sendData, 0, playerData.Length);
Array.Copy(payloadData, 1, sendData, playerData.Length, payloadData.Length - 1);
sendData[0] = (byte)RagonOperation.REPLICATE_RAW_DATA;
sendData[1] = (byte)peerId;
sendData[2] = (byte)(peerId >> 8);
Array.Copy(data, 1, sendData, headerSize, dataSize);
room.Broadcast(sendData, channel);
}
@@ -26,7 +26,7 @@ namespace Ragon.Server.Handler;
public sealed class RoomJoinOrCreateOperation : BaseOperation
{
private readonly RagonRoomParameters _roomParameters = new();
private readonly RagonRoomPayload _roomPayload = new();
private readonly Logger _logger = LogManager.GetCurrentClassLogger();
private readonly IServerPlugin _serverPlugin;
private readonly RagonWebHookPlugin _ragonWebHookPlugin;
@@ -48,11 +48,15 @@ public sealed class RoomJoinOrCreateOperation : BaseOperation
var roomId = Guid.NewGuid().ToString();
var lobbyPlayer = context.LobbyPlayer;
_roomParameters.Deserialize(Reader);
_roomPayload.Deserialize(Reader);
if (context.Lobby.FindRoomByScene(_roomParameters.Scene, out var existsRoom))
if (context.Lobby.FindRoomByScene(_roomPayload.Scene, out var existsRoom))
{
var player = new RagonRoomPlayer(context.Connection, lobbyPlayer.Id, lobbyPlayer.Name);
if (!existsRoom.Plugin.OnPlayerJoined(player))
return;
context.SetRoom(existsRoom, player);
_ragonWebHookPlugin.RoomJoined(context, existsRoom, player);
@@ -63,15 +67,18 @@ public sealed class RoomJoinOrCreateOperation : BaseOperation
{
var information = new RoomInformation()
{
Scene = _roomParameters.Scene,
Max = _roomParameters.Max,
Min = _roomParameters.Min,
Scene = _roomPayload.Scene,
Max = _roomPayload.Max,
Min = _roomPayload.Min,
};
var roomPlayer = new RagonRoomPlayer(context.Connection, lobbyPlayer.Id, lobbyPlayer.Name);
var roomPlugin = _serverPlugin.CreateRoomPlugin(information);
var room = new RagonRoom(roomId, information, roomPlugin);
if (!roomPlugin.OnPlayerJoined(roomPlayer))
return;
_ragonWebHookPlugin.RoomCreated(context, room, roomPlayer);
context.Lobby.Persist(room);
+3
View File
@@ -14,6 +14,8 @@
* limitations under the License.
*/
using Ragon.Protocol;
using Ragon.Server.Handler;
using Ragon.Server.IO;
using Ragon.Server.Lobby;
@@ -21,6 +23,7 @@ namespace Ragon.Server;
public interface IRagonServer
{
BaseOperation ResolveHandler(RagonOperation operation);
RagonLobbyPlayer? GetPlayerByConnection(INetworkConnection connection);
RagonLobbyPlayer? GetPlayerById(string id);
}
@@ -21,6 +21,7 @@ namespace Ragon.Server.Lobby;
public interface IRagonLobby
{
public IReadOnlyList<IRagonRoom> Rooms { get; }
public bool FindRoomById(string roomId, [MaybeNullWhen(false)] out RagonRoom room);
public bool FindRoomByScene(string sceneName, [MaybeNullWhen(false)] out RagonRoom room);
public void Persist(RagonRoom room);
@@ -0,0 +1,33 @@
using Ragon.Protocol;
using Ragon.Server.Room;
namespace Ragon.Server.Lobby;
public class RagonLobbyDispatcher
{
private IRagonLobby _lobby;
public RagonLobbyDispatcher(IRagonLobby lobby)
{
_lobby = lobby;
}
public void Write(RagonBuffer writer)
{
writer.Clear();
writer.WriteOperation(RagonOperation.ROOM_LIST_UPDATED);
var rooms = _lobby.Rooms;
writer.WriteUShort((ushort)rooms.Count);
for (int i = 0; i < rooms.Count; i++)
{
var room = rooms[i];
writer.WriteString(room.Id);
writer.WriteString(room.Scene);
writer.WriteUShort((ushort)room.PlayerMax);
writer.WriteUShort((ushort)room.PlayerMin);
writer.WriteUShort((ushort)room.PlayerCount);
}
}
}
@@ -25,12 +25,22 @@ public class LobbyInMemory : IRagonLobby
private readonly List<RagonRoom> _rooms = new();
private readonly Logger _logger = LogManager.GetCurrentClassLogger();
public bool FindRoomById(string RagonRoomId, [MaybeNullWhen(false)] out RagonRoom room)
public IReadOnlyList<IRagonRoom> Rooms => _rooms.AsReadOnly();
public bool FindRoomById(string roomId, [MaybeNullWhen(false)] out RagonRoom room)
{
foreach (var existRagonRoom in _rooms)
{
if (existRagonRoom.Id == RagonRoomId && existRagonRoom.PlayerMin < existRagonRoom.PlayerMax)
if (existRagonRoom.Id == roomId)
{
if (existRagonRoom.PlayerCount >= existRagonRoom.PlayerMax)
{
_logger.Warn($"Room with id {roomId} fulfilled");
room = default;
return false;
}
room = existRagonRoom;
return true;
}
@@ -44,8 +54,16 @@ public class LobbyInMemory : IRagonLobby
{
foreach (var existsRoom in _rooms)
{
if (existsRoom.Scene == sceneName && existsRoom.PlayerCount < existsRoom.PlayerMax)
if (existsRoom.Scene == sceneName)
{
if (existsRoom.PlayerCount >= existsRoom.PlayerMax)
{
_logger.Warn($"Room with scene {sceneName} fulfilled");
room = default;
return false;
}
room = existsRoom;
return true;
}
@@ -0,0 +1,10 @@
namespace Ragon.Server.Logging;
public interface IRagonLogger
{
public void Warning(string message);
public void Info(string message);
public void Error(string message);
public void Error(Exception ex);
public void Trace(string message);
}
@@ -0,0 +1,6 @@
namespace Ragon.Server.Logging;
public interface IRagonLoggerFactory
{
public IRagonLogger GetLogger(string tag);
}
@@ -0,0 +1,17 @@
namespace Ragon.Server.Logging
{
public class LoggerManager
{
private static IRagonLoggerFactory _factory = null!;
public static void SetLoggerFactory(IRagonLoggerFactory loggerFactory)
{
_factory = loggerFactory;
}
public static IRagonLogger GetLogger(string tag)
{
return _factory.GetLogger(tag);
}
}
}
@@ -49,7 +49,7 @@ public class BaseServerPlugin: IServerPlugin
return true;
}
public IRoomPlugin CreateRoomPlugin(RoomInformation information)
public virtual IRoomPlugin CreateRoomPlugin(RoomInformation information)
{
return new BaseRoomPlugin();
}
@@ -28,10 +28,10 @@ public class RagonWebHookPlugin
{
private Dictionary<string, string> _webHooks;
private RagonServer _server;
private IRagonServer _server;
private HttpClient _httpClient;
public RagonWebHookPlugin(RagonServer server, RagonServerConfiguration configuration)
public RagonWebHookPlugin(IRagonServer server, RagonServerConfiguration configuration)
{
_webHooks = new Dictionary<string, string>(configuration.WebHooks);
_httpClient = new HttpClient();
@@ -46,7 +46,7 @@ public class RagonWebHookPlugin
var executor = context.Executor;
executor.Run(async () =>
{
var authorizationOperation = (AuthorizationOperation) _server.ResolveOperation(RagonOperation.AUTHORIZE);
var authorizationOperation = (AuthorizationOperation) _server.ResolveHandler(RagonOperation.AUTHORIZE);
var response = await _httpClient.PostAsync(new Uri(value), httpContent);
if (response.StatusCode != HttpStatusCode.OK)
{
+24 -3
View File
@@ -45,6 +45,7 @@ public class RagonServer : IRagonServer, INetworkListener
private readonly Dictionary<ushort, RagonContext> _contextsByConnection;
private readonly Dictionary<string, RagonContext> _contextsByPlayerId;
private readonly Stopwatch _timer;
private readonly RagonLobbyDispatcher _lobbySerializer;
private readonly long _tickRate = 0;
public RagonServer(
@@ -59,6 +60,7 @@ public class RagonServer : IRagonServer, INetworkListener
_contextsByConnection = new Dictionary<ushort, RagonContext>();
_contextsByPlayerId = new Dictionary<string, RagonContext>();
_lobby = new LobbyInMemory();
_lobbySerializer = new RagonLobbyDispatcher(_lobby);
_scheduler = new RagonScheduler();
_webhooks = new RagonWebHookPlugin(this, configuration);
_dedicatedThread = new Thread(Execute);
@@ -71,6 +73,8 @@ public class RagonServer : IRagonServer, INetworkListener
var contextObserver = new RagonContextObserver(_contextsByPlayerId);
_scheduler.Run(new RagonActionTimer(SendRoomList, 1.0f));
_serverPlugin.OnAttached(this);
_handlers = new BaseOperation[byte.MaxValue];
@@ -99,10 +103,15 @@ public class RagonServer : IRagonServer, INetworkListener
_timer.Start();
while (true)
{
if (_timer.ElapsedMilliseconds > _tickRate * 2)
{
_logger.Warn($"Slow perfomance: {_timer.ElapsedMilliseconds}");
}
if (_timer.ElapsedMilliseconds > _tickRate)
{
_timer.Restart();
_scheduler.Update(_timer.ElapsedMilliseconds / 1000.0f);
_scheduler.Update(_tickRate);
SendTimestamp();
}
@@ -197,7 +206,7 @@ public class RagonServer : IRagonServer, INetworkListener
_reader.FromArray(data);
var operation = _reader.ReadByte();
_handlers[operation].Handle(context, channel);
_handlers[operation]?.Handle(context, channel);
}
}
catch (Exception ex)
@@ -223,7 +232,19 @@ public class RagonServer : IRagonServer, INetworkListener
_server.Broadcast(sendData, NetworkChannel.UNRELIABLE);
}
public BaseOperation ResolveOperation(RagonOperation operation)
public void SendRoomList()
{
_lobbySerializer.Write(_writer);
var sendData = _writer.ToArray();
foreach (var (_, value) in _contextsByPlayerId)
{
if (value.Room == null) // If only in lobby, then send room list data
value.Connection.Reliable.Send(sendData);
}
}
public BaseOperation ResolveHandler(RagonOperation operation)
{
return _handlers[(byte)operation];
}
@@ -25,11 +25,6 @@ public enum ServerType
WEBSOCKET,
}
public class WebHook
{
}
[Serializable]
public struct RagonServerConfiguration
{
@@ -47,7 +42,7 @@ public struct RagonServerConfiguration
public Dictionary<string, string> WebHooks;
private static readonly Logger Logger = LogManager.GetCurrentClassLogger();
private static readonly string ServerVersion = "1.2.9-rc";
private static readonly string ServerVersion = "1.3.2";
private static Dictionary<string, ServerType> _serverTypes = new Dictionary<string, ServerType>()
{
{"enet", Server.ServerType.ENET},
+6
View File
@@ -21,6 +21,12 @@ namespace Ragon.Server.Room;
public interface IRagonRoom
{
public string Id { get; }
public string Scene { get; }
public int PlayerMin { get; }
public int PlayerMax { get; }
public int PlayerCount { get; }
RagonRoomPlayer GetPlayerByConnection(INetworkConnection connection);
RagonRoomPlayer GetPlayerById(string id);
IRagonEntity GetEntityById(ushort id);
@@ -0,0 +1,24 @@
using Ragon.Server.Time;
public class RagonActionTimer: IRagonAction
{
private Action _callback;
private float _timer;
private float _time;
public RagonActionTimer(Action callback, float timeInSeconds)
{
_callback = callback;
_time = timeInSeconds * 1000;
}
public void Tick(float dt)
{
_timer += dt;
if (_timer >= _time)
{
_callback?.Invoke();
_timer = 0;
}
}
}
@@ -127,5 +127,10 @@ namespace Ragon.Client
if (_libraryLoaded)
Library.Deinitialize();
}
public void Close()
{
}
}
}
@@ -128,5 +128,10 @@ namespace Ragon.Client
if (_libraryLoaded)
Library.Deinitialize();
}
public void Close()
{
}
}
}
+1 -2
View File
@@ -1,5 +1,4 @@
using Ragon.Client.Property;
using Ragon.Protocol;
namespace Ragon.Client.Simulation;
+7
View File
@@ -0,0 +1,7 @@
{
"sdk": {
"version": "7.0.0",
"rollForward": "latestMajor",
"allowPrerelease": false
}
}