103 lines
3.3 KiB
C#
103 lines
3.3 KiB
C#
using System;
|
|
using System.Collections.Generic;
|
|
using System.Linq;
|
|
|
|
namespace Encompass
|
|
{
|
|
internal class MessageManager
|
|
{
|
|
private readonly TimeManager timeManager;
|
|
|
|
private readonly Dictionary<Type, List<IMessage>> messageTypeToMessages = new Dictionary<Type, List<IMessage>>();
|
|
|
|
private readonly List<(IMessage, double)> delayedMessages = new List<(IMessage, double)>();
|
|
private readonly List<(IMessage, double)> delayedMessagesIgnoringTimeDilation = new List<(IMessage, double)>();
|
|
|
|
public MessageManager(TimeManager timeManager)
|
|
{
|
|
this.timeManager = timeManager;
|
|
}
|
|
|
|
internal void RegisterMessageType(Type messageType)
|
|
{
|
|
if (!messageTypeToMessages.ContainsKey(messageType))
|
|
{
|
|
messageTypeToMessages.Add(messageType, new List<IMessage>());
|
|
}
|
|
}
|
|
|
|
internal void AddMessage(IMessage message)
|
|
{
|
|
var type = message.GetType();
|
|
|
|
messageTypeToMessages[type].Add(message);
|
|
}
|
|
|
|
internal void AddMessageDelayed(IMessage message, double time)
|
|
{
|
|
if (!messageTypeToMessages.ContainsKey(message.GetType())) { messageTypeToMessages.Add(message.GetType(), new List<IMessage>()); }
|
|
|
|
delayedMessages.Add((message, time));
|
|
}
|
|
|
|
internal void AddMessageDelayedIgnoringTimeDilation(IMessage message, double time)
|
|
{
|
|
if (!messageTypeToMessages.ContainsKey(message.GetType())) { messageTypeToMessages.Add(message.GetType(), new List<IMessage>()); }
|
|
|
|
delayedMessagesIgnoringTimeDilation.Add((message, time));
|
|
}
|
|
|
|
internal void ClearMessages()
|
|
{
|
|
foreach (var entry in messageTypeToMessages)
|
|
{
|
|
entry.Value.Clear();
|
|
}
|
|
}
|
|
|
|
internal void ProcessDelayedMessages(double dt)
|
|
{
|
|
for (int i = delayedMessages.Count - 1; i >= 0; i--)
|
|
{
|
|
var (message, time) = delayedMessages[i];
|
|
|
|
var updatedTime = time - (dt * timeManager.TimeDilationFactor);
|
|
|
|
if (updatedTime <= 0)
|
|
{
|
|
AddMessage(message);
|
|
delayedMessages.RemoveAt(i);
|
|
}
|
|
else
|
|
{
|
|
delayedMessages[i] = (message, updatedTime);
|
|
}
|
|
}
|
|
|
|
for (int i = delayedMessagesIgnoringTimeDilation.Count - 1; i >= 0; i--)
|
|
{
|
|
var (message, time) = delayedMessagesIgnoringTimeDilation[i];
|
|
|
|
var updatedTime = time - dt;
|
|
|
|
if (updatedTime <= 0)
|
|
{
|
|
AddMessage(message);
|
|
delayedMessagesIgnoringTimeDilation.RemoveAt(i);
|
|
}
|
|
else
|
|
{
|
|
delayedMessagesIgnoringTimeDilation[i] = (message, updatedTime);
|
|
}
|
|
}
|
|
}
|
|
|
|
internal IEnumerable<TMessage> GetMessagesByType<TMessage>() where TMessage : struct, IMessage
|
|
{
|
|
return messageTypeToMessages.ContainsKey(typeof(TMessage)) ?
|
|
messageTypeToMessages[typeof(TMessage)].Cast<TMessage>() :
|
|
Enumerable.Empty<TMessage>();
|
|
}
|
|
}
|
|
}
|