All checks were successful
Tag and Release Lightless / tag-and-release (push) Successful in 2m9s
# Patchnotes 2.1.0 The changes in this update are more than just "patches". With a new UI, a new feature, and a bunch of bug fixes, improvements and a new member on the dev team, we thought this was more of a minor update. We would like to introduce @tsubasahane of MareCN to the team! We’re happy to work with them to bring Lightless and its features to the CN client as well as having another talented dev bring features and ideas to us. Speaking of which: # Location Sharing (Big shout out to @tsubasahane for bringing this feature) - Are you TIRED of scrambling to find the address of the venue you're in to share with your friends? We are introducing Location Sharing! An optional feature where you can share your location with direct pairs temporarily [30 minutes, 1 hour, 3 hours] minutes or until you turn it off for them. That's up to you! [#125](<#125>) [#49](<Lightless-Sync/LightlessServer#49>) - To share your location with a pair, click the three dots beside the pair and choose a duration to share with them. [#125](<#125>) [#49](<Lightless-Sync/LightlessServer#49>) - To view the location of someone who's shared with you, simply hover over the globe icon! [#125](<#125>) [#49](<Lightless-Sync/LightlessServer#49>) [1] # Model Optimization (Mesh Decimating) - This new option can automatically “simplify” incoming character meshes to help performance by reducing triangle counts. You choose how strong the reduction is (default/recommended is 80%). [#131](<#131>) - Decimation only kicks in when a mesh is above a certain triangle threshold, and only for the items that qualify for it and you selected for. [#131](<#131>) - Hair meshes is always excluded, since simplifying hair meshes is very prone to breaking. - You can find everything under Settings → Performance → Model Optimization. [#131](<#131>) + ** IF YOU HAVE USED DECIMATION IN TESTING, PLEASE CLEAR YOUR CACHE ❗ ** [2] # Animation (PAP) Validation (Safer animations) - Lightless now checks your currently animations to see if they work with your local skeleton/bone mod. If an animation matches, it’s included in what gets sent to other players. If it doesn’t, Lightless will skip it and write a warning to your log showing how many were skipped due to skeleton changes. Its defaulted to Unsafe (off). turn it on if you experience crashes from others users. [#131](<#131>) - Lightless also does the same kind of check for incoming animation files, to make sure they match the body/skeleton they were sent with. [#131](<#131>) - Because these checks can sometimes be a little picky, you can adjust how strict they are in Settings -> General -> Animation & Bones to reduce false positives. [#131](<#131>) # UI Changes (Thanks to @kyuwu for UI Changes) - The top part of the main screen has gotten a makeover. You can adjust the colors of the gradiant in the Color settings of Lightless. [#127](<#127>) [3] - Settings have gotten some changes as well to make this change more universal, and will use the same color settings. [#127](<#127>) - The particle effects of the gradient are toggleable in 'Settings -> UI -> Behavior' [#127](<#127>) - Instead of showing download/upload on bottom of Main UI, it will show VRAM usage and triangles with their optimization options next to it [#138](<#138>) # LightFinder / ShellFinder - UI Changes that follow our new design follow the color codes for the Gradient top as the main screen does. [#127](<#127>) [4] Co-authored-by: defnotken <itsdefnotken@gmail.com> Co-authored-by: azyges <aaaaaa@aaa.aaa> Co-authored-by: cake <admin@cakeandbanana.nl> Co-authored-by: Tsubasa <tsubasa@noreply.git.lightless-sync.org> Co-authored-by: choco <choco@patat.nl> Co-authored-by: celine <aaa@aaa.aaa> Co-authored-by: celine <celine@noreply.git.lightless-sync.org> Co-authored-by: Tsubasahane <wozaiha@gmail.com> Co-authored-by: cake <cake@noreply.git.lightless-sync.org> Reviewed-on: #123
215 lines
7.8 KiB
C#
215 lines
7.8 KiB
C#
using LightlessSync.LightlessConfiguration;
|
|
using Microsoft.Extensions.Hosting;
|
|
using Microsoft.Extensions.Logging;
|
|
using System.Collections.Concurrent;
|
|
using System.Reflection;
|
|
using System.Text;
|
|
|
|
namespace LightlessSync.Services.Mediator;
|
|
|
|
public sealed class LightlessMediator : IHostedService
|
|
{
|
|
private readonly object _addRemoveLock = new();
|
|
private readonly ConcurrentDictionary<object, DateTime> _lastErrorTime = [];
|
|
private readonly ILogger<LightlessMediator> _logger;
|
|
private readonly CancellationTokenSource _loopCts = new();
|
|
private readonly ConcurrentQueue<MessageBase> _messageQueue = new();
|
|
private readonly PerformanceCollectorService _performanceCollector;
|
|
private readonly LightlessConfigService _lightlessConfigService;
|
|
private readonly ConcurrentDictionary<Type, HashSet<SubscriberAction>> _subscriberDict = [];
|
|
private bool _processQueue = false;
|
|
private readonly ConcurrentDictionary<Type, MethodInfo?> _genericExecuteMethods = new();
|
|
public LightlessMediator(ILogger<LightlessMediator> logger, PerformanceCollectorService performanceCollector, LightlessConfigService lightlessConfigService)
|
|
{
|
|
_logger = logger;
|
|
_performanceCollector = performanceCollector;
|
|
_lightlessConfigService = lightlessConfigService;
|
|
}
|
|
|
|
public void PrintSubscriberInfo()
|
|
{
|
|
foreach (var subscriber in _subscriberDict.SelectMany(c => c.Value.Select(v => v.Subscriber))
|
|
.DistinctBy(p => p).OrderBy(p => p.GetType().FullName, StringComparer.Ordinal).ToList())
|
|
{
|
|
_logger.LogInformation("Subscriber {type}: {sub}", subscriber.GetType().Name, subscriber.ToString());
|
|
StringBuilder sb = new();
|
|
sb.Append("=> ");
|
|
foreach (var item in _subscriberDict.Where(item => item.Value.Any(v => v.Subscriber == subscriber)).ToList())
|
|
{
|
|
sb.Append(item.Key.Name).Append(", ");
|
|
}
|
|
|
|
if (!string.Equals(sb.ToString(), "=> ", StringComparison.Ordinal))
|
|
_logger.LogInformation("{sb}", sb.ToString());
|
|
_logger.LogInformation("---");
|
|
}
|
|
}
|
|
|
|
public void Publish<T>(T message) where T : MessageBase
|
|
{
|
|
if (message.KeepThreadContext)
|
|
{
|
|
ExecuteMessage(message);
|
|
}
|
|
else
|
|
{
|
|
_messageQueue.Enqueue(message);
|
|
}
|
|
}
|
|
|
|
public Task StartAsync(CancellationToken cancellationToken)
|
|
{
|
|
_logger.LogInformation("Starting LightlessMediator");
|
|
|
|
_ = Task.Run(async () =>
|
|
{
|
|
try
|
|
{
|
|
while (!_loopCts.Token.IsCancellationRequested)
|
|
{
|
|
while (!_processQueue)
|
|
{
|
|
await Task.Delay(100, _loopCts.Token).ConfigureAwait(false);
|
|
}
|
|
|
|
await Task.Delay(100, _loopCts.Token).ConfigureAwait(false);
|
|
|
|
HashSet<MessageBase> processedMessages = [];
|
|
while (_messageQueue.TryDequeue(out var message))
|
|
{
|
|
if (processedMessages.Contains(message)) { continue; }
|
|
|
|
processedMessages.Add(message);
|
|
|
|
ExecuteMessage(message);
|
|
}
|
|
}
|
|
}
|
|
catch (OperationCanceledException)
|
|
{
|
|
_logger.LogInformation("LightlessMediator stopped");
|
|
}
|
|
});
|
|
|
|
_logger.LogInformation("Started LightlessMediator");
|
|
|
|
return Task.CompletedTask;
|
|
}
|
|
|
|
public Task StopAsync(CancellationToken cancellationToken)
|
|
{
|
|
_messageQueue.Clear();
|
|
_loopCts.Cancel();
|
|
_loopCts.Dispose();
|
|
return Task.CompletedTask;
|
|
}
|
|
|
|
public void Subscribe<T>(IMediatorSubscriber subscriber, Action<T> action) where T : MessageBase
|
|
{
|
|
lock (_addRemoveLock)
|
|
{
|
|
_subscriberDict.TryAdd(typeof(T), []);
|
|
|
|
if (!_subscriberDict[typeof(T)].Add(new(subscriber, action)))
|
|
{
|
|
throw new InvalidOperationException("Already subscribed");
|
|
}
|
|
}
|
|
}
|
|
|
|
public void Unsubscribe<T>(IMediatorSubscriber subscriber) where T : MessageBase
|
|
{
|
|
lock (_addRemoveLock)
|
|
{
|
|
if (_subscriberDict.ContainsKey(typeof(T)))
|
|
{
|
|
_subscriberDict[typeof(T)].RemoveWhere(p => p.Subscriber == subscriber);
|
|
}
|
|
}
|
|
}
|
|
|
|
internal void UnsubscribeAll(IMediatorSubscriber subscriber)
|
|
{
|
|
lock (_addRemoveLock)
|
|
{
|
|
foreach (Type kvp in _subscriberDict.Select(k => k.Key))
|
|
{
|
|
int unSubbed = _subscriberDict[kvp]?.RemoveWhere(p => p.Subscriber == subscriber) ?? 0;
|
|
if (unSubbed > 0)
|
|
{
|
|
_logger.LogDebug("{sub} unsubscribed from {msg}", subscriber.GetType().Name, kvp.Name);
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
private void ExecuteMessage(MessageBase message)
|
|
{
|
|
if (!_subscriberDict.TryGetValue(message.GetType(), out HashSet<SubscriberAction>? subscribers) || subscribers == null || !subscribers.Any()) return;
|
|
|
|
List<SubscriberAction> subscribersCopy = [];
|
|
lock (_addRemoveLock)
|
|
{
|
|
subscribersCopy = subscribers?.Where(s => s.Subscriber != null).OrderBy(k => k.Subscriber is IHighPriorityMediatorSubscriber ? 0 : 1).ToList() ?? [];
|
|
}
|
|
|
|
#pragma warning disable S3011 // Reflection should not be used to increase accessibility of classes, methods, or fields
|
|
var msgType = message.GetType();
|
|
if (!_genericExecuteMethods.TryGetValue(msgType, out var methodInfo))
|
|
{
|
|
_genericExecuteMethods[msgType] = methodInfo = GetType()
|
|
.GetMethod(nameof(ExecuteReflected), BindingFlags.NonPublic | BindingFlags.Instance)?
|
|
.MakeGenericMethod(msgType);
|
|
}
|
|
|
|
methodInfo!.Invoke(this, [subscribersCopy, message]);
|
|
#pragma warning restore S3011 // Reflection should not be used to increase accessibility of classes, methods, or fields
|
|
}
|
|
|
|
private void ExecuteReflected<T>(List<SubscriberAction> subscribers, T message) where T : MessageBase
|
|
{
|
|
foreach (SubscriberAction subscriber in subscribers)
|
|
{
|
|
try
|
|
{
|
|
if (_lightlessConfigService.Current.LogPerformance)
|
|
{
|
|
var isSameThread = message.KeepThreadContext ? "$" : string.Empty;
|
|
_performanceCollector.LogPerformance(this, $"{isSameThread}Execute>{message.GetType().Name}+{subscriber.Subscriber.GetType().Name}>{subscriber.Subscriber}",
|
|
() => ((Action<T>)subscriber.Action).Invoke(message));
|
|
}
|
|
else
|
|
{
|
|
((Action<T>)subscriber.Action).Invoke(message);
|
|
}
|
|
}
|
|
catch (Exception ex)
|
|
{
|
|
if (_lastErrorTime.TryGetValue(subscriber, out var lastErrorTime) && lastErrorTime.Add(TimeSpan.FromSeconds(10)) > DateTime.UtcNow)
|
|
continue;
|
|
|
|
_logger.LogError(ex.InnerException ?? ex, "Error executing {type} for subscriber {subscriber}",
|
|
message.GetType().Name, subscriber.Subscriber.GetType().Name);
|
|
_lastErrorTime[subscriber] = DateTime.UtcNow;
|
|
}
|
|
}
|
|
}
|
|
|
|
public void StartQueueProcessing()
|
|
{
|
|
_logger.LogInformation("Starting Message Queue Processing");
|
|
_processQueue = true;
|
|
}
|
|
|
|
private sealed class SubscriberAction
|
|
{
|
|
public SubscriberAction(IMediatorSubscriber subscriber, object action)
|
|
{
|
|
Subscriber = subscriber;
|
|
Action = action;
|
|
}
|
|
|
|
public object Action { get; }
|
|
public IMediatorSubscriber Subscriber { get; }
|
|
}
|
|
} |