Refactor server event processing and entity updates

This commit is contained in:
Eero
2026-05-02 00:28:12 +08:00
parent 8b6da6b033
commit 9d6cb5225a
6 changed files with 173 additions and 130 deletions
@@ -8,7 +8,6 @@ using System.Linq;
using System.Reflection;
using System.Threading.Tasks;
using System.Xml.Linq;
using static OneOf.Types.TrueFalseOrNull;
namespace Barotrauma
{
@@ -643,7 +642,7 @@ namespace Barotrauma
/// </summary>
public static void UpdateAll(float deltaTime, Camera cam, ParallelOptions parallelOptions)
{
Random rand = new Random();
mapEntityUpdateTick++;
#if CLIENT
var sw = new System.Diagnostics.Stopwatch();
sw.Start();
@@ -665,46 +664,50 @@ namespace Barotrauma
while (n > 1)
{
n--;
int k = rand.Next(n + 1);
int k = Rand.Int(n + 1);
(gapList[n], gapList[k]) = (gapList[k], gapList[n]);
}
var itemList = Item.ItemList.ToList();
// First phase: parallel updates that have no order dependencies
Parallel.Invoke(parallelOptions,
() =>
{
Parallel.ForEach(hullList, parallelOptions, hull =>
int mapEntityUpdateInterval = Math.Max(MapEntityUpdateInterval, 1);
int poweredUpdateInterval = Math.Max(PoweredUpdateInterval, 1);
if (mapEntityUpdateTick % mapEntityUpdateInterval == 0)
{
float mapEntityDeltaTime = deltaTime * mapEntityUpdateInterval;
Parallel.Invoke(parallelOptions,
() =>
{
hull.Update(deltaTime, cam);
});
},
// Structure parallel update
() =>
{
Parallel.ForEach(structureList, parallelOptions, structure =>
Parallel.ForEach(hullList, parallelOptions, hull =>
{
hull.Update(mapEntityDeltaTime, cam);
});
},
() =>
{
structure.Update(deltaTime, cam);
Parallel.ForEach(structureList, parallelOptions, structure =>
{
structure.Update(mapEntityDeltaTime, cam);
});
});
},
() =>
// moved waterflow reset here to see if we can reduce at least some time
{
// PLEASE WORK
Parallel.ForEach(gapList, parallelOptions, gap =>
{
gap.ResetWaterFlowThisFrame();
gap.Update(deltaTime, cam);
});
},
// Powered components update
() =>
{
Powered.UpdatePower(deltaTime);
}
);
}
foreach (Gap gap in gapList)
{
gap.ResetWaterFlowThisFrame();
}
foreach (Gap gap in gapList)
{
gap.Update(deltaTime, cam);
}
if (mapEntityUpdateTick % poweredUpdateInterval == 0)
{
Powered.UpdatePower(deltaTime * poweredUpdateInterval);
}
#if CLIENT
// Hull Cheats need to be executed after Hull update
@@ -720,27 +723,42 @@ namespace Barotrauma
// Item update (Item.Update() is not thread-safe and must be executed on the main thread)
Item.UpdatePendingConditionUpdates(deltaTime);
Item lastUpdatedItem = null;
try
if (mapEntityUpdateTick % mapEntityUpdateInterval == 0)
{
foreach (Item item in itemList)
float itemDeltaTime = deltaTime * mapEntityUpdateInterval;
Item lastUpdatedItem = null;
try
{
lastUpdatedItem = item;
item.Update(deltaTime, cam);
foreach (Item item in itemList)
{
if (LuaCsSetup.Instance.Game.UpdatePriorityItems.Contains(item)) { continue; }
lastUpdatedItem = item;
item.Update(itemDeltaTime, cam);
}
}
catch (InvalidOperationException e)
{
GameAnalyticsManager.AddErrorEventOnce(
"MapEntity.UpdateAll:ItemUpdateInvalidOperation",
GameAnalyticsManager.ErrorSeverity.Critical,
$"Error while updating item {lastUpdatedItem?.Name ?? "null"}: {e.Message}");
throw new InvalidOperationException($"Error while updating item {lastUpdatedItem?.Name ?? "null"}", innerException: e);
}
}
catch (InvalidOperationException e)
foreach (var item in LuaCsSetup.Instance.Game.UpdatePriorityItems)
{
GameAnalyticsManager.AddErrorEventOnce(
"MapEntity.UpdateAll:ItemUpdateInvalidOperation",
GameAnalyticsManager.ErrorSeverity.Critical,
$"Error while updating item {lastUpdatedItem?.Name ?? "null"}: {e.Message}");
throw new InvalidOperationException($"Error while updating item {lastUpdatedItem?.Name ?? "null"}", innerException: e);
if (item.Removed) { continue; }
item.Update(deltaTime, cam);
}
UpdateAllProjSpecific(deltaTime);
Spawner?.Update();
if (mapEntityUpdateTick % mapEntityUpdateInterval == 0)
{
UpdateAllProjSpecific(deltaTime * mapEntityUpdateInterval);
Spawner?.Update();
}
#if CLIENT
sw.Stop();
@@ -281,7 +281,6 @@ namespace Barotrauma
#endif
SingleThreadActionStandbySignal.Wait();
try
{
GameMain.World.Step((float)Timing.Step);
@@ -292,8 +291,10 @@ namespace Barotrauma
DebugConsole.ThrowError(errorMsg, e);
GameAnalyticsManager.AddErrorEventOnce("GameScreen.Update:WorldLockedException" + e.Message, GameAnalyticsManager.ErrorSeverity.Critical, errorMsg);
}
SingleThreadActionStandbySignal.Release();
finally
{
SingleThreadActionStandbySignal.Release();
}
#if CLIENT
sw.Stop();
@@ -1,9 +1,7 @@
using Barotrauma.Networking;
using System;
using System;
using System.Collections.Concurrent;
using System.Threading;
using System.Threading.Tasks;
using static Barotrauma.EosInterface.Ownership;
namespace Barotrauma
{
@@ -15,7 +13,8 @@ namespace Barotrauma
private readonly CancellationTokenSource cancellationTokenSource = new CancellationTokenSource();
private readonly SemaphoreSlim actionSignal = new SemaphoreSlim(0);
private static Task WorkerTask;
private readonly Task workerTask;
private bool disposed;
public static readonly SemaphoreSlim SingleThreadActionStandbySignal = new SemaphoreSlim(1);
@@ -26,28 +25,35 @@ namespace Barotrauma
public SingleThreadWorker()
{
ActionQueue = new ConcurrentQueue<Action>();
WorkerTask = CreateProcessTask(cancellationTokenSource.Token);
workerTask = CreateProcessTask(cancellationTokenSource.Token);
}
public void Dispose()
{
if (disposed) { return; }
disposed = true;
cancellationTokenSource.Cancel();
WorkerTask.Wait();
WorkerTask.Dispose();
Instance = null;
try
{
actionSignal.Release();
workerTask.Wait(2);
}
catch (AggregateException) { }
catch (ObjectDisposedException) { }
cancellationTokenSource.Dispose();
actionSignal.Dispose();
SingleThreadActionStandbySignal.Dispose();
}
private async Task CreateProcessTask(CancellationToken token)
{
while (!token.IsCancellationRequested)
{
bool lockTaken = false;
try
{
await actionSignal.WaitAsync(100, token);
SingleThreadActionStandbySignal.Wait(CancellationToken.None);
lockTaken = true;
RunActions();
}
catch (OperationCanceledException)
@@ -56,7 +62,10 @@ namespace Barotrauma
}
finally
{
SingleThreadActionStandbySignal.Release();
if (lockTaken)
{
SingleThreadActionStandbySignal.Release();
}
}
}
}
@@ -68,6 +77,8 @@ namespace Barotrauma
/// <param name="action"></param>
public void AddAction(Action action)
{
if (disposed || action == null) { return; }
// enqueue and let background task handle the rest
ActionQueue.Enqueue(action);
@@ -96,7 +107,7 @@ namespace Barotrauma
Console.ForegroundColor = ConsoleColor.Yellow;
Console.WriteLine($"WARNING: Error occurred when running Single Thread Actions." +
$"If the server didn't crash or stop responding then this should be fine \n{e}");
Console.ForegroundColor = Console.ForegroundColor;
Console.ForegroundColor = originalForeground;
}
}
}