Compare commits
11 Commits
913af2a4a4
...
developmen
| Author | SHA1 | Date | |
|---|---|---|---|
| 785fee9b6b | |||
| 9f54f89f6d | |||
| aadc87d78a | |||
| d653774357 | |||
| 45bd505da7 | |||
| 3b1c291588 | |||
| 32a7e9be24 | |||
| 499f875903 | |||
| b2cfb2a590 | |||
| 1d6b9d2421 | |||
| 882f9e8b29 |
50
Engine.Core/Config/BasicConfiguration.cs
Normal file
50
Engine.Core/Config/BasicConfiguration.cs
Normal file
@@ -0,0 +1,50 @@
|
||||
using System.Collections.Generic;
|
||||
|
||||
namespace Engine.Core.Config;
|
||||
|
||||
public class BasicConfiguration : IConfiguration
|
||||
{
|
||||
public Event<IConfiguration, IConfiguration.ConfigUpdateArguments> OnAdded { get; } = new();
|
||||
public Event<IConfiguration, IConfiguration.ConfigUpdateArguments> OnSet { get; } = new();
|
||||
public Event<IConfiguration, IConfiguration.ConfigUpdateArguments> OnRemoved { get; } = new();
|
||||
|
||||
private readonly Dictionary<string, object?> values = [];
|
||||
|
||||
public IReadOnlyDictionary<string, object?> Values => values;
|
||||
|
||||
public T? Get<T>(string key, T? defaultValue = default)
|
||||
{
|
||||
if (!values.TryGetValue(key, out object? value))
|
||||
return defaultValue;
|
||||
|
||||
if (value is T castedObject)
|
||||
return castedObject;
|
||||
|
||||
try { return (T?)System.Convert.ChangeType(value, typeof(T)); } catch { }
|
||||
|
||||
return defaultValue;
|
||||
}
|
||||
|
||||
public object? Get(string key)
|
||||
{
|
||||
values.TryGetValue(key, out object? value);
|
||||
return value;
|
||||
}
|
||||
|
||||
public bool Has(string key) => values.ContainsKey(key);
|
||||
|
||||
public void Remove<T>(string key)
|
||||
{
|
||||
if (values.Remove(key))
|
||||
OnRemoved.Invoke(this, new(key));
|
||||
}
|
||||
|
||||
public void Set<T>(string key, T value)
|
||||
{
|
||||
if (!values.TryAdd(key, value))
|
||||
values[key] = value;
|
||||
else
|
||||
OnAdded.Invoke(this, new(key));
|
||||
OnSet.Invoke(this, new(key));
|
||||
}
|
||||
}
|
||||
8
Engine.Core/Config/ConfigurationExtensions.cs
Normal file
8
Engine.Core/Config/ConfigurationExtensions.cs
Normal file
@@ -0,0 +1,8 @@
|
||||
using Engine.Core.Exceptions;
|
||||
|
||||
namespace Engine.Core.Config;
|
||||
|
||||
public static class ConfigurationExtensions
|
||||
{
|
||||
public static T GetRequired<T>(this IConfiguration configuration, string key) => configuration.Get<T>(key) ?? throw new NotFoundException($"Type of {typeof(T).FullName} with the key {key} was not present in the {configuration.GetType().FullName}");
|
||||
}
|
||||
23
Engine.Core/Config/IConfiguration.cs
Normal file
23
Engine.Core/Config/IConfiguration.cs
Normal file
@@ -0,0 +1,23 @@
|
||||
using System.Collections.Generic;
|
||||
|
||||
namespace Engine.Core.Config;
|
||||
|
||||
public interface IConfiguration
|
||||
{
|
||||
static IConfiguration System { get; set; } = new SystemConfiguration();
|
||||
static IConfiguration Shared { get; set; } = new BasicConfiguration();
|
||||
|
||||
Event<IConfiguration, ConfigUpdateArguments> OnAdded { get; }
|
||||
Event<IConfiguration, ConfigUpdateArguments> OnSet { get; }
|
||||
Event<IConfiguration, ConfigUpdateArguments> OnRemoved { get; }
|
||||
|
||||
IReadOnlyDictionary<string, object?> Values { get; }
|
||||
|
||||
bool Has(string key);
|
||||
object? Get(string key);
|
||||
T? Get<T>(string key, T? defaultValue = default);
|
||||
void Set<T>(string key, T value);
|
||||
void Remove<T>(string key);
|
||||
|
||||
readonly record struct ConfigUpdateArguments(string Key);
|
||||
}
|
||||
11
Engine.Core/Config/SystemConfiguration.cs
Normal file
11
Engine.Core/Config/SystemConfiguration.cs
Normal file
@@ -0,0 +1,11 @@
|
||||
namespace Engine.Core.Config;
|
||||
|
||||
public class SystemConfiguration : BasicConfiguration, IConfiguration
|
||||
{
|
||||
public SystemConfiguration()
|
||||
{
|
||||
foreach (System.Collections.DictionaryEntry entry in System.Environment.GetEnvironmentVariables())
|
||||
if (entry is { Key: string key, Value: not null })
|
||||
Set(key, entry.Value);
|
||||
}
|
||||
}
|
||||
@@ -4,15 +4,15 @@ namespace Engine.Core.Serialization;
|
||||
|
||||
public interface ISerializer
|
||||
{
|
||||
object Deserialize(string configuration);
|
||||
object Deserialize(string configuration, Type type);
|
||||
T Deserialize<T>(string configuration);
|
||||
object Deserialize(string content);
|
||||
object Deserialize(string content, Type type);
|
||||
T Deserialize<T>(string content);
|
||||
|
||||
string Serialize(object instance);
|
||||
|
||||
ProgressiveTask<object> DeserializeAsync(string configuration);
|
||||
ProgressiveTask<object> DeserializeAsync(string configuration, Type type);
|
||||
ProgressiveTask<T> DeserializeAsync<T>(string configuration);
|
||||
ProgressiveTask<object> DeserializeAsync(string content);
|
||||
ProgressiveTask<object> DeserializeAsync(string content, Type type);
|
||||
ProgressiveTask<T> DeserializeAsync<T>(string content);
|
||||
|
||||
ProgressiveTask<string> SerializeAsync(object instance);
|
||||
}
|
||||
|
||||
10
Engine.Core/Systems/Yields/WaitForSecondsYield.cs
Normal file
10
Engine.Core/Systems/Yields/WaitForSecondsYield.cs
Normal file
@@ -0,0 +1,10 @@
|
||||
using System;
|
||||
|
||||
namespace Engine.Core;
|
||||
|
||||
public class WaitForSecondsYield(float seconds) : ICoroutineYield
|
||||
{
|
||||
private readonly DateTime triggerTime = DateTime.UtcNow.AddSeconds(seconds);
|
||||
|
||||
public bool Yield() => DateTime.UtcNow < triggerTime;
|
||||
}
|
||||
10
Engine.Core/Systems/Yields/WaitUntilYield.cs
Normal file
10
Engine.Core/Systems/Yields/WaitUntilYield.cs
Normal file
@@ -0,0 +1,10 @@
|
||||
using System;
|
||||
|
||||
namespace Engine.Core;
|
||||
|
||||
public class WaitUntilYield(Func<bool> condition) : ICoroutineYield
|
||||
{
|
||||
private readonly Func<bool> condition = condition;
|
||||
|
||||
public bool Yield() => !condition.Invoke();
|
||||
}
|
||||
@@ -2,7 +2,7 @@ using System;
|
||||
|
||||
namespace Engine.Core;
|
||||
|
||||
public class CoroutineYield(Func<bool> condition) : ICoroutineYield
|
||||
public class WaitWhileYield(Func<bool> condition) : ICoroutineYield
|
||||
{
|
||||
private readonly Func<bool> condition = condition;
|
||||
|
||||
@@ -48,8 +48,6 @@ public class MonoGameTriangleBatch : Behaviour, ITriangleBatch, IFirstFrameUpdat
|
||||
|
||||
public void Begin(Matrix4x4? view = null, Matrix4x4? projection = null)
|
||||
{
|
||||
Viewport viewport = graphicsDevice.Viewport;
|
||||
|
||||
this.view = (view ?? camera.ViewMatrix).Transposed.ToXnaMatrix();
|
||||
this.projection = (projection ?? camera.ProjectionMatrix).Transposed.ToXnaMatrix();
|
||||
}
|
||||
|
||||
@@ -0,0 +1,33 @@
|
||||
using System;
|
||||
|
||||
using Engine.Core;
|
||||
|
||||
using YamlDotNet.Core;
|
||||
using YamlDotNet.Core.Events;
|
||||
using YamlDotNet.Serialization;
|
||||
|
||||
namespace Engine.Serializers.Yaml;
|
||||
|
||||
public class Matrix4x4Converter : EngineTypeYamlSerializerBase<Matrix4x4>
|
||||
{
|
||||
private static readonly int SUBSTRING_START_LENGTH = nameof(Matrix4x4).Length + 1;
|
||||
|
||||
public override Matrix4x4 Read(IParser parser, Type type, ObjectDeserializer rootDeserializer)
|
||||
{
|
||||
string value = parser.Consume<Scalar>().Value;
|
||||
string insideParenthesis = value[SUBSTRING_START_LENGTH..^1];
|
||||
string[] values = insideParenthesis.Split(", ");
|
||||
return new Matrix4x4(
|
||||
float.Parse(values[0]), float.Parse(values[1]), float.Parse(values[2]), float.Parse(values[3]),
|
||||
float.Parse(values[4]), float.Parse(values[5]), float.Parse(values[6]), float.Parse(values[7]),
|
||||
float.Parse(values[8]), float.Parse(values[9]), float.Parse(values[10]), float.Parse(values[11]),
|
||||
float.Parse(values[12]), float.Parse(values[13]), float.Parse(values[14]), float.Parse(values[15])
|
||||
);
|
||||
}
|
||||
|
||||
public override void WriteYaml(IEmitter emitter, object? value, Type type, ObjectSerializer serializer)
|
||||
{
|
||||
Matrix4x4 m = (Matrix4x4)value!;
|
||||
emitter.Emit(new Scalar($"{nameof(Matrix4x4)}({m.M11}, {m.M12}, {m.M13}, {m.M14},{m.M21}, {m.M22}, {m.M23}, {m.M24},{m.M31}, {m.M32}, {m.M33}, {m.M34},{m.M41}, {m.M42}, {m.M43}, {m.M44})"));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,44 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
|
||||
using Engine.Core.Config;
|
||||
|
||||
namespace Engine.Serializers.Yaml;
|
||||
|
||||
public class YamlConfiguration : BasicConfiguration
|
||||
{
|
||||
public readonly string FilePath;
|
||||
|
||||
private readonly YamlSerializer yamlSerializer = new();
|
||||
|
||||
public YamlConfiguration(string filePath)
|
||||
{
|
||||
if (!filePath.EndsWith(".yaml"))
|
||||
filePath += ".yaml";
|
||||
|
||||
FilePath = filePath;
|
||||
|
||||
bool isRelativePath = Path.GetFullPath(filePath).CompareTo(filePath) != 0;
|
||||
|
||||
if (isRelativePath)
|
||||
FilePath = Path.GetFullPath(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, filePath));
|
||||
|
||||
if (Path.GetDirectoryName(FilePath) is string directoryPath)
|
||||
Directory.CreateDirectory(directoryPath);
|
||||
|
||||
if (!File.Exists(FilePath))
|
||||
return;
|
||||
|
||||
string yamlFileText = File.ReadAllText(FilePath);
|
||||
Dictionary<string, string> valuePairs = yamlSerializer.Deserialize<Dictionary<string, string>>(yamlFileText);
|
||||
|
||||
foreach ((string key, string value) in valuePairs)
|
||||
Set(key, value);
|
||||
}
|
||||
|
||||
public void Save()
|
||||
{
|
||||
File.WriteAllText(FilePath, yamlSerializer.Serialize(Values));
|
||||
}
|
||||
}
|
||||
@@ -62,65 +62,65 @@ public class YamlSerializer : Core.Serialization.ISerializer
|
||||
}
|
||||
}
|
||||
|
||||
public object Deserialize(string configuration)
|
||||
public object Deserialize(string content)
|
||||
{
|
||||
lock (Lock)
|
||||
{
|
||||
identifiableRegistry.Reset();
|
||||
object result = deserializer.Deserialize(configuration)!;
|
||||
object result = deserializer.Deserialize(content)!;
|
||||
identifiableRegistry.AssignAll();
|
||||
return result;
|
||||
}
|
||||
}
|
||||
|
||||
public object Deserialize(string configuration, Type type)
|
||||
public object Deserialize(string content, Type type)
|
||||
{
|
||||
lock (Lock)
|
||||
{
|
||||
identifiableRegistry.Reset();
|
||||
object result = deserializer.Deserialize(configuration, type)!;
|
||||
object result = deserializer.Deserialize(content, type)!;
|
||||
identifiableRegistry.AssignAll();
|
||||
return result;
|
||||
}
|
||||
}
|
||||
|
||||
public T Deserialize<T>(string configuration)
|
||||
public T Deserialize<T>(string content)
|
||||
{
|
||||
lock (Lock)
|
||||
{
|
||||
identifiableRegistry.Reset();
|
||||
T result = deserializer.Deserialize<T>(configuration);
|
||||
T result = deserializer.Deserialize<T>(content);
|
||||
identifiableRegistry.AssignAll();
|
||||
return result;
|
||||
}
|
||||
}
|
||||
|
||||
public ProgressiveTask<object> DeserializeAsync(string configuration)
|
||||
public ProgressiveTask<object> DeserializeAsync(string content)
|
||||
{
|
||||
lock (Lock)
|
||||
{
|
||||
progressionTracker.Reset();
|
||||
Task<object> task = Task.Run(() => Deserialize(configuration));
|
||||
Task<object> task = Task.Run(() => Deserialize(content));
|
||||
return new ProgressiveTask<object>(progressionTracker, task);
|
||||
}
|
||||
}
|
||||
|
||||
public ProgressiveTask<object> DeserializeAsync(string configuration, Type type)
|
||||
public ProgressiveTask<object> DeserializeAsync(string content, Type type)
|
||||
{
|
||||
lock (Lock)
|
||||
{
|
||||
progressionTracker.Reset();
|
||||
Task<object> task = Task.Run(() => Deserialize(configuration, type));
|
||||
Task<object> task = Task.Run(() => Deserialize(content, type));
|
||||
return new ProgressiveTask<object>(progressionTracker, task);
|
||||
}
|
||||
}
|
||||
|
||||
public ProgressiveTask<T> DeserializeAsync<T>(string configuration)
|
||||
public ProgressiveTask<T> DeserializeAsync<T>(string content)
|
||||
{
|
||||
lock (Lock)
|
||||
{
|
||||
progressionTracker.Reset();
|
||||
Task<T> task = Task.Run(() => Deserialize<T>(configuration));
|
||||
Task<T> task = Task.Run(() => Deserialize<T>(content));
|
||||
return new ProgressiveTask<T>(progressionTracker, task);
|
||||
}
|
||||
}
|
||||
@@ -135,8 +135,8 @@ public class YamlSerializer : Core.Serialization.ISerializer
|
||||
}
|
||||
}
|
||||
|
||||
internal object InternalDeserialize(string configuration, Type type)
|
||||
internal object InternalDeserialize(string content, Type type)
|
||||
{
|
||||
return deserializer.Deserialize(configuration, type)!;
|
||||
return deserializer.Deserialize(content, type)!;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -10,35 +10,127 @@ namespace Engine.Systems.Network;
|
||||
/// <summary>
|
||||
/// Intermediary manager that looks up in it's hierarchy for a <see cref="INetworkCommunicator"/> to route/broadcast it's received packets to their destinations.
|
||||
/// </summary>
|
||||
/// TODO: I urgently need to add proper comments on this manager, I don't exactly remember the state I was in when I was writing it.
|
||||
/// TODO: I need to peer check this class, I don't exactly remember the state I was in when I was originally writing it and left it uncommented and the current comments are added later on.
|
||||
/// It's a fairly complex manager that relies heavily on Reflection and lots of generic method delegation which is making it very hard to read back.
|
||||
public class NetworkManager : Behaviour, IEnterUniverse, IExitUniverse, INetworkManager
|
||||
{
|
||||
private readonly Dictionary<Type, Dictionary<Type, List<MethodInfo>>> clientBroadcastPacketArrivalMethods = [];
|
||||
private readonly Dictionary<Type, Dictionary<Type, List<MethodInfo>>> serverBroadcastPacketArrivalMethods = [];
|
||||
#region Packet Router/Broadcaster to Listener Delegates
|
||||
|
||||
private readonly Dictionary<Type, Dictionary<string, object>> clientBroadcastPacketRouters = [];
|
||||
private readonly Dictionary<Type, Dictionary<string, object>> serverBroadcastPacketRouters = [];
|
||||
/// <summary>
|
||||
/// Behaviour Type → Packet Type → List of <see cref="IPacketListenerClient{T}"/> listener methods (broadcast packets, client-side)
|
||||
/// </summary>
|
||||
private readonly Dictionary<Type, Dictionary<Type, List<MethodInfo>>> clientBroadcastPacketListenerMethods = [];
|
||||
|
||||
private readonly Dictionary<Type, Dictionary<Type, List<MethodInfo>>> clientEntityPacketArrivalMethods = [];
|
||||
private readonly Dictionary<Type, Dictionary<Type, List<MethodInfo>>> serverEntityPacketArrivalMethods = [];
|
||||
/// <summary>
|
||||
/// Behaviour Type → Packet Type → List of <see cref="IPacketListenerServer{T}"/> listener methods (broadcast packets, server-side)
|
||||
/// </summary>
|
||||
private readonly Dictionary<Type, Dictionary<Type, List<MethodInfo>>> serverBroadcastPacketListenerMethods = [];
|
||||
|
||||
private readonly Dictionary<Type, Dictionary<string, object>> clientEntityPacketRouters = [];
|
||||
private readonly Dictionary<Type, Dictionary<string, object>> serverEntityPacketRouters = [];
|
||||
/// <summary>
|
||||
/// Behaviour Type → Packet Type → List of <see cref="IPacketListenerClientEntity{T}"/> listener methods (entity packets, client-side)
|
||||
/// </summary>
|
||||
private readonly Dictionary<Type, Dictionary<Type, List<MethodInfo>>> clientEntityPacketListenerMethods = [];
|
||||
|
||||
private readonly List<(Type packetType, Delegate @delegate)> broadcastPacketRetrievalDelegates = [];
|
||||
private readonly List<(Type packetType, Delegate @delegate)> entityPacketRetrievalDelegates = [];
|
||||
/// <summary>
|
||||
/// Behaviour Type → Packet Type → List of <see cref="IPacketListenerServerEntity{T}"/> listener methods (entity packets, server-side)
|
||||
/// </summary>
|
||||
private readonly Dictionary<Type, Dictionary<Type, List<MethodInfo>>> serverEntityPacketListenerMethods = [];
|
||||
|
||||
#endregion
|
||||
|
||||
#region Packet Router/Broadcaster Events
|
||||
|
||||
/// <summary>
|
||||
/// Packet Type → Behaviour.Id → Broadcaster Event (broadcast, client-side)
|
||||
/// </summary>
|
||||
private readonly Dictionary<Type, Dictionary<string, object>> clientPacketBroadcastEvents = [];
|
||||
|
||||
/// <summary>
|
||||
/// Packet Type → Behaviour.Id → Broadcaster Event (broadcast, server-side)
|
||||
/// </summary>
|
||||
private readonly Dictionary<Type, Dictionary<string, object>> serverPacketBroadcastEvents = [];
|
||||
|
||||
/// <summary>
|
||||
/// Maps an <see cref="IEntityNetworkPacket"/> type to a set of routing events,
|
||||
/// keyed by <see cref="IIdentifiable.Id"/>, for CLIENT entity listeners.
|
||||
/// The packet is routed to the correct <see cref="INetworkEntity"/> instance
|
||||
/// by matching <see cref="IEntityNetworkPacket.EntityId"/>.
|
||||
/// </summary>
|
||||
private readonly Dictionary<Type, Dictionary<string, object>> clientEntityPacketRouterEvents = [];
|
||||
|
||||
/// <summary>
|
||||
/// Maps an <see cref="IEntityNetworkPacket"/> type to a set of routing events,
|
||||
/// keyed by <see cref="IIdentifiable.Id"/>, for SERVER entity listeners.
|
||||
/// The packet is routed to the correct <see cref="INetworkEntity"/> instance
|
||||
/// by matching <see cref="IEntityNetworkPacket.EntityId"/>.
|
||||
/// </summary>
|
||||
private readonly Dictionary<Type, Dictionary<string, object>> serverEntityPacketRouterEvents = [];
|
||||
|
||||
#endregion
|
||||
|
||||
#region Packet Retrieval Delegates
|
||||
|
||||
/// <summary>
|
||||
/// Stores delegates that connect incoming broadcast packets from <see cref="INetworkCommunicator"/>
|
||||
/// to <see cref="OnPacketReceived{T}(IConnection, T)"/>.
|
||||
/// These are used to subscribe/unsubscribe from <see cref="INetworkCommunicator"/> events.
|
||||
/// </summary>
|
||||
private readonly List<PacketRetrievalDelegatePair> broadcastPacketRetrievalSubscriptionDelegates = [];
|
||||
|
||||
/// <summary>
|
||||
/// Stores delegates that connect incoming entity packets from <see cref="INetworkCommunicator"/>
|
||||
/// to <see cref="OnPacketReceived{T}(IConnection, T)"/>.
|
||||
/// These are used to subscribe/unsubscribe from <see cref="INetworkCommunicator"/> events.
|
||||
/// </summary>
|
||||
private readonly List<PacketRetrievalDelegatePair> entityPacketRetrievalSubscriptionDelegates = [];
|
||||
|
||||
/// <summary>
|
||||
/// Stores delegates that connect incoming all packets from <see cref="INetworkCommunicator"/> to
|
||||
/// <see cref="OnPacketReceived{T}(IConnection, T)"/>. This is a combination of all subscription
|
||||
/// delegates filtered so there are no duplicates packet entries.
|
||||
/// </summary>
|
||||
private readonly List<PacketRetrievalDelegatePair> uniqueRetrievalSubscriptionDelegates = [];
|
||||
|
||||
#endregion
|
||||
|
||||
#region Method Caches
|
||||
|
||||
/// <summary>
|
||||
/// Packet type → <see cref="ClearRouter{T}(object)"/> method.
|
||||
/// </summary>
|
||||
private readonly Dictionary<Type, MethodInfo> clearRoutesMethods = [];
|
||||
|
||||
/// <summary>
|
||||
/// Packet type → <see cref="RegisterBroadcastPacketListenerEvent{T}(INetworkEntity, Event{IConnection, T}, NetworkType)"/> method.
|
||||
/// </summary>
|
||||
private readonly Dictionary<Type, MethodInfo> registerBroadcastPacketListenersMethods = [];
|
||||
|
||||
/// <summary>
|
||||
/// Packet type → <see cref="RegisterEntityPacketListenerEvent{T}(INetworkEntity, Event{IConnection, T}, NetworkType)"/> method.
|
||||
/// </summary>
|
||||
private readonly Dictionary<Type, MethodInfo> registerEntityPacketListenersMethods = [];
|
||||
|
||||
#endregion
|
||||
|
||||
#region Network Entity Collector
|
||||
|
||||
/// <summary>
|
||||
/// All active network <see cref="INetworkEntity"/>, keyed by <see cref="IIdentifiable.Id"/>.
|
||||
/// </summary>
|
||||
private readonly Dictionary<string, INetworkEntity> _networkEntities = [];
|
||||
public IReadOnlyDictionary<string, INetworkEntity> NetworkEntities => _networkEntities;
|
||||
|
||||
/// <summary>
|
||||
/// Collector responsible for detecting <see cref="INetworkEntity"/>s entering/leaving the universe.
|
||||
/// </summary>
|
||||
private readonly BehaviourCollector<INetworkEntity> _networkEntityCollector = new();
|
||||
|
||||
public IBehaviourCollector<INetworkEntity> NetworkEntityCollector => _networkEntityCollector;
|
||||
|
||||
#endregion
|
||||
|
||||
#region Network Communicator
|
||||
|
||||
public INetworkCommunicator NetworkCommunicator
|
||||
{
|
||||
get;
|
||||
@@ -50,34 +142,46 @@ public class NetworkManager : Behaviour, IEnterUniverse, IExitUniverse, INetwork
|
||||
INetworkCommunicator? previousCommunicator = field;
|
||||
field = value;
|
||||
|
||||
if (previousCommunicator is not null) InvokeCommunicatorMethods(previousCommunicator, nameof(INetworkCommunicator.UnsubscribeFromPackets));
|
||||
if (field is not null) InvokeCommunicatorMethods(field, nameof(INetworkCommunicator.SubscribeToPackets));
|
||||
// Unsubscribe packet delegates from old communicator
|
||||
if (previousCommunicator is not null)
|
||||
InvokeCommunicatorMethods(nameof(INetworkCommunicator.UnsubscribeFromPackets), previousCommunicator);
|
||||
|
||||
// Subscribe packet delegates to new communicator
|
||||
if (field is not null)
|
||||
InvokeCommunicatorMethods(nameof(INetworkCommunicator.SubscribeToPackets), field);
|
||||
}
|
||||
} = null!;
|
||||
|
||||
/// Used to delegate subscription and unsubscription methods on the <see cref="INetworkCommunicator"/> to <see cref="OnPacketReceived{T}(IConnection, T)"/>.
|
||||
private void InvokeCommunicatorMethods(INetworkCommunicator networkCommunicator, string name)
|
||||
/// <summary>
|
||||
/// Dynamically invokes <see cref="INetworkCommunicator.SubscribeToPackets{T}(Event{IConnection, T}.EventHandler)"/>
|
||||
/// or <see cref="INetworkCommunicator.UnsubscribeFromPackets{T}(Event{IConnection, T}.EventHandler)"/>
|
||||
/// on the provided <see cref="INetworkCommunicator"/> for all known packet types.
|
||||
/// </summary>
|
||||
private void InvokeCommunicatorMethods(string methodName, INetworkCommunicator networkCommunicator)
|
||||
{
|
||||
MethodInfo unsubscribeFromPacketsMethod = typeof(INetworkCommunicator)
|
||||
.GetMethod(name, BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance)!;
|
||||
.GetMethod(methodName, BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance)!;
|
||||
|
||||
/// Get unique entries by the packetType so we don't get duplicate calls to <see cref="OnPacketReceived{T}(IConnection, T)"/>
|
||||
/// Because a class might have both <see cref="IPacketListenerClient{T}"/> and <see cref="IPacketListenerClientEntity{T}"/>
|
||||
/// or <see cref="IPacketListenerServer{T}"/> and <see cref="IPacketListenerServerEntity{T}"/> together.
|
||||
IEnumerable<(Type packetType, Delegate @delegate)> distinctRetrievalSubscriptionDelegates =
|
||||
broadcastPacketRetrievalDelegates.Concat(entityPacketRetrievalDelegates).DistinctBy(pair => pair.packetType);
|
||||
|
||||
foreach ((Type packetType, Delegate @delegate) in distinctRetrievalSubscriptionDelegates)
|
||||
foreach ((Type packetType, Delegate @delegate) in uniqueRetrievalSubscriptionDelegates)
|
||||
{
|
||||
MethodInfo genericMethod = unsubscribeFromPacketsMethod.MakeGenericMethod(packetType);
|
||||
genericMethod.Invoke(networkCommunicator, [@delegate]);
|
||||
}
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
////////////////////////////////////////////////////////////////
|
||||
|
||||
#region Packet Routing/Broadcasting
|
||||
|
||||
/// <summary>
|
||||
/// Entry point for ALL incoming packets from the <see cref="NetworkCommunicator"/>.
|
||||
/// </summary>
|
||||
private void OnPacketReceived<T>(IConnection sender, T entityDataPacket)
|
||||
{
|
||||
BroadcastPacket(sender, entityDataPacket);
|
||||
|
||||
if (entityDataPacket is IEntityNetworkPacket entityPacket)
|
||||
RoutePacket(sender, entityDataPacket, entityPacket);
|
||||
}
|
||||
@@ -85,25 +189,27 @@ public class NetworkManager : Behaviour, IEnterUniverse, IExitUniverse, INetwork
|
||||
private void RoutePacket<T>(IConnection sender, T entityDataPacket, IEntityNetworkPacket entityPacket)
|
||||
{
|
||||
if (NetworkCommunicator is INetworkCommunicatorClient)
|
||||
RoutePacket(clientEntityPacketRouters, entityPacket.EntityId, sender, entityDataPacket);
|
||||
RoutePacket(clientEntityPacketRouterEvents, entityPacket.EntityId, sender, entityDataPacket);
|
||||
|
||||
if (NetworkCommunicator is INetworkCommunicatorServer)
|
||||
RoutePacket(serverEntityPacketRouters, entityPacket.EntityId, sender, entityDataPacket);
|
||||
RoutePacket(serverEntityPacketRouterEvents, entityPacket.EntityId, sender, entityDataPacket);
|
||||
}
|
||||
|
||||
private void BroadcastPacket<T>(IConnection sender, T entityDataPacket)
|
||||
{
|
||||
if (NetworkCommunicator is INetworkCommunicatorClient)
|
||||
BroadcastPacket(clientBroadcastPacketRouters, sender, entityDataPacket);
|
||||
BroadcastPacket(clientPacketBroadcastEvents, sender, entityDataPacket);
|
||||
|
||||
if (NetworkCommunicator is INetworkCommunicatorServer)
|
||||
BroadcastPacket(serverBroadcastPacketRouters, sender, entityDataPacket);
|
||||
BroadcastPacket(serverPacketBroadcastEvents, sender, entityDataPacket);
|
||||
}
|
||||
|
||||
private void BroadcastPacket<T>(
|
||||
Dictionary<Type, Dictionary<string, object>> packetRouters,
|
||||
Dictionary<Type, Dictionary<string, object>> packetBroadcasters,
|
||||
IConnection sender,
|
||||
T entityDataPacket)
|
||||
{
|
||||
if (!packetRouters.TryGetValue(entityDataPacket!.GetType(), out Dictionary<string, object>? routers))
|
||||
if (!packetBroadcasters.TryGetValue(entityDataPacket!.GetType(), out Dictionary<string, object>? routers))
|
||||
return;
|
||||
|
||||
foreach ((string behaviourId, object routerEventReference) in routers)
|
||||
@@ -128,19 +234,25 @@ public class NetworkManager : Behaviour, IEnterUniverse, IExitUniverse, INetwork
|
||||
Event<IConnection, T> routerEvent = (Event<IConnection, T>)routerEventReference;
|
||||
routerEvent.Invoke(sender, entityDataPacket!);
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
#region Packet Routers
|
||||
|
||||
/// <summary>
|
||||
/// Registers routing events for the behaviour based on cached packet listener methods.
|
||||
/// </summary>
|
||||
private void RegisterPacketRoutersFor(
|
||||
INetworkEntity behaviour,
|
||||
Dictionary<Type, Dictionary<string, object>> packetRouters,
|
||||
Dictionary<Type, Dictionary<Type, List<MethodInfo>>> packetArrivalMethods,
|
||||
NetworkType networkType, Dictionary<Type, MethodInfo> registerPacketListenersMethods)
|
||||
Dictionary<Type, Dictionary<Type, List<MethodInfo>>> packetListenerMethods,
|
||||
NetworkType networkType,
|
||||
Dictionary<Type, MethodInfo> registerPacketListenerListenersMethods)
|
||||
{
|
||||
if (!packetArrivalMethods.TryGetValue(behaviour.GetType(), out Dictionary<Type, List<MethodInfo>>? arrivalMethods))
|
||||
if (!packetListenerMethods.TryGetValue(behaviour.GetType(), out Dictionary<Type, List<MethodInfo>>? listenerMethods))
|
||||
return;
|
||||
|
||||
foreach (Type packetType in arrivalMethods.Keys)
|
||||
foreach (Type packetType in listenerMethods.Keys)
|
||||
{
|
||||
if (!packetRouters.TryGetValue(packetType, out Dictionary<string, object>? routers))
|
||||
{
|
||||
@@ -148,14 +260,20 @@ public class NetworkManager : Behaviour, IEnterUniverse, IExitUniverse, INetwork
|
||||
packetRouters.Add(packetType, routers);
|
||||
}
|
||||
|
||||
object packetListenerEvent =
|
||||
CreateEventAndRegister(packetType, behaviour, networkType, registerPacketListenersMethods);
|
||||
object packetListenerEvent = CreateEventAndRegister(packetType, behaviour, networkType, registerPacketListenerListenersMethods);
|
||||
|
||||
routers.Add(behaviour.Id, packetListenerEvent);
|
||||
}
|
||||
}
|
||||
|
||||
private object CreateEventAndRegister(Type packetType, INetworkEntity behaviour, NetworkType networkType, Dictionary<Type, MethodInfo> registerPacketListenersMethods)
|
||||
/// <summary>
|
||||
/// Creates an Event<IConnection, TPacket> and attaches listener callbacks.
|
||||
/// </summary>
|
||||
private object CreateEventAndRegister(
|
||||
Type packetType,
|
||||
INetworkEntity behaviour,
|
||||
NetworkType networkType,
|
||||
Dictionary<Type, MethodInfo> registerPacketListenersMethods)
|
||||
{
|
||||
Type genericEventType = typeof(Event<,>).MakeGenericType(typeof(IConnection), packetType);
|
||||
object packetListenerEvent = Activator.CreateInstance(genericEventType)!;
|
||||
@@ -167,18 +285,31 @@ public class NetworkManager : Behaviour, IEnterUniverse, IExitUniverse, INetwork
|
||||
return packetListenerEvent;
|
||||
}
|
||||
|
||||
private static void RegisterPacketListenerEvent<T>(
|
||||
/// <summary>
|
||||
/// Registers broadcast packet listeners on the behaviour.
|
||||
/// </summary>
|
||||
private static void RegisterBroadcastPacketListenerEvent<T>(
|
||||
INetworkEntity behaviour,
|
||||
Event<IConnection, T> packetListenerEvent,
|
||||
NetworkType networkType)
|
||||
{
|
||||
switch (networkType)
|
||||
{
|
||||
case NetworkType.Client: packetListenerEvent.AddListener((sender, packet) => ((IPacketListenerClient<T>)behaviour).OnClientPacketArrived(sender, packet)); break;
|
||||
case NetworkType.Server: packetListenerEvent.AddListener((sender, packet) => ((IPacketListenerServer<T>)behaviour).OnServerPacketArrived(sender, packet)); break;
|
||||
case NetworkType.Client:
|
||||
packetListenerEvent.AddListener(
|
||||
(sender, packet) => ((IPacketListenerClient<T>)behaviour).OnClientPacketArrived(sender, packet));
|
||||
break;
|
||||
|
||||
case NetworkType.Server:
|
||||
packetListenerEvent.AddListener(
|
||||
(sender, packet) => ((IPacketListenerServer<T>)behaviour).OnServerPacketArrived(sender, packet));
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Registers entity-specific packet listeners on a network behaviour.
|
||||
/// </summary>
|
||||
private static void RegisterEntityPacketListenerEvent<T>(
|
||||
INetworkEntity behaviour,
|
||||
Event<IConnection, T> packetListenerEvent,
|
||||
@@ -187,20 +318,30 @@ public class NetworkManager : Behaviour, IEnterUniverse, IExitUniverse, INetwork
|
||||
{
|
||||
switch (networkType)
|
||||
{
|
||||
case NetworkType.Client: packetListenerEvent.AddListener((sender, packet) => ((IPacketListenerClientEntity<T>)behaviour).OnEntityClientPacketArrived(sender, packet)); break;
|
||||
case NetworkType.Server: packetListenerEvent.AddListener((sender, packet) => ((IPacketListenerServerEntity<T>)behaviour).OnEntityServerPacketArrived(sender, packet)); break;
|
||||
case NetworkType.Client:
|
||||
packetListenerEvent.AddListener(
|
||||
(sender, packet) => ((IPacketListenerClientEntity<T>)behaviour).OnEntityClientPacketArrived(sender, packet));
|
||||
break;
|
||||
|
||||
case NetworkType.Server:
|
||||
packetListenerEvent.AddListener(
|
||||
(sender, packet) => ((IPacketListenerServerEntity<T>)behaviour).OnEntityServerPacketArrived(sender, packet));
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Unregisters all routing events associated with the behaviour.
|
||||
/// </summary>
|
||||
private void UnregisterPacketRoutersFor(
|
||||
INetworkEntity behaviour,
|
||||
Dictionary<Type, Dictionary<string, object>> packetRouters,
|
||||
Dictionary<Type, Dictionary<Type, List<MethodInfo>>> packetArrivalMethods)
|
||||
Dictionary<Type, Dictionary<Type, List<MethodInfo>>> packetListenerMethods)
|
||||
{
|
||||
if (!packetArrivalMethods.TryGetValue(behaviour.GetType(), out Dictionary<Type, List<MethodInfo>>? arrivalMethods))
|
||||
if (!packetListenerMethods.TryGetValue(behaviour.GetType(), out Dictionary<Type, List<MethodInfo>>? listenerMethods))
|
||||
return;
|
||||
|
||||
foreach ((Type packetType, List<MethodInfo> methods) in arrivalMethods)
|
||||
foreach ((Type packetType, List<MethodInfo> methods) in listenerMethods)
|
||||
{
|
||||
if (!packetRouters.TryGetValue(packetType, out Dictionary<string, object>? routers))
|
||||
continue;
|
||||
@@ -215,6 +356,9 @@ public class NetworkManager : Behaviour, IEnterUniverse, IExitUniverse, INetwork
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Clears all listeners from a router event.
|
||||
/// </summary>
|
||||
private static void ClearRouter<T>(object routerEventReference)
|
||||
{
|
||||
Event<IConnection, T> routerEvent = (Event<IConnection, T>)routerEventReference;
|
||||
@@ -224,133 +368,192 @@ public class NetworkManager : Behaviour, IEnterUniverse, IExitUniverse, INetwork
|
||||
#endregion
|
||||
|
||||
#region Engine Callbacks
|
||||
private void OnCollected(IBehaviourCollector<INetworkEntity> sender, IBehaviourCollector<INetworkEntity>.BehaviourCollectedArguments args)
|
||||
|
||||
/// <summary>
|
||||
/// Called when an <see cref="INetworkEntity"/> enters the universe.
|
||||
/// Registers all packet routing for that entity.
|
||||
/// </summary>
|
||||
private void OnCollected(
|
||||
IBehaviourCollector<INetworkEntity> sender,
|
||||
IBehaviourCollector<INetworkEntity>.BehaviourCollectedArguments args)
|
||||
{
|
||||
INetworkEntity collectedBehaviour = args.BehaviourCollected;
|
||||
|
||||
if (!_networkEntities.TryAdd(collectedBehaviour.Id, collectedBehaviour))
|
||||
throw new($"Unable to add {collectedBehaviour.Id} to {nameof(NetworkManager)}");
|
||||
|
||||
RegisterPacketRoutersFor(collectedBehaviour, clientBroadcastPacketRouters, clientBroadcastPacketArrivalMethods, NetworkType.Client, registerBroadcastPacketListenersMethods);
|
||||
RegisterPacketRoutersFor(collectedBehaviour, clientEntityPacketRouters, clientEntityPacketArrivalMethods, NetworkType.Client, registerEntityPacketListenersMethods);
|
||||
RegisterPacketRoutersFor(collectedBehaviour, clientPacketBroadcastEvents, clientBroadcastPacketListenerMethods, NetworkType.Client, registerBroadcastPacketListenersMethods);
|
||||
RegisterPacketRoutersFor(collectedBehaviour, clientEntityPacketRouterEvents, clientEntityPacketListenerMethods, NetworkType.Client, registerEntityPacketListenersMethods);
|
||||
|
||||
RegisterPacketRoutersFor(collectedBehaviour, serverBroadcastPacketRouters, serverBroadcastPacketArrivalMethods, NetworkType.Server, registerBroadcastPacketListenersMethods);
|
||||
RegisterPacketRoutersFor(collectedBehaviour, serverEntityPacketRouters, serverEntityPacketArrivalMethods, NetworkType.Server, registerEntityPacketListenersMethods);
|
||||
RegisterPacketRoutersFor(collectedBehaviour, serverPacketBroadcastEvents, serverBroadcastPacketListenerMethods, NetworkType.Server, registerBroadcastPacketListenersMethods);
|
||||
RegisterPacketRoutersFor(collectedBehaviour, serverEntityPacketRouterEvents, serverEntityPacketListenerMethods, NetworkType.Server, registerEntityPacketListenersMethods);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Called when an <see cref="INetworkEntity"/> is removed from the universe.
|
||||
/// Cleans up all routing.
|
||||
/// </summary>
|
||||
private void OnRemoved(IBehaviourCollector<INetworkEntity> sender, IBehaviourCollector<INetworkEntity>.BehaviourRemovedArguments args)
|
||||
{
|
||||
INetworkEntity removedBehaviour = args.BehaviourRemoved;
|
||||
if (!_networkEntities.Remove(args.BehaviourRemoved.Id))
|
||||
|
||||
if (!_networkEntities.Remove(removedBehaviour.Id))
|
||||
return;
|
||||
|
||||
UnregisterPacketRoutersFor(removedBehaviour, clientBroadcastPacketRouters, clientBroadcastPacketArrivalMethods);
|
||||
UnregisterPacketRoutersFor(removedBehaviour, clientEntityPacketRouters, clientEntityPacketArrivalMethods);
|
||||
UnregisterPacketRoutersFor(removedBehaviour, clientPacketBroadcastEvents, clientBroadcastPacketListenerMethods);
|
||||
UnregisterPacketRoutersFor(removedBehaviour, clientEntityPacketRouterEvents, clientEntityPacketListenerMethods);
|
||||
|
||||
UnregisterPacketRoutersFor(removedBehaviour, serverBroadcastPacketRouters, serverBroadcastPacketArrivalMethods);
|
||||
UnregisterPacketRoutersFor(removedBehaviour, serverEntityPacketRouters, serverEntityPacketArrivalMethods);
|
||||
UnregisterPacketRoutersFor(removedBehaviour, serverPacketBroadcastEvents, serverBroadcastPacketListenerMethods);
|
||||
UnregisterPacketRoutersFor(removedBehaviour, serverEntityPacketRouterEvents, serverEntityPacketListenerMethods);
|
||||
}
|
||||
|
||||
public void ExitUniverse(IUniverse universe) => _networkEntityCollector.Unassign();
|
||||
|
||||
public void EnterUniverse(IUniverse universe)
|
||||
{
|
||||
_networkEntityCollector.Assign(universe);
|
||||
NetworkCommunicator = BehaviourController.GetRequiredBehaviourInParent<INetworkCommunicator>();
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
#region Initialization
|
||||
|
||||
public NetworkManager()
|
||||
{
|
||||
CachePacketRetrievalDelegates(typeof(INetworkPacket), broadcastPacketRetrievalDelegates);
|
||||
CachePacketRetrievalDelegates(typeof(IEntityNetworkPacket), entityPacketRetrievalDelegates);
|
||||
CacheRetrievalSubscriptionDelegates();
|
||||
CacheRegistrationMethods();
|
||||
CachePacketArrivalMethods();
|
||||
CachePacketListenerMethods();
|
||||
|
||||
_networkEntityCollector.OnCollected.AddListener(OnCollected);
|
||||
_networkEntityCollector.OnRemoved.AddListener(OnRemoved);
|
||||
}
|
||||
|
||||
private void CachePacketRetrievalDelegates(Type packetType, List<(Type packetType, Delegate @delegate)> retrievalDelegates)
|
||||
/// <summary>
|
||||
/// Caches all retrieval subscription delegates for packets.
|
||||
/// </summary>
|
||||
private void CacheRetrievalSubscriptionDelegates()
|
||||
{
|
||||
IEnumerable<Type> packetTypes = AppDomain.CurrentDomain.GetAssemblies().SelectMany(a => a.GetTypes())
|
||||
.Where(t => packetType.IsAssignableFrom(t) && !t.IsInterface && !t.IsAbstract && !t.IsGenericType);
|
||||
CachePacketRetrievalDelegates(typeof(INetworkPacket), broadcastPacketRetrievalSubscriptionDelegates);
|
||||
CachePacketRetrievalDelegates(typeof(IEntityNetworkPacket), entityPacketRetrievalSubscriptionDelegates);
|
||||
|
||||
MethodInfo onPacketArrivedMethod = GetType()
|
||||
.GetMethod(nameof(OnPacketReceived), BindingFlags.NonPublic | BindingFlags.Instance)!;
|
||||
uniqueRetrievalSubscriptionDelegates.AddRange(broadcastPacketRetrievalSubscriptionDelegates.Concat(entityPacketRetrievalSubscriptionDelegates).DistinctBy(pair => pair.PacketType));
|
||||
}
|
||||
|
||||
foreach (Type pType in packetTypes)
|
||||
/// <summary>
|
||||
/// Creates delegates for all concrete packet types that forward packets to <see cref="OnPacketReceived{T}(IConnection, T)"/>.
|
||||
/// </summary>
|
||||
private void CachePacketRetrievalDelegates(Type packetType, List<PacketRetrievalDelegatePair> retrievalDelegates)
|
||||
{
|
||||
IEnumerable<Type> packetTypes =
|
||||
AppDomain.CurrentDomain.GetAssemblies()
|
||||
.SelectMany(a => a.GetTypes())
|
||||
.Where(t =>
|
||||
packetType.IsAssignableFrom(t) &&
|
||||
!t.IsInterface &&
|
||||
!t.IsAbstract &&
|
||||
!t.IsGenericType
|
||||
);
|
||||
|
||||
MethodInfo onPacketArrivedMethod = GetType().GetMethod(nameof(OnPacketReceived), BindingFlags.NonPublic | BindingFlags.Instance)!;
|
||||
|
||||
foreach (Type type in packetTypes)
|
||||
{
|
||||
MethodInfo genericOnPacketArrivedMethod = onPacketArrivedMethod.MakeGenericMethod(pType);
|
||||
MethodInfo genericOnPacketArrivedMethod = onPacketArrivedMethod.MakeGenericMethod(type);
|
||||
|
||||
Type genericDelegateType = typeof(Event<,>.EventHandler).MakeGenericType(typeof(IConnection), type);
|
||||
|
||||
Type genericDelegateType = typeof(Event<,>.EventHandler).MakeGenericType(typeof(IConnection), pType);
|
||||
Delegate genericPacketReceivedDelegate = Delegate.CreateDelegate(genericDelegateType, this, genericOnPacketArrivedMethod);
|
||||
retrievalDelegates.Add((pType, genericPacketReceivedDelegate));
|
||||
|
||||
retrievalDelegates.Add((type, genericPacketReceivedDelegate));
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Caches all registration and cleanup methods for packets.
|
||||
/// </summary>
|
||||
private void CacheRegistrationMethods()
|
||||
{
|
||||
CacheRegistrationMethods(registerBroadcastPacketListenersMethods, nameof(RegisterPacketListenerEvent), broadcastPacketRetrievalDelegates);
|
||||
CacheRegistrationMethods(registerEntityPacketListenersMethods, nameof(RegisterEntityPacketListenerEvent), entityPacketRetrievalDelegates);
|
||||
CacheRegistrationMethods(clearRoutesMethods, nameof(ClearRouter), broadcastPacketRetrievalDelegates);
|
||||
CacheRegistrationMethods(registerBroadcastPacketListenersMethods, nameof(RegisterBroadcastPacketListenerEvent), broadcastPacketRetrievalSubscriptionDelegates);
|
||||
CacheRegistrationMethods(registerEntityPacketListenersMethods, nameof(RegisterEntityPacketListenerEvent), entityPacketRetrievalSubscriptionDelegates);
|
||||
CacheRegistrationMethods(clearRoutesMethods, nameof(ClearRouter), uniqueRetrievalSubscriptionDelegates);
|
||||
}
|
||||
|
||||
private void CacheRegistrationMethods(Dictionary<Type, MethodInfo> registrationMethods, string methodName, List<(Type packetType, Delegate @delegate)> packetRetrievalDelegates)
|
||||
/// <summary>
|
||||
/// Creates generic method instances for each packet type listener to be registered into the <see cref="NetworkEntity"/>.
|
||||
/// </summary>
|
||||
private void CacheRegistrationMethods(
|
||||
Dictionary<Type, MethodInfo> listenerRegistrationMethods,
|
||||
string methodName,
|
||||
List<PacketRetrievalDelegatePair> packetRetrievalDelegates)
|
||||
{
|
||||
MethodInfo registerPacketMethod = typeof(NetworkManager).GetMethod(methodName, BindingFlags.NonPublic | BindingFlags.Static)!;
|
||||
|
||||
foreach ((Type packetType, Delegate @delegate) in packetRetrievalDelegates)
|
||||
{
|
||||
MethodInfo genericMethod = registerPacketMethod.MakeGenericMethod(packetType);
|
||||
registrationMethods.TryAdd(packetType, genericMethod);
|
||||
listenerRegistrationMethods.TryAdd(packetType, genericMethod);
|
||||
}
|
||||
}
|
||||
|
||||
private void CachePacketArrivalMethods()
|
||||
/// <summary>
|
||||
/// Caches packet listener methods for all packet listener interfaces.
|
||||
/// </summary>
|
||||
private void CachePacketListenerMethods()
|
||||
{
|
||||
CachePacketArrivalMethods(clientBroadcastPacketArrivalMethods, typeof(IPacketListenerClient<>), nameof(IPacketListenerClient<>.OnClientPacketArrived));
|
||||
CachePacketArrivalMethods(serverBroadcastPacketArrivalMethods, typeof(IPacketListenerServer<>), nameof(IPacketListenerServer<>.OnServerPacketArrived));
|
||||
CachePacketArrivalMethods(clientEntityPacketArrivalMethods, typeof(IPacketListenerClientEntity<>), nameof(IPacketListenerClientEntity<>.OnEntityClientPacketArrived));
|
||||
CachePacketArrivalMethods(serverEntityPacketArrivalMethods, typeof(IPacketListenerServerEntity<>), nameof(IPacketListenerServerEntity<>.OnEntityServerPacketArrived));
|
||||
CachePacketListenerMethods(clientBroadcastPacketListenerMethods, typeof(IPacketListenerClient<>), nameof(IPacketListenerClient<>.OnClientPacketArrived));
|
||||
CachePacketListenerMethods(serverBroadcastPacketListenerMethods, typeof(IPacketListenerServer<>), nameof(IPacketListenerServer<>.OnServerPacketArrived));
|
||||
CachePacketListenerMethods(clientEntityPacketListenerMethods, typeof(IPacketListenerClientEntity<>), nameof(IPacketListenerClientEntity<>.OnEntityClientPacketArrived));
|
||||
CachePacketListenerMethods(serverEntityPacketListenerMethods, typeof(IPacketListenerServerEntity<>), nameof(IPacketListenerServerEntity<>.OnEntityServerPacketArrived));
|
||||
}
|
||||
|
||||
private static void CachePacketArrivalMethods(Dictionary<Type, Dictionary<Type, List<MethodInfo>>> packetArrivalMethods, Type listenerType, string packetArrivalMethodName)
|
||||
/// <summary>
|
||||
/// Discovers all types implementing a given packet listener interface and caches their methods.
|
||||
/// </summary>
|
||||
private static void CachePacketListenerMethods(
|
||||
Dictionary<Type, Dictionary<Type, List<MethodInfo>>> packetListenerMethods,
|
||||
Type listenerType,
|
||||
string packetListenerMethodName)
|
||||
{
|
||||
foreach (Type listenerClass in GetGenericsWith(listenerType))
|
||||
{
|
||||
Dictionary<Type, List<MethodInfo>> packetRouters = [];
|
||||
packetArrivalMethods.Add(listenerClass, packetRouters);
|
||||
Dictionary<Type, List<MethodInfo>> listenerMethodDictionary = [];
|
||||
packetListenerMethods.Add(listenerClass, listenerMethodDictionary);
|
||||
|
||||
foreach (Type packetListener in GetGenericInterfacesWith(listenerType, listenerClass))
|
||||
{
|
||||
Type packetType = packetListener.GetGenericArguments().First();
|
||||
|
||||
List<MethodInfo> arrivalMethods = packetListener
|
||||
.GetMethods()
|
||||
.Where(m => m.Name == packetArrivalMethodName)
|
||||
.ToList();
|
||||
List<MethodInfo> listenerMethods = [.. packetListener.GetMethods().Where(m => m.Name == packetListenerMethodName)];
|
||||
|
||||
packetRouters.Add(packetType, arrivalMethods);
|
||||
listenerMethodDictionary.Add(packetType, listenerMethods);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Finds all types that implement a generic interface.
|
||||
/// </summary>
|
||||
private static IEnumerable<Type> GetGenericsWith(Type type)
|
||||
=> AppDomain.CurrentDomain
|
||||
.GetAssemblies()
|
||||
.SelectMany(a =>
|
||||
a.GetTypes().Where(
|
||||
t => t.GetInterfaces().Any(
|
||||
i => i.IsGenericType && i.GetGenericTypeDefinition() == type
|
||||
)
|
||||
)
|
||||
);
|
||||
i => i.IsGenericType && i.GetGenericTypeDefinition() == type)));
|
||||
|
||||
// Gets all generic interfaces of a specific definition on a type
|
||||
private static IEnumerable<Type> GetGenericInterfacesWith(Type interfaceType, Type type)
|
||||
=> type.GetInterfaces().Where(
|
||||
i => i.IsGenericType && i.GetGenericTypeDefinition() == interfaceType
|
||||
);
|
||||
=> type.GetInterfaces().Where(i => i.IsGenericType && i.GetGenericTypeDefinition() == interfaceType);
|
||||
|
||||
#endregion
|
||||
|
||||
// Identifies whether packet routing is client-side or server-side
|
||||
private enum NetworkType { Client, Server }
|
||||
|
||||
private readonly record struct PacketRetrievalDelegatePair(Type PacketType, Delegate Delegate)
|
||||
{
|
||||
public static implicit operator (Type packetType, Delegate @delegate)(PacketRetrievalDelegatePair value) => (value.PacketType, value.Delegate);
|
||||
public static implicit operator PacketRetrievalDelegatePair((Type packetType, Delegate @delegate) value) => new(value.packetType, value.@delegate);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -27,8 +27,16 @@ internal class Tween : ITween
|
||||
field = value;
|
||||
switch (value)
|
||||
{
|
||||
case TweenState.Completed: OnCompleted?.Invoke(this); OnEnded?.Invoke(this); break;
|
||||
case TweenState.Cancelled: OnCancelled?.Invoke(this); OnEnded?.Invoke(this); break;
|
||||
case TweenState.Completed:
|
||||
OnCompleted?.Invoke(this);
|
||||
if (State == TweenState.Completed)
|
||||
OnEnded?.Invoke(this);
|
||||
break;
|
||||
case TweenState.Cancelled:
|
||||
OnCancelled?.Invoke(this);
|
||||
if (State == TweenState.Cancelled)
|
||||
OnEnded?.Invoke(this);
|
||||
break;
|
||||
case TweenState.Paused: OnPaused?.Invoke(this); break;
|
||||
case TweenState.Playing:
|
||||
if (previousState == TweenState.Idle)
|
||||
|
||||
@@ -4,35 +4,48 @@ namespace Engine.Systems.Tween;
|
||||
|
||||
public static class TweenExtensions
|
||||
{
|
||||
private static readonly System.Collections.Generic.Dictionary<ITween, int> loopDictionary = [];
|
||||
|
||||
public static ITween Loop(this ITween tween, int count)
|
||||
{
|
||||
Tween tweenConcrete = (Tween)tween;
|
||||
int counter = count;
|
||||
if (!loopDictionary.TryAdd(tween, count))
|
||||
throw new($"Tween already has a loop in progress.");
|
||||
|
||||
tweenConcrete.OnCompleted.AddListener(_ =>
|
||||
{
|
||||
if (counter-- <= 0)
|
||||
return;
|
||||
|
||||
tweenConcrete.Reset();
|
||||
tweenConcrete.State = TweenState.Playing;
|
||||
});
|
||||
tween.OnCompleted.AddListener(looperDelegate);
|
||||
tween.OnEnded.AddListener(looperEndDelegate);
|
||||
|
||||
return tween;
|
||||
}
|
||||
|
||||
private static readonly Core.Event<ITween>.EventHandler looperEndDelegate = sender => loopDictionary.Remove(sender);
|
||||
private static readonly Core.Event<ITween>.EventHandler looperDelegate = sender =>
|
||||
{
|
||||
int counter = loopDictionary[sender] = loopDictionary[sender] - 1;
|
||||
|
||||
if (counter <= 0)
|
||||
{
|
||||
loopDictionary.Remove(sender);
|
||||
return;
|
||||
}
|
||||
|
||||
Tween tweenConcrete = (Tween)sender;
|
||||
tweenConcrete.Reset();
|
||||
tweenConcrete.State = TweenState.Playing;
|
||||
};
|
||||
|
||||
public static ITween LoopInfinitely(this ITween tween)
|
||||
{
|
||||
Tween tweenConcrete = (Tween)tween;
|
||||
tweenConcrete.OnCompleted.AddListener(_ =>
|
||||
{
|
||||
tweenConcrete.Reset();
|
||||
tweenConcrete.State = TweenState.Playing;
|
||||
});
|
||||
|
||||
tween.OnCompleted.AddListener(repeaterDelegate);
|
||||
return tween;
|
||||
}
|
||||
|
||||
private static readonly Core.Event<ITween>.EventHandler repeaterDelegate = sender =>
|
||||
{
|
||||
Tween tweenConcrete = (Tween)sender;
|
||||
tweenConcrete.Reset();
|
||||
tweenConcrete.State = TweenState.Playing;
|
||||
};
|
||||
|
||||
public static ITween Ease(this ITween tween, IEasing easing)
|
||||
{
|
||||
Tween tweenConcrete = (Tween)tween;
|
||||
|
||||
@@ -2,4 +2,4 @@ using Engine.Core;
|
||||
|
||||
namespace Engine.Systems.Tween;
|
||||
|
||||
public class WaitForTweenCompleteCoroutineYield(ITween tween) : CoroutineYield(() => tween.State == TweenState.Completed);
|
||||
public class WaitForTweenCompleteCoroutineYield(ITween tween) : WaitUntilYield(() => tween.State == TweenState.Completed);
|
||||
|
||||
@@ -2,4 +2,4 @@ using Engine.Core;
|
||||
|
||||
namespace Engine.Systems.Tween;
|
||||
|
||||
public class WaitWhileTweenActiveCoroutineYield(ITween tween) : CoroutineYield(() => tween.State.CheckFlag(TweenState.Completed | TweenState.Cancelled));
|
||||
public class WaitWhileTweenActiveCoroutineYield(ITween tween) : WaitUntilYield(() => tween.State.CheckFlag(TweenState.Completed | TweenState.Cancelled));
|
||||
|
||||
Reference in New Issue
Block a user