This commit is contained in:
2024-09-28 20:11:56 +03:00
parent 5136f08dab
commit 672bb1ff6d
95 changed files with 741 additions and 601 deletions
@@ -15,6 +15,7 @@
*/
using Ragon.Client.Replication;
using Ragon.Protocol;
namespace Ragon.Client.Property
@@ -15,6 +15,7 @@
*/
using Ragon.Client.Replication;
using Ragon.Protocol;
namespace Ragon.Client
@@ -15,6 +15,7 @@
*/
using Ragon.Client.Replication;
using Ragon.Protocol;
namespace Ragon.Client.Property
@@ -16,6 +16,7 @@
using System.Numerics;
using Ragon.Client.Compressor;
using Ragon.Client.Replication;
using Ragon.Protocol;
namespace Ragon.Client.Property;
@@ -16,6 +16,7 @@
using System.Text;
using Ragon.Client.Replication;
using Ragon.Protocol;
namespace Ragon.Client.Property
@@ -17,6 +17,7 @@
using System;
using System.Numerics;
using Ragon.Client.Compressor;
using Ragon.Client.Replication;
using Ragon.Protocol;
namespace Ragon.Client.Property
@@ -27,7 +27,7 @@ internal class AuthorizeFailedHandler: IHandler
_listenerList = list;
}
public void Handle(RagonBuffer reader)
public void Handle(RagonStream reader)
{
var message = reader.ReadString();
_listenerList.OnAuthorizationFailed(message);
@@ -32,7 +32,7 @@ internal class AuthorizeSuccessHandler: IHandler
_listenerList = listenerList;
}
public void Handle(RagonBuffer reader)
public void Handle(RagonStream reader)
{
var playerId = reader.ReadString();
var playerName = reader.ReadString();
+1 -1
View File
@@ -21,5 +21,5 @@ namespace Ragon.Client;
public interface IHandler
{
public void Handle(RagonBuffer reader);
public void Handle(RagonStream reader);
}
@@ -28,7 +28,7 @@ internal class JoinFailedHandler: IHandler
_listenerList = listenerList;
}
public void Handle(RagonBuffer reader)
public void Handle(RagonStream reader)
{
var message = reader.ReadString();
_listenerList.OnFailed(message);
@@ -41,23 +41,20 @@ internal class JoinSuccessHandler : IHandler
{
private readonly RagonListenerList _listenerList;
private readonly RagonPlayerCache _playerCache;
private readonly RagonEntityCache _entityCache;
private readonly RagonClient _client;
public JoinSuccessHandler(
RagonClient client,
RagonListenerList listenerList,
RagonPlayerCache playerCache,
RagonEntityCache entityCache
RagonPlayerCache playerCache
)
{
_client = client;
_listenerList = listenerList;
_entityCache = entityCache;
_playerCache = playerCache;
}
public void Handle(RagonBuffer reader)
public void Handle(RagonStream reader)
{
var roomId = reader.ReadString();
var min = reader.ReadUShort();
@@ -68,9 +65,8 @@ internal class JoinSuccessHandler : IHandler
_playerCache.SetOwnerAndLocal(ownerId, localId);
var scene = new RagonScene(_client, _playerCache, _entityCache, sceneName);
var roomInfo = new RoomParameters(roomId, localId, ownerId, min, max);
var room = new RagonRoom(_client, _entityCache, _playerCache, roomInfo, scene);
var room = new RagonRoom(_client, _playerCache, roomInfo);
room.UserData.Read(reader);
@@ -93,6 +89,5 @@ internal class JoinSuccessHandler : IHandler
_client.SetStatus(RagonStatus.ROOM);
_listenerList.OnJoined();
_listenerList.OnSceneRequest(sceneName);
}
}
@@ -23,22 +23,18 @@ internal class LeaveRoomHandler : IHandler
{
private readonly RagonClient _client;
private readonly RagonListenerList _listenerList;
private readonly RagonEntityCache _entityCache;
public LeaveRoomHandler(
RagonClient client,
RagonListenerList listenerList,
RagonEntityCache entityCache)
RagonListenerList listenerList)
{
_client = client;
_listenerList = listenerList;
_entityCache = entityCache;
}
public void Handle(RagonBuffer reader)
public void Handle(RagonStream reader)
{
_listenerList.OnLeft();
_entityCache.Cleanup();
_client.Room.Cleanup();
}
}
@@ -23,19 +23,16 @@ internal class OwnershipRoomHandler : IHandler
{
private readonly RagonListenerList _listenerList;
private readonly RagonPlayerCache _playerCache;
private readonly RagonEntityCache _entityCache;
public OwnershipRoomHandler(
RagonListenerList listenerList,
RagonPlayerCache playerCache,
RagonEntityCache entityCache)
RagonPlayerCache playerCache)
{
_listenerList = listenerList;
_playerCache = playerCache;
_entityCache = entityCache;
}
public void Handle(RagonBuffer reader)
public void Handle(RagonStream reader)
{
var newOwnerId = reader.ReadUShort();
var player = _playerCache.GetPlayerByPeer(newOwnerId);
@@ -33,7 +33,7 @@ internal class PlayerJoinHandler : IHandler
_listenerList = listenerList;
}
public void Handle(RagonBuffer reader)
public void Handle(RagonStream reader)
{
var playerPeerId = reader.ReadUShort();
var playerId = reader.ReadString();
@@ -22,21 +22,18 @@ namespace Ragon.Client;
internal class PlayerLeftHandler : IHandler
{
private RagonPlayerCache _playerCache;
private RagonEntityCache _entityCache;
private RagonListenerList _listenerList;
public PlayerLeftHandler(
RagonEntityCache entityCache,
RagonPlayerCache playerCache,
RagonListenerList listenerList
)
{
_entityCache = entityCache;
_playerCache = playerCache;
_listenerList = listenerList;
}
public void Handle(RagonBuffer reader)
public void Handle(RagonStream reader)
{
var playerId = reader.ReadString();
var player = _playerCache.GetPlayerById(playerId);
@@ -53,9 +50,9 @@ internal class PlayerLeftHandler : IHandler
toDeleteIds[i] = entityId;
}
var emptyPayload = new RagonPayload(0);
foreach (var id in toDeleteIds)
_entityCache.OnDestroy(id, emptyPayload);
// var emptyPayload = new RagonPayload(0);
// foreach (var id in toDeleteIds)
// _entityCache.OnDestroy(id, emptyPayload);
}
else
{
@@ -32,7 +32,7 @@ namespace Ragon.Client
_playerCache = playerCache;
_listenerList = listenerList;
}
public void Handle(RagonBuffer reader)
public void Handle(RagonStream reader)
{
var playerPeerId = reader.ReadUShort();
var player = _playerCache.GetPlayerByPeer(playerPeerId);
@@ -32,9 +32,9 @@ internal class RoomDataHandler: IHandler
_listeners = listeners;
}
public void Handle(RagonBuffer reader)
public void Handle(RagonStream reader)
{
var rawData = reader.RawData;
var rawData = reader.ReadBinary(reader.Lenght);
var peerId = (ushort)(rawData[1] + (rawData[2] << 8));
RagonPlayer player = null;
@@ -32,7 +32,7 @@ public class RoomEventHandler : IHandler
_playerCache = playerCache;
}
public void Handle(RagonBuffer buffer)
public void Handle(RagonStream buffer)
{
var eventCode = buffer.ReadUShort();
var peerId = buffer.ReadUShort();
@@ -13,7 +13,7 @@ internal class RoomListHandler: IHandler
_listenerList = list;
}
public void Handle(RagonBuffer reader)
public void Handle(RagonStream reader)
{
var roomCount = reader.ReadUShort();
var roomList = new RagonRoomInformation[roomCount];
@@ -29,7 +29,7 @@ namespace Ragon.Client
_listenerList = listenerList;
}
public void Handle(RagonBuffer reader)
public void Handle(RagonStream reader)
{
var changes = _client.Room?.UserData.Read(reader);
_listenerList.OnRoomUserData(changes);
@@ -10,10 +10,10 @@ public class TimestampHandler: IHandler
_client = client;
}
public void Handle(RagonBuffer buffer)
public void Handle(RagonStream buffer)
{
var timestamp0 = buffer.Read(32);
var timestamp1 = buffer.Read(32);
var timestamp0 = (uint)buffer.ReadInt();
var timestamp1 = (uint)buffer.ReadInt();
var value = new DoubleToUInt { Int0 = timestamp0, Int1 = timestamp1 };
_client.SetTimestamp(value.Double);
+2 -2
View File
@@ -22,6 +22,6 @@ public interface IUserData
{
public byte[] this[string key] { get; set; }
bool Dirty { get; }
IReadOnlyList<string> Read(RagonBuffer buffer);
void Write(RagonBuffer buffer);
IReadOnlyList<string> Read(RagonStream buffer);
void Write(RagonStream buffer);
}
+13 -55
View File
@@ -22,16 +22,14 @@ namespace Ragon.Client
{
private readonly INetworkConnection _connection;
private readonly NetworkStatistics _stats;
private IRagonEntityListener _entityListener;
private IRagonSceneCollector _sceneCollector;
private IHandler[] _handlers;
private RagonBuffer _readBuffer;
private RagonBuffer _writeBuffer;
private RagonStream _readBuffer;
private RagonStream _writeBuffer;
private RagonRoom _room;
private RagonSession _session;
private RagonListenerList _listeners;
private RagonPlayerCache _playerCache;
private RagonEntityCache _entityCache;
private RagonEventCache _eventCache;
private RagonStatus _status;
@@ -44,11 +42,10 @@ namespace Ragon.Client
public RagonStatus Status => _status;
public RagonSession Session => _session;
public RagonEventCache Event => _eventCache;
public RagonEntityCache Entity => _entityCache;
public NetworkStatistics Statistics => _stats;
public RagonRoom Room => _room;
internal RagonBuffer Buffer => _writeBuffer;
internal RagonStream Buffer => _writeBuffer;
internal INetworkChannel Reliable => _connection.Reliable;
internal INetworkChannel Unreliable => _connection.Unreliable;
@@ -72,58 +69,23 @@ namespace Ragon.Client
}
public void Configure(IRagonSceneCollector sceneCollector)
{
_sceneCollector = sceneCollector;
}
public void Configure(IRagonEntityListener listener)
{
_entityListener = listener;
}
public void Connect(string address, ushort port, string protocol)
{
if (_sceneCollector == null)
{
RagonLog.Error("Scene collector is not defined!");
return;
}
if (_entityListener == null)
{
RagonLog.Error("Entity Listener is not defined!");
return;
}
_writeBuffer = new RagonBuffer();
_readBuffer = new RagonBuffer();
_writeBuffer = new RagonStream();
_readBuffer = new RagonStream();
_playerCache = new RagonPlayerCache();
_session = new RagonSession(this, _writeBuffer);
_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_SUCCESS] = new JoinSuccessHandler(this, _listeners, _playerCache);
_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.LEAVE_ROOM] = new LeaveRoomHandler(this, _listeners);
_handlers[(byte)RagonOperation.OWNERSHIP_ROOM_CHANGED] = new OwnershipRoomHandler(_listeners, _playerCache);
_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.PLAYER_LEAVED] = new PlayerLeftHandler(_playerCache, _listeners);
_handlers[(byte)RagonOperation.REPLICATE_ROOM_EVENT] = new RoomEventHandler(this, _playerCache);
_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.ROOM_LIST_UPDATED] = new RoomListHandler(_session, _listeners);
@@ -151,7 +113,7 @@ namespace Ragon.Client
if (_replicationTime >= _replicationRate)
{
_replicationTime = 0;
_entityCache.WriteState(_writeBuffer);
// _entityCache.WriteState(_writeBuffer);
SendTimestamp();
SendRoomUserData();
@@ -185,8 +147,6 @@ namespace Ragon.Client
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 AddListener(IRagonPlayerUserDataListener listener) => _listeners.Add(listener);
@@ -200,8 +160,6 @@ namespace Ragon.Client
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);
public void RemoveListener(IRagonRoomUserDataListener listener) => _listeners.Remove(listener);
@@ -241,8 +199,8 @@ namespace Ragon.Client
_writeBuffer.Clear();
_writeBuffer.WriteOperation(RagonOperation.TIMESTAMP_SYNCHRONIZATION);
_writeBuffer.Write(value.Int0, 32);
_writeBuffer.Write(value.Int1, 32);
_writeBuffer.WriteInt((int)value.Int0);
_writeBuffer.WriteInt((int)value.Int1);
}
private void SendRoomUserData()
-36
View File
@@ -26,8 +26,6 @@ namespace Ragon.Client
private readonly List<IRagonFailedListener> _failedListeners = new();
private readonly List<IRagonJoinListener> _joinListeners = new();
private readonly List<IRagonLeftListener> _leftListeners = new();
private readonly List<IRagonSceneListener> _sceneListeners = new();
private readonly List<IRagonSceneRequestListener> _sceneRequestListeners = new();
private readonly List<IRagonOwnershipChangedListener> _ownershipChangedListeners = new();
private readonly List<IRagonPlayerJoinListener> _playerJoinListeners = new();
private readonly List<IRagonPlayerLeftListener> _playerLeftListeners = new();
@@ -49,7 +47,6 @@ namespace Ragon.Client
_failedListeners.Add(listener);
_joinListeners.Add(listener);
_leftListeners.Add(listener);
_sceneListeners.Add(listener);
_ownershipChangedListeners.Add(listener);
_playerJoinListeners.Add(listener);
_playerLeftListeners.Add(listener);
@@ -66,7 +63,6 @@ namespace Ragon.Client
_failedListeners.Remove(listener);
_joinListeners.Remove(listener);
_leftListeners.Remove(listener);
_sceneListeners.Remove(listener);
_ownershipChangedListeners.Remove(listener);
_playerJoinListeners.Remove(listener);
_playerLeftListeners.Remove(listener);
@@ -93,11 +89,6 @@ namespace Ragon.Client
_authorizationListeners.Add(listener);
}
public void Add(IRagonSceneRequestListener listener)
{
_sceneRequestListeners.Add(listener);
}
public void Add(IRagonConnectionListener listener)
{
_connectionListeners.Add(listener);
@@ -118,11 +109,6 @@ namespace Ragon.Client
_leftListeners.Add(listener);
}
public void Add(IRagonSceneListener listener)
{
_sceneListeners.Add(listener);
}
public void Add(IRagonOwnershipChangedListener listener)
{
_ownershipChangedListeners.Add(listener);
@@ -158,11 +144,6 @@ namespace Ragon.Client
_delayedActions.Add(() => _dataListeners.Remove(listener));
}
public void Remove(IRagonSceneRequestListener listener)
{
_delayedActions.Add(() => _sceneRequestListeners.Remove(listener));
}
public void Remove(IRagonAuthorizationListener listener)
{
_delayedActions.Add(() => _authorizationListeners.Remove(listener));
@@ -188,11 +169,6 @@ namespace Ragon.Client
_delayedActions.Add(() => _leftListeners.Remove(listener));
}
public void Remove(IRagonSceneListener listener)
{
_delayedActions.Add(() => _sceneListeners.Remove(listener));
}
public void Remove(IRagonOwnershipChangedListener listener)
{
_delayedActions.Add(() => _ownershipChangedListeners.Remove(listener));
@@ -265,18 +241,6 @@ namespace Ragon.Client
listener.OnPlayerJoined(_client, player);
}
public void OnSceneLoaded()
{
foreach (var listener in _sceneListeners)
listener.OnSceneLoaded(_client);
}
public void OnSceneRequest(string sceneName)
{
foreach (var listener in _sceneRequestListeners)
listener.OnRequestScene(_client, sceneName);
}
public void OnJoined()
{
foreach (var listener in _joinListeners)
+71 -30
View File
@@ -47,11 +47,9 @@ namespace Ragon.Client
}
}
private delegate void OnEventDelegate(RagonPlayer player, RagonBuffer serializer);
private delegate void OnEventDelegate(RagonPlayer player, RagonStream serializer);
private readonly RagonClient _client;
private readonly RagonScene _scene;
private readonly RagonEntityCache _entityCache;
private readonly RagonPlayerCache _playerCache;
private readonly RoomParameters _parameters;
private readonly RagonUserData _userData;
@@ -59,47 +57,40 @@ namespace Ragon.Client
public string Id => _parameters.RoomId;
public int MinPlayers => _parameters.Min;
public int MaxPlayers => _parameters.Max;
public string Scene => _scene.Name;
public string Scene => "none";
public IReadOnlyList<RagonPlayer> Players => _playerCache.Players;
public RagonPlayer Local => _playerCache.Local;
public RagonPlayer Owner => _playerCache.Owner;
public RagonUserData UserData => _userData;
private readonly Dictionary<int, OnEventDelegate> _events = new Dictionary<int, OnEventDelegate>();
private readonly Dictionary<int, OnEventDelegate> _events = new();
private readonly Dictionary<int, List<Action<RagonPlayer, IRagonEvent>>> _localListeners =
new Dictionary<int, List<Action<RagonPlayer, IRagonEvent>>>();
private readonly Dictionary<int, List<Action<RagonPlayer, IRagonEvent>>> _localListeners = new();
private readonly Dictionary<int, List<Action<RagonPlayer, IRagonEvent>>> _listeners =
new Dictionary<int, List<Action<RagonPlayer, IRagonEvent>>>();
private readonly Dictionary<int, List<Action<RagonPlayer, IRagonEvent>>> _listeners = new();
public RagonRoom(RagonClient client,
RagonEntityCache entityCache,
RagonPlayerCache playerCache,
RoomParameters parameters,
RagonScene scene)
RoomParameters parameters)
{
_client = client;
_parameters = parameters;
_entityCache = entityCache;
_playerCache = playerCache;
_scene = scene;
_userData = new RagonUserData();
}
internal void Cleanup()
{
_entityCache.Cleanup();
_playerCache.Cleanup();
}
internal void Update(string sceneName)
{
_scene.Update(sceneName);
// _scene.Update(sceneName);
}
internal void HandleEvent(ushort eventCode, RagonPlayer caller, RagonBuffer buffer)
internal void HandleEvent(ushort eventCode, RagonPlayer caller, RagonStream buffer)
{
if (_events.TryGetValue(eventCode, out var evnt))
evnt?.Invoke(caller, buffer);
@@ -107,7 +98,7 @@ namespace Ragon.Client
RagonLog.Warn($"Handler event {Id} with eventCode {eventCode} not defined");
}
internal void HandleUserData(RagonBuffer buffer)
internal void HandleUserData(RagonStream buffer)
{
_userData.Read(buffer);
}
@@ -147,23 +138,73 @@ namespace Ragon.Client
return new EventSubscription(callbacks, localCallbacks, action);
}
public void LoadScene(string sceneName) => _scene.Load(sceneName);
public void SceneLoaded() => _scene.SceneLoaded();
public void ReplicateEvent<TEvent>(TEvent evnt, RagonTarget target, RagonReplicationMode replicationMode)
where TEvent : IRagonEvent, new()
{
var evntId = _client.Event.GetEventCode(evnt);
var buffer = _client.Buffer;
public void ReplicateEvent<TEvent>(TEvent evnt, RagonTarget target, RagonReplicationMode mode)
where TEvent : IRagonEvent, new() => _scene.ReplicateEvent(evnt, target, mode);
{
if (replicationMode == RagonReplicationMode.Local &&
_localListeners.TryGetValue(evntId, out var localListeners))
{
foreach (var listener in localListeners)
listener.Invoke(_client.Room.Local, evnt);
return;
}
}
public void ReplicateEvent<TEvent>(TEvent evnt, RagonPlayer target, RagonReplicationMode mode)
where TEvent : IRagonEvent, new() => _scene.ReplicateEvent(evnt, target, mode);
{
if (replicationMode == RagonReplicationMode.LocalAndServer &&
_localListeners.TryGetValue(evntId, out var localListeners))
{
foreach (var listener in localListeners)
listener.Invoke(_client.Room.Local, evnt);
}
}
public void ReplicateData(byte[] data, bool reliable = false) => _scene.ReplicateData(data, reliable);
buffer.Clear();
buffer.WriteOperation(RagonOperation.REPLICATE_ROOM_EVENT);
buffer.WriteUShort(evntId);
buffer.WriteByte((byte)replicationMode);
buffer.WriteByte((byte)target);
public void CreateEntity(RagonEntity entity) => CreateEntity(entity, null);
public void CreateEntity(RagonEntity entity, RagonPayload payload) => _entityCache.Create(entity, payload);
public void TransferEntity(RagonEntity entity, RagonPlayer player) => _entityCache.Transfer(entity, player);
evnt.Serialize(buffer);
public void DestroyEntity(RagonEntity entityId) => DestroyEntity(entityId, null);
public void DestroyEntity(RagonEntity entityId, RagonPayload payload) => _entityCache.Destroy(entityId, payload);
var sendData = buffer.ToArray();
_client.Reliable.Send(sendData);
}
public void ReplicateEvent<TEvent>(TEvent evnt, RagonPlayer target, RagonReplicationMode replicationMode)
where TEvent : IRagonEvent, new()
{
var evntId = _client.Event.GetEventCode(evnt);
var buffer = _client.Buffer;
buffer.Clear();
buffer.WriteOperation(RagonOperation.REPLICATE_ROOM_EVENT);
buffer.WriteUShort(evntId);
buffer.WriteByte((byte)replicationMode);
buffer.WriteByte((byte)RagonTarget.Player);
buffer.WriteUShort(target.PeerId);
evnt.Serialize(buffer);
var sendData = buffer.ToArray();
_client.Reliable.Send(sendData);
}
public void ReplicateData(byte[] data, bool reliable)
{
var sendData = new byte[data.Length + 1];
sendData[0] = (byte)RagonOperation.REPLICATE_RAW_DATA;
Array.Copy(data, 0, sendData, 1, data.Length);
if (reliable)
_client.Reliable.Send(sendData);
else
_client.Unreliable.Send(sendData);
}
public void Dispose()
{
+2 -2
View File
@@ -21,9 +21,9 @@ namespace Ragon.Client
public class RagonSession
{
private readonly RagonClient _client;
private readonly RagonBuffer _buffer;
private readonly RagonStream _buffer;
public RagonSession(RagonClient client, RagonBuffer buffer)
public RagonSession(RagonClient client, RagonStream buffer)
{
_client = client;
_buffer = buffer;
+4 -4
View File
@@ -57,7 +57,7 @@ namespace Ragon.Client
{
}
public IReadOnlyList<string> Read(RagonBuffer buffer)
public IReadOnlyList<string> Read(RagonStream buffer)
{
var len = buffer.ReadUShort();
var changes = new List<string>(len);
@@ -67,7 +67,7 @@ namespace Ragon.Client
var valueSize = buffer.ReadUShort();
if (valueSize > 0)
{
var value = buffer.ReadBytes(valueSize);
var value = buffer.ReadBinary(valueSize);
_properties[key] = value;
}
else
@@ -81,7 +81,7 @@ namespace Ragon.Client
return changes;
}
public void Write(RagonBuffer buffer)
public void Write(RagonStream buffer)
{
buffer.WriteUShort((ushort)_localChanges.Count);
foreach (var propertyChanged in _localChanges)
@@ -90,7 +90,7 @@ namespace Ragon.Client
if (_properties.TryGetValue(propertyChanged, out var property))
{
buffer.WriteUShort((ushort)property.Length);
buffer.WriteBytes(property);
buffer.WriteBinary(property);
}
else
{
@@ -35,12 +35,12 @@ public class RagonUserDataReadOnly : IUserData
{
}
public void Write(RagonBuffer buffer)
public void Write(RagonStream buffer)
{
}
public IReadOnlyList<string> Read(RagonBuffer buffer)
public IReadOnlyList<string> Read(RagonStream buffer)
{
var len = buffer.ReadUShort();
var changes = new List<string>(len);
@@ -50,7 +50,7 @@ public class RagonUserDataReadOnly : IUserData
var valueSize = buffer.ReadUShort();
if (valueSize > 0)
{
var value = buffer.ReadBytes(valueSize);
var value = buffer.ReadBinary(valueSize);
_properties[key] = value;
}
@@ -17,7 +17,7 @@
using Ragon.Protocol;
namespace Ragon.Client
namespace Ragon.Client.Replication
{
public sealed class RagonEntity : IDisposable
{
@@ -118,9 +118,9 @@ namespace Ragon.Client
var buffer = new RagonBuffer();
data.Write(buffer);
// data.Write(buffer);
payload.Deserialize(buffer);
// payload.Deserialize(buffer);
return payload;
}
@@ -251,7 +251,7 @@ namespace Ragon.Client
{
_events.Add(eventCode, (player, serializer) =>
{
t.Deserialize(serializer);
// t.Deserialize(serializer);
foreach (var callbackListener in callbacks)
callbackListener.Invoke(player, t);
@@ -17,7 +17,7 @@
using Ragon.Protocol;
namespace Ragon.Client;
namespace Ragon.Client.Replication;
public sealed class RagonEntityState
{
@@ -17,13 +17,13 @@
using Ragon.Protocol;
namespace Ragon.Client;
namespace Ragon.Client.Replication;
public class RagonPayload
{
public static RagonPayload Empty = new RagonPayload(0);
private readonly uint[] _data = new uint[128];
private byte[] _data = new byte[128];
private readonly int _size = 0;
public RagonPayload(int capacity)
@@ -32,14 +32,14 @@ public class RagonPayload
}
public int Size => _size;
public void Read(RagonBuffer buffer)
public void Read(RagonStream buffer)
{
buffer.ReadArray(_data, _size);
_data = buffer.ReadBinary(_size);
}
public void Write(RagonBuffer buffer)
public void Write(RagonStream buffer)
{
buffer.WriteArray(_data, _size);
buffer.WriteBinary(_data);
}
public override string ToString()
@@ -16,7 +16,7 @@
using Ragon.Protocol;
namespace Ragon.Client
namespace Ragon.Client.Replication
{
[Serializable]
public class RagonProperty
@@ -16,9 +16,9 @@
using Ragon.Protocol;
namespace Ragon.Client;
namespace Ragon.Client.Replication;
internal class EntityCreateHandler : IHandler
internal class EntityCreateHandler
{
private readonly RagonClient _client;
private readonly RagonPlayerCache _playerCache;
@@ -38,15 +38,15 @@ internal class EntityCreateHandler : IHandler
_entityListener = entityListener;
}
public void Handle(RagonBuffer reader)
public void Handle(RagonStream reader)
{
var attachId = reader.ReadUShort();
var entityType = reader.ReadUShort();
var entityId = reader.ReadUShort();
var ownerId = reader.ReadUShort();
var player = _playerCache.GetPlayerByPeer(ownerId);
var payload = new RagonPayload(reader.Capacity);
payload.Read(reader);
// var payload = new RagonPayload(reader.Capacity);
// payload.Read(reader);
if (player == null)
{
@@ -59,7 +59,7 @@ internal class EntityCreateHandler : IHandler
var hasAuthority = _playerCache.Local.Id == player.Id;
var entity = _entityCache.TryGetEntity(attachId, entityType, 0, entityId, hasAuthority, out var hasCreated);
entity.Prepare(_client, entityId, entityType, hasAuthority, player, payload);
// entity.Prepare(_client, entityId, entityType, hasAuthority, player, payload);
if (hasCreated)
_entityListener.OnEntityCreated(entity);
@@ -16,9 +16,9 @@
using Ragon.Protocol;
namespace Ragon.Client;
namespace Ragon.Client.Replication;
internal class EntityEventHandler : IHandler
internal class EntityEventHandler
{
private readonly RagonPlayerCache _playerCache;
private readonly RagonEntityCache _entityCache;
@@ -17,9 +17,9 @@
using Ragon.Protocol;
namespace Ragon.Client;
namespace Ragon.Client.Replication;
internal class EntityOwnershipHandler: IHandler
internal class EntityOwnershipHandler
{
private readonly RagonListenerList _listenerList;
private readonly RagonPlayerCache _playerCache;
@@ -17,9 +17,9 @@
using Ragon.Protocol;
namespace Ragon.Client;
namespace Ragon.Client.Replication;
internal class EntityRemoveHandler: IHandler
internal class EntityRemoveHandler
{
private readonly RagonEntityCache _entityCache;
@@ -31,9 +31,9 @@ internal class EntityRemoveHandler: IHandler
public void Handle(RagonBuffer reader)
{
var entityId = reader.ReadUShort();
var payload = new RagonPayload(reader.Capacity);
payload.Read(reader);
// var payload = new RagonPayload(reader.Capacity);
// payload.Read(reader);
_entityCache.OnDestroy(entityId, payload);
// _entityCache.OnDestroy(entityId, payload);
}
}
@@ -16,9 +16,9 @@
using Ragon.Protocol;
namespace Ragon.Client;
namespace Ragon.Client.Replication;
internal class StateEntityHandler: IHandler
internal class StateEntityHandler
{
private readonly RagonEntityCache _entityCache;
@@ -16,9 +16,9 @@
using Ragon.Protocol;
namespace Ragon.Client;
namespace Ragon.Client.Replication;
internal class SceneLoadHandler: IHandler
internal class SceneLoadHandler
{
private readonly RagonClient _client;
private readonly RagonListenerList _listenerList;
@@ -40,6 +40,6 @@ internal class SceneLoadHandler: IHandler
room.Cleanup();
room.Update(sceneName);
_listenerList.OnSceneRequest(sceneName);
// _listenerList.OnSceneRequest(sceneName);
}
}
@@ -14,13 +14,11 @@
* limitations under the License.
*/
using System.Diagnostics;
using Ragon.Protocol;
namespace Ragon.Client;
namespace Ragon.Client.Replication;
internal class SnapshotHandler : IHandler
internal class SnapshotHandler
{
private readonly IRagonEntityListener _entityListener;
private readonly RagonClient _client;
@@ -69,8 +67,8 @@ internal class SnapshotHandler : IHandler
var payload = RagonPayload.Empty;
if (payloadSize > 0)
{
payload = new RagonPayload(payloadSize);
payload.Read(buffer);
// payload = new RagonPayload(payloadSize);
// payload.Read(buffer);
}
entity.Prepare(_client, entityId, entityType, hasAuthority, player, payload);
@@ -113,6 +111,6 @@ internal class SnapshotHandler : IHandler
foreach (var entity in entities)
entity.Attach();
_listenerList.OnSceneLoaded();
// _listenerList.OnSceneLoaded();
}
}
@@ -14,7 +14,7 @@
* limitations under the License.
*/
namespace Ragon.Client;
namespace Ragon.Client.Replication;
public interface IRagonEntityListener
{
@@ -18,8 +18,9 @@ using Ragon.Protocol;
namespace Ragon.Client
{
public interface IRagonPayload: IRagonSerializable
public interface IRagonPayload
{
public void Serialize(RagonStream buffer);
public void Deserialize(RagonStream buffer);
}
}
@@ -14,7 +14,7 @@
* limitations under the License.
*/
namespace Ragon.Client;
namespace Ragon.Client.Replication;
public interface IRagonSceneCollector
{
@@ -16,7 +16,7 @@
using Ragon.Protocol;
namespace Ragon.Client;
namespace Ragon.Client.Replication;
public sealed class RagonEntityCache
{
@@ -58,7 +58,7 @@ public sealed class RagonEntityCache
buffer.WriteUShort(entity.Type);
buffer.WriteByte((byte)entity.Authority);
entity.State.WriteInfo(buffer);
// entity.State.WriteInfo(buffer);
spawnPayload?.Write(buffer);
@@ -16,7 +16,7 @@
using Ragon.Protocol;
namespace Ragon.Client;
namespace Ragon.Client.Replication;
public class RagonScene
{
@@ -59,16 +59,16 @@ public class RagonScene
buffer.Clear();
buffer.WriteOperation(RagonOperation.SCENE_LOADED);
if (_playerCache.IsRoomOwner)
_entityCache.WriteScene(buffer);
else
_entityCache.CacheScene();
// if (_playerCache.IsRoomOwner)
// _entityCache.WriteScene(buffer);
// else
// _entityCache.CacheScene();
var sendData = buffer.ToArray();
_client.Reliable.Send(sendData);
}
internal void ReplicateEvent<TEvent>(TEvent evnt, RagonTarget target, RagonReplicationMode replicationMode)
public void ReplicateEvent<TEvent>(TEvent evnt, RagonTarget target, RagonReplicationMode replicationMode)
where TEvent : IRagonEvent, new()
{
var evntId = _client.Event.GetEventCode(evnt);
@@ -86,7 +86,7 @@ public class RagonScene
_client.Reliable.Send(sendData);
}
internal void ReplicateEvent<TEvent>(TEvent evnt, RagonPlayer target, RagonReplicationMode replicationMode)
public void ReplicateEvent<TEvent>(TEvent evnt, RagonPlayer target, RagonReplicationMode replicationMode)
where TEvent : IRagonEvent, new()
{
var evntId = _client.Event.GetEventCode(evnt);
@@ -108,7 +108,7 @@ public class RagonScene
public void ReplicateData(byte[] data, bool reliable)
{
var sendData = new byte[data.Length + 1];
sendData[0] = (byte) RagonOperation.REPLICATE_RAW_DATA;
sendData[0] = (byte)RagonOperation.REPLICATE_RAW_DATA;
Array.Copy(data, 0, sendData, 1, data.Length);
if (reliable)
@@ -17,24 +17,24 @@
namespace Ragon.Protocol
{
public class RagonRoomParameters: IRagonSerializable
public class RagonRoomParameters
{
public string Scene { get; set; }
public int Min { get; set; }
public int Max { get; set; }
public void Serialize(RagonBuffer buffer)
public void Serialize(RagonStream buffer)
{
buffer.WriteString(Scene);
buffer.WriteInt(Min, 1, 32);
buffer.WriteInt(Max, 1, 32);
buffer.WriteInt(Min);
buffer.WriteInt(Max);
}
public void Deserialize(RagonBuffer buffer)
public void Deserialize(RagonStream buffer)
{
Scene = buffer.ReadString();
Min = buffer.ReadInt(1, 32);
Max = buffer.ReadInt(1, 32);
Min = buffer.ReadInt();
Max = buffer.ReadInt();
}
}
}
+2 -2
View File
@@ -19,7 +19,7 @@ namespace Ragon.Protocol
{
public interface IRagonSerializable
{
public void Serialize(RagonBuffer buffer);
public void Deserialize(RagonBuffer buffer);
public void Serialize(RagonStream buffer);
public void Deserialize(RagonStream buffer);
}
}
@@ -14,7 +14,7 @@
* limitations under the License.
*/
using System.Collections.Generic;
using Ragon.Protocol;
using Ragon.Server.Event;
using Ragon.Server.Room;
@@ -61,7 +61,7 @@ public class RagonEntity : IRagonEntity
{
}
public void RestoreBufferedEvents(RagonRoomPlayer roomPlayer, RagonBuffer writer)
public void RestoreBufferedEvents(RagonRoomPlayer roomPlayer, RagonStream writer)
{
foreach (var evnt in _bufferedEvents)
{
@@ -114,7 +114,7 @@ public class RagonEntity : IRagonEntity
player.Connection.Reliable.Send(sendData);
}
public void Snapshot(RagonBuffer buffer)
public void Snapshot(RagonStream buffer)
{
buffer.WriteUShort(Type);
buffer.WriteUShort(Id);
@@ -229,7 +229,7 @@ public class RagonEntity : IRagonEntity
_state.AddProperty(property);
}
public void WriteState(RagonBuffer writer)
public void WriteState(RagonStream writer)
{
_state.Write(writer);
}
@@ -14,6 +14,7 @@
* limitations under the License.
*/
using System.Collections.Generic;
using Ragon.Server.Entity;
namespace Ragon.Server;
@@ -14,6 +14,7 @@
* limitations under the License.
*/
using System.Collections.Generic;
using Ragon.Protocol;
namespace Ragon.Server.Entity;
@@ -34,7 +35,7 @@ public class RagonEntityState: IRagonEntityState
_properties.Add(property);
}
public void Write(RagonBuffer buffer)
public void Write(RagonStream buffer)
{
buffer.WriteUShort(_entity.Id);
foreach (var property in _properties)
@@ -60,7 +61,7 @@ public class RagonEntityState: IRagonEntityState
}
}
public void Snapshot(RagonBuffer buffer)
public void Snapshot(RagonStream buffer)
{
foreach (var property in _properties)
{
@@ -26,15 +26,15 @@ public class RagonPayload
public ushort Size => (ushort) _size;
public void Read(RagonBuffer buffer)
public void Read(RagonStream buffer)
{
_size = buffer.Capacity;
buffer.ReadArray(_data, _size);
// _size = buffer.Capacity;
// buffer.ReadArray(_data, _size);
}
public void Write(RagonBuffer buffer)
public void Write(RagonStream buffer)
{
if (_size == 0) return;
buffer.WriteArray(_data, _size);
// if (_size == 0) return;
// buffer.WriteArray(_data, _size);
}
}
@@ -14,6 +14,8 @@
* limitations under the License.
*/
using System;
using System.Linq;
using Ragon.Protocol;
namespace Ragon.Server.Entity;
@@ -26,8 +26,10 @@ public sealed class EntityCreateOperation : BaseOperation
private readonly IRagonLogger _logger = LoggerManager.GetLogger(nameof(EntityCreateOperation));
private RagonServerConfiguration _configuration;
public EntityCreateOperation(RagonBuffer reader, RagonBuffer writer, RagonServerConfiguration configuration) :
base(reader, writer)
public EntityCreateOperation(
RagonStream reader,
RagonStream writer,
RagonServerConfiguration configuration) : base(reader, writer)
{
_configuration = configuration;
}
@@ -38,7 +40,7 @@ public sealed class EntityCreateOperation : BaseOperation
var room = context.Room;
var attachId = Reader.ReadUShort();
var entityType = Reader.ReadUShort();
var eventAuthority = (RagonAuthority) Reader.ReadByte();
var eventAuthority = (RagonAuthority)Reader.ReadByte();
var propertiesCount = Reader.ReadUShort();
var entityParameters = new RagonEntityParameters()
@@ -59,21 +61,20 @@ public sealed class EntityCreateOperation : BaseOperation
entity.AddProperty(new RagonProperty(propertySize, propertyType, _configuration.LimitPropertySize));
}
if (Reader.Capacity > 0)
entity.Payload.Read(Reader);
// if (Reader.Capacity > 0)
// entity.Payload.Read(Reader);
var plugin = room.Plugin;
if (!plugin.OnEntityCreate(player, entity))
return;
// var plugin = room.Plugin;
// if (!plugin.OnEntityCreate(player, entity))
// return;
entity.Attach(player);
room.AttachEntity(entity);
player.AttachEntity(entity);
// room.AttachEntity(entity);
// player.AttachEntity(entity);
entity.Create();
_logger.Trace($"Player {context.Connection.Id}|{context.LobbyPlayer.Name} created entity {entity.Id}:{entity.Type}");
_logger.Trace(
$"Player {context.Connection.Id}|{context.LobbyPlayer.Name} created entity {entity.Id}:{entity.Type}");
}
}
@@ -25,7 +25,7 @@ public sealed class EntityEventOperation : BaseOperation
{
private readonly IRagonLogger _logger = LoggerManager.GetLogger(nameof(EntityEventOperation));
public EntityEventOperation(RagonBuffer reader, RagonBuffer writer) : base(reader, writer)
public EntityEventOperation(RagonStream reader, RagonStream writer) : base(reader, writer)
{
}
@@ -35,11 +35,11 @@ public sealed class EntityEventOperation : BaseOperation
var room = context.Room;
var entityId = Reader.ReadUShort();
if (!room.Entities.TryGetValue(entityId, out var ent))
{
_logger.Warning($"Entity not found for event with Id {entityId}");
return;
}
// if (!room.Entities.TryGetValue(entityId, out var ent))
// {
// _logger.Warning($"Entity not found for event with Id {entityId}");
// return;
// }
var eventId = Reader.ReadUShort();
var eventMode = (RagonReplicationMode)Reader.ReadByte();
@@ -52,12 +52,12 @@ public sealed class EntityEventOperation : BaseOperation
var @event = new RagonEvent(player, eventId);
@event.Read(Reader);
if (targetMode == RagonTarget.Player && room.Players.TryGetValue(targetPlayerPeerId, out var targetPlayer))
{
ent.ReplicateEvent(player, @event, eventMode, targetPlayer);
return;
}
ent.ReplicateEvent(player, @event, eventMode, targetMode);
// if (targetMode == RagonTarget.Player && room.Players.TryGetValue(targetPlayerPeerId, out var targetPlayer))
// {
// ent.ReplicateEvent(player, @event, eventMode, targetPlayer);
// return;
// }
//
// ent.ReplicateEvent(player, @event, eventMode, targetMode);
}
}
@@ -25,7 +25,7 @@ public sealed class EntityOwnershipOperation : BaseOperation
{
private readonly IRagonLogger _logger = LoggerManager.GetLogger(nameof(EntityOwnershipOperation));
public EntityOwnershipOperation(RagonBuffer reader, RagonBuffer writer) : base(reader, writer)
public EntityOwnershipOperation(RagonStream reader, RagonStream writer) : base(reader, writer)
{
}
@@ -37,17 +37,17 @@ public sealed class EntityOwnershipOperation : BaseOperation
var entityId = Reader.ReadUShort();
var playerPeerId = Reader.ReadUShort();
if (!room.Entities.TryGetValue(entityId, out var entity))
{
_logger.Error($"Entity not found with id {entityId}");
return;
}
// if (!room.Entities.TryGetValue(entityId, out var entity))
// {
// _logger.Error($"Entity not found with id {entityId}");
// return;
// }
if (entity.Owner.Connection.Id != currentOwner.Connection.Id)
{
_logger.Error($"Player not owner of entity with id {entityId}");
return;
}
// if (entity.Owner.Connection.Id != currentOwner.Connection.Id)
// {
// _logger.Error($"Player not owner of entity with id {entityId}");
// return;
// }
if (!room.Players.TryGetValue(playerPeerId, out var nextOwner))
{
@@ -55,21 +55,21 @@ public sealed class EntityOwnershipOperation : BaseOperation
return;
}
currentOwner.Entities.Remove(entity);
nextOwner.Entities.Add(entity);
entity.Attach(nextOwner);
_logger.Trace($"Entity {entity.Id} next owner {nextOwner.Connection.Id}");
Writer.Clear();
Writer.WriteOperation(RagonOperation.OWNERSHIP_ENTITY_CHANGED);
Writer.WriteUShort(playerPeerId);
Writer.WriteUShort(1);
Writer.WriteUShort(entity.Id);
var sendData = Writer.ToArray();
foreach (var player in room.PlayerList)
player.Connection.Reliable.Send(sendData);
// currentOwner.Entities.Remove(entity);
// nextOwner.Entities.Add(entity);
//
// entity.Attach(nextOwner);
//
// _logger.Trace($"Entity {entity.Id} next owner {nextOwner.Connection.Id}");
//
// Writer.Clear();
// Writer.WriteOperation(RagonOperation.OWNERSHIP_ENTITY_CHANGED);
// Writer.WriteUShort(playerPeerId);
// Writer.WriteUShort(1);
// Writer.WriteUShort(entity.Id);
//
// var sendData = Writer.ToArray();
// foreach (var player in room.PlayerList)
// player.Connection.Reliable.Send(sendData);
}
}
@@ -25,7 +25,7 @@ public sealed class EntityDestroyOperation: BaseOperation
{
private readonly IRagonLogger _logger = LoggerManager.GetLogger(nameof(EntityDestroyOperation));
public EntityDestroyOperation(RagonBuffer reader, RagonBuffer writer) : base(reader, writer)
public EntityDestroyOperation(RagonStream reader, RagonStream writer) : base(reader, writer)
{
}
@@ -35,21 +35,21 @@ public sealed class EntityDestroyOperation: BaseOperation
var room = context.Room;
var entityId = Reader.ReadUShort();
if (room.Entities.TryGetValue(entityId, out var entity) && entity.Owner.Connection.Id == player.Connection.Id)
{
var payload = new RagonPayload();
payload.Read(Reader);
room.DetachEntity(entity);
player.DetachEntity(entity);
entity.Destroy();
_logger.Trace($"Player {context.Connection.Id}|{context.LobbyPlayer.Name} destoyed entity {entity.Id}");
}
else
{
_logger.Trace($"Entity {entity.Id} not found or Player {context.Connection.Id}|{context.LobbyPlayer.Name} have not authority");
}
// if (room.Entities.TryGetValue(entityId, out var entity) && entity.Owner.Connection.Id == player.Connection.Id)
// {
// var payload = new RagonPayload();
// payload.Read(Reader);
//
// room.DetachEntity(entity);
// player.DetachEntity(entity);
//
// entity.Destroy();
//
// _logger.Trace($"Player {context.Connection.Id}|{context.LobbyPlayer.Name} destoyed entity {entity.Id}");
// }
// else
// {
// _logger.Trace($"Entity {entity.Id} not found or Player {context.Connection.Id}|{context.LobbyPlayer.Name} have not authority");
// }
}
}
@@ -24,7 +24,7 @@ public sealed class EntityStateOperation: BaseOperation
{
private readonly IRagonLogger _logger = LoggerManager.GetLogger(nameof(EntityStateOperation));
public EntityStateOperation(RagonBuffer reader, RagonBuffer writer) : base(reader, writer)
public EntityStateOperation(RagonStream reader, RagonStream writer) : base(reader, writer)
{
}
@@ -36,15 +36,15 @@ public sealed class EntityStateOperation: BaseOperation
for (var entityIndex = 0; entityIndex < entitiesCount; entityIndex++)
{
var entityId = Reader.ReadUShort();
if (room.Entities.TryGetValue(entityId, out var entity) && entity.TryReadState(player, Reader))
{
room.Track(entity);
}
else
{
_logger.Error($"Entity with Id {entityId} not found, replication interrupted");
}
// var entityId = Reader.ReadUShort();
// if (room.Entities.TryGetValue(entityId, out var entity) && entity.TryReadState(player, Reader))
// {
// room.Track(entity);
// }
// else
// {
// _logger.Error($"Entity with Id {entityId} not found, replication interrupted");
// }
}
}
}
@@ -24,7 +24,7 @@ public class SceneLoadOperation: BaseOperation
{
private readonly IRagonLogger _logger = LoggerManager.GetLogger(nameof(SceneLoadOperation));
public SceneLoadOperation(RagonBuffer reader, RagonBuffer writer) : base(reader, writer) {}
public SceneLoadOperation(RagonStream reader, RagonStream writer) : base(reader, writer) {}
public override void Handle(RagonContext context, NetworkChannel channel)
{
@@ -14,7 +14,6 @@
* limitations under the License.
*/
using Ragon.Protocol;
using Ragon.Server.Entity;
using Ragon.Server.IO;
@@ -29,7 +28,7 @@ namespace Ragon.Server.Handler
private readonly IRagonLogger _logger = LoggerManager.GetLogger(nameof(SceneLoadedOperation));
private RagonServerConfiguration _configuration;
public SceneLoadedOperation(RagonBuffer reader, RagonBuffer writer, RagonServerConfiguration serverConfiguration) : base(reader, writer)
public SceneLoadedOperation(RagonStream reader, RagonStream writer, RagonServerConfiguration serverConfiguration) : base(reader, writer)
{
_configuration = serverConfiguration;
}
@@ -78,16 +77,16 @@ namespace Ragon.Server.Handler
var roomPlugin = room.Plugin;
if (!roomPlugin.OnEntityCreate(player, entity)) continue;
var playerInfo = $"Player {context.Connection.Id}|{context.LobbyPlayer.Name}";
var entityInfo = $"{entity.Id}:{entity.Type}";
_logger.Trace($"{playerInfo} created static entity {entityInfo}");
entity.Attach(player);
room.AttachEntity(entity);
player.AttachEntity(entity);
// if (!roomPlugin.OnEntityCreate(player, entity)) continue;
//
// var playerInfo = $"Player {context.Connection.Id}|{context.LobbyPlayer.Name}";
// var entityInfo = $"{entity.Id}:{entity.Type}";
//
// _logger.Trace($"{playerInfo} created static entity {entityInfo}");
//
// entity.Attach(player);
// room.AttachEntity(entity);
// player.AttachEntity(entity);
}
_logger.Trace($"Player {context.Connection.Id}|{context.LobbyPlayer.Name} loaded");
@@ -98,27 +97,27 @@ namespace Ragon.Server.Handler
{
DispatchPlayerJoinExcludePlayer(room, roomPlayer, Writer);
roomPlayer.SetReady();
// roomPlayer.SetReady();
}
room.UpdateReadyPlayerList();
DispatchSnapshot(room, room.WaitPlayersList, Writer);
// DispatchSnapshot(room, room.WaitPlayersList, Writer);
room.WaitPlayersList.Clear();
}
else if (owner.IsLoaded)
{
player.SetReady();
// player.SetReady();
DispatchPlayerJoinExcludePlayer(room, player, Writer);
room.UpdateReadyPlayerList();
DispatchSnapshot(room, new List<RagonRoomPlayer>() { player }, Writer);
foreach (var entity in room.EntityList)
entity.RestoreBufferedEvents(player, Writer);
// DispatchSnapshot(room, new List<RagonRoomPlayer>() { player }, Writer);
//
// foreach (var entity in room.EntityList)
// entity.RestoreBufferedEvents(player, Writer);
}
else
{
@@ -127,7 +126,7 @@ namespace Ragon.Server.Handler
}
}
private void DispatchPlayerJoinExcludePlayer(RagonRoom room, RagonRoomPlayer roomPlayer, RagonBuffer writer)
private void DispatchPlayerJoinExcludePlayer(RagonRoom room, RagonRoomPlayer roomPlayer, RagonStream writer)
{
writer.Clear();
writer.WriteOperation(RagonOperation.PLAYER_JOINED);
@@ -143,26 +142,26 @@ namespace Ragon.Server.Handler
}
}
private void DispatchSnapshot(RagonRoom room, List<RagonRoomPlayer> receviersList, RagonBuffer writer)
{
writer.Clear();
writer.WriteOperation(RagonOperation.SNAPSHOT);
var dynamicEntities = room.DynamicEntitiesList;
var dynamicEntitiesCount = (ushort)dynamicEntities.Count;
writer.WriteUShort(dynamicEntitiesCount);
foreach (var entity in dynamicEntities)
entity.Snapshot(writer);
var staticEntities = room.StaticEntitiesList;
var staticEntitiesCount = (ushort)staticEntities.Count;
writer.WriteUShort(staticEntitiesCount);
foreach (var entity in staticEntities)
entity.Snapshot(writer);
var sendData = writer.ToArray();
foreach (var player in receviersList)
player.Connection.Reliable.Send(sendData);
}
// private void DispatchSnapshot(RagonRoom room, List<RagonRoomPlayer> receviersList, RagonBuffer writer)
// {
// writer.Clear();
// writer.WriteOperation(RagonOperation.SNAPSHOT);
//
// var dynamicEntities = room.DynamicEntitiesList;
// var dynamicEntitiesCount = (ushort)dynamicEntities.Count;
// writer.WriteUShort(dynamicEntitiesCount);
// foreach (var entity in dynamicEntities)
// entity.Snapshot(writer);
//
// var staticEntities = room.StaticEntitiesList;
// var staticEntitiesCount = (ushort)staticEntities.Count;
// writer.WriteUShort(staticEntitiesCount);
// foreach (var entity in staticEntities)
// entity.Snapshot(writer);
//
// var sendData = writer.ToArray();
// foreach (var player in receviersList)
// player.Connection.Reliable.Send(sendData);
// }
}
}
@@ -0,0 +1,136 @@
using System.Collections.Generic;
using System.Linq;
using Ragon.Protocol;
using Ragon.Server;
using Ragon.Server.Entity;
using Ragon.Server.Plugin;
using Ragon.Server.Room;
namespace Ragon.Relay.Entity;
public class RelayRoom: RagonRoom
{
public Dictionary<ushort, RagonEntity> Entities { get; private set; }
public List<RagonEntity> DynamicEntitiesList { get; private set; }
public List<RagonEntity> StaticEntitiesList { get; private set; }
public List<RagonEntity> EntityList { get; private set; }
private readonly HashSet<RagonEntity> _entitiesDirtySet;
public RelayRoom(string roomId, RoomInformation info, IRoomPlugin roomPlugin) : base(roomId, info, roomPlugin)
{
Entities = new Dictionary<ushort, RagonEntity>();
DynamicEntitiesList = new List<RagonEntity>();
StaticEntitiesList = new List<RagonEntity>();
EntityList = new List<RagonEntity>();
_entitiesDirtySet = new HashSet<RagonEntity>();
}
public void AttachEntity(RagonEntity entity)
{
Entities.Add(entity.Id, entity);
EntityList.Add(entity);
if (entity.StaticId == 0)
DynamicEntitiesList.Add(entity);
else
StaticEntitiesList.Add(entity);
}
public void DetachEntity(RagonEntity entity)
{
Entities.Remove(entity.Id);
EntityList.Remove(entity);
StaticEntitiesList.Remove(entity);
DynamicEntitiesList.Remove(entity);
_entitiesDirtySet.Remove(entity);
}
public void Track(RagonEntity entity)
{
_entitiesDirtySet.Add(entity);
}
public void OnLeaved(RagonRoomPlayer player)
{
// var entitiesToDelete = player.Entities.DynamicList;
// Writer.WriteUShort((ushort)entitiesToDelete.Count);
// foreach (var entity in entitiesToDelete)
// {
// Writer.WriteUShort(entity.Id);
// DetachEntity(entity);
// }
//
// var sendData = Writer.ToArray();
// Broadcast(sendData);
}
public void Tick(float dt)
{
var entities = (ushort)_entitiesDirtySet.Count;
if (entities > 0)
{
Writer.Clear();
Writer.WriteOperation(RagonOperation.REPLICATE_ENTITY_STATE);
Writer.WriteUShort(entities);
foreach (var entity in _entitiesDirtySet)
entity.WriteState(Writer);
_entitiesDirtySet.Clear();
var sendData = Writer.ToArray();
foreach (var roomPlayer in ReadyPlayersList)
roomPlayer.Connection.Unreliable.Send(sendData);
}
}
public IRagonEntity? GetEntityById(ushort id)
{
return Entities.TryGetValue(id, out var entity) ? entity : null;
}
public IRagonEntity[] GetEntitiesOfPlayer(RagonRoomPlayer player)
{
return EntityList.Where(e => e.Owner.Connection.Id == player.Connection.Id).ToArray();
}
void Deatach()
{
Entities.Clear();
DynamicEntitiesList.Clear();
StaticEntitiesList.Clear();
EntityList.Clear();
_entitiesDirtySet.Clear();
// if (roomPlayer.Connection.Id == Owner.Connection.Id && PlayerList.Count > 0)
// {
// var nextOwner = PlayerList[0];
//
// Owner = nextOwner;
//
// var entitiesToUpdate = roomPlayer.Entities.StaticList;
//
// Writer.Clear();
// Writer.WriteOperation(RagonOperation.OWNERSHIP_ENTITY_CHANGED);
// Writer.WriteUShort(Owner.Connection.Id);
// Writer.WriteUShort((ushort)entitiesToUpdate.Count);
//
// foreach (var entity in entitiesToUpdate)
// {
// Writer.WriteUShort(entity.Id);
//
// entity.Attach(nextOwner);
// nextOwner.Entities.Add(entity);
// }
//
// var sendData = Writer.ToArray();
// Broadcast(sendData);
// }
}
}
+6 -6
View File
@@ -12,7 +12,7 @@ public class RagonData
{
}
public void Read(RagonBuffer buffer)
public void Read(RagonStream buffer)
{
var len = buffer.ReadUShort();
for (int i = 0; i < len; i++)
@@ -21,7 +21,7 @@ public class RagonData
var valueSize = buffer.ReadUShort();
if (valueSize > 0)
{
var value = buffer.ReadBytes(valueSize);
var value = buffer.ReadBinary(valueSize);
_data[key] = value;
}
else
@@ -31,14 +31,14 @@ public class RagonData
}
}
public void Write(RagonBuffer buffer)
public void Write(RagonStream buffer)
{
buffer.WriteUShort((ushort)_data.Count);
foreach (var prop in _data)
{
buffer.WriteString(prop.Key);
buffer.WriteUShort((ushort)prop.Value.Length);
buffer.WriteBytes(prop.Value);
buffer.WriteBinary(prop.Value);
}
var toDelete = _data
@@ -51,14 +51,14 @@ public class RagonData
IsDirty = false;
}
public void Snapshot(RagonBuffer buffer)
public void Snapshot(RagonStream buffer)
{
buffer.WriteUShort((ushort)_data.Count);
foreach (var prop in _data)
{
buffer.WriteString(prop.Key);
buffer.WriteUShort((ushort)prop.Value.Length);
buffer.WriteBytes(prop.Value);
buffer.WriteBinary(prop.Value);
Console.WriteLine($"Key: {prop.Key} Value: {prop.Value.Length}");
}
+6 -6
View File
@@ -37,15 +37,15 @@ public class RagonEvent
EventCode = eventCode;
}
public void Read(RagonBuffer buffer)
public void Read(RagonStream buffer)
{
_size = buffer.Capacity;
buffer.ReadArray(_data, _size);
// _size = buffer.Capacity;
// buffer.ReadArray(_data, _size);
}
public void Write(RagonBuffer buffer)
public void Write(RagonStream buffer)
{
if (_size <= 0) return;
buffer.WriteArray(_data, _size);
// if (_size <= 0) return;
// buffer.WriteArray(_data, _size);
}
}
@@ -29,10 +29,10 @@ namespace Ragon.Server.Handler
private readonly IRagonServer _server;
private readonly RagonContextObserver _observer;
private readonly RagonServerConfiguration _configuration;
private readonly RagonBuffer _writer;
private readonly RagonStream _writer;
public AuthorizationOperation(RagonBuffer reader,
RagonBuffer writer,
public AuthorizationOperation(RagonStream reader,
RagonStream writer,
IRagonServer server,
IServerPlugin serverPlugin,
RagonContextObserver observer,
@@ -21,10 +21,10 @@ namespace Ragon.Server.Handler;
public abstract class BaseOperation
{
protected readonly RagonBuffer Reader;
protected readonly RagonBuffer Writer;
protected readonly RagonStream Reader;
protected readonly RagonStream Writer;
public BaseOperation(RagonBuffer reader, RagonBuffer writer)
public BaseOperation(RagonStream reader, RagonStream writer)
{
Reader = reader;
Writer = writer;
@@ -11,8 +11,8 @@ namespace Ragon.Server.Handler
private readonly int _userDataLimit;
public PlayerUserDataOperation(
RagonBuffer reader,
RagonBuffer writer,
RagonStream reader,
RagonStream writer,
int userDataLimit
) : base(reader, writer)
{
@@ -32,8 +32,8 @@ namespace Ragon.Server.Handler
private readonly RagonServerConfiguration _configuration;
public RoomCreateOperation(
RagonBuffer reader,
RagonBuffer writer,
RagonStream reader,
RagonStream writer,
IServerPlugin serverPlugin,
RagonServerConfiguration configuration
) : base(reader,
@@ -107,7 +107,7 @@ namespace Ragon.Server.Handler
_logger.Trace($"Player {context.Connection.Id}|{context.LobbyPlayer.Name} joined to room {room.Id}");
}
private void JoinSuccess(RagonRoomPlayer player, RagonRoom room, RagonBuffer writer)
private void JoinSuccess(RagonRoomPlayer player, RagonRoom room, RagonStream writer)
{
writer.Clear();
writer.WriteOperation(RagonOperation.JOIN_SUCCESS);
@@ -21,7 +21,7 @@ namespace Ragon.Server.Handler;
public sealed class RoomDataOperation : BaseOperation
{
public RoomDataOperation(RagonBuffer reader, RagonBuffer writer) : base(reader, writer)
public RoomDataOperation(RagonStream reader, RagonStream writer) : base(reader, writer)
{
}
@@ -30,7 +30,7 @@ public sealed class RoomDataOperation : BaseOperation
var player = context.RoomPlayer;
var room = context.Room;
var data = Reader.RawData;
var data = Reader.ReadBinary(Reader.Lenght);
var dataSize = data.Length - 1;
var headerSize = 3;
var size = headerSize + dataSize;
@@ -10,7 +10,7 @@ public class RoomEventOperation : BaseOperation
{
private readonly IRagonLogger _logger = LoggerManager.GetLogger(nameof(RoomEventOperation));
public RoomEventOperation(RagonBuffer reader, RagonBuffer writer) : base(reader, writer)
public RoomEventOperation(RagonStream reader, RagonStream writer) : base(reader, writer)
{
}
@@ -26,7 +26,7 @@ public sealed class RoomJoinOperation : BaseOperation
{
private readonly IRagonLogger _logger = LoggerManager.GetLogger(nameof(RoomJoinOperation));
public RoomJoinOperation(RagonBuffer reader, RagonBuffer writer) : base(reader, writer)
public RoomJoinOperation(RagonStream reader, RagonStream writer) : base(reader, writer)
{
}
@@ -54,7 +54,7 @@ public sealed class RoomJoinOperation : BaseOperation
_logger.Trace($"Player {context.Connection.Id}|{context.LobbyPlayer.Name} joined to {existsRoom.Id}");
}
private void JoinSuccess(RagonContext context, RagonRoom room, RagonBuffer writer)
private void JoinSuccess(RagonContext context, RagonRoom room, RagonStream writer)
{
writer.Clear();
writer.WriteOperation(RagonOperation.JOIN_SUCCESS);
@@ -81,7 +81,7 @@ public sealed class RoomJoinOperation : BaseOperation
context.Connection.Reliable.Send(sendData);
}
private void JoinFailed(RagonContext context, RagonBuffer writer)
private void JoinFailed(RagonContext context, RagonStream writer)
{
writer.Clear();
writer.WriteOperation(RagonOperation.JOIN_FAILED);
@@ -32,8 +32,8 @@ public sealed class RoomJoinOrCreateOperation : BaseOperation
private readonly RagonServerConfiguration _configuration;
public RoomJoinOrCreateOperation(
RagonBuffer reader,
RagonBuffer writer,
RagonStream reader,
RagonStream writer,
IServerPlugin serverPlugin,
RagonServerConfiguration configuration
) : base(reader, writer)
@@ -100,7 +100,7 @@ public sealed class RoomJoinOrCreateOperation : BaseOperation
}
}
private void JoinSuccess(RagonRoomPlayer player, RagonRoom room, RagonBuffer writer)
private void JoinSuccess(RagonRoomPlayer player, RagonRoom room, RagonStream writer)
{
writer.Clear();
writer.WriteOperation(RagonOperation.JOIN_SUCCESS);
@@ -24,7 +24,7 @@ public sealed class RoomLeaveOperation: BaseOperation
{
private readonly IRagonLogger _logger = LoggerManager.GetLogger(nameof(RoomLeaveOperation));
public RoomLeaveOperation(RagonBuffer reader, RagonBuffer writer): base(reader, writer)
public RoomLeaveOperation(RagonStream reader, RagonStream writer): base(reader, writer)
{
}
@@ -23,7 +23,7 @@ public sealed class RoomOwnershipOperation : BaseOperation
{
private readonly IRagonLogger _logger = LoggerManager.GetLogger(nameof(RoomOwnershipOperation));
public RoomOwnershipOperation(RagonBuffer reader, RagonBuffer writer) : base(reader, writer)
public RoomOwnershipOperation(RagonStream reader, RagonStream writer) : base(reader, writer)
{
}
@@ -27,8 +27,8 @@ public sealed class RoomUserDataOperation : BaseOperation
private readonly int _userDataLimit;
public RoomUserDataOperation(
RagonBuffer reader,
RagonBuffer writer,
RagonStream reader,
RagonStream writer,
int userDataLimit
) : base(reader, writer)
{
@@ -19,16 +19,16 @@ using Ragon.Server.IO;
namespace Ragon.Server.Handler;
public class TimestampSyncOperation: BaseOperation
public class TimestampSyncOperation : BaseOperation
{
public TimestampSyncOperation(RagonBuffer reader, RagonBuffer writer) : base(reader, writer)
public TimestampSyncOperation(RagonStream reader, RagonStream writer) : base(reader, writer)
{
}
public override void Handle(RagonContext context, NetworkChannel channel)
{
var timestamp0 = Reader.Read(32);
var timestamp1 = Reader.Read(32);
var timestamp0 = (uint)Reader.ReadInt();
var timestamp1 = (uint)Reader.ReadInt();
var value = new DoubleToUInt() { Int0 = timestamp0, Int1 = timestamp1 };
context.RoomPlayer?.SetTimestamp(value.Double);
@@ -12,7 +12,7 @@ public class RagonLobbyDispatcher
_lobby = lobby;
}
public void Write(RagonBuffer writer)
public void Write(RagonStream writer)
{
writer.Clear();
writer.WriteOperation(RagonOperation.ROOM_LIST_UPDATED);
@@ -81,7 +81,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} Entities: {r.Entities.Count}");
_logger.Trace($"Room: {r.Id} Scene: {r.Scene} Players: {r.Players.Count}");
}
public bool RemoveIfEmpty(RagonRoom room)
@@ -98,7 +98,7 @@ public class LobbyInMemory : IRagonLobby
}
foreach (var r in _rooms)
_logger.Trace($"Room: {r.Id} Scene: {r.Scene} Players: {r.Players.Count} Entities: {r.Entities.Count}");
_logger.Trace($"Room: {r.Id} Scene: {r.Scene} Players: {r.Players.Count}");
return result;
}
@@ -14,8 +14,6 @@
* limitations under the License.
*/
using Ragon.Server.Entity;
using Ragon.Server.IO;
using Ragon.Server.Room;
namespace Ragon.Server.Plugin;
@@ -51,18 +49,6 @@ public class BaseRoomPlugin: IRoomPlugin
}
public virtual bool OnEntityCreate(RagonRoomPlayer creator, IRagonEntity entity)
{
return true;
}
public virtual bool OnEntityRemove(RagonRoomPlayer remover, IRagonEntity entity)
{
return true;
}
public virtual bool OnData(RagonRoomPlayer player, byte[] data)
{
return true;
@@ -14,7 +14,6 @@
* limitations under the License.
*/
using Ragon.Server.Entity;
using Ragon.Server.Room;
namespace Ragon.Server.Plugin;
@@ -26,7 +25,5 @@ public interface IRoomPlugin
void OnDetached(IRagonRoom room);
bool OnPlayerJoined(RagonRoomPlayer player);
bool OnPlayerLeaved(RagonRoomPlayer player);
bool OnEntityCreate(RagonRoomPlayer player, IRagonEntity entity);
bool OnEntityRemove(RagonRoomPlayer player, IRagonEntity entity);
bool OnData(RagonRoomPlayer player, byte[] data);
}
+10 -16
View File
@@ -35,8 +35,8 @@ public class RagonServer : IRagonServer, INetworkListener
private readonly IRagonLobby _lobby;
private readonly IServerPlugin _serverPlugin;
private readonly RagonServerConfiguration _configuration;
private readonly RagonBuffer _reader;
private readonly RagonBuffer _writer;
private readonly RagonStream _reader;
private readonly RagonStream _writer;
private readonly RagonScheduler _scheduler;
private readonly Dictionary<ushort, RagonContext> _contextsByConnection;
private readonly Dictionary<string, RagonContext> _contextsByPlayerId;
@@ -60,8 +60,8 @@ public class RagonServer : IRagonServer, INetworkListener
_lobby = new LobbyInMemory();
_lobbySerializer = new RagonLobbyDispatcher(_lobby);
_scheduler = new RagonScheduler();
_reader = new RagonBuffer();
_writer = new RagonBuffer();
_reader = new RagonStream();
_writer = new RagonStream();
_tickRate = 1000 / _configuration.ServerTickRate;
_timer = new Stopwatch();
@@ -78,14 +78,6 @@ public class RagonServer : IRagonServer, INetworkListener
_handlers[(byte)RagonOperation.CREATE_ROOM] = new RoomCreateOperation(_reader, _writer, plugin, _configuration);
_handlers[(byte)RagonOperation.JOIN_ROOM] = new RoomJoinOperation(_reader, _writer);
_handlers[(byte)RagonOperation.LEAVE_ROOM] = new RoomLeaveOperation(_reader, _writer);
_handlers[(byte)RagonOperation.LOAD_SCENE] = new SceneLoadOperation(_reader, _writer);
_handlers[(byte)RagonOperation.SCENE_LOADED] = new SceneLoadedOperation(_reader, _writer, _configuration);
_handlers[(byte)RagonOperation.CREATE_ENTITY] = new EntityCreateOperation(_reader, _writer, _configuration);
_handlers[(byte)RagonOperation.REMOVE_ENTITY] = new EntityDestroyOperation(_reader, _writer);
_handlers[(byte)RagonOperation.REPLICATE_ENTITY_EVENT] = new EntityEventOperation(_reader, _writer);
_handlers[(byte)RagonOperation.REPLICATE_ENTITY_STATE] = new EntityStateOperation(_reader, _writer);
_handlers[(byte)RagonOperation.TRANSFER_ROOM_OWNERSHIP] = new EntityOwnershipOperation(_reader, _writer);
_handlers[(byte)RagonOperation.TRANSFER_ENTITY_OWNERSHIP] = new EntityOwnershipOperation(_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);
@@ -101,11 +93,13 @@ public class RagonServer : IRagonServer, INetworkListener
if (_timer.ElapsedMilliseconds > _tickRate)
{
_scheduler.Update(_timer.ElapsedMilliseconds);
_timer.Restart();
_scheduler.Update(_timer.ElapsedMilliseconds / 1000.0f);
}
SendTimestamp();
}
_server.Update();
}
@@ -219,8 +213,8 @@ public class RagonServer : IRagonServer, INetworkListener
_writer.Clear();
_writer.WriteOperation(RagonOperation.TIMESTAMP_SYNCHRONIZATION);
_writer.Write(value.Int0, 32);
_writer.Write(value.Int1, 32);
_writer.WriteInt((int)value.Int0);
_writer.WriteInt((int)value.Int1);
var sendData = _writer.ToArray();
_server.Broadcast(sendData, NetworkChannel.UNRELIABLE);
-3
View File
@@ -15,7 +15,6 @@
*/
using Ragon.Server.Data;
using Ragon.Server.Entity;
using Ragon.Server.IO;
namespace Ragon.Server.Room;
@@ -36,6 +35,4 @@ public interface IRagonRoom
RagonRoomPlayer GetPlayerByConnection(INetworkConnection connection);
RagonRoomPlayer GetPlayerById(string id);
IRagonEntity GetEntityById(ushort id);
IRagonEntity[] GetEntitiesOfPlayer(RagonRoomPlayer id);
}
+2 -108
View File
@@ -16,7 +16,6 @@
using Ragon.Protocol;
using Ragon.Server.Data;
using Ragon.Server.Entity;
using Ragon.Server.Event;
using Ragon.Server.IO;
using Ragon.Server.Plugin;
@@ -36,7 +35,7 @@ public class RagonRoom : IRagonRoom, IRagonAction
public RagonData UserData { get; set; }
public RagonRoomPlayer Owner { get; private set; }
public RagonBuffer Writer { get; }
public RagonStream Writer { get; }
public IRoomPlugin Plugin { get; private set; }
public Dictionary<ushort, RagonRoomPlayer> Players { get; private set; }
@@ -44,12 +43,6 @@ public class RagonRoom : IRagonRoom, IRagonAction
public List<RagonRoomPlayer> ReadyPlayersList { get; private set; }
public List<RagonRoomPlayer> PlayerList { get; private set; }
public Dictionary<ushort, RagonEntity> Entities { get; private set; }
public List<RagonEntity> DynamicEntitiesList { get; private set; }
public List<RagonEntity> StaticEntitiesList { get; private set; }
public List<RagonEntity> EntityList { get; private set; }
private readonly HashSet<RagonEntity> _entitiesDirtySet;
private readonly List<RagonEvent> _bufferedEvents;
private readonly int _limitBufferedEvents;
@@ -66,39 +59,14 @@ public class RagonRoom : IRagonRoom, IRagonAction
ReadyPlayersList = new List<RagonRoomPlayer>(info.Max);
PlayerList = new List<RagonRoomPlayer>(info.Max);
Entities = new Dictionary<ushort, RagonEntity>();
DynamicEntitiesList = new List<RagonEntity>();
StaticEntitiesList = new List<RagonEntity>();
EntityList = new List<RagonEntity>();
_entitiesDirtySet = new HashSet<RagonEntity>();
_bufferedEvents = new List<RagonEvent>();
_limitBufferedEvents = 1000;
UserData = new RagonData();
Writer = new RagonBuffer();
Writer = new RagonStream();
}
public void AttachEntity(RagonEntity entity)
{
Entities.Add(entity.Id, entity);
EntityList.Add(entity);
if (entity.StaticId == 0)
DynamicEntitiesList.Add(entity);
else
StaticEntitiesList.Add(entity);
}
public void DetachEntity(RagonEntity entity)
{
Entities.Remove(entity.Id);
EntityList.Remove(entity);
StaticEntitiesList.Remove(entity);
DynamicEntitiesList.Remove(entity);
_entitiesDirtySet.Remove(entity);
}
public void RestoreBufferedEvents(RagonRoomPlayer roomPlayer)
{
@@ -238,22 +206,7 @@ public class RagonRoom : IRagonRoom, IRagonAction
public void Tick(float dt)
{
var entities = (ushort)_entitiesDirtySet.Count;
if (entities > 0)
{
Writer.Clear();
Writer.WriteOperation(RagonOperation.REPLICATE_ENTITY_STATE);
Writer.WriteUShort(entities);
foreach (var entity in _entitiesDirtySet)
entity.WriteState(Writer);
_entitiesDirtySet.Clear();
var sendData = Writer.ToArray();
foreach (var roomPlayer in ReadyPlayersList)
roomPlayer.Connection.Unreliable.Send(sendData);
}
}
public void AttachPlayer(RagonRoomPlayer player)
@@ -277,43 +230,9 @@ public class RagonRoom : IRagonRoom, IRagonAction
Writer.Clear();
Writer.WriteOperation(RagonOperation.PLAYER_LEAVED);
Writer.WriteString(player.Id);
var entitiesToDelete = player.Entities.DynamicList;
Writer.WriteUShort((ushort)entitiesToDelete.Count);
foreach (var entity in entitiesToDelete)
{
Writer.WriteUShort(entity.Id);
DetachEntity(entity);
}
var sendData = Writer.ToArray();
Broadcast(sendData);
}
if (roomPlayer.Connection.Id == Owner.Connection.Id && PlayerList.Count > 0)
{
var nextOwner = PlayerList[0];
Owner = nextOwner;
var entitiesToUpdate = roomPlayer.Entities.StaticList;
Writer.Clear();
Writer.WriteOperation(RagonOperation.OWNERSHIP_ENTITY_CHANGED);
Writer.WriteUShort(Owner.Connection.Id);
Writer.WriteUShort((ushort)entitiesToUpdate.Count);
foreach (var entity in entitiesToUpdate)
{
Writer.WriteUShort(entity.Id);
entity.Attach(nextOwner);
nextOwner.Entities.Add(entity);
}
var sendData = Writer.ToArray();
Broadcast(sendData);
}
player.OnDetached();
@@ -332,22 +251,12 @@ public class RagonRoom : IRagonRoom, IRagonAction
{
Scene = sceneName;
DynamicEntitiesList.Clear();
StaticEntitiesList.Clear();
Entities.Clear();
EntityList.Clear();
foreach (var player in PlayerList)
player.UnsetReady();
UpdateReadyPlayerList();
}
public void Track(RagonEntity entity)
{
_entitiesDirtySet.Add(entity);
}
public void Broadcast(byte[] data, NetworkChannel channel = NetworkChannel.RELIABLE)
{
if (channel == NetworkChannel.RELIABLE)
@@ -386,15 +295,6 @@ public class RagonRoom : IRagonRoom, IRagonAction
return PlayerList.FirstOrDefault(p => p.Id == id);
}
public IRagonEntity? GetEntityById(ushort id)
{
return Entities.TryGetValue(id, out var entity) ? entity : null;
}
public IRagonEntity[] GetEntitiesOfPlayer(RagonRoomPlayer player)
{
return EntityList.Where(e => e.Owner.Connection.Id == player.Connection.Id).ToArray();
}
public void Attach()
{
@@ -410,12 +310,6 @@ public class RagonRoom : IRagonRoom, IRagonAction
ReadyPlayersList.Clear();
PlayerList.Clear();
Entities.Clear();
DynamicEntitiesList.Clear();
StaticEntitiesList.Clear();
EntityList.Clear();
_entitiesDirtySet.Clear();
_bufferedEvents.Clear();
IsDone = true;
@@ -14,8 +14,6 @@
* limitations under the License.
*/
using Ragon.Server.Data;
using Ragon.Server.Entity;
using Ragon.Server.IO;
namespace Ragon.Server.Room;
@@ -29,7 +27,6 @@ public class RagonRoomPlayer
public bool IsLoaded { get; private set; }
public double Timestamp { get; private set; }
public RagonRoom Room { get; private set; }
public RagonEntityCache Entities { get; private set; }
public RagonRoomPlayer(RagonContext context, string id, string name)
{
@@ -37,17 +34,6 @@ public class RagonRoomPlayer
Name = name;
Context = context;
Connection = context.Connection;
Entities = new RagonEntityCache();
}
public void AttachEntity(RagonEntity entity)
{
Entities.Add(entity);
}
public void DetachEntity(RagonEntity entity)
{
Entities.Remove(entity);
}
internal void OnAttached(RagonRoom room)
+45
View File
@@ -0,0 +1,45 @@
using NUnit.Mocks;
using Ragon.Client;
using Ragon.Relay;
using Ragon.Server;
using Ragon.Server.Logging;
using Ragon.Server.Plugin;
namespace Ragon.Tests;
public class Tests
{
private RagonClient _client;
private RagonServer _server;
[SetUp]
public void Setup()
{
LoggerManager.SetLoggerFactory(new RelayLoggerFactory());
var fakeNetwork = new FakeNetwork();
var serverConfiguration = new RagonServerConfiguration()
{
LimitConnections = 100,
LimitRooms = 10,
LimitBufferedEvents = 500,
LimitPlayersPerRoom = 10,
LimitUserDataSize = 512,
LimitPropertySize = 512,
Port = 5000,
Protocol = "udp",
ServerKey = "defaultkey",
ServerTickRate = 30,
ServerAddress = "0.0.0.0",
};
_client = new RagonClient(fakeNetwork.ClientNetwork, 30);
_server = new RagonServer(fakeNetwork.ServerNetwork, new BaseServerPlugin(), serverConfiguration);
}
[Test]
public void Test1()
{
}
}
+31
View File
@@ -0,0 +1,31 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net8.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
<IsPackable>false</IsPackable>
<IsTestProject>true</IsTestProject>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="coverlet.collector" Version="6.0.0"/>
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.8.0"/>
<PackageReference Include="NUnit" Version="3.14.0"/>
<PackageReference Include="NUnit.Analyzers" Version="3.9.0"/>
<PackageReference Include="NUnit.Mocks" Version="2.6.4" />
<PackageReference Include="NUnit3TestAdapter" Version="4.5.0"/>
</ItemGroup>
<ItemGroup>
<Using Include="NUnit.Framework"/>
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\Ragon.Client\Ragon.Client.csproj" />
<ProjectReference Include="..\Ragon.Relay\Ragon.Relay.csproj" />
<ProjectReference Include="..\Ragon.Server\Ragon.Server.csproj" />
</ItemGroup>
</Project>
@@ -0,0 +1,45 @@
using Ragon.Client;
using Ragon.Protocol;
namespace Ragon.Tests;
public class FakeClientNetwork: INetworkConnection
{
public void Close()
{
throw new NotImplementedException();
}
public INetworkChannel Reliable { get; }
public INetworkChannel Unreliable { get; }
public Action<byte[]> OnData { get; set; }
public Action OnConnected { get; set; }
public Action<RagonDisconnect> OnDisconnected { get; set; }
public ulong BytesSent { get; }
public ulong BytesReceived { get; }
public int Ping { get; }
public void Prepare()
{
throw new NotImplementedException();
}
public void Connect(string address, ushort port, uint protocol)
{
}
public void Disconnect()
{
}
public void Update()
{
}
public void Dispose()
{
}
}
@@ -0,0 +1,11 @@
using Ragon.Client;
namespace Ragon.Tests;
public class FakeClientNetworkChannel: INetworkChannel
{
public void Send(byte[] data)
{
}
}
+15
View File
@@ -0,0 +1,15 @@
namespace Ragon.Tests;
public class FakeNetwork
{
public FakeClientNetwork ClientNetwork;
public FakeServerNetwork ServerNetwork;
public FakeNetwork()
{
ClientNetwork = new FakeClientNetwork();
ServerNetwork = new FakeServerNetwork();
}
}
@@ -0,0 +1,28 @@
using Ragon.Server.IO;
namespace Ragon.Tests;
public class FakeServerNetwork: INetworkServer
{
public void Close()
{
}
public void Stop()
{
}
public void Update()
{
}
public void Broadcast(byte[] data, NetworkChannel channel)
{
}
public void Listen(INetworkListener listener, NetworkConfiguration configuration)
{
}
}
@@ -0,0 +1,18 @@
using Ragon.Protocol;
using Ragon.Server.IO;
namespace Ragon.Tests;
public class FakeServerNetworkChannel: INetworkChannel
{
public void Send(byte[] data)
{
}
public void Send(RagonBuffer buffer)
{
}
}
+5 -5
View File
@@ -12,7 +12,7 @@ Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Ragon.Server.ENetServer", "
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Ragon.Client", "Ragon.Client\Ragon.Client.csproj", "{C82D65BF-6D80-4263-ADFE-CB9ED990B6C3}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Ragon.Client.Property", "Ragon.Client.Property\Ragon.Client.Property.csproj", "{46A60DAB-F854-4BB6-A119-BD4C5B2B0D29}"
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Ragon.Tests", "Ragon.Tests\Ragon.Tests.csproj", "{5833194D-CAD0-4517-BBC6-4DB0D7F1BEF1}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
@@ -44,9 +44,9 @@ Global
{C82D65BF-6D80-4263-ADFE-CB9ED990B6C3}.Debug|Any CPU.Build.0 = Debug|Any CPU
{C82D65BF-6D80-4263-ADFE-CB9ED990B6C3}.Release|Any CPU.ActiveCfg = Release|Any CPU
{C82D65BF-6D80-4263-ADFE-CB9ED990B6C3}.Release|Any CPU.Build.0 = Release|Any CPU
{46A60DAB-F854-4BB6-A119-BD4C5B2B0D29}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{46A60DAB-F854-4BB6-A119-BD4C5B2B0D29}.Debug|Any CPU.Build.0 = Debug|Any CPU
{46A60DAB-F854-4BB6-A119-BD4C5B2B0D29}.Release|Any CPU.ActiveCfg = Release|Any CPU
{46A60DAB-F854-4BB6-A119-BD4C5B2B0D29}.Release|Any CPU.Build.0 = Release|Any CPU
{5833194D-CAD0-4517-BBC6-4DB0D7F1BEF1}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{5833194D-CAD0-4517-BBC6-4DB0D7F1BEF1}.Debug|Any CPU.Build.0 = Debug|Any CPU
{5833194D-CAD0-4517-BBC6-4DB0D7F1BEF1}.Release|Any CPU.ActiveCfg = Release|Any CPU
{5833194D-CAD0-4517-BBC6-4DB0D7F1BEF1}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
EndGlobal