Compare commits

..

41 Commits

Author SHA1 Message Date
edmand46 5aa159ed2f fixed: custom property wrong size 2023-11-05 21:53:57 +03:00
edmand46 892558ab16 chore: update version 2023-10-22 21:10:31 +03:00
edmand46 f55634877a 📝 update readme.md 2023-10-21 23:10:41 +03:00
edmand46 8b3a29a750 📝 update readme.md 2023-10-21 23:09:49 +03:00
edmand46 6a50bffe1e 📝 update readme.md 2023-10-21 23:03:55 +03:00
edmand46 9144ad58ef 📝 update readme.md 2023-10-21 23:03:37 +03:00
edmand46 ee9f3fbe3a 🐛 crash on abnormal disconnecting from websocket server 2023-10-19 20:20:40 +03:00
edmand46 893c73512a feat: allow control replication via code, fix null owner on OnEntityCreated 2023-10-16 23:37:35 +03:00
edmand46 e7dd693147 🐛 Event Payload 2023-10-14 23:50:25 +03:00
edmand46 fef1007c8c 🔖 update version 2023-10-14 21:48:33 +03:00
edmand46 e33c442a18 🐛 WebSocket buffer size 2023-10-14 21:35:51 +03:00
edmand46 09b185a3ad 🐛 checking size event 2023-10-13 12:10:46 +03:00
edmand46 7d154ea4d4 🎨 cleanup 2023-10-13 11:02:56 +03:00
edmand46 d2577e5d1f remove allocation on raw data replication 2023-10-13 10:58:15 +03:00
edmand46 e25f42f9ff Merge pull request #14 from edmand46/v1.3.0
Ragon v1.3.0
2023-10-12 17:41:30 +03:00
edmand46 28cc41c3ad 🎨 update project 2023-10-12 17:40:57 +03:00
edmand46 fc483c0854 🚑 crash on timeout disconnect 2023-10-12 16:09:24 +03:00
edmand46 bcc45f7db8 🐛 lost piece of data 2023-10-12 15:38:34 +03:00
edmand46 689a240e5b 🐛 lost piece of data 2023-10-12 15:35:40 +03:00
edmand46 85b75766a9 🎨 remove $ from logs 2023-10-12 11:21:21 +03:00
edmand46 b90ed974e5 🐛 checking authority on destroy object 2023-10-12 11:18:04 +03:00
edmand46 3da57e086e 🐛 channels more then capacity 2023-10-11 21:21:58 +03:00
edmand46 745d196a8b wip 2023-10-11 20:49:00 +03:00
edmand46 860051777e wip 2023-10-11 19:38:26 +03:00
edmand46 6422db783a wip 2023-10-11 19:37:50 +03:00
edmand46 5d812d7acc 🚧 clean up listeners 2023-10-09 09:17:43 +03:00
edmand46 c214b6ca7f wip 2023-10-08 21:13:31 +03:00
edmand46 64842886d7 multiple subscribers, and unsubscribe 2023-10-07 20:20:02 +03:00
edmand46 c892c2b67a 🐛 operation code for room 2023-10-07 19:33:55 +03:00
edmand46 e1a3ea45e2 🚧 pass-through raw data, refactoring 2023-10-07 19:30:52 +03:00
edmand46 8788cb0fcf wip 2023-10-04 14:42:59 +03:00
edmand46 27db256902 🐛 scene entities not execute buffered events 2023-09-03 13:29:37 +03:00
edmand46 8705e93929 🐛 event size 2023-08-02 22:13:51 +03:00
edmand46 08e931d1bd 🚑 remove static entity spawn 2023-08-01 22:21:21 +03:00
edmand46 fb58dedfaf changed scene loading flow 2023-07-30 21:46:42 +03:00
edmand46 92062cd708 🎨 update naming of fields 2023-07-30 21:19:39 +03:00
edmand46 5fc55eaddc wip 2023-07-30 21:14:14 +03:00
edmand46 4a8aae11e3 🚑 fixed empty state values 2023-07-30 17:44:51 +03:00
edmand46 cd9304e63a Merge pull request #13 from edmand46/fix/payload
Fix/payload
2023-07-30 17:01:08 +03:00
edmand46 5199b5271b 🐛 Remove listener inside callback 2023-07-30 16:56:11 +03:00
edmand46 c01b748031 wip 2023-07-29 10:58:06 +03:00
109 changed files with 2232 additions and 752 deletions
+25
View File
@@ -0,0 +1,25 @@
**/.dockerignore
**/.env
**/.git
**/.gitignore
**/.project
**/.settings
**/.toolstarget
**/.vs
**/.vscode
**/.idea
**/*.*proj.user
**/*.dbmdl
**/*.jfm
**/azds.yaml
**/bin
**/charts
**/docker-compose*
**/Dockerfile*
**/node_modules
**/npm-debug.log
**/obj
**/secrets.dev.yaml
**/values.dev.yaml
LICENSE
README.md
+1
View File
@@ -1,6 +1,7 @@
.DS_Store
.idea
.vs
.vscode
obj
bin
*.user
BIN
View File
Binary file not shown.

After

Width:  |  Height:  |  Size: 26 KiB

