Cleaner sync

This commit is contained in:
2026-01-08 21:47:58 +01:00
parent bcf830d52d
commit e76df964e5
3 changed files with 219 additions and 156 deletions

View File

@@ -21,6 +21,7 @@ namespace Marro.PacManUdon
FullSync = 0,
PacManTurn = 1,
}
public class NetworkManager : UdonSharpBehaviour
{
// The network manager works by serializing event and state data into a byte array, including a timestamp for each event.
@@ -70,10 +71,6 @@ namespace Marro.PacManUdon
/// The total length of the header of an event, in bytes.
/// </summary>
private const ushort HeaderLength = 8;
/// <summary>
/// The amount of parts of which the header consists.
/// </summary>
private const ushort HeaderPartsCount = 4;
/// <summary>
/// The delay at which the receiving side replays events.
@@ -115,6 +112,11 @@ namespace Marro.PacManUdon
/// </summary>
private int retriesWithoutSuccess;
/// <summary>
/// True if there is a full sync in the queue and we are not currently synced.
/// </summary>
private bool fullSyncInQueue;
/// <summary>
/// Main buffer of data to be transmitted or processed
/// </summary>
@@ -155,7 +157,7 @@ namespace Marro.PacManUdon
/// <summary>
/// Is the current simulation to prepare for applying a network event?
/// True = Yes, This update is preparing for a network update.
/// False = No, this update is after the network update or there was no
/// False = No, this update is after the network update or there was no network update this cycle.
/// </summary>
public bool IsEventUpdate { get; private set; }
@@ -188,6 +190,7 @@ namespace Marro.PacManUdon
retriesWithoutSuccess = 0;
lastEventTimestamp = 0;
lastEventId = 0;
fullSyncInQueue = false;
offsetTime = Time.fixedTime;
internalTime = 0;
@@ -262,7 +265,7 @@ namespace Marro.PacManUdon
private void SetOwner(bool isOwner)
{
this.IsOwner = isOwner;
IsOwner = isOwner;
if (DebugImageToIndicateOwner != null)
{
@@ -313,7 +316,7 @@ namespace Marro.PacManUdon
var eventSizeBytes = BitConverter.GetBytes((ushort)eventSize);
Array.Copy(eventSizeBytes, 0, result, HeaderEventSizeIndex, eventSizeBytes.Length);
AppendEventToBuffer(result);
QueueEventInBuffer(result);
Debug.Log($"({nameof(PacManUdon)} {nameof(NetworkManager)}) Prepared event with {eventSize} bytes and timestamp {timestamp} for serialization, index went from {oldIndex} to {this.bufferIndex}");
@@ -419,62 +422,61 @@ namespace Marro.PacManUdon
var @event = GetArrayPart(networkedData, index, eventSize);
var eventType = GetEventTypeFromHeader(@event);
if (eventType == NetworkEventType.FullSync)
{
ProcessIncomingFullSync(@event); // Immediately process full sync
continue;
}
if (!Synced)
{
Debug.LogWarning($"({nameof(PacManUdon)} {nameof(NetworkManager)}) Received event of type {eventType} while we are not yet synced to the remote time, ignoring event.");
continue;
}
var timestamp = GetTimestampFromHeader(@event);
var eventId = GetEventIdFromHeader(@event);
if (timestamp == lastEventTimestamp
if (Synced || fullSyncInQueue)
{
if (timestamp == lastEventTimestamp
&& eventId == lastEventId)
{
Debug.LogWarning($"({nameof(PacManUdon)} {nameof(NetworkManager)}) Duplicate message of type {eventType}, timestamp: {timestamp}, messageId: {eventId}.");
continue;
}
{
Debug.LogWarning($"({nameof(PacManUdon)} {nameof(NetworkManager)}) Duplicate message of type {eventType}, timestamp: {timestamp}, messageId: {eventId}.");
continue;
}
if (eventId != GetNextEventId(lastEventId))
{
Debug.LogWarning($"({nameof(PacManUdon)} {nameof(NetworkManager)}) EventIds were not sequential! Did we miss a serialization? Timestamp: {timestamp}, eventId: {eventId}, lastEventId: {lastEventId}.");
HandleError(false);
return;
}
if (eventId != GetNextEventId(lastEventId))
{
Debug.LogWarning($"({nameof(PacManUdon)} {nameof(NetworkManager)}) EventIds were not sequential! Did we miss a serialization? Timestamp: {timestamp}, eventId: {eventId}, lastEventId: {lastEventId}.");
HandleError(false);
return;
}
AppendEventToBuffer(@event);
QueueEventInBuffer(@event);
}
else
{
// If we're not yet synced, we only care about full sync events.
if (eventType == NetworkEventType.FullSync)
{
QueueFullSyncInBuffer(@event); // Immediately process full sync
}
}
lastEventTimestamp = timestamp;
lastEventId = eventId;
}
UpdateNextEventTime();
if (Synced)
{
UpdateNextEventTime();
}
}
private void ProcessIncomingFullSync(byte[] @event)
private void QueueFullSyncInBuffer(byte[] @event)
{
// Intentionally not doing a buffer size check here, since this is not appended to the buffer
// (and there is no good way to continue if this event is too large)
// Clear buffer and put the full sync into it
ClearBuffer();
AppendEventToBuffer(@event);
QueueEventInBuffer(@event);
// Sync up to the time in the full sync
var timestamp = GetTimestampFromHeader(@event);
var eventId = GetEventIdFromHeader(@event);
SyncToTimestamp(timestamp, eventId);
// Set this event to play after the default delay
nextEventTime = internalTime + Delay;
// Immediately apply the full sync
UpdateNextEventTime(ignoreOrder: true);
Synced = true;
fullSyncInQueue = true;
Debug.Log($"({nameof(PacManUdon)} {nameof(NetworkManager)}) Queued full sync in buffer, should execute at {nextEventTime}.");
}
private void ProgressEventTime()
@@ -483,17 +485,22 @@ namespace Marro.PacManUdon
while (bufferIndex != 0 && nextEventTime <= internalTime)
{
ProcessIncomingEvent();
PerformEvent(buffer[0]);
DequeueEventsFromBuffer(1);
UpdateNextEventTime();
}
}
private void ProcessIncomingEvent()
private void PerformEvent(byte[] @event)
{
var @event = NextEvent;
var timestamp = GetTimestampFromHeader(@event);
var eventType = GetEventTypeFromHeader(@event);
if (eventType == NetworkEventType.FullSync)
{
SyncToTimestamp(timestamp, GetEventIdFromHeader(@event));
}
var index = (int)HeaderLength; // Skip header
ProgressSyncedTime(timestamp);
@@ -523,7 +530,11 @@ namespace Marro.PacManUdon
return;
}
RemoveProcessedDataFromBuffer(1);
if (!Synced && eventType == NetworkEventType.FullSync)
{
fullSyncInQueue = false;
Synced = true;
}
Debug.Log($"({nameof(PacManUdon)} {nameof(NetworkManager)}) Processed incoming event! Total {index} bytes.");
@@ -538,15 +549,15 @@ namespace Marro.PacManUdon
bufferIndex = 0;
}
private void RemoveProcessedDataFromBuffer(int amountProcessed)
private void DequeueEventsFromBuffer(int eventCount)
{
var oldBuffer = buffer;
bufferIndex -= amountProcessed;
bufferIndex -= eventCount;
buffer = new byte[BufferMaxTotalEvents][];
Array.Copy(oldBuffer, amountProcessed, buffer, 0, bufferIndex);
Array.Copy(oldBuffer, eventCount, buffer, 0, bufferIndex);
}
private bool AppendEventToBuffer(byte[] @event)
private bool QueueEventInBuffer(byte[] @event)
{
if (bufferIndex >= BufferMaxTotalEvents)
{
@@ -559,9 +570,6 @@ namespace Marro.PacManUdon
return true;
}
private byte[] NextEvent =>
buffer[0];
#endregion
#region Time
@@ -581,28 +589,28 @@ namespace Marro.PacManUdon
private void SyncToTimestamp(float timestamp, byte eventId)
{
var oldOffset = offsetTime;
var timeToSyncTo = timestamp - Delay;
offsetTime = Time.fixedTime - timeToSyncTo;
offsetTime = Time.fixedTime - timestamp;
var delta = offsetTime - oldOffset;
internalTime = internalTime - delta;
SyncedTime = SyncedTime - delta;
internalTime -= delta;
SyncedTime -= delta;
nextEventTime -= delta;
lastEventTimestamp = timestamp;
lastEventId = eventId;
Debug.Log($"({nameof(PacManUdon)} {nameof(NetworkManager)}) Synced to timestamp {timestamp}, current time is {Time.fixedTime}, timeToSyncTo is {timeToSyncTo}, offsetTime is now {offsetTime}, internalTime is now {internalTime}, SyncedTime is now {SyncedTime}");
Debug.Log($"({nameof(PacManUdon)} {nameof(NetworkManager)}) Synced to timestamp {timestamp}, current time is {Time.fixedTime}, offsetTime is now {offsetTime}, internalTime is now {internalTime}, SyncedTime is now {SyncedTime}, nextEventTime is now {nextEventTime}");
}
private void UpdateNextEventTime(bool ignoreOrder = false)
private void UpdateNextEventTime()
{
if (bufferIndex == 0)
{
return;
}
var nextEventTime = GetTimestampFromHeader(NextEvent);
if (ignoreOrder || nextEventTime >= this.nextEventTime)
var nextEventTime = GetTimestampFromHeader(buffer[0]);
if (nextEventTime >= this.nextEventTime)
{
this.nextEventTime = nextEventTime;
}
@@ -698,7 +706,7 @@ namespace Marro.PacManUdon
Debug.Log($"({nameof(PacManUdon)} {nameof(NetworkManager)}) Serialized with {networkedData.Length} bytes!\nBytes sent:\n{BytesToString(networkedData)}");
// Remove all transferred data from the buffer, leaving data that came in after serialization
RemoveProcessedDataFromBuffer(indexAtLastSerialization);
DequeueEventsFromBuffer(indexAtLastSerialization);
networkedData = new byte[0];
}
@@ -774,6 +782,8 @@ namespace Marro.PacManUdon
debugOutput.text += $"{nameof(NetworkManager)}:\n" +
$"IsOwner: {IsOwner}\n" +
$"Ready: {Ready}\n" +
$"Synced: {Synced}\n" +
$"fullSyncInQueue: {fullSyncInQueue}\n" +
$"Time.fixedTime: {Time.fixedTime}\n" +
$"offsetTime: {offsetTime}\n" +
$"internalTime: {internalTime}\n" +