Compare commits

...

13 Commits

Author SHA1 Message Date
edmand46 72ff37e94a bump version 2022-08-30 01:54:50 +04:00
edmand46 75dab9d16f fixed: on scene entities load 2022-08-30 01:53:47 +04:00
edmand46 25b0e54d13 fixed: changed flow of joining 2022-08-29 01:45:47 +04:00
edmand46 e4f664b557 refactor: renamed plugin api 2022-08-28 19:31:07 +04:00
edmand46 174a4c4422 bump version 2022-08-28 11:51:14 +04:00
edmand46 a51d7c73cd fixed: mistype 2022-08-28 11:46:30 +04:00
edmand46 957622a170 fix: on player leave logic 2022-08-28 00:18:26 +04:00
edmand46 4a07424293 feat: added checks for size of payload 2022-08-27 11:21:51 +04:00
edmand46 568a3282c3 fix: restoring properties 2022-08-27 10:51:57 +04:00
edmand46 6a71fe5fe0 feat: restore properties 2022-08-25 23:12:33 +04:00
edmand46 082e183989 chore: move copyright on top of license 2022-08-24 00:06:37 +04:00
edmand46 51c0482a40 fix: leave player logic 2022-08-21 00:15:07 +04:00
edmand46 9e16c53cad fix: gameloop optimization 2022-08-20 22:05:43 +04:00
13 changed files with 211 additions and 165 deletions
+1
View File
@@ -16,6 +16,7 @@ namespace Ragon.Common
LOAD_SCENE,
SCENE_IS_LOADED,
SCENE_IS_PROCESSED,
PLAYER_JOINED,
PLAYER_LEAVED,
+1
View File
@@ -27,6 +27,7 @@ namespace Ragon.Common
private byte[] _data;
private int _offset;
private int _size;
public int Lenght => _offset;
public int Size => _size - _offset;
@@ -1,4 +1,5 @@
using Ragon.Core;
using NLog.Fluent;
using Ragon.Core;
namespace Game.Source
{
@@ -17,12 +18,22 @@ namespace Game.Source
public override void OnPlayerJoined(Player player)
{
// _logger.Info($"Player({player.PlayerName}) joined to Room({GameRoom.Id})");
// Logger.Info($"Player({player.PlayerName}) joined to Room({Room.Id})");
}
public override void OnPlayerLeaved(Player player)
{
// _logger.Info($"Player({player.PlayerName}) left from Room({GameRoom.Id})");
// Logger.Info($"Player({player.PlayerName}) left from Room({Room.Id})");
}
public override void OnEntityCreated(Player player, Entity entity)
{
// Logger.Info($"Player({player.PlayerName}) create entity {entity.EntityId}:{entity.EntityType}");
}
public override void OnEntityDestroyed(Player player, Entity entity)
{
// Logger.Info($"Player({player.PlayerName}) destroy entity {entity.EntityId}:{entity.EntityType}");
}
}
}
@@ -48,7 +48,7 @@ public class AuthorizationManager : IAuthorizationManager
PeerId = peerId,
IsLoaded = false,
Entities = new List<Entity>(),
EntitiesIds = new List<int>(),
EntitiesIds = new List<ushort>(),
};
_playersByIds.Add(playerId, player);
@@ -9,7 +9,7 @@ namespace Ragon.Core
public static class ConfigurationLoader
{
private static readonly Logger _logger = LogManager.GetCurrentClassLogger();
private static readonly string _serverVersion = "1.0.9-rc";
private static readonly string _serverVersion = "1.0.17-rc";
private static void CopyrightInfo()
{
+2 -1
View File
@@ -1,3 +1,4 @@
using System;
using Ragon.Common;
namespace Ragon.Core;
@@ -20,7 +21,7 @@ public class Entity
EntityType = entityType;
EntityId = _idGenerator++;
Properties = new EntityProperty[props];
Payload = new byte[1024];
Payload = Array.Empty<byte>();
Authority = eventAuthority;
}
}
+4 -2
View File
@@ -6,17 +6,19 @@ namespace Ragon.Core;
public class EntityProperty
{
public int Size { get; set; }
public int Capacity { get; set; }
public bool IsDirty { get; private set; }
public bool IsFixed { get; private set; }
private byte[] _data;
public EntityProperty(int size, bool isFixed)
{
_data = new byte[512];
Capacity = 512;
Size = size;
IsFixed = isFixed;
IsDirty = true;
_data = new byte[Capacity];
}
public ReadOnlySpan<byte> Read()
+106 -40
View File
@@ -1,6 +1,5 @@
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using NLog;
using Ragon.Common;
@@ -33,6 +32,7 @@ namespace Ragon.Core
private HashSet<Entity> _entitiesDirtySet = new HashSet<Entity>();
private List<Entity> _entitiesDirty = new List<Entity>();
private List<uint> _peersCache = new List<uint>();
private List<uint> _loadedPeers = new List<uint>();
public GameRoom(IGameThread gameThread, PluginBase pluginBase, string roomId, string map, int min, int max)
{
@@ -55,17 +55,6 @@ namespace Ragon.Core
_owner = player.PeerId;
}
{
_serializer.Clear();
_serializer.WriteOperation(RagonOperation.PLAYER_JOINED);
_serializer.WriteUShort((ushort) player.PeerId);
_serializer.WriteString(player.Id);
_serializer.WriteString(player.PlayerName);
var sendData = _serializer.ToArray();
Broadcast(_readyPlayers, sendData, DeliveryType.Reliable);
}
_players.Add(player.PeerId, player);
_allPlayers = _players.Select(p => p.Key).ToArray();
@@ -109,7 +98,7 @@ namespace Ragon.Core
_serializer.WriteUShort((ushort) player.EntitiesIds.Count);
foreach (var entityId in player.EntitiesIds)
{
_serializer.WriteInt(entityId);
_serializer.WriteUShort(entityId);
_entities.Remove(entityId);
}
@@ -117,7 +106,7 @@ namespace Ragon.Core
Broadcast(_readyPlayers, sendData);
}
if (_allPlayers.Length > 0)
if (_allPlayers.Length > 0 && player.PeerId == _owner)
{
var nextOwnerId = _allPlayers[0];
_owner = nextOwnerId;
@@ -161,11 +150,19 @@ namespace Ragon.Core
if (_serializer.ReadBool())
{
var property = ent.Properties[i];
var size = property.Size;
if (!property.IsFixed)
property.Size = _serializer.ReadUShort();
size = _serializer.ReadUShort();
var propertyPayload = _serializer.ReadData(property.Size);
if (size > property.Capacity)
{
_logger.Warn($"Property {i} payload too large, size: {size}");
continue;
}
var propertyPayload = _serializer.ReadData(size);
property.Write(ref propertyPayload);
property.Size = size;
}
}
@@ -178,6 +175,7 @@ namespace Ragon.Core
break;
}
}
break;
}
case RagonOperation.REPLICATE_ENTITY_EVENT:
@@ -204,7 +202,7 @@ namespace Ragon.Core
_serializer.Clear();
_serializer.WriteOperation(RagonOperation.REPLICATE_ENTITY_EVENT);
_serializer.WriteUShort(evntId);
_serializer.WriteUShort((ushort) peerId);
_serializer.WriteUShort(peerId);
_serializer.WriteByte(evntMode);
_serializer.WriteUShort(entityId);
_serializer.WriteData(ref payload);
@@ -323,7 +321,7 @@ namespace Ragon.Core
player.Entities.Add(entity);
player.EntitiesIds.Add(entity.EntityId);
var ownerId = (ushort) peerId;
var ownerId = peerId;
_entities.Add(entity.EntityId, entity);
_entitiesAll = _entities.Values.ToArray();
@@ -339,11 +337,12 @@ namespace Ragon.Core
{
ReadOnlySpan<byte> entityPayload = entity.Payload.AsSpan();
_serializer.WriteUShort((ushort) entityPayload.Length);
_serializer.WriteData(ref entityPayload);
}
var sendData = _serializer.ToArray();
Broadcast(_readyPlayers, sendData, DeliveryType.Reliable);
Send(peerId, sendData, DeliveryType.Reliable);
break;
}
case RagonOperation.CREATE_ENTITY:
@@ -351,13 +350,11 @@ namespace Ragon.Core
var entityType = _serializer.ReadUShort();
var propertiesCount = _serializer.ReadUShort();
var entity = new Entity(peerId, entityType, 0, RagonAuthority.ALL, RagonAuthority.ALL, propertiesCount);
// _logger.Trace("Created entity with properties: " + propertiesCount);
for (var i = 0; i < propertiesCount; i++)
{
var propertyType = _serializer.ReadBool();
var propertySize = _serializer.ReadUShort();
entity.Properties[i] = new EntityProperty(propertySize, propertyType);
// _logger.Trace($"Property: {i} Size: {propertySize} IsFixed: {propertyType}");
}
{
@@ -369,7 +366,7 @@ namespace Ragon.Core
player.Entities.Add(entity);
player.EntitiesIds.Add(entity.EntityId);
var ownerId = (ushort) peerId;
var ownerId = peerId;
_entities.Add(entity.EntityId, entity);
_entitiesAll = _entities.Values.ToArray();
@@ -384,6 +381,7 @@ namespace Ragon.Core
{
ReadOnlySpan<byte> entityPayload = entity.Payload.AsSpan();
_serializer.WriteUShort((ushort) entityPayload.Length);
_serializer.WriteData(ref entityPayload);
}
@@ -413,6 +411,7 @@ namespace Ragon.Core
_serializer.Clear();
_serializer.WriteOperation(RagonOperation.DESTROY_ENTITY);
_serializer.WriteInt(entityId);
_serializer.WriteUShort((ushort) destroyPayload.Length);
_serializer.WriteData(ref destroyPayload);
var sendData = _serializer.ToArray();
@@ -421,7 +420,54 @@ namespace Ragon.Core
break;
}
case RagonOperation.SCENE_IS_PROCESSED:
{
var player = _players[peerId];
_serializer.Clear();
_serializer.WriteOperation(RagonOperation.PLAYER_JOINED);
_serializer.WriteUShort((ushort) player.PeerId);
_serializer.WriteString(player.Id);
_serializer.WriteString(player.PlayerName);
var sendData = _serializer.ToArray();
Broadcast(_readyPlayers, sendData, DeliveryType.Reliable);
player.IsLoaded = true;
_readyPlayers = _players.Where(p => p.Value.IsLoaded).Select(p => p.Key).ToArray();
_plugin.OnPlayerJoined(player);
var isOwner = _owner == peerId;
if (isOwner)
{
foreach (var peer in _loadedPeers)
ReplicateSnapshot(peer);
_loadedPeers.Clear();
}
break;
}
case RagonOperation.SCENE_IS_LOADED:
{
var player = GetOwner();
if (player.IsLoaded || _owner == peerId)
ReplicateSnapshot(peerId);
else
_loadedPeers.Add(peerId);
break;
}
}
}
public void Tick(float deltaTime)
{
_scheduler.Tick(deltaTime);
ReplicateProperties();
}
public void ReplicateSnapshot(uint peerId)
{
_serializer.Clear();
_serializer.WriteOperation(RagonOperation.SNAPSHOT);
@@ -464,18 +510,11 @@ namespace Ragon.Core
var sendData = _serializer.ToArray();
Send(peerId, sendData, DeliveryType.Reliable);
_players[peerId].IsLoaded = true;
_readyPlayers = _players.Where(p => p.Value.IsLoaded).Select(p => p.Key).ToArray();
_plugin.OnPlayerJoined(_players[peerId]);
break;
}
}
RestoreProperties(peerId);
}
public void Tick(float deltaTime)
private void ReplicateProperties()
{
_scheduler.Tick(deltaTime);
if (_entitiesDirty.Count > 0)
{
_serializer.Clear();
@@ -513,6 +552,39 @@ namespace Ragon.Core
}
}
public void RestoreProperties(uint peerId)
{
_serializer.Clear();
_serializer.WriteOperation(RagonOperation.REPLICATE_ENTITY_STATE);
_serializer.WriteUShort((ushort) _entitiesAll.Length);
for (var entityIndex = 0; entityIndex < _entitiesAll.Length; entityIndex++)
{
var entity = _entitiesAll[entityIndex];
_serializer.WriteUShort(entity.EntityId);
for (int propertyIndex = 0; propertyIndex < entity.Properties.Length; propertyIndex++)
{
var property = entity.Properties[propertyIndex];
var hasPayload = property.IsFixed || property.Size > 0 && !property.IsFixed;
if (hasPayload)
{
_serializer.WriteBool(true);
var span = _serializer.GetWritableData(property.Size);
var data = property.Read();
data.CopyTo(span);
}
else
{
_serializer.WriteBool(false);
}
}
}
var sendData = _serializer.ToArray();
Send(peerId, sendData, DeliveryType.Reliable);
}
public void Start()
{
_plugin.OnStart();
@@ -537,19 +609,13 @@ namespace Ragon.Core
public IScheduler GetScheduler() => _scheduler;
public void Send(uint peerId, byte[] rawData, DeliveryType deliveryType = DeliveryType.Unreliable)
{
public void Send(uint peerId, byte[] rawData, DeliveryType deliveryType = DeliveryType.Unreliable) =>
_gameThread.Server.Send(peerId, rawData, deliveryType);
}
public void Broadcast(uint[] peersIds, byte[] rawData, DeliveryType deliveryType = DeliveryType.Unreliable)
{
public void Broadcast(uint[] peersIds, byte[] rawData, DeliveryType deliveryType = DeliveryType.Unreliable) =>
_gameThread.Server.Broadcast(peersIds, rawData, deliveryType);
}
public void Broadcast(byte[] rawData, DeliveryType deliveryType = DeliveryType.Unreliable)
{
public void Broadcast(byte[] rawData, DeliveryType deliveryType = DeliveryType.Unreliable) =>
_gameThread.Server.Broadcast(_allPlayers, rawData, deliveryType);
}
}
}
+16 -52
View File
@@ -1,7 +1,4 @@
using System;
using System.Diagnostics;
using System.Linq;
using System.Security.Cryptography;
using System.Threading;
using Ragon.Common;
using ENet;
@@ -13,42 +10,33 @@ namespace Ragon.Core
{
private readonly RoomManager _roomManager;
private readonly Thread _thread;
private readonly Stopwatch _gameLoopTimer;
private readonly Stopwatch _statisticsTimer;
private readonly Stopwatch _serverTimer;
private readonly Stopwatch _logicTimer;
private readonly Lobby _lobby;
private readonly ISocketServer _server;
private readonly IDispatcherInternal _dispatcherInternal;
private readonly IDispatcher _dispatcher;
private readonly ILogger _logger = LogManager.GetCurrentClassLogger();
private readonly float _deltaTime = 0.0f;
private readonly Configuration _configuration;
private readonly IDispatcherInternal _dispatcherInternal;
public IDispatcher ThreadDispatcher { get; private set; }
public ISocketServer Server { get; private set; }
public ISocketServer Server => _server;
public IDispatcher ThreadDispatcher => _dispatcher;
public GameThread(PluginFactory factory, Configuration configuration)
{
var authorizationProvider = factory.CreateAuthorizationProvider(configuration);
_configuration = configuration;
var authorizationProvider = factory.CreateAuthorizationProvider(configuration);
var dispatcher = new Dispatcher();
_dispatcherInternal = dispatcher;
_dispatcher = dispatcher;
ThreadDispatcher = dispatcher;
Server = new ENetServer(this);
_server = new ENetServer(this);
_deltaTime = 1000.0f / configuration.SendRate;
_roomManager = new RoomManager(factory, this);
_lobby = new Lobby(authorizationProvider, _roomManager, this);
_gameLoopTimer = new Stopwatch();
_statisticsTimer = new Stopwatch();
_serverTimer = new Stopwatch();
_logicTimer = new Stopwatch();
_thread = new Thread(Execute);
_thread.Name = "Game Thread";
_thread.IsBackground = true;
@@ -62,6 +50,7 @@ namespace Ragon.Core
_logger.Error("Wrong protocol passed to connect method");
return;
}
var parts = new uint[] {0, 0, 0};
for (int i = 0; i < parts.Length; i++)
{
@@ -70,25 +59,18 @@ namespace Ragon.Core
_logger.Error("Wrong protocol");
return;
}
parts[i] = v;
}
uint encoded = (parts[0] << 16) | (parts[1] << 8) | parts[2];
Server.Start(_configuration.Port, _configuration.MaxConnections, encoded);
_gameLoopTimer.Start();
_statisticsTimer.Start();
_logicTimer.Start();
_serverTimer.Start();
_server.Start(_configuration.Port, _configuration.MaxConnections, encoded);
_thread.Start();
}
public void Stop()
{
Server.Stop();
_gameLoopTimer.Stop();
_statisticsTimer.Stop();
_server.Stop();
_thread.Interrupt();
}
@@ -96,29 +78,11 @@ namespace Ragon.Core
{
while (true)
{
_logicTimer.Restart();
_serverTimer.Restart();
Server.Process();
_server.Process();
_dispatcherInternal.Process();
_roomManager.Tick(_deltaTime);
var elapsedMilliseconds = _gameLoopTimer.ElapsedMilliseconds;
if (elapsedMilliseconds > _deltaTime)
{
_roomManager.Tick(elapsedMilliseconds / 1000.0f);
_gameLoopTimer.Restart();
continue;
}
if (_statisticsTimer.Elapsed.Seconds > _configuration.StatisticsInterval && _roomManager.RoomsBySocket.Count > 0)
{
var rooms = _roomManager.Rooms.Count;
var clients = _roomManager.RoomsBySocket.Count;
var entities = _roomManager.Rooms.Select(r => r.EntitiesCount).Sum();
_logger.Trace($"Rooms: {rooms} Clients: {clients} Entities: {entities}");
_statisticsTimer.Restart();
}
Thread.Sleep((int) _deltaTime);
}
}
+1 -1
View File
@@ -11,6 +11,6 @@ namespace Ragon.Core
public bool IsLoaded { get; set; }
public List<Entity> Entities;
public List<int> EntitiesIds;
public List<ushort> EntitiesIds;
}
}
+18 -18
View File
@@ -8,21 +8,20 @@ namespace Ragon.Core
public class PluginBase
{
private delegate void SubscribeDelegate(Player player, ref ReadOnlySpan<byte> data);
private delegate void SubscribeEntityDelegate(Player player, Entity entity, ref ReadOnlySpan<byte> data);
private Dictionary<ushort, SubscribeDelegate> _globalEvents = new();
private Dictionary<int, Dictionary<ushort, SubscribeEntityDelegate>> _entityEvents = new();
private readonly RagonSerializer _serializer = new();
protected IGameRoom GameRoom { get; private set; } = null!;
protected IGameRoom Room { get; private set; } = null!;
protected ILogger Logger = null!;
public void Attach(GameRoom gameRoom)
{
Logger = LogManager.GetLogger($"Plugin<{GetType().Name}>");
GameRoom = gameRoom;
Room = gameRoom;
_globalEvents.Clear();
_entityEvents.Clear();
@@ -34,7 +33,7 @@ namespace Ragon.Core
_entityEvents.Clear();
}
public void Subscribe<T>(ushort evntCode, Action<Player, T> action) where T : IRagonSerializable, new()
public void OnEvent<T>(ushort evntCode, Action<Player, T> action) where T : IRagonSerializable, new()
{
if (_globalEvents.ContainsKey(evntCode))
{
@@ -58,7 +57,7 @@ namespace Ragon.Core
});
}
public void Subscribe(ushort evntCode, Action<Player> action)
public void OnEvent(ushort evntCode, Action<Player> action)
{
if (_globalEvents.ContainsKey(evntCode))
{
@@ -69,7 +68,7 @@ namespace Ragon.Core
_globalEvents.Add(evntCode, (Player player, ref ReadOnlySpan<byte> raw) => { action.Invoke(player); });
}
public void Subscribe<T>(Entity entity, ushort evntCode, Action<Player, Entity, T> action) where T : IRagonSerializable, new()
public void OnEvent<T>(Entity entity, ushort evntCode, Action<Player, Entity, T> action) where T : IRagonSerializable, new()
{
if (_entityEvents.ContainsKey(entity.EntityId))
{
@@ -116,7 +115,7 @@ namespace Ragon.Core
}
}
public void Subscribe(Entity entity, ushort evntCode, Action<Player, Entity> action)
public void OnEvent(Entity entity, ushort evntCode, Action<Player, Entity> action)
{
if (_entityEvents.ContainsKey(entity.EntityId))
{
@@ -150,8 +149,9 @@ namespace Ragon.Core
if (!_entityEvents[entityId].ContainsKey(evntCode))
return false;
var player = GameRoom.GetPlayerById(peerId);
var entity = GameRoom.GetEntityById(entityId);
var player = Room.GetPlayerById(peerId);
var entity = Room.GetEntityById(entityId);
_entityEvents[entityId][evntCode].Invoke(player, entity, ref payload);
return true;
@@ -161,7 +161,7 @@ namespace Ragon.Core
{
if (_globalEvents.ContainsKey(evntCode))
{
var player = GameRoom.GetPlayerById(peerId);
var player = Room.GetPlayerById(peerId);
_globalEvents[evntCode].Invoke(player, ref payload);
return true;
}
@@ -169,7 +169,7 @@ namespace Ragon.Core
return false;
}
public void SendEvent(Player player, uint eventCode, IRagonSerializable payload)
public void ReplicateEvent(Player player, uint eventCode, IRagonSerializable payload)
{
_serializer.Clear();
_serializer.WriteOperation(RagonOperation.REPLICATE_EVENT);
@@ -177,10 +177,10 @@ namespace Ragon.Core
payload.Serialize(_serializer);
var sendData = _serializer.ToArray();
GameRoom.Send(player.PeerId, sendData);
Room.Send(player.PeerId, sendData);
}
public void BroadcastEvent(ushort eventCode, IRagonSerializable payload)
public void ReplicateEvent(ushort eventCode, IRagonSerializable payload)
{
_serializer.Clear();
_serializer.WriteOperation(RagonOperation.REPLICATE_EVENT);
@@ -188,10 +188,10 @@ namespace Ragon.Core
payload.Serialize(_serializer);
var sendData = _serializer.ToArray();
GameRoom.Broadcast(sendData, DeliveryType.Reliable);
Room.Broadcast(sendData, DeliveryType.Reliable);
}
public void SendEntityEvent(Player player, Entity entity, IRagonSerializable payload)
public void ReplicateEntityEvent(Player player, Entity entity, IRagonSerializable payload)
{
_serializer.Clear();
_serializer.WriteOperation(RagonOperation.REPLICATE_ENTITY_EVENT);
@@ -200,10 +200,10 @@ namespace Ragon.Core
payload.Serialize(_serializer);
var sendData = _serializer.ToArray();
GameRoom.Send(player.PeerId, sendData, DeliveryType.Reliable);
Room.Send(player.PeerId, sendData, DeliveryType.Reliable);
}
public void BroadcastEntityEvent(Entity entity, IRagonSerializable payload)
public void ReplicateEntityEvent(Entity entity, IRagonSerializable payload)
{
_serializer.Clear();
_serializer.WriteOperation(RagonOperation.REPLICATE_ENTITY_EVENT);
@@ -212,7 +212,7 @@ namespace Ragon.Core
payload.Serialize(_serializer);
var sendData = _serializer.ToArray();
GameRoom.Broadcast(sendData);
Room.Broadcast(sendData);
}
+1 -1
View File
@@ -94,7 +94,7 @@ namespace Ragon.Core
{
if (_host.CheckEvents(out _netEvent) <= 0)
{
if (_host.Service(15, out _netEvent) <= 0)
if (_host.Service(0, out _netEvent) <= 0)
break;
polled = true;
+2 -2
View File
@@ -1,7 +1,7 @@
MIT License
Copyright (c) 2022 Eduard Kargin (theedison4@gmail.com)
MIT License:
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights