This commit is contained in:
2025-01-18 17:30:03 +03:00
parent edf90b39c4
commit 2f919e4fd8
45 changed files with 1403 additions and 466 deletions
+2 -2
View File
@@ -39,8 +39,8 @@ public class RagonEvent
public void Read(RagonStream buffer)
{
// _size = buffer.Capacity;
// buffer.ReadArray(_data, _size);
// _size = buffer.Capacity;
// buffer.ReadArray(_data, _size);
}
public void Write(RagonStream buffer)
@@ -76,11 +76,10 @@ namespace Ragon.Server.Handler
var information = new RoomInformation()
{
Scene = _roomParameters.Scene,
Max = _roomParameters.Max,
Min = _roomParameters.Min,
};
if (information.Max > _configuration.LimitPlayersPerRoom)
information.Max = _configuration.LimitPlayersPerRoom;
@@ -97,8 +96,7 @@ namespace Ragon.Server.Handler
context.Lobby.Persist(room);
context.SetRoom(room, roomPlayer);
_logger.Trace(
$"Player {context.Connection.Id}|{context.LobbyPlayer.Name} create room {room.Id} with scene {information.Scene}");
_logger.Trace($"Player {context.Connection.Id}|{context.LobbyPlayer.Name} create room {room.Id}");
JoinSuccess(roomPlayer, room, Writer);
@@ -114,7 +112,6 @@ namespace Ragon.Server.Handler
writer.WriteString(room.Id);
writer.WriteUShort((ushort)room.PlayerMin);
writer.WriteUShort((ushort)room.PlayerMax);
writer.WriteString(room.Scene);
writer.WriteString(player.Id);
writer.WriteString(room.Owner.Id);
@@ -1,52 +0,0 @@
/*
* 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.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using Ragon.Protocol;
using Ragon.Server.IO;
namespace Ragon.Server.Handler;
public sealed class RoomDataOperation : BaseOperation
{
public RoomDataOperation(RagonStream reader, RagonStream writer) : base(reader, writer)
{
}
public override void Handle(RagonContext context, NetworkChannel channel)
{
var player = context.RoomPlayer;
var room = context.Room;
var data = Reader.ReadBinary(Reader.Lenght);
var dataSize = data.Length - 1;
var headerSize = 3;
var size = headerSize + dataSize;
var sendData = new byte[size];
var peerId = player.Connection.Id;
sendData[0] = (byte)RagonOperation.REPLICATE_RAW_DATA;
sendData[1] = (byte)peerId;
sendData[2] = (byte)(peerId >> 8);
var pluginData = new byte[dataSize];
Array.Copy(data, 1, pluginData, 0, dataSize);
room.Plugin.OnData(player, pluginData);
Array.Copy(data, 1, sendData, headerSize, dataSize);
room.Broadcast(sendData, room.ReadyPlayersList, NetworkChannel.RELIABLE);
}
}
@@ -61,7 +61,6 @@ public sealed class RoomJoinOperation : BaseOperation
writer.WriteString(room.Id);
writer.WriteUShort((ushort)room.PlayerMin);
writer.WriteUShort((ushort)room.PlayerMax);
writer.WriteString(room.Scene);
writer.WriteString(context.RoomPlayer.Id);
writer.WriteString(room.Owner.Id);
@@ -30,11 +30,11 @@ public sealed class RoomJoinOrCreateOperation : BaseOperation
private readonly RagonRoomParameters _roomParameters = new();
private readonly IServerPlugin _serverPlugin;
private readonly RagonServerConfiguration _configuration;
public RoomJoinOrCreateOperation(
RagonStream reader,
RagonStream writer,
IServerPlugin serverPlugin,
IServerPlugin serverPlugin,
RagonServerConfiguration configuration
) : base(reader, writer)
{
@@ -52,52 +52,35 @@ public sealed class RoomJoinOrCreateOperation : BaseOperation
var roomId = Guid.NewGuid().ToString();
var lobbyPlayer = context.LobbyPlayer;
_roomParameters.Deserialize(Reader);
if (context.Lobby.FindRoomByScene(_roomParameters.Scene, out var existsRoom))
var information = new RoomInformation()
{
var player = new RagonRoomPlayer(context, lobbyPlayer.Id, lobbyPlayer.Name);
Max = _roomParameters.Max,
Min = _roomParameters.Min,
};
context.SetRoom(existsRoom, player);
if (information.Max > _configuration.LimitPlayersPerRoom)
information.Max = _configuration.LimitPlayersPerRoom;
JoinSuccess(player, existsRoom, Writer);
var roomPlayer = new RagonRoomPlayer(context, lobbyPlayer.Id, lobbyPlayer.Name);
var roomPlugin = _serverPlugin.CreateRoomPlugin(information);
var room = new RagonRoom(roomId, information, roomPlugin);
existsRoom.RestoreBufferedEvents(player);
_serverPlugin.OnRoomCreate(lobbyPlayer, room);
existsRoom.Plugin.OnPlayerJoined(player);
}
else
{
var information = new RoomInformation()
{
Scene = _roomParameters.Scene,
Max = _roomParameters.Max,
Min = _roomParameters.Min,
};
room.Plugin.OnAttached(room);
if (information.Max > _configuration.LimitPlayersPerRoom)
information.Max = _configuration.LimitPlayersPerRoom;
context.Lobby.Persist(room);
context.Scheduler.Run(room);
context.SetRoom(room, roomPlayer);
var roomPlayer = new RagonRoomPlayer(context, lobbyPlayer.Id, lobbyPlayer.Name);
var roomPlugin = _serverPlugin.CreateRoomPlugin(information);
var room = new RagonRoom(roomId, information, roomPlugin);
_logger.Trace($"Player {context.Connection.Id}|{context.LobbyPlayer.Name} create room {room.Id}");
_serverPlugin.OnRoomCreate(lobbyPlayer, room);
JoinSuccess(roomPlayer, room, Writer);
room.Plugin.OnAttached(room);
context.Lobby.Persist(room);
context.Scheduler.Run(room);
context.SetRoom(room, roomPlayer);
_logger.Trace(
$"Player {context.Connection.Id}|{context.LobbyPlayer.Name} create room {room.Id} with scene {information.Scene}");
JoinSuccess(roomPlayer, room, Writer);
room.Plugin.OnPlayerJoined(roomPlayer);
}
room.Plugin.OnPlayerJoined(roomPlayer);
}
private void JoinSuccess(RagonRoomPlayer player, RagonRoom room, RagonStream writer)
@@ -107,7 +90,6 @@ public sealed class RoomJoinOrCreateOperation : BaseOperation
writer.WriteString(room.Id);
writer.WriteUShort((ushort)room.PlayerMin);
writer.WriteUShort((ushort)room.PlayerMax);
writer.WriteString(room.Scene);
writer.WriteString(player.Id);
writer.WriteString(room.Owner.Id);
@@ -26,7 +26,7 @@ public sealed class RoomLeaveOperation: BaseOperation
public RoomLeaveOperation(RagonStream reader, RagonStream writer): base(reader, writer)
{
}
public override void Handle(RagonContext context, NetworkChannel channel)
@@ -18,14 +18,15 @@ namespace Ragon.Server;
public class RagonContextObserver
{
private Dictionary<string, RagonContext> _contexts;
public RagonContextObserver(Dictionary<string, RagonContext> contexts)
private readonly RagonConnectionRegistry _registry;
public RagonContextObserver(RagonConnectionRegistry registry)
{
_contexts = contexts;
_registry = registry;
}
public void OnAuthorized(RagonContext context)
public void OnAuthorized(RagonContext context)
{
_contexts.Add(context.LobbyPlayer.Id, context);
_registry.Add(context.LobbyPlayer.Id, context);
}
}
+4 -3
View File
@@ -16,14 +16,15 @@
using Ragon.Protocol;
using Ragon.Server.Handler;
using Ragon.Server.IO;
using Ragon.Server.Lobby;
using Ragon.Server.Time;
namespace Ragon.Server;
public interface IRagonServer
{
BaseOperation ResolveHandler(RagonOperation operation);
public RagonContext? GetContextByConnectionId(ushort peerId);
public RagonContext? GetContextById(string playerId);
public RagonConnectionRegistry ConnectionRegistry { get; }
public RagonScheduler Scheduler { get; }
public IRagonLobby Lobby { get; }
}
@@ -23,7 +23,6 @@ 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);
public bool RemoveIfEmpty(RagonRoom room);
}
@@ -24,7 +24,6 @@ public class RagonLobbyDispatcher
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);
@@ -49,35 +49,7 @@ public class LobbyInMemory : IRagonLobby
room = default;
return false;
}
public bool FindRoomByScene(string sceneName, [MaybeNullWhen(false)] out RagonRoom room)
{
foreach (var existsRoom in _rooms)
{
if (existsRoom.Scene == sceneName)
{
if (existsRoom.PlayerCount >= existsRoom.PlayerMax)
{
_logger.Warning($"Room with scene {sceneName} fulfilled");
room = default;
return false;
}
room = existsRoom;
return true;
}
}
room = default;
return false;
}
public bool FindRoomByProperties(Dictionary<string, object> props)
{
return true;
}
public void Persist(RagonRoom room)
{
room.Attach();
@@ -86,7 +58,7 @@ public class LobbyInMemory : IRagonLobby
_logger.Trace($"New room: {room.Id}");
foreach (var r in _rooms)
_logger.Trace($"Room: {r.Id} Scene: {r.Scene} Players: {r.Players.Count}");
_logger.Trace($"Room: {r.Id} ID: {r.Id} Players: {r.Players.Count}");
}
public bool RemoveIfEmpty(RagonRoom room)
@@ -103,7 +75,7 @@ public class LobbyInMemory : IRagonLobby
}
foreach (var r in _rooms)
_logger.Trace($"Room: {r.Id} Scene: {r.Scene} Players: {r.Players.Count}");
_logger.Trace($"Room: {r.Id} ID: {r.Id} Players: {r.Players.Count}");
return result;
}
@@ -16,7 +16,6 @@
using Ragon.Protocol;
using Ragon.Server.Handler;
using Ragon.Server.IO;
using Ragon.Server.Lobby;
using Ragon.Server.Room;
@@ -42,7 +41,7 @@ namespace Ragon.Server.Plugin
public void Approve(string id, string name, string payload)
{
var ctx = _server.GetContextByConnectionId(PeerID);
var ctx = _server.ConnectionRegistry.GetContextByConnectionId(PeerID);
if (ctx == null)
return;
@@ -52,7 +51,7 @@ namespace Ragon.Server.Plugin
public void Reject()
{
var ctx = _server.GetContextByConnectionId(PeerID);
var ctx = _server.ConnectionRegistry.GetContextByConnectionId(PeerID);
if (ctx == null)
return;
@@ -80,7 +79,9 @@ namespace Ragon.Server.Plugin
{
public IRagonServer Server { get; protected set; }
public virtual void OnAttached(IRagonServer server)
public virtual void OnAttached(
IRagonServer server
)
{
Server = server;
}
@@ -16,6 +16,7 @@
using Ragon.Server.Lobby;
using Ragon.Server.Room;
using Ragon.Server.Time;
namespace Ragon.Server.Plugin
{
@@ -0,0 +1,60 @@
namespace Ragon.Server;
public class RagonConnectionRegistry
{
private readonly Dictionary<ushort, RagonContext> _contextsByConnection = new();
private readonly Dictionary<string, RagonContext> _contextsByPlayerId = new();
private readonly List<RagonContext> _contexts = new();
private readonly List<RagonContext> _playerContexts = new();
public void Add(string playerId, RagonContext context)
{
_contextsByPlayerId.Add(playerId, context);
_playerContexts.Add(context);
}
public void Add(ushort connectionId, RagonContext context)
{
_contextsByConnection.Add(connectionId, context);
_contexts.Add(context);
}
public bool Remove(ushort connectionId, out RagonContext o)
{
if (_contextsByConnection.Remove(connectionId, out var context))
{
_contexts.Remove(context);
o = context;
return true;
}
o = null;
return false;
}
public bool Remove(string playerId)
{
if (_contextsByPlayerId.Remove(playerId, out var context))
{
_playerContexts.Remove(context);
return true;
}
return false;
}
public bool TryGetValue(ushort connectionId, out RagonContext o)
{
return _contextsByConnection.TryGetValue(connectionId, out o);
}
public IReadOnlyList<RagonContext> Contexts => _contexts;
public IReadOnlyList<RagonContext> PlayerContexts => _playerContexts;
public RagonContext? GetContextByConnectionId(ushort peerId) => _contextsByConnection.GetValueOrDefault(peerId);
public RagonContext? GetContextById(string playerId) => _contextsByPlayerId.GetValueOrDefault(playerId);
}
+22 -31
View File
@@ -38,8 +38,7 @@ public class RagonServer : IRagonServer, INetworkListener
private readonly RagonStream _reader;
private readonly RagonStream _writer;
private readonly RagonScheduler _scheduler;
private readonly Dictionary<ushort, RagonContext> _contextsByConnection;
private readonly Dictionary<string, RagonContext> _contextsByPlayerId;
private readonly RagonConnectionRegistry _connectionRegistry;
private readonly Stopwatch _timer;
private readonly RagonLobbyDispatcher _lobbySerializer;
private readonly long _tickRate = 0;
@@ -55,8 +54,7 @@ public class RagonServer : IRagonServer, INetworkListener
_server = server;
_configuration = configuration;
_serverPlugin = plugin;
_contextsByConnection = new Dictionary<ushort, RagonContext>();
_contextsByPlayerId = new Dictionary<string, RagonContext>();
_connectionRegistry = new RagonConnectionRegistry();
_lobby = new LobbyInMemory();
_lobbySerializer = new RagonLobbyDispatcher(_lobby);
_scheduler = new RagonScheduler();
@@ -65,13 +63,11 @@ public class RagonServer : IRagonServer, INetworkListener
_tickRate = 1000 / _configuration.ServerTickRate;
_timer = new Stopwatch();
var contextObserver = new RagonContextObserver(_contextsByPlayerId);
var contextObserver = new RagonContextObserver(_connectionRegistry);
_scheduler.Run(new RagonActionTimer(SendRoomList, 2.0f));
_scheduler.Run(new RagonActionTimer(SendPlayerUserData, 0.1f));
_scheduler.Run(new RagonActionTimer(SendRoomUserData, 0.1f));
_serverPlugin.OnAttached(this);
_handlers = new BaseOperation[byte.MaxValue];
_handlers[(byte)RagonOperation.AUTHORIZE] = new AuthorizationOperation(_reader, _writer, this, _serverPlugin, contextObserver, configuration);
_handlers[(byte)RagonOperation.JOIN_OR_CREATE_ROOM] = new RoomJoinOrCreateOperation(_reader, _writer, plugin, _configuration);
@@ -80,7 +76,6 @@ public class RagonServer : IRagonServer, INetworkListener
_handlers[(byte)RagonOperation.LEAVE_ROOM] = new RoomLeaveOperation(_reader, _writer);
_handlers[(byte)RagonOperation.TIMESTAMP_SYNCHRONIZATION] = new TimestampSyncOperation(_reader, _writer);
_handlers[(byte)RagonOperation.REPLICATE_ROOM_EVENT] = new RoomEventOperation(_reader, _writer);
_handlers[(byte)RagonOperation.REPLICATE_RAW_DATA] = new RoomDataOperation(_reader, _writer);
_handlers[(byte)RagonOperation.ROOM_DATA_UPDATED] = new RoomUserDataOperation(_reader, _writer, _configuration.LimitUserDataSize);
_handlers[(byte)RagonOperation.PLAYER_DATA_UPDATED] = new PlayerUserDataOperation(_reader, _writer, _configuration.LimitUserDataSize);
}
@@ -133,12 +128,12 @@ public class RagonServer : IRagonServer, INetworkListener
var context = new RagonContext(connection, _lobby, _scheduler, _configuration.LimitBufferedEvents);
_logger.Trace($"Connected: {connection.Id}");
_contextsByConnection.Add(connection.Id, context);
_connectionRegistry.Add(connection.Id, context);
}
public void OnDisconnected(INetworkConnection connection)
{
if (_contextsByConnection.Remove(connection.Id, out var context))
if (_connectionRegistry.Remove(connection.Id, out var context))
{
var room = context.Room;
if (room != null)
@@ -149,7 +144,7 @@ public class RagonServer : IRagonServer, INetworkListener
}
if (context.ConnectionStatus == ConnectionStatus.Authorized)
_contextsByPlayerId.Remove(context.LobbyPlayer.Id);
_connectionRegistry.Remove(context.LobbyPlayer.Id);
_logger.Trace($"Disconnected: {connection.Id}");
}
@@ -161,7 +156,7 @@ public class RagonServer : IRagonServer, INetworkListener
public void OnTimeout(INetworkConnection connection)
{
if (_contextsByConnection.Remove(connection.Id, out var context) && context.ConnectionStatus == ConnectionStatus.Authorized)
if (_connectionRegistry.Remove(connection.Id, out var context) && context.ConnectionStatus == ConnectionStatus.Authorized)
{
var room = context.Room;
if (room != null)
@@ -171,7 +166,7 @@ public class RagonServer : IRagonServer, INetworkListener
}
if (context.ConnectionStatus == ConnectionStatus.Authorized)
_contextsByPlayerId.Remove(context.LobbyPlayer.Id);
_connectionRegistry.Remove(context.LobbyPlayer.Id);
_logger.Trace($"Timeout: {connection.Id}|{context.LobbyPlayer.Name}|{context.LobbyPlayer.Id}");
}
@@ -185,7 +180,7 @@ public class RagonServer : IRagonServer, INetworkListener
{
try
{
if (_contextsByConnection.TryGetValue(connection.Id, out var context))
if (_connectionRegistry.TryGetValue(connection.Id, out var context))
{
_writer.Clear();
_reader.Clear();
@@ -223,24 +218,24 @@ public class RagonServer : IRagonServer, INetworkListener
_lobbySerializer.Write(_writer);
var sendData = _writer.ToArray();
foreach (var (_, value) in _contextsByPlayerId)
foreach (var ctx in _connectionRegistry.Contexts)
{
if (value.Room == null) // If only in lobby, then send room list data
value.Connection.Reliable.Send(sendData);
if (ctx.Room == null) // If only in lobby, then send room list data
ctx.Connection.Reliable.Send(sendData);
}
}
public void SendPlayerUserData()
{
foreach (var (_, value) in _contextsByPlayerId)
foreach (var playerContext in _connectionRegistry.PlayerContexts)
{
if (value.UserData.IsDirty)
if (playerContext.UserData.IsDirty)
{
_writer.Clear();
_writer.WriteOperation(RagonOperation.PLAYER_DATA_UPDATED);
_writer.WriteUShort(value.Connection.Id);
_writer.WriteUShort(playerContext.Connection.Id);
value.UserData.Write(_writer);
playerContext.UserData.Write(_writer);
var sendData = _writer.ToArray();
_server.Broadcast(sendData, NetworkChannel.RELIABLE);
@@ -264,22 +259,18 @@ public class RagonServer : IRagonServer, INetworkListener
}
}
}
public BaseOperation ResolveHandler(RagonOperation operation)
{
return _handlers[(byte)operation];
}
public RagonContext? GetContextByConnectionId(ushort peerId)
{
return _contextsByConnection.TryGetValue(peerId, out var context) ? context : null;
}
public RagonContext? GetContextById(string playerId)
{
return _contextsByPlayerId.TryGetValue(playerId, out var context) ? context : null;
}
public RagonConnectionRegistry ConnectionRegistry => _connectionRegistry;
public RagonScheduler Scheduler => _scheduler;
public IRagonLobby Lobby => _lobby;
private void CopyrightInfo()
{
_logger.Info($"Server Version: {ServerVersion}");
+1 -6
View File
@@ -22,17 +22,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; }
public RagonData UserData { get; }
public void ReplicateData(byte[] data, NetworkChannel channel);
public void ReplicateData(byte[] data, List<RagonRoomPlayer> player, NetworkChannel channel);
public void ReplicateData(RagonRoomPlayer invoker, byte[] data, List<RagonRoomPlayer> receivers,
NetworkChannel channel = NetworkChannel.RELIABLE);
RagonRoomPlayer GetPlayerByConnection(INetworkConnection connection);
RagonRoomPlayer GetPlayerById(string id);
IReadOnlyList<RagonRoomPlayer> GetPlayers();
}
+1 -54
View File
@@ -26,10 +26,10 @@ namespace Ragon.Server.Room;
public class RagonRoom : IRagonRoom, IRagonAction
{
public string Id { get; private set; }
public string Scene { get; private set; }
public int PlayerMax { get; private set; }
public int PlayerMin { get; private set; }
public int PlayerCount => WaitPlayersList.Count;
public IReadOnlyList<RagonRoomPlayer> GetPlayers() => PlayerList;
public bool IsDone { get; private set; }
@@ -49,7 +49,6 @@ public class RagonRoom : IRagonRoom, IRagonAction
public RagonRoom(string roomId, RoomInformation info, IRoomPlugin roomPlugin)
{
Id = roomId;
Scene = info.Scene;
PlayerMax = info.Max;
PlayerMin = info.Min;
Plugin = roomPlugin;
@@ -66,8 +65,6 @@ public class RagonRoom : IRagonRoom, IRagonAction
Writer = new RagonStream();
}
public void RestoreBufferedEvents(RagonRoomPlayer roomPlayer)
{
foreach (var evnt in _bufferedEvents)
@@ -163,47 +160,7 @@ public class RagonRoom : IRagonRoom, IRagonAction
}
}
}
public void ReplicateData(byte[] data, NetworkChannel channel)
{
ReplicateData(data, ReadyPlayersList, channel);
}
public void ReplicateData(byte[] data, List<RagonRoomPlayer> receivers,
NetworkChannel channel = NetworkChannel.RELIABLE)
{
var dataSize = data.Length;
var headerSize = 3;
var size = headerSize + dataSize;
var sendData = new byte[size];
var peerId = 10000; // Server Peer
sendData[0] = (byte)RagonOperation.REPLICATE_RAW_DATA;
sendData[1] = (byte)peerId;
sendData[2] = (byte)(peerId >> 8);
Array.Copy(data, 0, sendData, headerSize, dataSize);
Broadcast(sendData, receivers, channel);
}
public void ReplicateData(RagonRoomPlayer invoker, byte[] data, List<RagonRoomPlayer> receivers,
NetworkChannel channel = NetworkChannel.RELIABLE)
{
var dataSize = data.Length;
var headerSize = 3;
var size = headerSize + dataSize;
var sendData = new byte[size];
var peerId = invoker.Connection.Id;
sendData[0] = (byte)RagonOperation.REPLICATE_RAW_DATA;
sendData[1] = (byte)peerId;
sendData[2] = (byte)(peerId >> 8);
Array.Copy(data, 0, sendData, headerSize, dataSize);
Broadcast(sendData, receivers, channel);
}
public void Tick(float dt)
{
@@ -247,16 +204,6 @@ public class RagonRoom : IRagonRoom, IRagonAction
ReadyPlayersList = PlayerList.Where(p => p.IsLoaded).ToList();
}
public void UpdateMap(string sceneName)
{
Scene = sceneName;
foreach (var player in PlayerList)
player.UnsetReady();
UpdateReadyPlayerList();
}
public void Broadcast(byte[] data, NetworkChannel channel = NetworkChannel.RELIABLE)
{
if (channel == NetworkChannel.RELIABLE)
@@ -18,7 +18,6 @@ namespace Ragon.Server;
public ref struct RoomInformation
{
public string Scene;
public int Min;
public int Max;
public int BufferedEventsLimit;