Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: scene switch stream corruption #504

Closed
wants to merge 9 commits into from
29 changes: 25 additions & 4 deletions com.unity.multiplayer.mlapi/Runtime/Core/NetworkingManager.cs
Expand Up @@ -1030,6 +1030,10 @@ private void HandleRawTransportPoll(NetEventType eventType, ulong clientId, Chan
}

private readonly BitStream m_InputStreamWrapper = new BitStream(new byte[0]);
bool m_InputStreamWrapperUsed;
// The fallback wrapper is used in case we have to handle incoming data but the InputStreamWrapper is already being used.
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nice comment

LukeStampfli marked this conversation as resolved.
Show resolved Hide resolved
// This change is needed because MLAPI calls HandleIncomingData nested when it is applying buffered messages to an object spawned in HandleIncomingData.
private readonly BitStream m_FallbackInputStreamWrapper = new BitStream(new byte[0]);
private readonly RpcBatcher m_RpcBatcher = new RpcBatcher();

internal void HandleIncomingData(ulong clientId, Channel channel, ArraySegment<byte> data, float receiveTime, bool allowBuffer)
Expand All @@ -1039,11 +1043,22 @@ internal void HandleIncomingData(ulong clientId, Channel channel, ArraySegment<b
#endif
if (NetworkLog.CurrentLogLevel <= LogLevel.Developer) NetworkLog.LogInfo("Unwrapping Data Header");

m_InputStreamWrapper.SetTarget(data.Array);
m_InputStreamWrapper.SetLength(data.Count + data.Offset);
m_InputStreamWrapper.Position = data.Offset;
BitStream inputStreamWrapper;
if (m_InputStreamWrapperUsed)
{
inputStreamWrapper = m_FallbackInputStreamWrapper;
}
else
{
inputStreamWrapper = m_InputStreamWrapper;
m_InputStreamWrapperUsed = true;
}

using (var messageStream = MessagePacker.UnwrapMessage(m_InputStreamWrapper, clientId, out byte messageType, out SecuritySendFlags security))
inputStreamWrapper.SetTarget(data.Array);
inputStreamWrapper.SetLength(data.Count + data.Offset);
inputStreamWrapper.Position = data.Offset;

using (var messageStream = MessagePacker.UnwrapMessage(inputStreamWrapper, clientId, out byte messageType, out SecuritySendFlags security))
{
if (messageStream == null)
{
Expand Down Expand Up @@ -1199,6 +1214,12 @@ internal void HandleIncomingData(ulong clientId, Channel channel, ArraySegment<b

NetworkProfiler.EndEvent();
}

if (inputStreamWrapper == m_InputStreamWrapper)
{
m_InputStreamWrapperUsed = false;
}

#if DEVELOPMENT_BUILD || UNITY_EDITOR
s_HandleIncomingData.End();
#endif
Expand Down