+1 -1
View File
@@ -1,5 +1,5 @@
<p align="center">
<img src="Images/ragon-logo.png" width="200" >
<img src="Images/logo.png">
</p>
## Ragon Server
+1 -1
View File
@@ -17,7 +17,7 @@
using Ragon.Protocol;
namespace Ragon.Client.Simulation
namespace Ragon.Client.Property
{
[Serializable]
public class RagonBool : RagonProperty
+1 -1
View File
@@ -17,7 +17,7 @@
using Ragon.Protocol;
namespace Ragon.Client.Simulation
namespace Ragon.Client.Property
{
[Serializable]
public class RagonInt : RagonProperty
@@ -0,0 +1,76 @@
/*
* Copyright 2023 Eduard Kargin <kargin.eduard@gmail.com>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System.Numerics;
using Ragon.Client.Compressor;
using Ragon.Protocol;
namespace Ragon.Client.Property;
public class RagonQuaternion : RagonProperty
{
private Quaternion _value;
public Quaternion Value
{
get => _value;
set
{
_value = value;
MarkAsChanged();
}
}
private readonly FloatCompressor _compressor;
public RagonQuaternion(bool invokeLocal = false, int priority = 0) : base(priority, invokeLocal)
{
_compressor = new FloatCompressor(-1.0f, 1f, 0.01f);
SetFixedSize(_compressor.RequiredBits * 4);
}
public override void Serialize(RagonBuffer buffer)
{
var compressedX = _compressor.Compress(_value.X);
var compressedY = _compressor.Compress(_value.Y);
var compressedZ = _compressor.Compress(_value.Z);
var compressedW = _compressor.Compress(_value.W);
buffer.Write(compressedX, _compressor.RequiredBits);
buffer.Write(compressedY, _compressor.RequiredBits);
buffer.Write(compressedZ, _compressor.RequiredBits);
buffer.Write(compressedW, _compressor.RequiredBits);
}
public override void Deserialize(RagonBuffer buffer)
{
var compressedX = buffer.Read(_compressor.RequiredBits);
var compressedY = buffer.Read(_compressor.RequiredBits);
var compressedZ = buffer.Read(_compressor.RequiredBits);
var compressedW = buffer.Read(_compressor.RequiredBits);
var x = _compressor.Decompress(compressedX);
var y = _compressor.Decompress(compressedY);
var z = _compressor.Decompress(compressedZ);
var w = _compressor.Decompress(compressedW);
_value = new Quaternion(x, y, z, w);
InvokeChanged();
}
}
+1 -1
View File
@@ -18,7 +18,7 @@
using System.Text;
using Ragon.Protocol;
namespace Ragon.Client.Simulation
namespace Ragon.Client.Property
{
[Serializable]
public class RagonString : RagonProperty
@@ -0,0 +1,330 @@
/*
* Copyright 2023 Eduard Kargin <kargin.eduard@gmail.com>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
using System.Numerics;
using Ragon.Client.Compressor;
using Ragon.Protocol;
namespace Ragon.Client.Property
{
[Serializable]
public enum RagonAxis
{
XYZ,
XY,
YZ,
XZ,
X,
Y,
Z
}
[Serializable]
public class RagonVector3 : RagonProperty
{
private Vector3 _value;
public Vector3 Value
{
get => _value;
set
{
_value = value;
MarkAsChanged();
}
}
private RagonAxis _axis;
private FloatCompressor _compressorX;
private FloatCompressor _compressorY;
private FloatCompressor _compressorZ;
public RagonVector3(
RagonAxis axis = RagonAxis.XYZ,
bool invokeLocal = true,
int priority = 0
) : base(priority, invokeLocal)
{
_axis = axis;
var defaultCompressor = new FloatCompressor(-1024.0f, 1024f, 0.01f);
_compressorX = defaultCompressor;
_compressorY = defaultCompressor;
_compressorZ = defaultCompressor;
switch (_axis)
{
case RagonAxis.XYZ:
SetFixedSize(_compressorX.RequiredBits + _compressorY.RequiredBits + _compressorZ.RequiredBits);
break;
case RagonAxis.XY:
SetFixedSize(_compressorX.RequiredBits + _compressorY.RequiredBits);
break;
case RagonAxis.XZ:
SetFixedSize(_compressorX.RequiredBits + _compressorZ.RequiredBits);
break;
case RagonAxis.YZ:
SetFixedSize(_compressorY.RequiredBits + _compressorZ.RequiredBits);
break;
case RagonAxis.X:
SetFixedSize(_compressorX.RequiredBits);
break;
case RagonAxis.Y:
SetFixedSize(_compressorY.RequiredBits);
break;
case RagonAxis.Z:
SetFixedSize(_compressorZ.RequiredBits);
break;
}
}
public RagonVector3(
Vector3 initialValue,
RagonAxis axis = RagonAxis.XYZ,
float min = -1024.0f,
float max = 1024.0f,
float precision = 0.1f,
bool invokeLocal = true,
int priority = 0
) : base(priority, invokeLocal)
{
_value = initialValue;
_axis = axis;
var defaultCompressor = new FloatCompressor(min, max, precision);
_compressorX = defaultCompressor;
_compressorY = defaultCompressor;
_compressorZ = defaultCompressor;
switch (_axis)
{
case RagonAxis.XYZ:
SetFixedSize(_compressorX.RequiredBits + _compressorY.RequiredBits + _compressorZ.RequiredBits);
break;
case RagonAxis.XY:
SetFixedSize(_compressorX.RequiredBits + _compressorY.RequiredBits);
break;
case RagonAxis.XZ:
SetFixedSize(_compressorX.RequiredBits + _compressorZ.RequiredBits);
break;
case RagonAxis.YZ:
SetFixedSize(_compressorY.RequiredBits + _compressorZ.RequiredBits);
break;
case RagonAxis.X:
SetFixedSize(_compressorX.RequiredBits);
break;
case RagonAxis.Y:
SetFixedSize(_compressorY.RequiredBits);
break;
case RagonAxis.Z:
SetFixedSize(_compressorZ.RequiredBits);
break;
}
}
public RagonVector3(
RagonAxis axis = RagonAxis.XYZ,
FloatCompressor compressorX = null,
FloatCompressor compressorY = null,
FloatCompressor compressorZ = null,
bool invokeLocal = true,
int priority = 0
) : base(priority, invokeLocal)
{
_axis = axis;
var defaultCompressor = new FloatCompressor(-1024.0f, 1024f, 0.01f);
_compressorX = defaultCompressor;
_compressorY = defaultCompressor;
_compressorZ = defaultCompressor;
if (compressorX != null)
_compressorX = compressorX;
if (compressorY != null)
_compressorY = compressorY;
if (compressorZ != null)
_compressorZ = compressorZ;
switch (_axis)
{
case RagonAxis.XYZ:
SetFixedSize(_compressorX.RequiredBits + _compressorY.RequiredBits + _compressorZ.RequiredBits);
break;
case RagonAxis.XY:
SetFixedSize(_compressorX.RequiredBits + _compressorY.RequiredBits);
break;
case RagonAxis.XZ:
SetFixedSize(_compressorX.RequiredBits + _compressorZ.RequiredBits);
break;
case RagonAxis.YZ:
SetFixedSize(_compressorY.RequiredBits + _compressorZ.RequiredBits);
break;
case RagonAxis.X:
SetFixedSize(_compressorX.RequiredBits);
break;
case RagonAxis.Y:
SetFixedSize(_compressorY.RequiredBits);
break;
case RagonAxis.Z:
SetFixedSize(_compressorZ.RequiredBits);
break;
}
}
public override void Serialize(RagonBuffer buffer)
{
switch (_axis)
{
case RagonAxis.XYZ:
{
var compressedX = _compressorX.Compress(_value.X);
var compressedY = _compressorY.Compress(_value.Y);
var compressedZ = _compressorZ.Compress(_value.Z);
buffer.Write(compressedX, _compressorX.RequiredBits);
buffer.Write(compressedY, _compressorY.RequiredBits);
buffer.Write(compressedZ, _compressorZ.RequiredBits);
}
break;
case RagonAxis.XY:
{
var compressedX = _compressorX.Compress(_value.X);
var compressedY = _compressorY.Compress(_value.Y);
buffer.Write(compressedX, _compressorX.RequiredBits);
buffer.Write(compressedY, _compressorY.RequiredBits);
}
break;
case RagonAxis.XZ:
{
var compressedX = _compressorX.Compress(_value.X);
var compressedZ = _compressorZ.Compress(_value.Z);
buffer.Write(compressedX, _compressorX.RequiredBits);
buffer.Write(compressedZ, _compressorZ.RequiredBits);
break;
}
case RagonAxis.YZ:
{
var compressedY = _compressorY.Compress(_value.Y);
var compressedZ = _compressorZ.Compress(_value.Z);
buffer.Write(compressedY, _compressorY.RequiredBits);
buffer.Write(compressedZ, _compressorZ.RequiredBits);
break;
}
case RagonAxis.X:
{
var compressedX = _compressorX.Compress(_value.X);
buffer.Write(compressedX, _compressorX.RequiredBits);
break;
}
case RagonAxis.Y:
{
var compressedY = _compressorY.Compress(_value.Y);
buffer.Write(compressedY, _compressorY.RequiredBits);
break;
}
case RagonAxis.Z:
{
var compressedZ = _compressorZ.Compress(_value.Z);
buffer.Write(compressedZ, _compressorZ.RequiredBits);
break;
}
}
}
public override void Deserialize(RagonBuffer buffer)
{
switch (_axis)
{
case RagonAxis.XYZ:
{
var compressedX = buffer.Read(_compressorX.RequiredBits);
var compressedY = buffer.Read(_compressorY.RequiredBits);
var compressedZ = buffer.Read(_compressorZ.RequiredBits);
_value.X = _compressorX.Decompress(compressedX);
_value.Y = _compressorY.Decompress(compressedY);
_value.Z = _compressorZ.Decompress(compressedZ);
break;
}
case RagonAxis.XY:
{
var compressedX = buffer.Read(_compressorX.RequiredBits);
var compressedY = buffer.Read(_compressorY.RequiredBits);
_value.X = _compressorX.Decompress(compressedX);
_value.Z = _compressorY.Decompress(compressedY);
break;
}
case RagonAxis.XZ:
{
var compressedX = buffer.Read(_compressorX.RequiredBits);
var compressedZ = buffer.Read(_compressorZ.RequiredBits);
_value.X = _compressorX.Decompress(compressedX);
_value.Z = _compressorZ.Decompress(compressedZ);
break;
}
case RagonAxis.YZ:
{
var compressedY = buffer.Read(_compressorY.RequiredBits);
var compressedZ = buffer.Read(_compressorZ.RequiredBits);
_value.Y = _compressorY.Decompress(compressedY);
_value.Z = _compressorZ.Decompress(compressedZ);
break;
}
case RagonAxis.X:
{
var compressedX = buffer.Read(_compressorX.RequiredBits);
_value.X = _compressorX.Decompress(compressedX);
break;
}
case RagonAxis.Y:
{
var compressedY = buffer.Read(_compressorY.RequiredBits);
_value.Y = _compressorY.Decompress(compressedY);
break;
}
case RagonAxis.Z:
{
var compressedZ = buffer.Read(_compressorZ.RequiredBits);
_value.Z = _compressorZ.Decompress(compressedZ);
break;
}
}
InvokeChanged();
}
}
}
+3 -3
View File
@@ -1,22 +1,22 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>netstandard2.1</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
<LangVersion>10</LangVersion>
<RootNamespace>Ragon.Client.Simulation</RootNamespace>
<Authors>Eduard Kargin (Edmand46)</Authors>
<TargetFramework>netstandard2.0</TargetFramework>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)' == 'Release' ">
<AllowUnsafeBlocks>true</AllowUnsafeBlocks>
<DebugType>none</DebugType>
<OutputPath>/Users/edmand46/RagonProjects/ragon-oss-sdk/Assets/Ragon/Plugins/</OutputPath>
<OutputPath>/Users/edmand46/RagonProjects/ragon-oss-examples/Assets/Ragon/Runtime/Plugins</OutputPath>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)' == 'Debug' ">
<OutputPath>/Users/edmand46/RagonProjects/ragon-unity-sdk/Assets/Ragon/Runtime/Plugins</OutputPath>
<OutputPath>/Users/edmand46/RagonProjects/ragon-oss-examples/Assets/Ragon/Plugins/</OutputPath>
</PropertyGroup>
<ItemGroup>
+93 -38
View File
@@ -19,20 +19,49 @@ using Ragon.Protocol;
namespace Ragon.Client
{
public sealed class RagonEntity
public sealed class RagonEntity : IDisposable
{
private class EventSubscription : IDisposable
{
private List<Action<RagonPlayer, IRagonEvent>> _callbacks;
private List<Action<RagonPlayer, IRagonEvent>> _localCallbacks;
private Action<RagonPlayer, IRagonEvent> _callback;
public EventSubscription(
List<Action<RagonPlayer, IRagonEvent>> callbacks,
List<Action<RagonPlayer, IRagonEvent>> localCallbacks,
Action<RagonPlayer, IRagonEvent> callback)
{
_callbacks = callbacks;
_localCallbacks = localCallbacks;
_callback = callback;
}
public void Dispose()
{
_callbacks.Remove(_callback);
_localCallbacks.Remove(_callback);
_callbacks = null!;
_localCallbacks = null!;
_callback = null!;
}
}
private delegate void OnEventDelegate(RagonPlayer player, RagonBuffer serializer);
private RagonClient _client;
public ushort Id { get; private set; }
public ushort Type { get; private set; }
public bool Replication { get; private set; }
public RagonAuthority Authority { get; private set; }
public RagonPlayer Owner { get; private set; }
public RagonEntityState State { get; private set; }
public bool IsStatic => SceneId > 0;
public bool IsReplicated { get; private set; }
public bool IsAttached { get; private set; }
public bool HasAuthority { get; private set; }
@@ -49,32 +78,33 @@ namespace Ragon.Client
private RagonPayload _spawnPayload;
private RagonPayload _destroyPayload;
private Dictionary<int, OnEventDelegate> _events = new();
private Dictionary<int, Action<RagonPlayer, IRagonEvent>> _localEvents = new();
private readonly Dictionary<int, OnEventDelegate> _events = new Dictionary<int, OnEventDelegate>();
private readonly Dictionary<int, List<Action<RagonPlayer, IRagonEvent>>> _localListeners = new Dictionary<int, List<Action<RagonPlayer, IRagonEvent>>>();
private readonly Dictionary<int, List<Action<RagonPlayer, IRagonEvent>>> _listeners = new Dictionary<int, List<Action<RagonPlayer, IRagonEvent>>>();
public RagonEntity(ushort type = 0, ushort sceneId = 0)
public RagonEntity(ushort type = 0, ushort sceneId = 0, bool replicated = true)
{
State = new RagonEntityState(this);
Type = type;
IsReplicated = replicated;
_spawnPayload = new RagonPayload(0);
_destroyPayload = new RagonPayload(0);
_sceneId = sceneId;
}
internal void Attach(RagonClient client, ushort entityId, ushort entityType, bool hasAuthority, RagonPlayer owner, RagonPayload payload)
internal void Attach()
{
Type = entityType;
Id = entityId;
Owner = owner;
IsAttached = true;
Replication = true;
HasAuthority = hasAuthority;
_client = client;
_spawnPayload = payload;
Attached?.Invoke(this);
}
public void SetReplication(bool enabled)
{
IsReplicated = enabled;
}
internal void Detach(RagonPayload payload)
{
_destroyPayload = payload;
@@ -96,15 +126,16 @@ namespace Ragon.Client
return payload;
}
public void AttachPayload(IRagonPayload? payload)
public void Prepare(RagonClient client, ushort entityId, ushort entityType, bool hasAuthority, RagonPlayer player, RagonPayload payload)
{
if (payload == null) return;
Type = entityType;
Id = entityId;
HasAuthority = hasAuthority;
var buffer = new RagonBuffer();
payload.Serialize(buffer);
_client = client;
_spawnPayload = payload;
_spawnPayload = new RagonPayload();
_spawnPayload.Read(buffer);
Owner = player;
}
public T GetAttachPayload<T>() where T : IRagonPayload, new()
@@ -155,29 +186,31 @@ namespace Ragon.Client
return;
}
var eventCode = _client.Event.GetEventCode(evnt);
if (target != RagonTarget.ExceptOwner)
{
if (replicationMode == RagonReplicationMode.Local)
{
var eventCode = _client.Event.GetEventCode(evnt);
_localEvents[eventCode].Invoke(_client.Room.Local, evnt);
var localListeners = _localListeners[eventCode];
foreach (var listener in localListeners)
listener.Invoke(_client.Room.Local, evnt);
return;
}
if (replicationMode == RagonReplicationMode.LocalAndServer)
{
var eventCode = _client.Event.GetEventCode(evnt);
_localEvents[eventCode].Invoke(_client.Room.Local, evnt);
var localListeners = _localListeners[eventCode];
foreach (var listener in localListeners)
listener.Invoke(_client.Room.Local, evnt);
}
}
var evntId = _client.Event.GetEventCode(evnt);
var buffer = _client.Buffer;
buffer.Clear();
buffer.WriteOperation(RagonOperation.REPLICATE_ENTITY_EVENT);
buffer.WriteUShort(Id);
buffer.WriteUShort(evntId);
buffer.WriteUShort(eventCode);
buffer.WriteByte((byte)replicationMode);
buffer.WriteByte((byte)target);
@@ -187,25 +220,39 @@ namespace Ragon.Client
_client.Reliable.Send(sendData);
}
public void OnEvent<TEvent>(Action<RagonPlayer, TEvent> callback) where TEvent : IRagonEvent, new()
public IDisposable OnEvent<TEvent>(Action<RagonPlayer, TEvent> callback) where TEvent : IRagonEvent, new()
{
var t = new TEvent();
var eventCode = _client.Event.GetEventCode(t);
var action = (RagonPlayer player, IRagonEvent eventData) => callback.Invoke(player, (TEvent)eventData);
if (_events.ContainsKey(eventCode))
if (!_listeners.TryGetValue(eventCode, out var callbacks))
{
_events.Remove(eventCode);
_localEvents.Remove(eventCode);
RagonLog.Warn($"Event already {eventCode} subscribed, removed old one!");
callbacks = new List<Action<RagonPlayer, IRagonEvent>>();
_listeners.Add(eventCode, callbacks);
}
_localEvents.Add(eventCode, (player, eventData) => { callback.Invoke(player, (TEvent)eventData); });
_events.Add(eventCode, (player, serializer) =>
if (!_localListeners.TryGetValue(eventCode, out var localCallbacks))
{
t.Deserialize(serializer);
callback.Invoke(player, t);
});
localCallbacks = new List<Action<RagonPlayer, IRagonEvent>>();
_localListeners.Add(eventCode, localCallbacks);
}
callbacks.Add(action);
localCallbacks.Add(action);
if (!_events.ContainsKey(eventCode))
{
_events.Add(eventCode, (player, serializer) =>
{
t.Deserialize(serializer);
foreach (var callbackListener in callbacks)
callbackListener.Invoke(player, t);
});
}
return new EventSubscription(callbacks, localCallbacks, action);
}
internal void Write(RagonBuffer buffer)
@@ -217,7 +264,6 @@ namespace Ragon.Client
_propertiesChanged = false;
}
internal void Read(RagonBuffer buffer)
{
State.ReadState(buffer);
@@ -225,6 +271,8 @@ namespace Ragon.Client
internal void Event(ushort eventCode, RagonPlayer caller, RagonBuffer buffer)
{
if (!IsReplicated) return;
if (_events.TryGetValue(eventCode, out var evnt))
evnt?.Invoke(caller, buffer);
else
@@ -245,5 +293,12 @@ namespace Ragon.Client
OwnershipChanged?.Invoke(prevOwner, player);
}
public void Dispose()
{
_events.Clear();
_listeners.Clear();
_localListeners.Clear();
}
}
}
+5 -7
View File
@@ -19,8 +19,10 @@ using Ragon.Protocol;
namespace Ragon.Client;
public struct RagonPayload
public class RagonPayload
{
public static RagonPayload Empty = new RagonPayload(0);
private readonly uint[] _data = new uint[128];
private readonly int _size = 0;
@@ -32,16 +34,12 @@ public struct RagonPayload
public void Read(RagonBuffer buffer)
{
var readOnlySpan = _data.AsSpan();
buffer.ReadSpan(ref readOnlySpan, _size);
buffer.ReadArray(_data, _size);
}
public void Write(RagonBuffer buffer)
{
ReadOnlySpan<uint> readOnlySpan = _data.AsSpan();
buffer.WriteSpan(ref readOnlySpan, _size);
buffer.WriteArray(_data, _size);
}
public override string ToString()
+2 -2
View File
@@ -106,7 +106,7 @@ namespace Ragon.Client
{
Serialize(_propertyBuffer);
buffer.FromBuffer(_propertyBuffer, _size);
buffer.CopyFrom(_propertyBuffer, _size);
return;
}
@@ -114,7 +114,7 @@ namespace Ragon.Client
var propertySize = (ushort) _propertyBuffer.WriteOffset;
buffer.WriteUShort(propertySize);;
buffer.FromBuffer(_propertyBuffer, propertySize);
buffer.CopyFrom(_propertyBuffer, propertySize);
}
internal void Read(RagonBuffer buffer)
@@ -19,7 +19,7 @@ using Ragon.Protocol;
namespace Ragon.Client;
internal class AuthorizeFailedHandler: Handler
internal class AuthorizeFailedHandler: IHandler
{
private readonly RagonListenerList _listenerList;
public AuthorizeFailedHandler(RagonListenerList list)
@@ -27,9 +27,9 @@ internal class AuthorizeFailedHandler: Handler
_listenerList = list;
}
public void Handle(RagonBuffer buffer)
public void Handle(RagonBuffer reader)
{
var message = buffer.ReadString();
var message = reader.ReadString();
_listenerList.OnAuthorizationFailed(message);
}
}
@@ -19,21 +19,26 @@ using Ragon.Protocol;
namespace Ragon.Client;
internal class AuthorizeSuccessHandler: Handler
internal class AuthorizeSuccessHandler: IHandler
{
private readonly RagonListenerList _listenerList;
private readonly RagonClient _client;
public AuthorizeSuccessHandler(RagonListenerList listenerList)
public AuthorizeSuccessHandler(
RagonClient client,
RagonListenerList listenerList)
{
_client = client;
_listenerList = listenerList;
}
public void Handle(RagonBuffer buffer)
public void Handle(RagonBuffer reader)
{
var playerId = buffer.ReadString();
var playerName = buffer.ReadString();
var playerPayload = buffer.ReadString();
var playerId = reader.ReadString();
var playerName = reader.ReadString();
var playerPayload = reader.ReadString();
_client.SetStatus(RagonStatus.LOBBY);
_listenerList.OnAuthorizationSuccess(playerId, playerName, playerPayload);
}
}
@@ -18,32 +18,35 @@ using Ragon.Protocol;
namespace Ragon.Client;
internal class EntityCreateHandler : Handler
internal class EntityCreateHandler : IHandler
{
private readonly RagonClient _client;
private readonly RagonPlayerCache _playerCache;
private readonly RagonEntityCache _entityCache;
private readonly IRagonEntityListener _entityListener;
public EntityCreateHandler(
RagonClient client,
RagonPlayerCache playerCache,
RagonEntityCache entityCache
RagonEntityCache entityCache,
IRagonEntityListener entityListener
)
{
_client = client;
_entityCache = entityCache;
_playerCache = playerCache;
_entityListener = entityListener;
}
public void Handle(RagonBuffer buffer)
public void Handle(RagonBuffer reader)
{
var attachId = buffer.ReadUShort();
var entityType = buffer.ReadUShort();
var entityId = buffer.ReadUShort();
var ownerId = buffer.ReadUShort();
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(buffer.Capacity);
payload.Read(buffer);
var payload = new RagonPayload(reader.Capacity);
payload.Read(reader);
if (player == null)
{
@@ -52,7 +55,13 @@ internal class EntityCreateHandler : Handler
}
var hasAuthority = _playerCache.Local.Id == player.Id;
var entity = _entityCache.OnCreate(attachId, entityType, 0, entityId, hasAuthority);
entity.Attach(_client, entityId, entityType, hasAuthority, player, payload);
var entity = _entityCache.TryGetEntity(attachId, entityType, 0, entityId, hasAuthority, out var hasCreated);
entity.Prepare(_client, entityId, entityType, hasAuthority, player, payload);
if (hasCreated)
_entityListener.OnEntityCreated(entity);
entity.Attach();
}
}
@@ -18,29 +18,26 @@ using Ragon.Protocol;
namespace Ragon.Client;
internal class EntityEventHandler : Handler
internal class EntityEventHandler : IHandler
{
private readonly RagonClient _client;
private readonly RagonPlayerCache _playerCache;
private readonly RagonEntityCache _entityCache;
public EntityEventHandler(
RagonClient client,
RagonPlayerCache playerCache,
RagonEntityCache entityCache
)
{
_client = client;
_playerCache = playerCache;
_entityCache = entityCache;
}
public void Handle(RagonBuffer buffer)
public void Handle(RagonBuffer reader)
{
var eventCode = buffer.ReadUShort();
var peerId = buffer.ReadUShort();
var executionMode = (RagonReplicationMode)buffer.ReadByte();
var entityId = buffer.ReadUShort();
var eventCode = reader.ReadUShort();
var peerId = reader.ReadUShort();
var executionMode = (RagonReplicationMode)reader.ReadByte();
var entityId = reader.ReadUShort();
var player = _playerCache.GetPlayerByPeer(peerId);
if (player == null)
@@ -52,6 +49,6 @@ internal class EntityEventHandler : Handler
if (player.IsLocal && executionMode == RagonReplicationMode.LocalAndServer)
return;
_entityCache.OnEvent(player, entityId, eventCode, buffer);
_entityCache.OnEvent(player, entityId, eventCode, reader);
}
}
@@ -19,7 +19,7 @@ using Ragon.Protocol;
namespace Ragon.Client;
internal class EntityOwnershipHandler: Handler
internal class EntityOwnershipHandler: IHandler
{
private readonly RagonListenerList _listenerList;
private readonly RagonPlayerCache _playerCache;
@@ -35,15 +35,15 @@ internal class EntityOwnershipHandler: Handler
_entityCache = entityCache;
}
public void Handle(RagonBuffer buffer)
public void Handle(RagonBuffer reader)
{
var newOwnerId = buffer.ReadUShort();
var entities = buffer.ReadUShort();
var newOwnerId = reader.ReadUShort();
var entities = reader.ReadUShort();
var player = _playerCache.GetPlayerByPeer(newOwnerId);
for (var i = 0; i < entities; i++)
{
var entityId = buffer.ReadUShort();
var entityId = reader.ReadUShort();
_entityCache.OnOwnershipChanged(player, entityId);
RagonLog.Trace("Entity changed owner: " + entityId);
@@ -19,7 +19,7 @@ using Ragon.Protocol;
namespace Ragon.Client;
internal class EntityRemoveHandler: Handler
internal class EntityRemoveHandler: IHandler
{
private readonly RagonEntityCache _entityCache;
@@ -28,11 +28,11 @@ internal class EntityRemoveHandler: Handler
_entityCache = entityCache;
}
public void Handle(RagonBuffer buffer)
public void Handle(RagonBuffer reader)
{
var entityId = buffer.ReadUShort();
var payload = new RagonPayload(buffer.Capacity);
payload.Read(buffer);
var entityId = reader.ReadUShort();
var payload = new RagonPayload(reader.Capacity);
payload.Read(reader);
_entityCache.OnDestroy(entityId, payload);
}
@@ -18,7 +18,7 @@ using Ragon.Protocol;
namespace Ragon.Client;
internal class StateEntityHandler: Handler
internal class StateEntityHandler: IHandler
{
private readonly RagonEntityCache _entityCache;
@@ -27,13 +27,13 @@ internal class StateEntityHandler: Handler
_entityCache = entityCache;
}
public void Handle(RagonBuffer buffer)
public void Handle(RagonBuffer reader)
{
var entitiesCount = buffer.ReadUShort();
var entitiesCount = reader.ReadUShort();
for (var i = 0; i < entitiesCount; i++)
{
var entityId = buffer.ReadUShort();
_entityCache.OnState(entityId, buffer);
var entityId = reader.ReadUShort();
_entityCache.OnState(entityId, reader);
}
}
}
@@ -19,7 +19,7 @@ using Ragon.Protocol;
namespace Ragon.Client;
public interface Handler
public interface IHandler
{
public void Handle(RagonBuffer buffer);
public void Handle(RagonBuffer reader);
}
@@ -19,7 +19,7 @@ using Ragon.Protocol;
namespace Ragon.Client;
internal class JoinFailedHandler: Handler
internal class JoinFailedHandler: IHandler
{
private readonly RagonListenerList _listenerList;
@@ -28,9 +28,9 @@ internal class JoinFailedHandler: Handler
_listenerList = listenerList;
}
public void Handle(RagonBuffer buffer)
public void Handle(RagonBuffer reader)
{
var message = buffer.ReadString();
var message = reader.ReadString();
_listenerList.OnFailed(message);
}
}
@@ -37,44 +37,42 @@ public struct RagonRoomInformation
public ushort Max { get; private set; }
}
internal class JoinSuccessHandler : Handler
internal class JoinSuccessHandler : IHandler
{
private readonly RagonListenerList _listenerList;
private readonly RagonPlayerCache _playerCache;
private readonly RagonEntityCache _entityCache;
private readonly RagonClient _client;
private readonly RagonBuffer _buffer;
public JoinSuccessHandler(
RagonClient client,
RagonBuffer buffer,
RagonListenerList listenerList,
RagonPlayerCache playerCache,
RagonEntityCache entityCache
)
{
_buffer = buffer;
_client = client;
_listenerList = listenerList;
_entityCache = entityCache;
_playerCache = playerCache;
}
public void Handle(RagonBuffer buffer)
public void Handle(RagonBuffer reader)
{
var roomId = buffer.ReadString();
var localId = buffer.ReadString();
var ownerId = buffer.ReadString();
var min = buffer.ReadUShort();
var max = buffer.ReadUShort();
var map = buffer.ReadString();
var roomId = reader.ReadString();
var localId = reader.ReadString();
var ownerId = reader.ReadString();
var min = reader.ReadUShort();
var max = reader.ReadUShort();
var sceneName = reader.ReadString();
var scene = new RagonScene(_client, _playerCache, _entityCache);
var scene = new RagonScene(_client, _playerCache, _entityCache, sceneName);
var roomInfo = new RagonRoomInformation(roomId, localId, ownerId, min, max);
var room = new RagonRoom(_client, _entityCache, _playerCache, roomInfo, scene);
_playerCache.SetOwnerAndLocal(ownerId, localId);
_client.AssignRoom(room);
_listenerList.OnLevel(map);
_listenerList.OnSceneRequest(sceneName);
}
}
@@ -19,7 +19,7 @@ using Ragon.Protocol;
namespace Ragon.Client;
internal class LeaveRoomHandler : Handler
internal class LeaveRoomHandler : IHandler
{
private readonly RagonClient _client;
private readonly RagonListenerList _listenerList;
@@ -35,7 +35,7 @@ internal class LeaveRoomHandler : Handler
_entityCache = entityCache;
}
public void Handle(RagonBuffer buffer)
public void Handle(RagonBuffer reader)
{
_listenerList.OnLeft();
_entityCache.Cleanup();
@@ -18,7 +18,7 @@ using Ragon.Protocol;
namespace Ragon.Client;
internal class SceneLoadHandler: Handler
internal class SceneLoadHandler: IHandler
{
private readonly RagonClient _client;
private readonly RagonListenerList _listenerList;
@@ -32,13 +32,14 @@ internal class SceneLoadHandler: Handler
_listenerList = listenerList;
}
public void Handle(RagonBuffer buffer)
public void Handle(RagonBuffer reader)
{
var sceneName = buffer.ReadString();
var sceneName = reader.ReadString();
var room = _client.Room;
room.Cleanup();
room.Update(sceneName);
_listenerList.OnLevel(sceneName);
_listenerList.OnSceneRequest(sceneName);
}
}
@@ -19,7 +19,7 @@ using Ragon.Protocol;
namespace Ragon.Client;
internal class OwnershipRoomHandler: Handler
internal class OwnershipRoomHandler: IHandler
{
private readonly RagonListenerList _listenerList;
private readonly RagonPlayerCache _playerCache;
@@ -35,9 +35,9 @@ internal class OwnershipRoomHandler: Handler
_entityCache = entityCache;
}
public void Handle(RagonBuffer buffer)
public void Handle(RagonBuffer reader)
{
var newOwnerId = buffer.ReadUShort();
var newOwnerId = reader.ReadUShort();
var player = _playerCache.GetPlayerByPeer(newOwnerId);
_playerCache.OnOwnershipChanged(newOwnerId);
@@ -19,7 +19,7 @@ using Ragon.Protocol;
namespace Ragon.Client;
internal class PlayerJoinHandler : Handler
internal class PlayerJoinHandler : IHandler
{
private RagonPlayerCache _playerCache;
private RagonListenerList _listenerList;
@@ -33,11 +33,11 @@ internal class PlayerJoinHandler : Handler
_listenerList = listenerList;
}
public void Handle(RagonBuffer buffer)
public void Handle(RagonBuffer reader)
{
var playerPeerId = buffer.ReadUShort();
var playerId = buffer.ReadString();
var playerName = buffer.ReadString();
var playerPeerId = reader.ReadUShort();
var playerId = reader.ReadString();
var playerName = reader.ReadString();
_playerCache.AddPlayer(playerPeerId, playerId, playerName);
@@ -19,7 +19,7 @@ using Ragon.Protocol;
namespace Ragon.Client;
internal class PlayerLeftHandler : Handler
internal class PlayerLeftHandler : IHandler
{
private RagonPlayerCache _playerCache;
private RagonEntityCache _entityCache;
@@ -36,25 +36,26 @@ internal class PlayerLeftHandler : Handler
_listenerList = listenerList;
}
public void Handle(RagonBuffer buffer)
public void Handle(RagonBuffer reader)
{
var playerId = buffer.ReadString();
var playerId = reader.ReadString();
var player = _playerCache.GetPlayerById(playerId);
if (player != null)
{
_playerCache.RemovePlayer(playerId);
_listenerList.OnPlayerLeft(player);
var entities = buffer.ReadUShort();
var entities = reader.ReadUShort();
var toDeleteIds = new ushort[entities];
for (var i = 0; i < entities; i++)
{
var entityId = buffer.ReadUShort();
var entityId = reader.ReadUShort();
toDeleteIds[i] = entityId;
}
var emptyPayload = new RagonPayload(0);
foreach (var id in toDeleteIds)
_entityCache.OnDestroy(id, new RagonPayload());
_entityCache.OnDestroy(id, emptyPayload);
}
}
}
@@ -0,0 +1,47 @@
/*
* Copyright 2023 Eduard Kargin <kargin.eduard@gmail.com>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using Ragon.Protocol;
namespace Ragon.Client;
internal class RoomDataHandler: IHandler
{
private readonly RagonListenerList _listeners;
private readonly RagonPlayerCache _playerCache;
public RoomDataHandler(
RagonPlayerCache playerCache,
RagonListenerList listeners)
{
_playerCache = playerCache;
_listeners = listeners;
}
public void Handle(RagonBuffer reader)
{
var rawData = reader.RawData;
var peerId = (ushort)(rawData[1] + (rawData[2] << 8));
var player = _playerCache.GetPlayerByPeer(peerId);
var headerSize = 3;
var payload = new byte[rawData.Length - headerSize];
Array.Copy(rawData, headerSize, payload, 0, payload.Length);
_listeners.OnData(player, payload);
}
}
@@ -0,0 +1,53 @@
/*
* Copyright 2023 Eduard Kargin <kargin.eduard@gmail.com>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using Ragon.Protocol;
namespace Ragon.Client;
public class RoomEventHandler: IHandler
{
private readonly RagonClient _client;
private readonly RagonPlayerCache _playerCache;
public RoomEventHandler(
RagonClient client,
RagonPlayerCache playerCache
)
{
_client = client;
_playerCache = playerCache;
}
public void Handle(RagonBuffer buffer)
{
var eventCode = buffer.ReadUShort();
var peerId = buffer.ReadUShort();
var executionMode = (RagonReplicationMode)buffer.ReadByte();
var player = _playerCache.GetPlayerByPeer(peerId);
if (player == null)
{
RagonLog.Warn($"Player not found for event {eventCode}");
return;
}
if (player.IsLocal && executionMode == RagonReplicationMode.LocalAndServer)
return;
_client.Room.Event(eventCode, player, buffer);
}
}
+47 -17
View File
@@ -20,21 +20,24 @@ using Ragon.Protocol;
namespace Ragon.Client;
internal class SnapshotHandler : Handler
internal class SnapshotHandler : IHandler
{
private RagonClient _client;
private RagonListenerList _listenerList;
private RagonEntityCache _entityCache;
private RagonPlayerCache _playerCache;
private readonly IRagonEntityListener _entityListener;
private readonly RagonClient _client;
private readonly RagonListenerList _listenerList;
private readonly RagonEntityCache _entityCache;
private readonly RagonPlayerCache _playerCache;
public SnapshotHandler(
RagonClient ragonClient,
RagonListenerList listenerList,
RagonEntityCache entityCache,
RagonPlayerCache playerCache
RagonPlayerCache playerCache,
IRagonEntityListener entityListener
)
{
_client = ragonClient;
_entityListener = entityListener;
_listenerList = listenerList;
_entityCache = entityCache;
_playerCache = playerCache;
@@ -51,7 +54,10 @@ internal class SnapshotHandler : Handler
var playerName = buffer.ReadString();
_playerCache.AddPlayer(playerPeerId, playerId, playerName);
RagonLog.Trace($"Player {playerPeerId} - {playerId} - {playerName}");
}
var dynamicEntities = buffer.ReadUShort();
RagonLog.Trace("Dynamic Entities: " + dynamicEntities);
for (var i = 0; i < dynamicEntities; i++)
@@ -60,16 +66,29 @@ internal class SnapshotHandler : Handler
var entityId = buffer.ReadUShort();
var ownerPeerId = buffer.ReadUShort();
var payloadSize = buffer.ReadUShort();
var player = _playerCache.GetPlayerByPeer(ownerPeerId);
var payload = new RagonPayload(payloadSize);
payload.Read(buffer);
var player = _playerCache.GetPlayerByPeer(ownerPeerId);
if (player == null)
{
RagonLog.Error($"Player not found with peerId: ${ownerPeerId}");
return;
}
var hasAuthority = _playerCache.Local.Id == player.Id;
var entity = _entityCache.OnCreate(0, entityType, 0, entityId, hasAuthority);
var entity = _entityCache.TryGetEntity(0, entityType, 0, entityId, hasAuthority, out _);
var payload = RagonPayload.Empty;
if (payloadSize > 0)
{
payload = new RagonPayload(payloadSize);
payload.Read(buffer);
}
entity.Prepare(_client, entityId, entityType, hasAuthority, player, payload);
_entityListener.OnEntityCreated(entity);
entity.Read(buffer);
entity.Attach(_client, entityId, entityType, hasAuthority, player, payload);
entity.Attach();
}
var staticEntities = buffer.ReadUShort();
@@ -81,18 +100,29 @@ internal class SnapshotHandler : Handler
var staticId = buffer.ReadUShort();
var ownerPeerId = buffer.ReadUShort();
var payloadSize = buffer.ReadUShort();
var player = _playerCache.GetPlayerByPeer(ownerPeerId);
var payload = new RagonPayload(payloadSize);
payload.Read(buffer);
var player = _playerCache.GetPlayerByPeer(ownerPeerId);
if (player == null)
{
RagonLog.Error($"Player not found with peerId: ${ownerPeerId}");
return;
}
var hasAuthority = _playerCache.Local.Id == player.Id;
var entity = _entityCache.OnCreate(0, entityType, staticId, entityId, hasAuthority);
var entity = _entityCache.TryGetEntity(0, entityType, staticId, entityId, hasAuthority, out _);
entity.Prepare(_client, entityId, entityType, hasAuthority, player, RagonPayload.Empty);
entity.Read(buffer);
entity.Attach(_client, entityId, entityType, hasAuthority, player, payload);
entity.Attach();
}
_listenerList.OnJoined();
if (_client.Status == RagonStatus.LOBBY)
{
_client.SetStatus(RagonStatus.ROOM);
_listenerList.OnJoined();
}
_listenerList.OnSceneLoaded();
}
}
@@ -0,0 +1,21 @@
using Ragon.Protocol;
namespace Ragon.Client;
public class TimestampHandler: IHandler
{
private readonly RagonClient _client;
public TimestampHandler(RagonClient client)
{
_client = client;
}
public void Handle(RagonBuffer buffer)
{
var timestamp0 = buffer.Read(32);
var timestamp1 = buffer.Read(32);
var value = new DoubleToUInt { Int0 = timestamp0, Int1 = timestamp1 };
_client.SetTimestamp(value.Double);
}
}
+1 -1
View File
@@ -18,5 +18,5 @@ namespace Ragon.Client;
public interface IRagonConnection
{
public void Close();
}
@@ -16,7 +16,7 @@
namespace Ragon.Client;
public interface IRagonLevelListener
public interface IRagonDataListener
{
void OnLevel(RagonClient client, string sceneName);
public void OnData(RagonPlayer player, byte[] data);
}
@@ -22,10 +22,11 @@ namespace Ragon.Client
IRagonFailedListener,
IRagonJoinListener,
IRagonLeftListener,
IRagonLevelListener,
IRagonSceneListener,
IRagonOwnershipChangedListener,
IRagonPlayerJoinListener,
IRagonPlayerLeftListener
{
}
}
@@ -0,0 +1,22 @@
/*
* Copyright 2023 Eduard Kargin <kargin.eduard@gmail.com>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
namespace Ragon.Client;
public interface IRagonSceneListener
{
void OnSceneLoaded(RagonClient client);
}
@@ -0,0 +1,6 @@
namespace Ragon.Client;
public interface IRagonSceneRequestListener
{
void OnRequestScene(RagonClient client, string sceneName);
}
+87 -48
View File
@@ -21,23 +21,25 @@ namespace Ragon.Client
public sealed class RagonClient
{
private readonly INetworkConnection _connection;
private readonly NetworkStatistics _stats;
private IRagonEntityListener _entityListener;
private IRagonSceneCollector _sceneCollector;
private Handler[] _handlers;
private IHandler[] _handlers;
private RagonBuffer _readBuffer;
private RagonBuffer _writeBuffer;
private RagonRoom _room;
private RagonSession _session;
private RagonListenerList _listenerList;
private RagonListenerList listeners;
private RagonPlayerCache _playerCache;
private RagonEntityCache _entityCache;
private RagonEventCache _eventCache;
private RagonStatus _status;
private NetworkStatistics _stats;
private double _serverTimestamp;
private float _replicationRate = 0;
private float _replicationTime = 0;
public double ServerTimestamp => _serverTimestamp;
public IRagonConnection Connection => _connection;
public RagonStatus Status => _status;
public RagonSession Session => _session;
@@ -54,13 +56,13 @@ namespace Ragon.Client
public RagonClient(INetworkConnection connection, int rate)
{
listeners = new RagonListenerList(this);
_connection = connection;
_connection.OnData += OnData;
_connection.OnConnected += OnConnected;
_connection.OnDisconnected += OnDisconnected;
_listenerList = new RagonListenerList(this);
_replicationRate = (1000.0f / rate) / 1000.0f;
_replicationTime = 0;
@@ -96,27 +98,30 @@ namespace Ragon.Client
_writeBuffer = new RagonBuffer();
_readBuffer = new RagonBuffer();
_session = new RagonSession(this, _readBuffer);
_session = new RagonSession(this, _writeBuffer);
_playerCache = new RagonPlayerCache();
_entityCache = new RagonEntityCache(this, _playerCache, _entityListener, _sceneCollector);
_entityCache = new RagonEntityCache(this, _playerCache, _sceneCollector);
_handlers = new Handler[byte.MaxValue];
_handlers[(byte)RagonOperation.AUTHORIZED_SUCCESS] = new AuthorizeSuccessHandler(_listenerList);
_handlers[(byte)RagonOperation.AUTHORIZED_FAILED] = new AuthorizeFailedHandler(_listenerList);
_handlers[(byte)RagonOperation.JOIN_SUCCESS] = new JoinSuccessHandler(this, _readBuffer, _listenerList, _playerCache, _entityCache);
_handlers[(byte)RagonOperation.JOIN_FAILED] = new JoinFailedHandler(_listenerList);
_handlers[(byte)RagonOperation.LEAVE_ROOM] = new LeaveRoomHandler(this, _listenerList, _entityCache);
_handlers[(byte)RagonOperation.OWNERSHIP_ROOM_CHANGED] = new OwnershipRoomHandler(_listenerList, _playerCache, _entityCache);
_handlers[(byte)RagonOperation.OWNERSHIP_ENTITY_CHANGED] = new EntityOwnershipHandler(_listenerList, _playerCache, _entityCache);
_handlers[(byte)RagonOperation.PLAYER_JOINED] = new PlayerJoinHandler(_playerCache, _listenerList);
_handlers[(byte)RagonOperation.PLAYER_LEAVED] = new PlayerLeftHandler(_entityCache, _playerCache, _listenerList);
_handlers[(byte)RagonOperation.LOAD_SCENE] = new SceneLoadHandler(this, _listenerList);
_handlers[(byte)RagonOperation.CREATE_ENTITY] = new EntityCreateHandler(this, _playerCache, _entityCache);
_handlers = new IHandler[byte.MaxValue];
_handlers[(byte)RagonOperation.AUTHORIZED_SUCCESS] = new AuthorizeSuccessHandler(this, listeners);
_handlers[(byte)RagonOperation.AUTHORIZED_FAILED] = new AuthorizeFailedHandler(listeners);
_handlers[(byte)RagonOperation.JOIN_SUCCESS] = new JoinSuccessHandler(this, listeners, _playerCache, _entityCache);
_handlers[(byte)RagonOperation.JOIN_FAILED] = new JoinFailedHandler(listeners);
_handlers[(byte)RagonOperation.LEAVE_ROOM] = new LeaveRoomHandler(this, listeners, _entityCache);
_handlers[(byte)RagonOperation.OWNERSHIP_ROOM_CHANGED] = new OwnershipRoomHandler(listeners, _playerCache, _entityCache);
_handlers[(byte)RagonOperation.OWNERSHIP_ENTITY_CHANGED] = new EntityOwnershipHandler(listeners, _playerCache, _entityCache);
_handlers[(byte)RagonOperation.PLAYER_JOINED] = new PlayerJoinHandler(_playerCache, listeners);
_handlers[(byte)RagonOperation.PLAYER_LEAVED] = new PlayerLeftHandler(_entityCache, _playerCache, listeners);
_handlers[(byte)RagonOperation.LOAD_SCENE] = new SceneLoadHandler(this, listeners);
_handlers[(byte)RagonOperation.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(this, _playerCache, _entityCache);
_handlers[(byte)RagonOperation.SNAPSHOT] = new SnapshotHandler(this, _listenerList, _entityCache, _playerCache);
_handlers[(byte)RagonOperation.REPLICATE_ENTITY_EVENT] = new EntityEventHandler(_playerCache, _entityCache);
_handlers[(byte)RagonOperation.REPLICATE_ROOM_EVENT] = new RoomEventHandler(this, _playerCache);
_handlers[(byte)RagonOperation.SNAPSHOT] = new SnapshotHandler(this, listeners, _entityCache, _playerCache, _entityListener);
_handlers[(byte)RagonOperation.TIMESTAMP_SYNCHRONIZATION] = new TimestampHandler(this);
_handlers[(byte)RagonOperation.REPLICATE_RAW_DATA] = new RoomDataHandler(_playerCache, listeners);
var protocolRaw = RagonVersion.Parse(protocol);
_connection.Connect(address, port, protocolRaw);
@@ -138,44 +143,54 @@ namespace Ragon.Client
_replicationTime += dt;
if (_replicationTime >= _replicationRate)
{
_entityCache.WriteState(_readBuffer);
_replicationTime = 0;
_entityCache.WriteState(_writeBuffer);
SendTimestamp();
}
_stats.Update(_connection.BytesSent, _connection.BytesReceived, _connection.Ping, dt);
}
listeners.Update();
_connection.Update();
}
public void Dispose()
{
_status = RagonStatus.DISCONNECTED;
_connection.Disconnect();
if (_status != RagonStatus.DISCONNECTED)
{
_status = RagonStatus.DISCONNECTED;
_connection.Disconnect();
}
_connection.Dispose();
}
public void AddListener(IRagonListener listener) => _listenerList.Add(listener);
public void AddListener(IRagonAuthorizationListener listener) => _listenerList.Add(listener);
public void AddListener(IRagonConnectionListener listener) => _listenerList.Add(listener);
public void AddListener(IRagonFailedListener listener) => _listenerList.Add(listener);
public void AddListener(IRagonJoinListener listener) => _listenerList.Add(listener);
public void AddListener(IRagonLeftListener listener) => _listenerList.Add(listener);
public void AddListener(IRagonLevelListener listener) => _listenerList.Add(listener);
public void AddListener(IRagonOwnershipChangedListener listener) => _listenerList.Add(listener);
public void AddListener(IRagonPlayerJoinListener listener) => _listenerList.Add(listener);
public void AddListener(IRagonPlayerLeftListener listener) => _listenerList.Add(listener);
public void AddListener(IRagonListener listener) => listeners.Add(listener);
public void AddListener(IRagonAuthorizationListener listener) => listeners.Add(listener);
public void AddListener(IRagonConnectionListener listener) => listeners.Add(listener);
public void AddListener(IRagonFailedListener listener) => listeners.Add(listener);
public void AddListener(IRagonJoinListener listener) => listeners.Add(listener);
public void AddListener(IRagonLeftListener listener) => listeners.Add(listener);
public void AddListener(IRagonOwnershipChangedListener listener) => listeners.Add(listener);
public void AddListener(IRagonPlayerJoinListener listener) => listeners.Add(listener);
public void AddListener(IRagonPlayerLeftListener listener) => listeners.Add(listener);
public void AddListener(IRagonSceneListener listener) => listeners.Add(listener);
public void AddListener(IRagonSceneRequestListener listener) => listeners.Add(listener);
public void AddListener(IRagonDataListener listener) => listeners.Add(listener);
public void RemoveListener(IRagonListener listener) => _listenerList.Remove(listener);
public void RemoveListener(IRagonAuthorizationListener listener) => _listenerList.Remove(listener);
public void RemoveListener(IRagonConnectionListener listener) => _listenerList.Remove(listener);
public void RemoveListener(IRagonFailedListener listener) => _listenerList.Remove(listener);
public void RemoveListener(IRagonJoinListener listener) => _listenerList.Remove(listener);
public void RemoveListener(IRagonLeftListener listener) => _listenerList.Remove(listener);
public void RemoveListener(IRagonLevelListener listener) => _listenerList.Remove(listener);
public void RemoveListener(IRagonOwnershipChangedListener listener) => _listenerList.Remove(listener);
public void RemoveListener(IRagonPlayerJoinListener listener) => _listenerList.Remove(listener);
public void RemoveListener(IRagonPlayerLeftListener listener) => _listenerList.Remove(listener);
public void RemoveListener(IRagonListener listener) => listeners.Remove(listener);
public void RemoveListener(IRagonAuthorizationListener listener) => listeners.Remove(listener);
public void RemoveListener(IRagonConnectionListener listener) => listeners.Remove(listener);
public void RemoveListener(IRagonFailedListener listener) => listeners.Remove(listener);
public void RemoveListener(IRagonJoinListener listener) => listeners.Remove(listener);
public void RemoveListener(IRagonLeftListener listener) => listeners.Remove(listener);
public void RemoveListener(IRagonOwnershipChangedListener listener) => listeners.Remove(listener);
public void RemoveListener(IRagonPlayerJoinListener listener) => listeners.Remove(listener);
public void RemoveListener(IRagonPlayerLeftListener listener) => listeners.Remove(listener);
public void RemoveListener(IRagonSceneListener listener) => listeners.Remove(listener);
public void RemoveListener(IRagonSceneRequestListener listener) => listeners.Remove(listener);
public void RemoveListener(IRagonDataListener listener) => listeners.Remove(listener);
#endregion
@@ -183,19 +198,43 @@ namespace Ragon.Client
internal void AssignRoom(RagonRoom room)
{
_room?.Dispose();
_room = room;
_status = RagonStatus.ROOM;
}
internal void SetStatus(RagonStatus status)
{
_status = status;
}
internal void SetTimestamp(double time)
{
_serverTimestamp = time;
}
#endregion
#region PRIVATE
private void SendTimestamp()
{
var timestamp = RagonTime.CurrentTimestamp();
var value = new DoubleToUInt()
{
Double = timestamp,
};
_writeBuffer.Clear();
_writeBuffer.WriteOperation(RagonOperation.TIMESTAMP_SYNCHRONIZATION);
_writeBuffer.Write(value.Int0, 32);
_writeBuffer.Write(value.Int1, 32);
}
private void OnConnected()
{
RagonLog.Trace("Connected");
_listenerList.OnConnected();
listeners.OnConnected();
_status = RagonStatus.CONNECTED;
}
@@ -203,11 +242,11 @@ namespace Ragon.Client
{
RagonLog.Trace($"Disconnected: {reason}");
_listenerList.OnDisconnected(reason);
listeners.OnDisconnected(reason);
_status = RagonStatus.DISCONNECTED;
}
public void OnData(byte[] data)
private void OnData(byte[] data)
{
_readBuffer.Clear();
_readBuffer.FromArray(data);
+38 -32
View File
@@ -26,7 +26,6 @@ public sealed class RagonEntityCache
private readonly Dictionary<uint, RagonEntity> _sceneEntities = new();
private readonly RagonClient _client;
private readonly IRagonEntityListener _entityListener;
private readonly IRagonSceneCollector _sceneCollector;
private readonly RagonPlayerCache _playerCache;
@@ -35,12 +34,10 @@ public sealed class RagonEntityCache
public RagonEntityCache(
RagonClient client,
RagonPlayerCache playerCache,
IRagonEntityListener listener,
IRagonSceneCollector sceneCollector
)
{
_client = client;
_entityListener = listener;
_sceneCollector = sceneCollector;
_playerCache = playerCache;
}
@@ -50,7 +47,7 @@ public sealed class RagonEntityCache
return _entityMap.TryGetValue(id, out entity);
}
public void Create(RagonEntity entity, IRagonPayload? spawnPayload)
public void Create(RagonEntity entity, RagonPayload spawnPayload)
{
var attachId = (ushort)(_playerCache.Local.PeerId + _localEntitiesCounter++);
var buffer = _client.Buffer;
@@ -63,7 +60,7 @@ public sealed class RagonEntityCache
entity.State.WriteInfo(buffer);
spawnPayload?.Serialize(buffer);
spawnPayload?.Write(buffer);
_pendingEntities.Add(attachId, entity);
@@ -84,21 +81,23 @@ public sealed class RagonEntityCache
_client.Reliable.Send(sendData);
}
public void Destroy(RagonEntity entity, IRagonPayload? destroyPayload)
public void Destroy(RagonEntity entity, RagonPayload destroyPayload)
{
if (!entity.IsAttached)
if (!entity.IsAttached && !entity.HasAuthority)
{
RagonLog.Warn("Can't destroy object, he is not created");
RagonLog.Warn("Can't destroy object");
return;
}
entity.SetReplication(false);
var buffer = _client.Buffer;
buffer.Clear();
buffer.WriteOperation(RagonOperation.REMOVE_ENTITY);
buffer.WriteUShort(entity.Id);
destroyPayload?.Serialize(buffer);
destroyPayload?.Write(buffer);
var sendData = buffer.ToArray();
_client.Reliable.Send(sendData);
@@ -117,7 +116,7 @@ public sealed class RagonEntityCache
foreach (var ent in _entityList)
{
if (!ent.IsAttached ||
!ent.Replication ||
!ent.IsReplicated ||
!ent.PropertiesChanged) continue;
ent.Write(buffer);
@@ -162,7 +161,7 @@ public sealed class RagonEntityCache
internal void Cleanup()
{
var payload = new RagonPayload();
var payload = new RagonPayload(0);
foreach (var ent in _entityList)
ent.Detach(payload);
@@ -170,53 +169,60 @@ public sealed class RagonEntityCache
_entityList.Clear();
}
internal RagonEntity OnCreate(ushort attachId, ushort entityType, ushort sceneId, ushort entityId, bool hasAuthority)
internal RagonEntity TryGetEntity(ushort attachId, ushort entityType, ushort sceneId, ushort entityId, bool hasAuthority, out bool hasCreated)
{
if (sceneId > 0)
{
if (_sceneEntities.TryGetValue(sceneId, out var entity))
if (_sceneEntities.TryGetValue(sceneId, out var sceneEntity))
{
_entityMap.Add(entityId, entity);
_entityMap.Add(entityId, sceneEntity);
if (hasAuthority)
_entityList.Add(entity);
_entityList.Add(sceneEntity);
return entity;
hasCreated = false;
return sceneEntity;
}
}
if (_pendingEntities.Remove(attachId, out var existsEntity))
if (_pendingEntities.TryGetValue(attachId, out var pendingEntity))
{
_entityMap.Add(entityId, existsEntity);
_pendingEntities.Remove(attachId);
_entityMap.Add(entityId, pendingEntity);
if (hasAuthority)
_entityList.Add(existsEntity);
_entityList.Add(pendingEntity);
return existsEntity;
hasCreated = false;
return pendingEntity;
}
else
{
var entity = new RagonEntity(entityType, sceneId);
_entityMap.Add(entityId, entity);
if (hasAuthority)
_entityList.Add(entity);
var entity = new RagonEntity(entityType, sceneId);
_entityListener.OnEntityCreated(entity);
_entityMap.Add(entityId, entity);
return entity;
}
if (hasAuthority)
_entityList.Add(entity);
hasCreated = true;
return entity;
}
internal void OnDestroy(ushort entityId, RagonPayload payload)
{
if (_entityMap.Remove(entityId, out var ragonEntity))
if (_entityMap.TryGetValue(entityId, out var entity))
{
_entityList.Remove(ragonEntity);
ragonEntity.Detach(payload);
_entityMap.Remove(entityId);
_entityList.Remove(entity);
entity.Detach(payload);
entity.Dispose();
}
}
+80 -34
View File
@@ -26,10 +26,13 @@ namespace Ragon.Client
private readonly List<IRagonFailedListener> _failedListeners = new();
private readonly List<IRagonJoinListener> _joinListeners = new();
private readonly List<IRagonLeftListener> _leftListeners = new();
private readonly List<IRagonLevelListener> _levelListeners = 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();
private readonly List<IRagonDataListener> _dataListeners = new();
private readonly List<Action> _delayedActions = new();
public RagonListenerList(RagonClient client)
{
@@ -43,7 +46,7 @@ namespace Ragon.Client
_failedListeners.Add(listener);
_joinListeners.Add(listener);
_leftListeners.Add(listener);
_levelListeners.Add(listener);
_sceneListeners.Add(listener);
_ownershipChangedListeners.Add(listener);
_playerJoinListeners.Add(listener);
_playerLeftListeners.Add(listener);
@@ -51,15 +54,31 @@ namespace Ragon.Client
public void Remove(IRagonListener listener)
{
_authorizationListeners.Remove(listener);
_connectionListeners.Remove(listener);
_failedListeners.Remove(listener);
_joinListeners.Remove(listener);
_leftListeners.Remove(listener);
_levelListeners.Remove(listener);
_ownershipChangedListeners.Remove(listener);
_playerJoinListeners.Remove(listener);
_playerLeftListeners.Remove(listener);
_delayedActions.Add(() =>
{
_authorizationListeners.Remove(listener);
_connectionListeners.Remove(listener);
_failedListeners.Remove(listener);
_joinListeners.Remove(listener);
_leftListeners.Remove(listener);
_sceneListeners.Remove(listener);
_ownershipChangedListeners.Remove(listener);
_playerJoinListeners.Remove(listener);
_playerLeftListeners.Remove(listener);
});
}
public void Update()
{
foreach (var action in _delayedActions)
action.Invoke();
_delayedActions.Clear();
}
public void Add(IRagonDataListener dataListener)
{
_dataListeners.Add(dataListener);
}
public void Add(IRagonAuthorizationListener listener)
@@ -67,6 +86,11 @@ namespace Ragon.Client
_authorizationListeners.Add(listener);
}
public void Add(IRagonSceneRequestListener listener)
{
_sceneRequestListeners.Add(listener);
}
public void Add(IRagonConnectionListener listener)
{
_connectionListeners.Add(listener);
@@ -82,74 +106,84 @@ namespace Ragon.Client
_joinListeners.Add(listener);
}
public void Add(IRagonLeftListener listener)
public void Add(IRagonLeftListener listener)
{
_leftListeners.Add(listener);
}
public void Add(IRagonLevelListener listener)
public void Add(IRagonSceneListener listener)
{
_levelListeners.Add(listener);
_sceneListeners.Add(listener);
}
public void Add(IRagonOwnershipChangedListener listener)
public void Add(IRagonOwnershipChangedListener listener)
{
_ownershipChangedListeners.Add(listener);
}
public void Add(IRagonPlayerJoinListener listener)
public void Add(IRagonPlayerJoinListener listener)
{
_playerJoinListeners.Add(listener);
}
public void Add(IRagonPlayerLeftListener listener)
public void Add(IRagonPlayerLeftListener listener)
{
_playerLeftListeners.Add(listener);
}
public void Remove(IRagonDataListener listener)
{
_delayedActions.Add(() => _dataListeners.Remove(listener));
}
public void Remove(IRagonSceneRequestListener listener)
{
_delayedActions.Add(() => _sceneRequestListeners.Remove(listener));
}
public void Remove(IRagonAuthorizationListener listener)
{
_authorizationListeners.Remove(listener);
_delayedActions.Add(() => _authorizationListeners.Remove(listener));
}
public void Remove(IRagonConnectionListener listener)
{
_connectionListeners.Remove(listener);
_delayedActions.Add(() => _connectionListeners.Remove(listener));
}
public void Remove(IRagonFailedListener listener)
{
_failedListeners.Remove(listener);
_delayedActions.Add(() => _failedListeners.Remove(listener));
}
public void Remove(IRagonJoinListener listener)
{
_joinListeners.Remove(listener);
_delayedActions.Add(() => _joinListeners.Remove(listener));
}
public void Remove(IRagonLeftListener listener)
public void Remove(IRagonLeftListener listener)
{
_leftListeners.Remove(listener);
_delayedActions.Add(() => _leftListeners.Remove(listener));
}
public void Remove(IRagonLevelListener listener)
public void Remove(IRagonSceneListener listener)
{
_levelListeners.Remove(listener);
_delayedActions.Add(() => _sceneListeners.Remove(listener));
}
public void Remove(IRagonOwnershipChangedListener listener)
public void Remove(IRagonOwnershipChangedListener listener)
{
_ownershipChangedListeners.Remove(listener);
_delayedActions.Add(() => _ownershipChangedListeners.Remove(listener));
}
public void Remove(IRagonPlayerJoinListener listener)
public void Remove(IRagonPlayerJoinListener listener)
{
_playerJoinListeners.Remove(listener);
_delayedActions.Add(() => _playerJoinListeners.Remove(listener));
}
public void Remove(IRagonPlayerLeftListener listener)
public void Remove(IRagonPlayerLeftListener listener)
{
_playerLeftListeners.Remove(listener);
_delayedActions.Add(() => _playerLeftListeners.Remove(listener));
}
public void OnAuthorizationSuccess(string playerId, string playerName, string payload)
@@ -194,10 +228,16 @@ namespace Ragon.Client
listener.OnPlayerJoined(_client, player);
}
public void OnLevel(string sceneName)
public void OnSceneLoaded()
{
foreach (var listener in _levelListeners)
listener.OnLevel(_client, sceneName);
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()
@@ -217,5 +257,11 @@ namespace Ragon.Client
foreach (var listener in _connectionListeners)
listener.OnDisconnected(_client, disconnect);
}
public void OnData(RagonPlayer player, byte[] data)
{
foreach (var listener in _dataListeners)
listener.OnData(player, data);
}
}
}
+2 -1
View File
@@ -64,9 +64,10 @@ public sealed class RagonPlayerCache
public void RemovePlayer(string playerId)
{
if (_playersById.Remove(playerId, out var player))
if (_playersById.TryGetValue(playerId, out var player))
{
_players.Remove(player);
_playersById.Remove(playerId);
_playersByConnection.Remove(player.PeerId);
}
}
+87 -4
View File
@@ -14,10 +14,14 @@
* limitations under the License.
*/
using Ragon.Protocol;
namespace Ragon.Client
{
public class RagonRoom
public class RagonRoom: IDisposable
{
private delegate void OnEventDelegate(RagonPlayer player, RagonBuffer serializer);
private RagonClient _client;
private RagonScene _scene;
private RagonEntityCache _entityCache;
@@ -27,11 +31,16 @@ namespace Ragon.Client
public string Id => _information.RoomId;
public int MinPlayers => _information.Min;
public int MaxPlayers => _information.Max;
public string Scene => _scene.Name;
public IReadOnlyList<RagonPlayer> Players => _playerCache.Players;
public RagonPlayer Local => _playerCache.Local;
public RagonPlayer Owner => _playerCache.Owner;
private readonly Dictionary<int, OnEventDelegate> _events = new Dictionary<int, OnEventDelegate>();
private readonly Dictionary<int, List<Action<RagonPlayer, IRagonEvent>>> _localListeners = new Dictionary<int, List<Action<RagonPlayer, IRagonEvent>>>();
private readonly Dictionary<int, List<Action<RagonPlayer, IRagonEvent>>> _listeners = new Dictionary<int, List<Action<RagonPlayer, IRagonEvent>>>();
public RagonRoom(RagonClient client,
RagonEntityCache entityCache,
RagonPlayerCache playerCache,
@@ -51,14 +60,88 @@ namespace Ragon.Client
_playerCache.Cleanup();
}
public void LoadScene(string map) => _scene.Load(map);
internal void Update(string sceneName)
{
_scene.Update(sceneName);
}
internal void Event(ushort eventCode, RagonPlayer caller, RagonBuffer buffer)
{
if (_events.TryGetValue(eventCode, out var evnt))
evnt?.Invoke(caller, buffer);
else
RagonLog.Warn($"Handler event on entity {Id} with eventCode {eventCode} not defined");
}
public Action<RagonPlayer, IRagonEvent> OnEvent<TEvent>(Action<RagonPlayer, TEvent> callback) where TEvent : IRagonEvent, new()
{
var t = new TEvent();
var eventCode = _client.Event.GetEventCode(t);
var action = (RagonPlayer player, IRagonEvent eventData) => callback.Invoke(player, (TEvent)eventData);
if (!_listeners.TryGetValue(eventCode, out var callbacks))
{
callbacks = new List<Action<RagonPlayer, IRagonEvent>>();
_listeners.Add(eventCode, callbacks);
}
if (!_localListeners.TryGetValue(eventCode, out var localCallbacks))
{
localCallbacks = new List<Action<RagonPlayer, IRagonEvent>>();
_localListeners.Add(eventCode, localCallbacks);
}
callbacks.Add(action);
localCallbacks.Add(action);
if (!_events.ContainsKey(eventCode))
{
_events.Add(eventCode, (player, serializer) =>
{
t.Deserialize(serializer);
foreach (var callbackListener in callbacks)
callbackListener.Invoke(player, t);
});
}
return action;
}
public void OffEvent<TEvent>(Action<RagonPlayer, IRagonEvent> callback) where TEvent : IRagonEvent, new()
{
var t = new TEvent();
var eventCode = _client.Event.GetEventCode(t);
if (_listeners.TryGetValue(eventCode, out var callbacks))
callbacks.Remove(callback);
if (_localListeners.TryGetValue(eventCode, out var localCallbacks))
localCallbacks.Remove(callback);
}
public void LoadScene(string sceneName) => _scene.Load(sceneName);
public void SceneLoaded() => _scene.SceneLoaded();
public void ReplicateEvent<TEvent>(TEvent evnt, RagonTarget target, RagonReplicationMode mode) where TEvent : IRagonEvent, new() => _scene.ReplicateEvent(evnt, target, mode);
public void ReplicateEvent<TEvent>(TEvent evnt, RagonPlayer target, RagonReplicationMode mode) where TEvent : IRagonEvent, new() => _scene.ReplicateEvent(evnt, target, mode);
public void ReplicateData(byte[] data, bool reliable = false) => _scene.ReplicateData(data, reliable);
public void CreateEntity(RagonEntity entity) => CreateEntity(entity, null);
public void CreateEntity(RagonEntity entity, IRagonPayload? payload) => _entityCache.Create(entity, payload);
public void CreateEntity(RagonEntity entity, RagonPayload payload) => _entityCache.Create(entity, payload);
public void TransferEntity(RagonEntity entity, RagonPlayer player) => _entityCache.Transfer(entity, player);
public void DestroyEntity(RagonEntity entityId) => DestroyEntity(entityId, null);
public void DestroyEntity(RagonEntity entityId, IRagonPayload? payload) => _entityCache.Destroy(entityId, payload);
public void DestroyEntity(RagonEntity entityId, RagonPayload payload) => _entityCache.Destroy(entityId, payload);
public void Dispose()
{
Cleanup();
_events.Clear();
_listeners.Clear();
_localListeners.Clear();
}
}
}
+59 -3
View File
@@ -20,24 +20,33 @@ namespace Ragon.Client;
public class RagonScene
{
public string Name { get; private set; }
private readonly RagonClient _client;
private readonly RagonEntityCache _entityCache;
private readonly RagonPlayerCache _playerCache;
public RagonScene(RagonClient client, RagonPlayerCache playerCache, RagonEntityCache entityCache)
public RagonScene(RagonClient client, RagonPlayerCache playerCache, RagonEntityCache entityCache, string sceneName)
{
Name = sceneName;
_client = client;
_playerCache = playerCache;
_entityCache = entityCache;
}
internal void Load(string map)
internal void Update(string scene)
{
Name = scene;
}
internal void Load(string sceneName)
{
var buffer = _client.Buffer;
buffer.Clear();
buffer.WriteOperation(RagonOperation.LOAD_SCENE);
buffer.WriteString(map);
buffer.WriteString(sceneName);
var sendData = buffer.ToArray();
_client.Reliable.Send(sendData);
@@ -58,4 +67,51 @@ public class RagonScene
var sendData = buffer.ToArray();
_client.Reliable.Send(sendData);
}
internal void ReplicateEvent<TEvent>(TEvent evnt, RagonTarget 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)target);
var sendData = buffer.ToArray();
_client.Reliable.Send(sendData);
}
internal 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);
}
}
+6 -6
View File
@@ -29,9 +29,9 @@ namespace Ragon.Client
_buffer = buffer;
}
public void CreateOrJoin(string map, int minPlayers, int maxPlayers)
public void CreateOrJoin(string sceneName, int minPlayers, int maxPlayers)
{
var parameters = new RagonRoomParameters() {Map = map, Min = minPlayers, Max = maxPlayers};
var parameters = new RagonRoomParameters() {Scene = sceneName, Min = minPlayers, Max = maxPlayers};
CreateOrJoin(parameters);
}
@@ -46,14 +46,14 @@ namespace Ragon.Client
_client.Reliable.Send(sendData);
}
public void Create(string map, int minPlayers, int maxPlayers)
public void Create(string sceneName, int minPlayers, int maxPlayers)
{
Create(null, new RagonRoomParameters() {Map = map, Min = minPlayers, Max = maxPlayers});
Create(null, new RagonRoomParameters() {Scene = sceneName, Min = minPlayers, Max = maxPlayers});
}
public void Create(string roomId, string map, int minPlayers, int maxPlayers)
public void Create(string roomId, string sceneNa, int minPlayers, int maxPlayers)
{
Create(roomId, new RagonRoomParameters() {Map = map, Min = minPlayers, Max = maxPlayers});
Create(roomId, new RagonRoomParameters() {Scene = sceneNa, Min = minPlayers, Max = maxPlayers});
}
public void Create(string roomId, RagonRoomParameters parameters)
+1 -2
View File
@@ -6,14 +6,13 @@
<LangVersion>8</LangVersion>
<RootNamespace>Ragon.Common</RootNamespace>
<GeneratePackageOnBuild>true</GeneratePackageOnBuild>
<Version>1.2.4-rc</Version>
<Title>Ragon.Protocol</Title>
<Copyright>Eduard Kargin</Copyright>
<PackageProjectUrl>https://ragon-server.com</PackageProjectUrl>
<RepositoryUrl>https://github.com/edmand46/Ragon</RepositoryUrl>
<RepositoryType>Source</RepositoryType>
<PackageLicenseExpression>Apache-2.0</PackageLicenseExpression>
<TargetFramework>netstandard2.1</TargetFramework>
<TargetFramework>netstandard2.0</TargetFramework>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)' == 'Debug' ">
+39 -12
View File
@@ -58,7 +58,6 @@
using System;
using System.Diagnostics;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Text;
@@ -69,8 +68,10 @@ namespace Ragon.Protocol
private int _read;
private int _write;
private uint[] _buckets;
private byte[] _rawData;
private readonly UTF8Encoding _utf8Encoding = new UTF8Encoding(false, true);
public byte[] RawData => _rawData;
public int ReadOffset => _read;
public int WriteOffset => _write;
public int Length => ((_write - 1) >> 3) + 1;
@@ -79,6 +80,7 @@ namespace Ragon.Protocol
public RagonBuffer(int capacity = 128)
{
_buckets = new uint[capacity];
_rawData = Array.Empty<byte>();
_read = 0;
_write = 0;
}
@@ -234,9 +236,6 @@ namespace Ragon.Protocol
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void Write(uint value, int numBits = 16)
{
Debug.Assert(!(numBits < 0));
Debug.Assert(!(numBits > 32));
var currentBucketIndex = _write >> 5;
var used = _write & 0x0000001F;
var mask = (1UL << used) - 1;
@@ -292,7 +291,7 @@ namespace Ragon.Protocol
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void ReadSpan(ref Span<uint> data, int size)
public void ReadArray(uint[] data, int size)
{
var used = _read & 0x0000001F;
var index = _read >> 5;
@@ -321,8 +320,9 @@ namespace Ragon.Protocol
_read += size;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void WriteSpan(ref ReadOnlySpan<uint> data, int size)
public void WriteArray(uint[] data, int size)
{
var used = _write & 0x0000001F;
var index = _write >> 5;
@@ -333,7 +333,7 @@ namespace Ragon.Protocol
for (var i = 0; i < limit; i += 1)
{
var prepared = (ulong) data[i] << used;
var prepared = (ulong)data[i] << used;
var mask = (1UL << used) - 1;
var scratch = _buckets[index] & mask;
var result = scratch | prepared;
@@ -354,17 +354,15 @@ namespace Ragon.Protocol
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void FromBuffer(RagonBuffer buffer, int size)
public void CopyFrom(RagonBuffer buffer, int size)
{
ReadOnlySpan<uint> data = buffer._buckets.AsSpan();
WriteSpan(ref data, size);
WriteArray(buffer._buckets, size);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void ToBuffer(RagonBuffer buffer, int size)
{
var data = buffer._buckets.AsSpan();
ReadSpan(ref data, size);
ReadArray(buffer._buckets, size);
}
public void FromArray(byte[] data)
@@ -399,10 +397,13 @@ namespace Ragon.Protocol
_write = ((length - 1) * 8) + positionInByte;
_read = 0;
_rawData = data;
}
public byte[] ToArray()
{
Write(1, 1);
var data = new byte[Length];
int bucketsCount = (_write >> 5) + 1;
int length = data.Length;
@@ -428,6 +429,32 @@ namespace Ragon.Protocol
return data;
}
public void ToArray(byte[] outData)
{
Write(1, 1);
var bucketsCount = (_write >> 5) + 1;
var length = Length;
for (int i = 0; i < bucketsCount; i++)
{
var dataIdx = i * 4;
var bucket = _buckets[i];
if (dataIdx < length)
outData[dataIdx] = (byte)bucket;
if (dataIdx + 1 < length)
outData[dataIdx + 1] = (byte)(bucket >> 8);
if (dataIdx + 2 < length)
outData[dataIdx + 2] = (byte)(bucket >> 16);
if (dataIdx + 3 < length)
outData[dataIdx + 3] = (byte)(bucket >> 24);
}
}
private void Resize(int capacity)
{
var buckets = new uint[_buckets.Length * 2 + capacity];
+25 -22
View File
@@ -19,27 +19,30 @@ namespace Ragon.Protocol
{
public enum RagonOperation: byte
{
AUTHORIZE,
AUTHORIZED_SUCCESS,
AUTHORIZED_FAILED,
JOIN_OR_CREATE_ROOM,
CREATE_ROOM,
JOIN_ROOM,
LEAVE_ROOM,
OWNERSHIP_ENTITY_CHANGED,
OWNERSHIP_ROOM_CHANGED,
JOIN_SUCCESS,
JOIN_FAILED,
LOAD_SCENE,
SCENE_LOADED,
PLAYER_JOINED,
PLAYER_LEAVED,
CREATE_ENTITY,
REMOVE_ENTITY,
SNAPSHOT,
REPLICATE_ENTITY_STATE,
REPLICATE_ENTITY_EVENT,
TRANSFER_ROOM_OWNERSHIP,
TRANSFER_ENTITY_OWNERSHIP,
AUTHORIZE = 1,
AUTHORIZED_SUCCESS = 2,
AUTHORIZED_FAILED = 3,
JOIN_OR_CREATE_ROOM = 4,
CREATE_ROOM = 5,
JOIN_ROOM = 6,
LEAVE_ROOM = 7,
OWNERSHIP_ENTITY_CHANGED = 8,
OWNERSHIP_ROOM_CHANGED= 9,
JOIN_SUCCESS = 10,
JOIN_FAILED = 11,
LOAD_SCENE = 12,
SCENE_LOADED = 13,
PLAYER_JOINED = 14,
PLAYER_LEAVED = 15,
CREATE_ENTITY = 16,
REMOVE_ENTITY = 17,
SNAPSHOT = 18,
REPLICATE_ENTITY_STATE = 19,
REPLICATE_ENTITY_EVENT = 20,
REPLICATE_RAW_DATA = 21,
REPLICATE_ROOM_EVENT = 22,
TRANSFER_ROOM_OWNERSHIP = 23,
TRANSFER_ENTITY_OWNERSHIP = 24,
TIMESTAMP_SYNCHRONIZATION = 25,
}
}
@@ -19,20 +19,20 @@ namespace Ragon.Protocol
{
public class RagonRoomParameters: IRagonSerializable
{
public string Map { get; set; }
public string Scene { get; set; }
public int Min { get; set; }
public int Max { get; set; }
public void Serialize(RagonBuffer buffer)
{
buffer.WriteString(Map);
buffer.WriteString(Scene);
buffer.WriteInt(Min, 1, 32);
buffer.WriteInt(Max, 1, 32);
}
public void Deserialize(RagonBuffer buffer)
{
Map = buffer.ReadString();
Scene = buffer.ReadString();
Min = buffer.ReadInt(1, 32);
Max = buffer.ReadInt(1, 32);
}
+25
View File
@@ -16,9 +16,34 @@
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
namespace Ragon.Protocol
{
[StructLayout(LayoutKind.Explicit)]
public struct DoubleToUInt
{
[FieldOffset(0)]
public double Double;
[FieldOffset(0)]
public uint Int0;
[FieldOffset(4)]
public uint Int1;
}
public static class RagonTime {
public static double CurrentTimestamp()
{
var currentTime = System.DateTime.UtcNow.ToUniversalTime().Subtract(
new System.DateTime(1970, 1, 1, 0, 0, 0, System.DateTimeKind.Utc)
).TotalMilliseconds;
return currentTime;
}
}
public static class DeBruijn
{
private static readonly int[] _lookup = new int[32]
+6 -6
View File
@@ -16,12 +16,12 @@
namespace Ragon.Relay
{
class Program
class Program
{
static void Main(string[] args)
{
static void Main(string[] args)
{
var relay = new Relay();
relay.Start();
}
var relay = new Relay();
relay.Start();
}
}
}
+1 -1
View File
@@ -23,7 +23,7 @@
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\Ragon.Server.ENet\Ragon.Server.ENet.csproj" />
<ProjectReference Include="..\Ragon.Server.ENetServer\Ragon.Server.ENetServer.csproj" />
<ProjectReference Include="..\Ragon.Server.WebSocketServer\Ragon.Server.WebSocketServer.csproj" />
<ProjectReference Include="..\Ragon.Server\Ragon.Server.csproj" />
</ItemGroup>
+1 -1
View File
@@ -16,7 +16,7 @@
using NLog;
using Ragon.Server;
using Ragon.Server.ENet;
using Ragon.Server.ENetServer;
using Ragon.Server.WebSocketServer;
using Ragon.Server.IO;
using Ragon.Server.Plugin;
@@ -17,7 +17,7 @@
using ENet;
using Ragon.Server.IO;
namespace Ragon.Server.ENet;
namespace Ragon.Server.ENetServer;
public sealed class ENetConnection: INetworkConnection
{
@@ -31,8 +31,8 @@ public sealed class ENetConnection: INetworkConnection
_peer = peer;
Id = (ushort) peer.ID;
Reliable = new ENetReliableChannel(peer, 0);
Unreliable = new ENetUnreliableChannel(peer, 1);
Reliable = new ENetReliableChannel(peer, NetworkChannel.RELIABLE);
Unreliable = new ENetUnreliableChannel(peer, NetworkChannel.UNRELIABLE);
}
public void Close()
@@ -14,20 +14,24 @@
* limitations under the License.
*/
using System.Net;
using ENet;
using Ragon.Protocol;
using Ragon.Server.IO;
namespace Ragon.Server.ENet;
namespace Ragon.Server.ENetServer;
public sealed class ENetReliableChannel: INetworkChannel
{
private Peer _peer;
private byte _channelId;
private byte[] _data;
public ENetReliableChannel(Peer peer, int channelId)
public ENetReliableChannel(Peer peer, NetworkChannel channel)
{
_peer = peer;
_channelId = (byte) channelId;
_data = new byte[1500];
_channelId = (byte) channel;
}
public void Send(byte[] data)
@@ -37,4 +41,14 @@ public sealed class ENetReliableChannel: INetworkChannel
_peer.Send(_channelId, ref newPacket);
}
public void Send(RagonBuffer buffer)
{
buffer.ToArray(_data);
var newPacket = new Packet();
newPacket.Create(_data, buffer.Length, PacketFlags.Reliable);
_peer.Send(_channelId, ref newPacket);
}
}
@@ -19,27 +19,20 @@ using NLog;
using Ragon.Protocol;
using Ragon.Server.IO;
namespace Ragon.Server.ENet
namespace Ragon.Server.ENetServer
{
public sealed class ENetServer: INetworkServer
public sealed class ENetServer : INetworkServer
{
public Executor Executor => _executor;
private readonly Host _host;
private readonly Host _host = new();
private readonly ILogger _logger = LogManager.GetCurrentClassLogger();
private ENetConnection[] _connections;
private ENetConnection[] _connections = Array.Empty<ENetConnection>();
private INetworkListener _listener;
private uint _protocol;
private Event _event;
private Executor _executor;
public ENetServer()
{
_host = new Host();
_executor = new Executor();
_connections = Array.Empty<ENetConnection>();
}
private ENet.Event _event;
private Executor _executor = new();
public void Start(INetworkListener listener, NetworkConfiguration configuration)
{
@@ -52,7 +45,7 @@ namespace Ragon.Server.ENet
var address = new Address
{
Port = (ushort) configuration.Port,
Port = (ushort)configuration.Port,
};
_host.Create(address, _connections.Length, 2, 0, 0, 1024 * 1024);
@@ -90,6 +83,7 @@ namespace Ragon.Server.ENet
_event.Peer.DisconnectNow(0);
break;
}
var connection = new ENetConnection(_event.Peer);
_connections[_event.Peer.ID] = connection;
@@ -110,20 +104,30 @@ namespace Ragon.Server.ENet
}
case EventType.Receive:
{
var peerId = (ushort) _event.Peer.ID;
var peerId = (ushort)_event.Peer.ID;
var connection = _connections[peerId];
var dataRaw = new byte[_event.Packet.Length];
_event.Packet.CopyTo(dataRaw);
_event.Packet.Dispose();
_listener.OnData(connection, dataRaw);
_listener.OnData(connection, (NetworkChannel)_event.ChannelID, dataRaw);
break;
}
}
}
}
public void Broadcast(byte[] data, NetworkChannel channel)
{
var packet = new Packet();
var flag = channel == NetworkChannel.RELIABLE? PacketFlags.Reliable: PacketFlags.None;
packet.Create(data, flag);
_host.Broadcast((byte)channel, ref packet);
}
public void Stop()
{
_host?.Dispose();
@@ -15,19 +15,21 @@
*/
using ENet;
using Ragon.Protocol;
using Ragon.Server.IO;
namespace Ragon.Server.ENet;
namespace Ragon.Server.ENetServer;
public sealed class ENetUnreliableChannel: INetworkChannel
{
private Peer _peer;
private byte _channelId;
private byte[] _data;
public ENetUnreliableChannel(Peer peer, int channelId)
public ENetUnreliableChannel(Peer peer, NetworkChannel channel)
{
_peer = peer;
_channelId = (byte) channelId;
_channelId = (byte) channel;
}
public void Send(byte[] data)
@@ -37,4 +39,14 @@ public sealed class ENetUnreliableChannel: INetworkChannel
_peer.Send(_channelId, ref newPacket);
}
public void Send(RagonBuffer buffer)
{
buffer.ToArray(_data);
var newPacket = new Packet();
newPacket.Create(_data, buffer.Length, PacketFlags.None);
_peer.Send(_channelId, ref newPacket);
}
}
@@ -15,6 +15,7 @@
*/
using System.Net.WebSockets;
using Ragon.Protocol;
using Ragon.Server.IO;
namespace Ragon.Server.WebSocketServer;
@@ -35,9 +36,17 @@ public class WebSocketReliableChannel : INetworkChannel
_queue.Enqueue(data);
}
public void Send(RagonBuffer buffer)
{
var sendData = buffer.ToArray();
_queue.Enqueue(sendData);
}
public async Task Flush()
{
while (_queue.TryDequeue(out var sendData) && _socket.State == WebSocketState.Open)
{
await _socket.SendAsync(sendData, WebSocketMessageType.Binary, WebSocketMessageFlags.EndOfMessage, CancellationToken.None);
}
}
}
@@ -47,22 +47,32 @@ public class WebSocketServer : INetworkServer
{
while (!cancellationToken.IsCancellationRequested)
{
var context = await _httpListener.GetContextAsync();
if (!context.Request.IsWebSocketRequest)
WebSocketConnection connection = null!;
try
{
context.Response.StatusCode = 200;
context.Response.ContentLength64 = 0;
context.Response.Close();
continue;
var context = await _httpListener.GetContextAsync();
if (!context.Request.IsWebSocketRequest)
{
context.Response.StatusCode = 200;
context.Response.ContentLength64 = 0;
context.Response.Close();
continue;
}
var webSocketContext = await context.AcceptWebSocketAsync(null);
var webSocket = webSocketContext.WebSocket;
var peerId = _sequencer.Pop();
connection = new WebSocketConnection(webSocket, peerId);
}
catch (Exception ex)
{
_logger.Warn(ex);
continue;
}
var webSocketContext = await context.AcceptWebSocketAsync(null);
var webSocket = webSocketContext.WebSocket;
_connections[connection.Id] = connection;
var peerId = _sequencer.Pop();
var connection = new WebSocketConnection(webSocket, peerId);
_connections[peerId] = connection;
StartListen(connection, cancellationToken);
}
}
@@ -75,6 +85,7 @@ public class WebSocketServer : INetworkServer
var webSocket = connection.Socket;
var bytes = new byte[2048];
var buffer = new Memory<byte>(bytes);
while (
webSocket.State == WebSocketState.Open ||
!cancellationToken.IsCancellationRequested)
@@ -82,9 +93,11 @@ public class WebSocketServer : INetworkServer
try
{
var result = await webSocket.ReceiveAsync(buffer, cancellationToken);
var dataRaw = buffer.Slice(0, result.Count);
if (dataRaw.Length > 0)
_networkListener.OnData(connection, dataRaw.ToArray());
if (result.Count > 0)
{
var payload = buffer.Slice(0, result.Count);
_networkListener.OnData(connection, NetworkChannel.RELIABLE, payload.ToArray());
}
}
catch (Exception ex)
{
@@ -94,6 +107,7 @@ public class WebSocketServer : INetworkServer
_sequencer.Push(connection.Id);
_activeConnections.Remove(connection);
_networkListener.OnDisconnected(connection);
}
@@ -102,6 +116,12 @@ public class WebSocketServer : INetworkServer
Flush();
}
public void Broadcast(byte[] data, NetworkChannel channel)
{
foreach (var activeConnection in _activeConnections)
activeConnection.Reliable.Send(data);
}
public async void Flush()
{
foreach (var conn in _activeConnections)
+2 -1
View File
@@ -5,7 +5,7 @@
<Nullable>enable</Nullable>
<RootNamespace>Ragon.Core</RootNamespace>
<GeneratePackageOnBuild>true</GeneratePackageOnBuild>
<Version>1.2.4-rc</Version>
<Version>1.3.1</Version>
<Title>Ragon.Server</Title>
<Copyright>Eduard Kargin</Copyright>
<PackageProjectUrl>https://ragon-server.com</PackageProjectUrl>
@@ -25,4 +25,5 @@
<ProjectReference Include="..\Ragon.Protocol\Ragon.Protocol.csproj" />
</ItemGroup>
</Project>
+16 -12
View File
@@ -16,6 +16,7 @@
using Ragon.Protocol;
using Ragon.Server.Event;
using Ragon.Server.Room;
namespace Ragon.Server.Entity;
@@ -117,30 +118,37 @@ public class RagonEntity : IRagonEntity
{
buffer.WriteUShort(Type);
buffer.WriteUShort(Id);
if (StaticId != 0)
buffer.WriteUShort(StaticId);
buffer.WriteUShort(Owner.Connection.Id);
buffer.WriteUShort(Owner.Connection.Id);
buffer.WriteUShort(Payload.Size);
Payload.Write(buffer);
_state.Snapshot(buffer);
}
public void ReplicateEvent(
RagonRoomPlayer caller,
RagonRoomPlayer invoker,
RagonEvent evnt,
RagonReplicationMode eventMode,
RagonRoomPlayer targetPlayer
)
{
if (Authority == RagonAuthority.OwnerOnly && invoker.Connection.Id != Owner.Connection.Id)
{
return;
}
var room = Owner.Room;
var buffer = room.Writer;
buffer.Clear();
buffer.WriteOperation(RagonOperation.REPLICATE_ENTITY_EVENT);
buffer.WriteUShort(evnt.EventCode);
buffer.WriteUShort(caller.Connection.Id);
buffer.WriteUShort(invoker.Connection.Id);
buffer.WriteByte((byte)eventMode);
buffer.WriteUShort(Id);
@@ -151,22 +159,18 @@ public class RagonEntity : IRagonEntity
}
public void ReplicateEvent(
RagonRoomPlayer caller,
RagonRoomPlayer invoker,
RagonEvent evnt,
RagonReplicationMode eventMode,
RagonTarget targetMode
)
{
if (Authority == RagonAuthority.OwnerOnly &&
Owner.Connection.Id != caller.Connection.Id)
if (Authority == RagonAuthority.OwnerOnly && invoker.Connection.Id != Owner.Connection.Id)
{
Console.WriteLine($"Player have not enough authority for event with Id {evnt.EventCode}");
return;
}
if (eventMode == RagonReplicationMode.Buffered &&
targetMode != RagonTarget.Owner &&
_bufferedEvents.Count < _limitBufferedEvents)
if (eventMode == RagonReplicationMode.Buffered && targetMode != RagonTarget.Owner && _bufferedEvents.Count < _limitBufferedEvents)
{
_bufferedEvents.Add(evnt);
}
@@ -177,7 +181,7 @@ public class RagonEntity : IRagonEntity
buffer.Clear();
buffer.WriteOperation(RagonOperation.REPLICATE_ENTITY_EVENT);
buffer.WriteUShort(evnt.EventCode);
buffer.WriteUShort(caller.Connection.Id);
buffer.WriteUShort(invoker.Connection.Id);
buffer.WriteByte((byte)eventMode);
buffer.WriteUShort(Id);
@@ -205,7 +209,7 @@ public class RagonEntity : IRagonEntity
{
foreach (var roomPlayer in room.ReadyPlayersList)
{
if (roomPlayer.Connection.Id != caller.Connection.Id)
if (roomPlayer.Connection.Id != invoker.Connection.Id)
roomPlayer.Connection.Reliable.Send(sendData);
}
@@ -14,21 +14,18 @@
* limitations under the License.
*/
using Ragon.Protocol;
namespace Ragon.Server.Entity;
public class RagonEntityState: IRagonEntityState
{
private List<RagonProperty> _properties;
private RagonEntity _entity;
private RagonBuffer _buffer;
private readonly List<RagonProperty> _properties;
private readonly RagonEntity _entity;
public RagonEntityState(RagonEntity entity, int capacity = 10)
{
_entity = entity;
_buffer = new RagonBuffer(8);
_properties = new List<RagonProperty>(capacity);
}
@@ -67,8 +64,7 @@ public class RagonEntityState: IRagonEntityState
{
foreach (var property in _properties)
{
var hasPayloadOrFixed = property.IsFixed || property is { IsFixed: false, Size: > 0 };
if (hasPayloadOrFixed)
if (property.HasData)
{
buffer.WriteBool(true);
property.Write(buffer);
+3 -9
View File
@@ -28,19 +28,13 @@ public class RagonPayload
public void Read(RagonBuffer buffer)
{
var readOnlySpan = _data.AsSpan();
_size = buffer.Capacity;
buffer.ReadSpan(ref readOnlySpan, _size);
_size = buffer.Capacity - 1;
buffer.ReadArray(_data, _size);
}
public void Write(RagonBuffer buffer)
{
if (_size == 0) return;
ReadOnlySpan<uint> readOnlySpan = _data.AsSpan();
buffer.WriteSpan(ref readOnlySpan, _size);
buffer.WriteArray(_data, _size);
}
}
+12 -5
View File
@@ -23,6 +23,7 @@ public class RagonProperty : RagonPayload
public int Size { get; set; }
public bool IsDirty { get; private set; }
public bool IsFixed { get; private set; }
public bool HasData { get; private set; }
private uint[] _data;
@@ -37,24 +38,30 @@ public class RagonProperty : RagonPayload
public void Read(RagonBuffer buffer)
{
var readOnlySpan = _data.AsSpan();
if (IsFixed)
{
buffer.ReadSpan(ref readOnlySpan, Size);
buffer.ReadArray(_data, Size);
}
else
{
Size = (int) buffer.Read();
buffer.ReadSpan(ref readOnlySpan, Size);
buffer.ReadArray(_data, Size);
}
HasData = true;
IsDirty = true;
}
public void Write(RagonBuffer buffer)
{
ReadOnlySpan<uint> readOnlySpan = _data.AsSpan();
buffer.WriteSpan(ref readOnlySpan, Size);
if (IsFixed)
{
buffer.WriteArray(_data, Size);
return;
}
buffer.Write((ushort) Size);
buffer.WriteArray(_data, Size);
}
public void Clear()
@@ -17,7 +17,7 @@
using Ragon.Protocol;
using Ragon.Server.Room;
namespace Ragon.Server.Entity;
namespace Ragon.Server.Event;
public class RagonEvent
{
@@ -39,15 +39,13 @@ public class RagonEvent
public void Read(RagonBuffer buffer)
{
var readOnlySpan = _data.AsSpan();
_size = buffer.Capacity;
buffer.ReadSpan(ref readOnlySpan, _size);
_size = buffer.Capacity - 1;
buffer.ReadArray(_data, _size);
}
public void Write(RagonBuffer buffer)
{
if (_size == 0) return;
ReadOnlySpan<uint> readOnlySpan = _data.AsSpan();
buffer.WriteSpan(ref readOnlySpan, _size);
if (_size <= 0) return;
buffer.WriteArray(_data, _size);
}
}
@@ -16,31 +16,32 @@
using NLog;
using Ragon.Protocol;
using Ragon.Server.IO;
using Ragon.Server.Lobby;
using Ragon.Server.Plugin;
using Ragon.Server.Plugin.Web;
namespace Ragon.Server.Handler;
public sealed class AuthorizationOperation: IRagonOperation
public sealed class AuthorizationOperation: BaseOperation
{
private Logger _logger = LogManager.GetCurrentClassLogger();
private readonly RagonWebHookPlugin _ragonWebHook;
private readonly RagonContextObserver _contextObserver;
private readonly RagonWebHookPlugin _webhook;
private readonly RagonContextObserver _observer;
private readonly RagonBuffer _writer;
public AuthorizationOperation(
RagonWebHookPlugin ragonWebHook,
RagonContextObserver contextObserver,
RagonBuffer writer)
RagonBuffer reader,
RagonBuffer writer,
RagonWebHookPlugin webhook,
RagonContextObserver observer): base(reader, writer)
{
_ragonWebHook = ragonWebHook;
_contextObserver = contextObserver;
_webhook = webhook;
_observer = observer;
_writer = writer;
}
public void Handle(RagonContext context, RagonBuffer reader, RagonBuffer writer)
public override void Handle(RagonContext context, NetworkChannel channel)
{
if (context.ConnectionStatus == ConnectionStatus.Authorized)
{
@@ -55,13 +56,13 @@ public sealed class AuthorizationOperation: IRagonOperation
}
var configuration = context.Configuration;
var key = reader.ReadString();
var name = reader.ReadString();
var payload = reader.ReadString();
var key = Reader.ReadString();
var name = Reader.ReadString();
var payload = Reader.ReadString();
if (key == configuration.ServerKey)
{
if (_ragonWebHook.RequestAuthorization(context, name, payload))
if (_webhook.RequestAuthorization(context, name, payload))
return;
var lobbyPlayer = new RagonLobbyPlayer(context.Connection, Guid.NewGuid().ToString(), name, payload);
@@ -79,7 +80,7 @@ public sealed class AuthorizationOperation: IRagonOperation
{
context.ConnectionStatus = ConnectionStatus.Authorized;
_contextObserver.OnAuthorized(context);
_observer.OnAuthorized(context);
var playerId = context.LobbyPlayer.Id;
var playerName = context.LobbyPlayer.Name;
@@ -109,4 +110,6 @@ public sealed class AuthorizationOperation: IRagonOperation
_logger.Trace($"Connection {context.Connection.Id}");
}
}
@@ -0,0 +1,34 @@
/*
* Copyright 2023 Eduard Kargin <kargin.eduard@gmail.com>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using Ragon.Protocol;
using Ragon.Server.IO;
namespace Ragon.Server.Handler;
public abstract class BaseOperation
{
protected readonly RagonBuffer Reader;
protected readonly RagonBuffer Writer;
public BaseOperation(RagonBuffer reader, RagonBuffer writer)
{
Reader = reader;
Writer = writer;
}
public abstract void Handle(RagonContext context, NetworkChannel channel);
}
@@ -17,21 +17,26 @@
using NLog;
using Ragon.Protocol;
using Ragon.Server.Entity;
using Ragon.Server.IO;
namespace Ragon.Server.Handler;
public sealed class EntityCreateOperation : IRagonOperation
public sealed class EntityCreateOperation : BaseOperation
{
private readonly Logger _logger = LogManager.GetCurrentClassLogger();
public void Handle(RagonContext context, RagonBuffer reader, RagonBuffer writer)
public EntityCreateOperation(RagonBuffer reader, RagonBuffer writer) : base(reader, writer)
{
}
public override void Handle(RagonContext context, NetworkChannel channel)
{
var player = context.RoomPlayer;
var room = context.Room;
var attachId = reader.ReadUShort();
var entityType = reader.ReadUShort();
var eventAuthority = (RagonAuthority) reader.ReadByte();
var propertiesCount = reader.ReadUShort();
var attachId = Reader.ReadUShort();
var entityType = Reader.ReadUShort();
var eventAuthority = (RagonAuthority) Reader.ReadByte();
var propertiesCount = Reader.ReadUShort();
var entityParameters = new RagonEntityParameters()
{
@@ -45,14 +50,14 @@ public sealed class EntityCreateOperation : IRagonOperation
var entity = new RagonEntity(entityParameters);
for (var i = 0; i < propertiesCount; i++)
{
var propertyType = reader.ReadBool();
var propertySize = reader.ReadUShort();
var propertyType = Reader.ReadBool();
var propertySize = Reader.ReadUShort();
entity.AddProperty(new RagonProperty(propertySize, propertyType));
}
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))
@@ -66,4 +71,6 @@ public sealed class EntityCreateOperation : IRagonOperation
_logger.Trace($"Player {context.Connection.Id}|{context.LobbyPlayer.Name} created entity {entity.Id}:{entity.Type}");
}
}
@@ -16,19 +16,24 @@
using NLog;
using Ragon.Protocol;
using Ragon.Server.Entity;
using Ragon.Server.Event;
using Ragon.Server.IO;
namespace Ragon.Server.Handler;
public sealed class EntityEventOperation : IRagonOperation
public sealed class EntityEventOperation : BaseOperation
{
private readonly Logger _logger = LogManager.GetCurrentClassLogger();
public void Handle(RagonContext context, RagonBuffer reader, RagonBuffer writer)
public EntityEventOperation(RagonBuffer reader, RagonBuffer writer) : base(reader, writer)
{
}
public override void Handle(RagonContext context, NetworkChannel channel)
{
var player = context.RoomPlayer;
var room = context.Room;
var entityId = reader.ReadUShort();
var entityId = Reader.ReadUShort();
if (!room.Entities.TryGetValue(entityId, out var ent))
{
@@ -36,16 +41,16 @@ public sealed class EntityEventOperation : IRagonOperation
return;
}
var eventId = reader.ReadUShort();
var eventMode = (RagonReplicationMode)reader.ReadByte();
var targetMode = (RagonTarget)reader.ReadByte();
var eventId = Reader.ReadUShort();
var eventMode = (RagonReplicationMode)Reader.ReadByte();
var targetMode = (RagonTarget)Reader.ReadByte();
var targetPlayerPeerId = (ushort)0;
if (targetMode == RagonTarget.Player)
targetPlayerPeerId = reader.ReadUShort();
targetPlayerPeerId = Reader.ReadUShort();
var @event = new RagonEvent(player, eventId);
@event.Read(reader);
@event.Read(Reader);
if (targetMode == RagonTarget.Player && room.Players.TryGetValue(targetPlayerPeerId, out var targetPlayer))
{
@@ -1,19 +1,41 @@
/*
* Copyright 2023 Eduard Kargin <kargin.eduard@gmail.com>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using NLog;
using Ragon.Protocol;
using Ragon.Server.IO;
namespace Ragon.Server.Handler;
public sealed class EntityOwnershipOperation : IRagonOperation
public sealed class EntityOwnershipOperation : BaseOperation
{
private readonly Logger _logger = LogManager.GetCurrentClassLogger();
public void Handle(RagonContext context, RagonBuffer reader, RagonBuffer writer)
public EntityOwnershipOperation(RagonBuffer reader, RagonBuffer writer) : base(reader, writer)
{
}
public override void Handle(RagonContext context, NetworkChannel channel)
{
var currentOwner = context.RoomPlayer;
var room = context.Room;
var entityId = reader.ReadUShort();
var playerPeerId = reader.ReadUShort();
var entityId = Reader.ReadUShort();
var playerPeerId = Reader.ReadUShort();
if (!room.Entities.TryGetValue(entityId, out var entity))
{
@@ -29,7 +51,7 @@ public sealed class EntityOwnershipOperation : IRagonOperation
if (!room.Players.TryGetValue(playerPeerId, out var nextOwner))
{
_logger.Error($"Player not found with id {entityId}");
_logger.Error($"Player not found with id {playerPeerId}");
return;
}
@@ -40,13 +62,13 @@ public sealed class EntityOwnershipOperation : IRagonOperation
_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);
Writer.Clear();
Writer.WriteOperation(RagonOperation.OWNERSHIP_ENTITY_CHANGED);
Writer.WriteUShort(playerPeerId);
Writer.WriteUShort(1);
Writer.WriteUShort(entity.Id);
var sendData = writer.ToArray();
var sendData = Writer.ToArray();
foreach (var player in room.PlayerList)
player.Connection.Reliable.Send(sendData);
}
@@ -17,23 +17,28 @@
using NLog;
using Ragon.Protocol;
using Ragon.Server.Entity;
using Ragon.Server.IO;
namespace Ragon.Server.Handler;
public sealed class EntityDestroyOperation: IRagonOperation
public sealed class EntityDestroyOperation: BaseOperation
{
private readonly Logger _logger = LogManager.GetCurrentClassLogger();
public void Handle(RagonContext context, RagonBuffer reader, RagonBuffer writer)
public EntityDestroyOperation(RagonBuffer reader, RagonBuffer writer) : base(reader, writer)
{
}
public override void Handle(RagonContext context, NetworkChannel channel)
{
var player = context.RoomPlayer;
var room = context.Room;
var entityId = reader.ReadUShort();
var entityId = Reader.ReadUShort();
if (room.Entities.TryGetValue(entityId, out var entity))
if (room.Entities.TryGetValue(entityId, out var entity) && entity.Owner.Connection.Id == player.Connection.Id)
{
var payload = new RagonPayload();
payload.Read(reader);
payload.Read(Reader);
room.DetachEntity(entity);
player.DetachEntity(entity);
@@ -42,5 +47,9 @@ public sealed class EntityDestroyOperation: IRagonOperation
_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");
}
}
}
@@ -16,23 +16,28 @@
using NLog;
using Ragon.Protocol;
using Ragon.Server.IO;
namespace Ragon.Server.Handler;
public sealed class EntityStateOperation: IRagonOperation
public sealed class EntityStateOperation: BaseOperation
{
private readonly ILogger _logger = LogManager.GetCurrentClassLogger();
public void Handle(RagonContext context, RagonBuffer reader, RagonBuffer writer)
public EntityStateOperation(RagonBuffer reader, RagonBuffer writer) : base(reader, writer)
{
}
public override void Handle(RagonContext context, NetworkChannel channel)
{
var room = context.Room;
var player = context.RoomPlayer;
var entitiesCount = reader.ReadUShort();
var entitiesCount = Reader.ReadUShort();
for (var entityIndex = 0; entityIndex < entitiesCount; entityIndex++)
{
var entityId = reader.ReadUShort();
if (room.Entities.TryGetValue(entityId, out var entity) && entity.TryReadState(player, reader))
var entityId = Reader.ReadUShort();
if (room.Entities.TryGetValue(entityId, out var entity) && entity.TryReadState(player, Reader))
{
room.Track(entity);
}
@@ -16,6 +16,7 @@
using NLog;
using Ragon.Protocol;
using Ragon.Server.IO;
using Ragon.Server.Lobby;
using Ragon.Server.Plugin;
using Ragon.Server.Plugin.Web;
@@ -23,20 +24,20 @@ using Ragon.Server.Room;
namespace Ragon.Server.Handler;
public sealed class RoomCreateOperation: IRagonOperation
public sealed class RoomCreateOperation : BaseOperation
{
private readonly RagonRoomParameters _roomParameters = new();
private readonly Logger _logger = LogManager.GetCurrentClassLogger();
private readonly IServerPlugin _serverPlugin;
private readonly RagonWebHookPlugin _ragonWebHookPlugin;
public RoomCreateOperation(IServerPlugin serverPlugin, RagonWebHookPlugin ragonWebHook)
public RoomCreateOperation(RagonBuffer reader, RagonBuffer writer, IServerPlugin serverPlugin, RagonWebHookPlugin ragonWebHook) : base(reader, writer)
{
_serverPlugin = serverPlugin;
_ragonWebHookPlugin = ragonWebHook;
}
public void Handle(RagonContext context, RagonBuffer reader, RagonBuffer writer)
public override void Handle(RagonContext context, NetworkChannel channel)
{
if (context.ConnectionStatus == ConnectionStatus.Unauthorized)
{
@@ -44,19 +45,19 @@ public sealed class RoomCreateOperation: IRagonOperation
return;
}
var custom = reader.ReadBool();
var custom = Reader.ReadBool();
var roomId = Guid.NewGuid().ToString();
if (custom)
{
roomId = reader.ReadString();
roomId = Reader.ReadString();
if (context.Lobby.FindRoomById(roomId, out _))
{
writer.Clear();
writer.WriteOperation(RagonOperation.JOIN_FAILED);
writer.WriteString($"Room with id {roomId} already exists");
Writer.Clear();
Writer.WriteOperation(RagonOperation.JOIN_FAILED);
Writer.WriteString($"Room with id {roomId} already exists");
var sendData = writer.ToArray();
var sendData = Writer.ToArray();
context.Connection.Reliable.Send(sendData);
_logger.Trace($"Player {context.Connection.Id}|{context.LobbyPlayer.Name} join failed to room {roomId}, room already exist");
@@ -64,13 +65,13 @@ public sealed class RoomCreateOperation: IRagonOperation
}
}
_roomParameters.Deserialize(reader);
_roomParameters.Deserialize(Reader);
var information = new RoomInformation()
{
Map = _roomParameters.Map,
Max = _roomParameters.Max,
Min = _roomParameters.Min,
Scene = _roomParameters.Scene,
Max = _roomParameters.Max,
Min = _roomParameters.Min,
};
var lobbyPlayer = context.LobbyPlayer;
@@ -87,9 +88,9 @@ public sealed class RoomCreateOperation: IRagonOperation
_ragonWebHookPlugin.RoomCreated(context, room, roomPlayer);
_logger.Trace($"Player {context.Connection.Id}|{context.LobbyPlayer.Name} create room {room.Id} with map {information.Map}");
_logger.Trace($"Player {context.Connection.Id}|{context.LobbyPlayer.Name} create room {room.Id} with scene {information.Scene}");
JoinSuccess(roomPlayer, room, writer);
JoinSuccess(roomPlayer, room, Writer);
_logger.Trace($"Player {context.Connection.Id}|{context.LobbyPlayer.Name} joined to room {room.Id}");
}
@@ -101,9 +102,9 @@ public sealed class RoomCreateOperation: IRagonOperation
writer.WriteString(room.Id);
writer.WriteString(player.Id);
writer.WriteString(room.Owner.Id);
writer.WriteUShort((ushort) room.PlayerMin);
writer.WriteUShort((ushort) room.PlayerMax);
writer.WriteString(room.Map);
writer.WriteUShort((ushort)room.PlayerMin);
writer.WriteUShort((ushort)room.PlayerMax);
writer.WriteString(room.Scene);
var sendData = writer.ToArray();
player.Connection.Reliable.Send(sendData);
@@ -0,0 +1,49 @@
/*
* Copyright 2023 Eduard Kargin <kargin.eduard@gmail.com>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using NLog;
using Ragon.Protocol;
using Ragon.Server.IO;
namespace Ragon.Server.Handler;
public sealed class RoomDataOperation : BaseOperation
{
public RoomDataOperation(RagonBuffer reader, RagonBuffer writer) : base(reader, writer)
{
}
public override void Handle(RagonContext context, NetworkChannel channel)
{
var player = context.RoomPlayer;
var room = context.Room;
var data = Reader.RawData;
var dataSize = data.Length - 1;
var headerSize = 3;
var size = headerSize + dataSize;
var sendData = new byte[size];
var peerId = player.Connection.Id;
sendData[0] = (byte)RagonOperation.REPLICATE_RAW_DATA;
sendData[1] = (byte)peerId;
sendData[2] = (byte)(peerId >> 8);
Array.Copy(data, 1, sendData, headerSize, dataSize);
room.Broadcast(sendData, channel);
}
}
@@ -0,0 +1,45 @@
using Ragon.Protocol;
using Ragon.Server.Event;
using Ragon.Server.IO;
namespace Ragon.Server.Handler;
public class RoomEventOperation : BaseOperation
{
public RoomEventOperation(RagonBuffer reader, RagonBuffer writer) : base(reader, writer)
{
}
public override void Handle(RagonContext context, NetworkChannel channel)
{
var room = context.Room;
var player = context.RoomPlayer;
var eventId = Reader.ReadUShort();
var replicationMode = (RagonReplicationMode)Reader.ReadByte();
var targetMode = (RagonTarget)Reader.ReadByte();
var targetPlayerPeerId = (ushort)0;
if (targetMode == RagonTarget.Player)
targetPlayerPeerId = Reader.ReadUShort();
var @event = new RagonEvent(player, eventId);
@event.Read(Reader);
Writer.Clear();
Writer.WriteUShort(eventId);
Writer.WriteUShort(player.Connection.Id);
Writer.WriteUShort((ushort) replicationMode);
var sendData = Writer.ToArray();
if (targetMode == RagonTarget.Player && room.Players.TryGetValue(targetPlayerPeerId, out var targetPlayer))
{
targetPlayer.Connection.Reliable.Send(sendData);
return;
}
foreach (var roomPlayer in room.ReadyPlayersList)
roomPlayer.Connection.Reliable.Send(sendData);
}
}
@@ -16,31 +16,31 @@
using NLog;
using Ragon.Protocol;
using Ragon.Server.Plugin;
using Ragon.Server.IO;
using Ragon.Server.Plugin.Web;
using Ragon.Server.Room;
namespace Ragon.Server.Handler;
public sealed class RoomJoinOperation : IRagonOperation
public sealed class RoomJoinOperation : BaseOperation
{
private readonly Logger _logger = LogManager.GetCurrentClassLogger();
private readonly RagonWebHookPlugin _webHook;
public RoomJoinOperation(RagonWebHookPlugin plugin)
public RoomJoinOperation(RagonBuffer reader, RagonBuffer writer, RagonWebHookPlugin plugin) : base(reader, writer)
{
_webHook = plugin;
}
public void Handle(RagonContext context, RagonBuffer reader, RagonBuffer writer)
public override void Handle(RagonContext context, NetworkChannel channel)
{
var roomId = reader.ReadString();
var roomId = Reader.ReadString();
var lobbyPlayer = context.LobbyPlayer;
if (!context.Lobby.FindRoomById(roomId, out var existsRoom))
{
JoinFailed(context, writer);
JoinFailed(context, Writer);
_logger.Trace($"Player {context.Connection.Id}|{context.LobbyPlayer.Name} failed to join room {roomId}");
return;
@@ -54,7 +54,7 @@ public sealed class RoomJoinOperation : IRagonOperation
_webHook.RoomJoined(context, existsRoom, player);
JoinSuccess(context, existsRoom, writer);
JoinSuccess(context, existsRoom, Writer);
_logger.Trace($"Player {context.Connection.Id}|{context.LobbyPlayer.Name} joined to {existsRoom.Id}");
}
@@ -66,9 +66,9 @@ public sealed class RoomJoinOperation : IRagonOperation
writer.WriteString(room.Id);
writer.WriteString(context.RoomPlayer.Id);
writer.WriteString(room.Owner.Id);
writer.WriteUShort((ushort) room.PlayerMin);
writer.WriteUShort((ushort) room.PlayerMax);
writer.WriteString(room.Map);
writer.WriteUShort((ushort)room.PlayerMin);
writer.WriteUShort((ushort)room.PlayerMax);
writer.WriteString(room.Scene);
var sendData = writer.ToArray();
context.Connection.Reliable.Send(sendData);
@@ -16,6 +16,7 @@
using NLog;
using Ragon.Protocol;
using Ragon.Server.IO;
using Ragon.Server.Lobby;
using Ragon.Server.Plugin;
using Ragon.Server.Plugin.Web;
@@ -23,20 +24,20 @@ using Ragon.Server.Room;
namespace Ragon.Server.Handler;
public sealed class RoomJoinOrCreateOperation : IRagonOperation
public sealed class RoomJoinOrCreateOperation : BaseOperation
{
private readonly RagonRoomParameters _roomParameters = new();
private readonly Logger _logger = LogManager.GetCurrentClassLogger();
private readonly IServerPlugin _serverPlugin;
private readonly RagonWebHookPlugin _ragonWebHookPlugin;
public RoomJoinOrCreateOperation(IServerPlugin serverPlugin, RagonWebHookPlugin plugin)
public RoomJoinOrCreateOperation(RagonBuffer reader, RagonBuffer writer, IServerPlugin serverPlugin, RagonWebHookPlugin plugin): base(reader, writer)
{
_serverPlugin = serverPlugin;
_ragonWebHookPlugin = plugin;
}
public void Handle(RagonContext context, RagonBuffer reader, RagonBuffer writer)
public override void Handle(RagonContext context, NetworkChannel channel)
{
if (context.ConnectionStatus == ConnectionStatus.Unauthorized)
{
@@ -47,22 +48,22 @@ public sealed class RoomJoinOrCreateOperation : IRagonOperation
var roomId = Guid.NewGuid().ToString();
var lobbyPlayer = context.LobbyPlayer;
_roomParameters.Deserialize(reader);
_roomParameters.Deserialize(Reader);
if (context.Lobby.FindRoomByMap(_roomParameters.Map, out var existsRoom))
if (context.Lobby.FindRoomByScene(_roomParameters.Scene, out var existsRoom))
{
var player = new RagonRoomPlayer(context.Connection, lobbyPlayer.Id, lobbyPlayer.Name);
context.SetRoom(existsRoom, player);
_ragonWebHookPlugin.RoomJoined(context, existsRoom, player);
JoinSuccess(player, existsRoom, writer);
JoinSuccess(player, existsRoom, Writer);
}
else
{
var information = new RoomInformation()
{
Map = _roomParameters.Map,
Scene = _roomParameters.Scene,
Max = _roomParameters.Max,
Min = _roomParameters.Min,
};
@@ -77,9 +78,9 @@ public sealed class RoomJoinOrCreateOperation : IRagonOperation
context.Scheduler.Run(room);
context.SetRoom(room, roomPlayer);
_logger.Trace($"Player {context.Connection.Id}|{context.LobbyPlayer.Name} create room {room.Id} with map {information.Map}");
_logger.Trace($"Player {context.Connection.Id}|{context.LobbyPlayer.Name} create room {room.Id} with scene {information.Scene}");
JoinSuccess(roomPlayer, room, writer);
JoinSuccess(roomPlayer, room, Writer);
}
}
@@ -92,7 +93,7 @@ public sealed class RoomJoinOrCreateOperation : IRagonOperation
writer.WriteString(room.Owner.Id);
writer.WriteUShort((ushort) room.PlayerMin);
writer.WriteUShort((ushort) room.PlayerMax);
writer.WriteString(room.Map);
writer.WriteString(room.Scene);
var sendData = writer.ToArray();
player.Connection.Reliable.Send(sendData);
@@ -16,21 +16,23 @@
using NLog;
using Ragon.Protocol;
using Ragon.Server.IO;
using Ragon.Server.Plugin;
using Ragon.Server.Plugin.Web;
namespace Ragon.Server.Handler;
public sealed class RoomLeaveOperation: IRagonOperation
public sealed class RoomLeaveOperation: BaseOperation
{
private readonly Logger _logger = LogManager.GetCurrentClassLogger();
private readonly RagonWebHookPlugin _webHook;
public RoomLeaveOperation(RagonWebHookPlugin plugin)
public RoomLeaveOperation(RagonBuffer reader, RagonBuffer writer, RagonWebHookPlugin plugin): base(reader, writer)
{
_webHook = plugin;
}
public void Handle(RagonContext context, RagonBuffer reader, RagonBuffer writer)
public override void Handle(RagonContext context, NetworkChannel channel)
{
var room = context.Room;
var roomPlayer = context.RoomPlayer;
@@ -1,13 +1,34 @@
/*
* Copyright 2023 Eduard Kargin <kargin.eduard@gmail.com>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using NLog;
using Ragon.Protocol;
using Ragon.Server.Entity;
using Ragon.Server.IO;
namespace Ragon.Server.Handler;
public sealed class RoomOwnershipOperation : IRagonOperation
public sealed class RoomOwnershipOperation : BaseOperation
{
private readonly Logger _logger = LogManager.GetCurrentClassLogger();
public void Handle(RagonContext context, RagonBuffer reader, RagonBuffer writer)
public RoomOwnershipOperation(RagonBuffer reader, RagonBuffer writer) : base(reader, writer)
{
}
public override void Handle(RagonContext context, NetworkChannel channel)
{
}
@@ -14,36 +14,38 @@
* limitations under the License.
*/
using NLog;
using Ragon.Protocol;
using Ragon.Server.IO;
namespace Ragon.Server.Handler;
public class SceneLoadOperation: IRagonOperation
public class SceneLoadOperation: BaseOperation
{
private readonly Logger _logger = LogManager.GetCurrentClassLogger();
public void Handle(RagonContext context, RagonBuffer reader, RagonBuffer writer)
public SceneLoadOperation(RagonBuffer reader, RagonBuffer writer) : base(reader, writer) {}
public override void Handle(RagonContext context, NetworkChannel channel)
{
var roomOwner = context.Room.Owner;
var currentPlayer = context.RoomPlayer;
var room = context.Room;
var sceneName = reader.ReadString();
var sceneName = Reader.ReadString();
if (roomOwner.Connection.Id != currentPlayer.Connection.Id)
{
_logger.Warn("Only owner can change map!");
_logger.Warn("Only owner can change scene!");
return;
}
room.UpdateMap(sceneName);
writer.Clear();
writer.WriteOperation(RagonOperation.LOAD_SCENE);
writer.WriteString(sceneName);
Writer.Clear();
Writer.WriteOperation(RagonOperation.LOAD_SCENE);
Writer.WriteString(sceneName);
var sendData = writer.ToArray();
var sendData = Writer.ToArray();
foreach (var player in room.PlayerList)
player.Connection.Reliable.Send(sendData);
}
@@ -17,21 +17,22 @@
using NLog;
using Ragon.Protocol;
using Ragon.Server.Entity;
using Ragon.Server.IO;
using Ragon.Server.Lobby;
using Ragon.Server.Room;
namespace Ragon.Server.Handler;
public sealed class SceneLoadedOperation : IRagonOperation
public sealed class SceneLoadedOperation : BaseOperation
{
private readonly Logger _logger = LogManager.GetCurrentClassLogger();
public SceneLoadedOperation()
public SceneLoadedOperation(RagonBuffer reader, RagonBuffer writer): base(reader, writer)
{
}
public void Handle(RagonContext context, RagonBuffer reader, RagonBuffer writer)
public override void Handle(RagonContext context, NetworkChannel channel)
{
if (context.ConnectionStatus == ConnectionStatus.Unauthorized)
return;
@@ -39,17 +40,21 @@ public sealed class SceneLoadedOperation : IRagonOperation
var owner = context.Room.Owner;
var player = context.RoomPlayer;
var room = context.Room;
if (player.IsLoaded)
{
_logger.Warn($"Player {player.Name}:{player.Connection.Id} already ready");
return;
}
if (player == owner)
{
var statics = reader.ReadUShort();
var statics = Reader.ReadUShort();
for (var staticIndex = 0; staticIndex < statics; staticIndex++)
{
var entityType = reader.ReadUShort();
var eventAuthority = (RagonAuthority)reader.ReadByte();
var staticId = reader.ReadUShort();
var propertiesCount = reader.ReadUShort();
var entityType = Reader.ReadUShort();
var eventAuthority = (RagonAuthority)Reader.ReadByte();
var staticId = Reader.ReadUShort();
var propertiesCount = Reader.ReadUShort();
var entityParameters = new RagonEntityParameters()
{
@@ -57,13 +62,14 @@ public sealed class SceneLoadedOperation : IRagonOperation
Authority = eventAuthority,
AttachId = 0,
StaticId = staticId,
BufferedEvents = context.Configuration.LimitBufferedEvents,
};
var entity = new RagonEntity(entityParameters);
for (var propertyIndex = 0; propertyIndex < propertiesCount; propertyIndex++)
{
var propertyType = reader.ReadBool();
var propertySize = reader.ReadUShort();
var propertyType = Reader.ReadBool();
var propertySize = Reader.ReadUShort();
entity.AddProperty(new RagonProperty(propertySize, propertyType));
}
@@ -73,7 +79,7 @@ public sealed class SceneLoadedOperation : IRagonOperation
var playerInfo = $"Player {context.Connection.Id}|{context.LobbyPlayer.Name}";
var entityInfo = $"{entity.Id}:{entity.Type}";
_logger.Trace($"{playerInfo} created entity {entityInfo}");
_logger.Trace($"{playerInfo} created static entity {entityInfo}");
entity.Attach(player);
room.AttachEntity(entity);
@@ -86,14 +92,14 @@ public sealed class SceneLoadedOperation : IRagonOperation
foreach (var roomPlayer in room.WaitPlayersList)
{
DispatchPlayerJoinExcludePlayer(room, roomPlayer, writer);
DispatchPlayerJoinExcludePlayer(room, roomPlayer, Writer);
roomPlayer.SetReady();
}
room.UpdateReadyPlayerList();
DispatchSnapshot(room, room.WaitPlayersList, writer);
DispatchSnapshot(room, room.WaitPlayersList, Writer);
room.WaitPlayersList.Clear();
}
@@ -101,14 +107,14 @@ public sealed class SceneLoadedOperation : IRagonOperation
{
player.SetReady();
DispatchPlayerJoinExcludePlayer(room, player, writer);
DispatchPlayerJoinExcludePlayer(room, player, Writer);
room.UpdateReadyPlayerList();
DispatchSnapshot(room, new List<RagonRoomPlayer>() { player }, writer);
DispatchSnapshot(room, new List<RagonRoomPlayer>() { player }, Writer);
foreach (var entity in room.EntityList)
entity.RestoreBufferedEvents(player, writer);
entity.RestoreBufferedEvents(player, Writer);
}
else
{
@@ -0,0 +1,36 @@
/*
* Copyright 2023 Eduard Kargin <kargin.eduard@gmail.com>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using Ragon.Protocol;
using Ragon.Server.IO;
namespace Ragon.Server.Handler;
public class TimestampSyncOperation: BaseOperation
{
public TimestampSyncOperation(RagonBuffer reader, RagonBuffer writer) : base(reader, writer)
{
}
public override void Handle(RagonContext context, NetworkChannel channel)
{
var timestamp0 = Reader.Read(32);
var timestamp1 = Reader.Read(32);
var value = new DoubleToUInt() { Int0 = timestamp0, Int1 = timestamp1 };
context.RoomPlayer?.SetTimestamp(value.Double);
}
}
@@ -14,9 +14,12 @@
* limitations under the License.
*/
using Ragon.Protocol;
namespace Ragon.Server.IO;
public interface INetworkChannel
{
void Send(byte[] data);
void Send(RagonBuffer buffer);
}
+1 -1
View File
@@ -21,5 +21,5 @@ public interface INetworkListener
void OnConnected(INetworkConnection connection);
void OnDisconnected(INetworkConnection connection);
void OnTimeout(INetworkConnection connection);
void OnData(INetworkConnection connection, byte[] data);
void OnData(INetworkConnection connection, NetworkChannel channel, byte[] data);
}
@@ -21,5 +21,6 @@ public interface INetworkServer
public Executor Executor { get; }
public void Stop();
public void Update();
public void Broadcast(byte[] data, NetworkChannel channel);
public void Start(INetworkListener listener, NetworkConfiguration configuration);
}
@@ -14,11 +14,11 @@
* limitations under the License.
*/
using Ragon.Protocol;
namespace Ragon.Server.Handler;
namespace Ragon.Server.IO;
public interface IRagonOperation
public enum NetworkChannel
{
public void Handle(RagonContext context, RagonBuffer reader, RagonBuffer writer);
RELIABLE = 0,
UNRELIABLE = 1,
}
+3
View File
@@ -14,6 +14,8 @@
* limitations under the License.
*/
using Ragon.Protocol;
using Ragon.Server.Handler;
using Ragon.Server.IO;
using Ragon.Server.Lobby;
@@ -21,6 +23,7 @@ namespace Ragon.Server;
public interface IRagonServer
{
BaseOperation ResolveHandler(RagonOperation operation);
RagonLobbyPlayer? GetPlayerByConnection(INetworkConnection connection);
RagonLobbyPlayer? GetPlayerById(string id);
}
+1 -1
View File
@@ -22,7 +22,7 @@ namespace Ragon.Server.Lobby;
public interface IRagonLobby
{
public bool FindRoomById(string roomId, [MaybeNullWhen(false)] out RagonRoom room);
public bool FindRoomByMap(string map, [MaybeNullWhen(false)] out RagonRoom room);
public bool FindRoomByScene(string sceneName, [MaybeNullWhen(false)] out RagonRoom room);
public void Persist(RagonRoom room);
public bool RemoveIfEmpty(RagonRoom room);
}
@@ -40,11 +40,11 @@ public class LobbyInMemory : IRagonLobby
return false;
}
public bool FindRoomByMap(string map, [MaybeNullWhen(false)] out RagonRoom room)
public bool FindRoomByScene(string sceneName, [MaybeNullWhen(false)] out RagonRoom room)
{
foreach (var existsRoom in _rooms)
{
if (existsRoom.Map == map && existsRoom.PlayerCount < existsRoom.PlayerMax)
if (existsRoom.Scene == sceneName && existsRoom.PlayerCount < existsRoom.PlayerMax)
{
room = existsRoom;
return true;
@@ -61,7 +61,7 @@ public class LobbyInMemory : IRagonLobby
_logger.Trace($"New room: {room.Id}");
foreach (var r in _rooms)
_logger.Trace($"Room: {r.Id} Map: {r.Map} Players: {r.Players.Count} Entities: {r.Entities.Count}");
_logger.Trace($"Room: {r.Id} Scene: {r.Scene} Players: {r.Players.Count} Entities: {r.Entities.Count}");
}
public bool RemoveIfEmpty(RagonRoom room)
@@ -76,7 +76,7 @@ public class LobbyInMemory : IRagonLobby
}
foreach (var r in _rooms)
_logger.Trace($"Room: {r.Id} Map: {r.Map} Players: {r.Players.Count} Entities: {r.Entities.Count}");
_logger.Trace($"Room: {r.Id} Scene: {r.Scene} Players: {r.Players.Count} Entities: {r.Entities.Count}");
return result;
}
@@ -28,10 +28,10 @@ public class RagonWebHookPlugin
{
private Dictionary<string, string> _webHooks;
private RagonServer _server;
private IRagonServer _server;
private HttpClient _httpClient;
public RagonWebHookPlugin(RagonServer server, RagonServerConfiguration configuration)
public RagonWebHookPlugin(IRagonServer server, RagonServerConfiguration configuration)
{
_webHooks = new Dictionary<string, string>(configuration.WebHooks);
_httpClient = new HttpClient();
@@ -46,7 +46,7 @@ public class RagonWebHookPlugin
var executor = context.Executor;
executor.Run(async () =>
{
var authorizationOperation = (AuthorizationOperation) _server.ResolveOperation(RagonOperation.AUTHORIZE);
var authorizationOperation = (AuthorizationOperation) _server.ResolveHandler(RagonOperation.AUTHORIZE);
var response = await _httpClient.PostAsync(new Uri(value), httpContent);
if (response.StatusCode != HttpStatusCode.OK)
{
+50 -27
View File
@@ -31,7 +31,7 @@ public class RagonServer : IRagonServer, INetworkListener
{
private readonly Logger _logger = LogManager.GetCurrentClassLogger();
private readonly INetworkServer _server;
private readonly IRagonOperation[] _handlers;
private readonly BaseOperation[] _handlers;
private readonly IRagonLobby _lobby;
private readonly IServerPlugin _serverPlugin;
private readonly Thread _dedicatedThread;
@@ -73,20 +73,23 @@ public class RagonServer : IRagonServer, INetworkListener
_serverPlugin.OnAttached(this);
_handlers = new IRagonOperation[byte.MaxValue];
_handlers[(byte) RagonOperation.AUTHORIZE] = new AuthorizationOperation(_webhooks, contextObserver, _writer);
_handlers[(byte) RagonOperation.JOIN_OR_CREATE_ROOM] = new RoomJoinOrCreateOperation(plugin, _webhooks);
_handlers[(byte) RagonOperation.CREATE_ROOM] = new RoomCreateOperation(plugin, _webhooks);
_handlers[(byte) RagonOperation.JOIN_ROOM] = new RoomJoinOperation(_webhooks);
_handlers[(byte) RagonOperation.LEAVE_ROOM] = new RoomLeaveOperation(_webhooks);
_handlers[(byte) RagonOperation.LOAD_SCENE] = new SceneLoadOperation();
_handlers[(byte) RagonOperation.SCENE_LOADED] = new SceneLoadedOperation();
_handlers[(byte) RagonOperation.CREATE_ENTITY] = new EntityCreateOperation();
_handlers[(byte) RagonOperation.REMOVE_ENTITY] = new EntityDestroyOperation();
_handlers[(byte) RagonOperation.REPLICATE_ENTITY_EVENT] = new EntityEventOperation();
_handlers[(byte) RagonOperation.REPLICATE_ENTITY_STATE] = new EntityStateOperation();
_handlers[(byte) RagonOperation.TRANSFER_ROOM_OWNERSHIP] = new EntityOwnershipOperation();
_handlers[(byte) RagonOperation.TRANSFER_ENTITY_OWNERSHIP] = new EntityOwnershipOperation();
_handlers = new BaseOperation[byte.MaxValue];
_handlers[(byte)RagonOperation.AUTHORIZE] = new AuthorizationOperation(_reader, _writer, _webhooks, contextObserver);
_handlers[(byte)RagonOperation.JOIN_OR_CREATE_ROOM] = new RoomJoinOrCreateOperation(_reader, _writer, plugin, _webhooks);
_handlers[(byte)RagonOperation.CREATE_ROOM] = new RoomCreateOperation(_reader, _writer, plugin, _webhooks);
_handlers[(byte)RagonOperation.JOIN_ROOM] = new RoomJoinOperation(_reader, _writer, _webhooks);
_handlers[(byte)RagonOperation.LEAVE_ROOM] = new RoomLeaveOperation(_reader, _writer, _webhooks);
_handlers[(byte)RagonOperation.LOAD_SCENE] = new SceneLoadOperation(_reader, _writer);
_handlers[(byte)RagonOperation.SCENE_LOADED] = new SceneLoadedOperation(_reader, _writer);
_handlers[(byte)RagonOperation.CREATE_ENTITY] = new EntityCreateOperation(_reader, _writer);
_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);
_logger.Trace($"Server Tick Rate: {_configuration.ServerTickRate}");
}
@@ -96,10 +99,17 @@ public class RagonServer : IRagonServer, INetworkListener
_timer.Start();
while (true)
{
if (_timer.ElapsedMilliseconds > _tickRate * 2)
{
_logger.Warn($"Slow perfomance: {_timer.ElapsedMilliseconds}");
}
if (_timer.ElapsedMilliseconds > _tickRate)
{
_scheduler.Update(_timer.ElapsedMilliseconds / 1000.0f);
_timer.Restart();
_scheduler.Update(_timer.ElapsedMilliseconds / 1000.0f);
SendTimestamp();
}
_executor.Update();
@@ -158,13 +168,13 @@ public class RagonServer : IRagonServer, INetworkListener
}
else
{
_logger.Trace($"Disconnected: {connection.Id}");
_logger.Trace($"Disconnected without context: {connection.Id}");
}
}
public void OnTimeout(INetworkConnection connection)
{
if (_contextsByConnection.Remove(connection.Id, out var context))
if (_contextsByConnection.Remove(connection.Id, out var context) && context.ConnectionStatus == ConnectionStatus.Authorized)
{
var room = context.Room;
if (room != null)
@@ -181,7 +191,7 @@ public class RagonServer : IRagonServer, INetworkListener
}
}
public void OnData(INetworkConnection connection, byte[] data)
public void OnData(INetworkConnection connection, NetworkChannel channel, byte[] data)
{
try
{
@@ -192,7 +202,7 @@ public class RagonServer : IRagonServer, INetworkListener
_reader.FromArray(data);
var operation = _reader.ReadByte();
_handlers[operation].Handle(context, _reader, _writer);
_handlers[operation]?.Handle(context, channel);
}
}
catch (Exception ex)
@@ -201,22 +211,35 @@ public class RagonServer : IRagonServer, INetworkListener
}
}
public IRagonOperation ResolveOperation(RagonOperation operation)
public void SendTimestamp()
{
var timestamp = RagonTime.CurrentTimestamp();
var value = new DoubleToUInt
{
Double = timestamp,
};
_writer.Clear();
_writer.WriteOperation(RagonOperation.TIMESTAMP_SYNCHRONIZATION);
_writer.Write(value.Int0, 32);
_writer.Write(value.Int1, 32);
var sendData = _writer.ToArray();
_server.Broadcast(sendData, NetworkChannel.UNRELIABLE);
}
public BaseOperation ResolveHandler(RagonOperation operation)
{
return _handlers[(byte)operation];
}
public RagonLobbyPlayer? GetPlayerByConnection(INetworkConnection connection)
{
return _contextsByConnection.TryGetValue(connection.Id, out var context) ?
context.LobbyPlayer :
null;
return _contextsByConnection.TryGetValue(connection.Id, out var context) ? context.LobbyPlayer : null;
}
public RagonLobbyPlayer? GetPlayerById(string playerId)
{
return _contextsByPlayerId.TryGetValue(playerId, out var context) ?
context.LobbyPlayer :
null;
return _contextsByPlayerId.TryGetValue(playerId, out var context) ? context.LobbyPlayer : null;
}
}
@@ -25,11 +25,6 @@ public enum ServerType
WEBSOCKET,
}
public class WebHook
{
}
[Serializable]
public struct RagonServerConfiguration
{
@@ -47,7 +42,7 @@ public struct RagonServerConfiguration
public Dictionary<string, string> WebHooks;
private static readonly Logger Logger = LogManager.GetCurrentClassLogger();
private static readonly string ServerVersion = "1.2.0-rc";
private static readonly string ServerVersion = "1.3.2";
private static Dictionary<string, ServerType> _serverTypes = new Dictionary<string, ServerType>()
{
{"enet", Server.ServerType.ENET},
+15 -9
View File
@@ -25,7 +25,7 @@ namespace Ragon.Server.Room;
public class RagonRoom : IRagonRoom, IRagonAction
{
public string Id { get; private set; }
public string Map { get; private set; }
public string Scene { get; private set; }
public int PlayerMax { get; private set; }
public int PlayerMin { get; private set; }
public int PlayerCount => WaitPlayersList.Count;
@@ -49,7 +49,7 @@ public class RagonRoom : IRagonRoom, IRagonAction
public RagonRoom(string roomId, RoomInformation info, IRoomPlugin roomPlugin)
{
Id = roomId;
Map = info.Map;
Scene = info.Scene;
PlayerMax = info.Max;
PlayerMin = info.Min;
Plugin = roomPlugin;
@@ -182,7 +182,7 @@ public class RagonRoom : IRagonRoom, IRagonAction
public void UpdateMap(string sceneName)
{
Map = sceneName;
Scene = sceneName;
DynamicEntitiesList.Clear();
StaticEntitiesList.Clear();
@@ -200,10 +200,18 @@ public class RagonRoom : IRagonRoom, IRagonAction
_entitiesDirtySet.Add(entity);
}
public void Broadcast(byte[] data)
public void Broadcast(byte[] data, NetworkChannel channel = NetworkChannel.RELIABLE)
{
foreach (var readyPlayer in ReadyPlayersList)
readyPlayer.Connection.Reliable.Send(data);
if (channel == NetworkChannel.RELIABLE)
{
foreach (var readyPlayer in ReadyPlayersList)
readyPlayer.Connection.Reliable.Send(data);
}
else
{
foreach (var readyPlayer in ReadyPlayersList)
readyPlayer.Connection.Unreliable.Send(data);
}
}
public RagonRoomPlayer GetPlayerByConnection(INetworkConnection connection)
@@ -218,9 +226,7 @@ public class RagonRoom : IRagonRoom, IRagonAction
public IRagonEntity? GetEntityById(ushort id)
{
return Entities.TryGetValue(id, out var entity) ?
entity :
null;
return Entities.TryGetValue(id, out var entity) ? entity : null;
}
public IRagonEntity[] GetEntitiesOfPlayer(RagonRoomPlayer player)
@@ -18,7 +18,7 @@ namespace Ragon.Server;
public ref struct RoomInformation
{
public string Map;
public string Scene;
public int Min;
public int Max;
}
@@ -25,6 +25,7 @@ public class RagonRoomPlayer
public string Id { get; }
public string Name { get; }
public bool IsLoaded { get; private set; }
public double Timestamp { get; private set; }
public RagonRoom Room { get; private set; }
public RagonEntityCache Entities { get; private set; }
@@ -65,4 +66,9 @@ public class RagonRoomPlayer
{
IsLoaded = false;
}
internal void SetTimestamp(double time)
{
Timestamp = time;
}
}
@@ -6,6 +6,7 @@
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
<DockerDefaultTargetOS>Linux</DockerDefaultTargetOS>
<RootNamespace>Ragon.Client.Simulation</RootNamespace>
</PropertyGroup>
<ItemGroup>
@@ -15,6 +16,7 @@
<ItemGroup>
<PackageReference Include="ENet-CSharp" Version="2.4.8" />
<PackageReference Include="Raylib-cs" Version="4.5.0.4" />
</ItemGroup>
<ItemGroup>
@@ -23,4 +25,8 @@
</None>
</ItemGroup>
<ItemGroup>
<Folder Include="Sources\Server\" />
</ItemGroup>
</Project>
+143
View File
@@ -0,0 +1,143 @@
using System.Numerics;
using Raylib_cs;
using static Raylib_cs.Raylib;
namespace Ragon.Simulation;
public class Client
{
public void Start()
{
// Initialization
//--------------------------------------------------------------------------------------
const int screenWidth = 800;
const int screenHeight = 450;
InitWindow(screenWidth, screenHeight, "raylib [models] example - first person maze");
// Define the camera to look into our 3d world
Camera3D camera = new();
camera.Position = new Vector3(0.2f, 0.4f, 0.2f);
camera.Target = new Vector3(0.0f, 0.0f, 0.0f);
camera.Up = new Vector3(0.0f, 1.0f, 0.0f);
camera.FovY = 45.0f;
camera.Projection = CameraProjection.CAMERA_PERSPECTIVE;
Image imMap = LoadImage("resources/cubicmap.png");
Texture2D cubicmap = LoadTextureFromImage(imMap);
Mesh mesh = GenMeshCubicmap(imMap, new Vector3(1.0f, 1.0f, 1.0f));
Model model = LoadModelFromMesh(mesh);
// NOTE: By default each cube is mapped to one part of texture atlas
Texture2D texture = LoadTexture("resources/cubicmap_atlas.png");
// Set map diffuse texture
Raylib.SetMaterialTexture(ref model, 0, MaterialMapIndex.MATERIAL_MAP_ALBEDO, ref texture);
// Get map image data to be used for collision detection
Color* mapPixels = LoadImageColors(imMap);
UnloadImage(imMap);
Vector3 mapPosition = new(-16.0f, 0.0f, -8.0f);
Vector3 playerPosition = camera.Position;
SetTargetFPS(60);
//--------------------------------------------------------------------------------------
// Main game loop
while (!WindowShouldClose())
{
// Update
//----------------------------------------------------------------------------------
Vector3 oldCamPos = camera.Position;
UpdateCamera(ref camera, CameraMode.CAMERA_FIRST_PERSON);
// Check player collision (we simplify to 2D collision detection)
Vector2 playerPos = new(camera.Position.X, camera.Position.Z);
// Collision radius (player is modelled as a cilinder for collision)
float playerRadius = 0.1f;
int playerCellX = (int)(playerPos.X - mapPosition.X + 0.5f);
int playerCellY = (int)(playerPos.Y - mapPosition.Z + 0.5f);
// Out-of-limits security check
if (playerCellX < 0)
{
playerCellX = 0;
}
else if (playerCellX >= cubicmap.Width)
{
playerCellX = cubicmap.Width - 1;
}
if (playerCellY < 0)
{
playerCellY = 0;
}
else if (playerCellY >= cubicmap.Height)
{
playerCellY = cubicmap.Height - 1;
}
// Check map collisions using image data and player position
// TODO: Improvement: Just check player surrounding cells for collision
for (int y = 0; y < cubicmap.Height; y++)
{
for (int x = 0; x < cubicmap.Width; x++)
{
Color* mapPixelsData = mapPixels;
// Collision: Color.white pixel, only check R channel
Rectangle rec = new(
mapPosition.X - 0.5f + x * 1.0f,
mapPosition.Z - 0.5f + y * 1.0f,
1.0f,
1.0f
);
bool collision = CheckCollisionCircleRec(playerPos, playerRadius, rec);
if ((mapPixelsData[y * cubicmap.Width + x].R == 255) && collision)
{
// Collision detected, reset camera position
camera.Position = oldCamPos;
}
}
}
//----------------------------------------------------------------------------------
// Draw
//----------------------------------------------------------------------------------
BeginDrawing();
ClearBackground(Color.RAYWHITE);
// Draw maze map
BeginMode3D(camera);
DrawModel(model, mapPosition, 1.0f, Color.WHITE);
EndMode3D();
DrawTextureEx(cubicmap, new Vector2(GetScreenWidth() - cubicmap.Width * 4 - 20, 20), 0.0f, 4.0f, Color.WHITE);
DrawRectangleLines(GetScreenWidth() - cubicmap.Width * 4 - 20, 20, cubicmap.Width * 4, cubicmap.Height * 4, Color.GREEN);
// Draw player position radar
DrawRectangle(GetScreenWidth() - cubicmap.Width * 4 - 20 + playerCellX * 4, 20 + playerCellY * 4, 4, 4, Color.RED);
DrawFPS(10, 10);
EndDrawing();
//----------------------------------------------------------------------------------
}
// De-Initialization
//--------------------------------------------------------------------------------------
UnloadImageColors(mapPixels);
UnloadTexture(cubicmap);
UnloadTexture(texture);
UnloadModel(model);
CloseWindow();
//--------------------------------------------------------------------------------------
}
}
@@ -127,5 +127,10 @@ namespace Ragon.Client
if (_libraryLoaded)
Library.Deinitialize();
}
public void Close()
{
}
}
}

Some files were not shown because too many files have changed in this diff Show More