This repository has been archived on 2025-04-22. You can view files and clone it. You cannot open issues or pull requests or push a commit.
Files
com.unity.netcode.gameobjects/Tests/Runtime/TransformInterpolationTests.cs
Unity Technologies 63c7e4c78a com.unity.netcode.gameobjects@2.0.0-exp.4
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/) and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).

Additional documentation and release notes are available at [Multiplayer Documentation](https://docs-multiplayer.unity3d.com).

## [2.0.0-exp.4] - 2024-05-31

### Added

- Added `NetworkRigidbodyBase.AttachToFixedJoint` and `NetworkRigidbodyBase.DetachFromFixedJoint` to replace parenting for rigid bodies that have `NetworkRigidbodyBase.UseRigidBodyForMotion` enabled. (#2933)
- Added `NetworkBehaviour.OnNetworkPreSpawn` and `NetworkBehaviour.OnNetworkPostSpawn` methods that provide the ability to handle pre and post spawning actions during the `NetworkObject` spawn sequence. (#2912)
- Added a client-side only `NetworkBehaviour.OnNetworkSessionSynchronized` convenience method that is invoked on all `NetworkBehaviour`s after a newly joined client has finished synchronizing with the network session in progress. (#2912)
- Added `NetworkBehaviour.OnInSceneObjectsSpawned` convenience method that is invoked when all in-scene `NetworkObject`s have been spawned after a scene has been loaded or upon a host or server starting. (#2912)

### Fixed

- Fixed issue where non-authoritative rigid bodies with `NetworkRigidbodyBase.UseRigidBodyForMotion` enabled would constantly log errors about the renderTime being before `StartTimeConsumed`. (#2933)
- Fixed issue where in-scene placed NetworkObjects could be destroyed if a client disconnects early and/or before approval. (#2924)
- Fixed issue where a `NetworkObject` component's associated `NetworkBehaviour` components would not be detected if scene loading is disabled in the editor and the currently loaded scene has in-scene placed `NetworkObject`s. (#2912)
- Fixed issue where an in-scene placed `NetworkObject` with `NetworkTransform` that is also parented under a `GameObject` would not properly synchronize when the parent `GameObject` had a world space position other than 0,0,0. (#2898)

### Changed

- Change all the access modifiers of test class from Public to Internal (#2930)
- Changed messages are now sorted by enum values as opposed to ordinally sorting the messages by their type name. (#2929)
- Changed `NetworkClient.SessionModeTypes` to `NetworkClient.NetworkTopologyTypes`. (#2875)
- Changed `NetworkClient.SessionModeType` to `NetworkClient.NetworkTopologyType`. (#2875)
- Changed `NetworkConfig.SessionMode` to `NeworkConfig.NetworkTopology`. (#2875)
2024-05-31 00:00:00 +00:00

231 lines
9.5 KiB
C#

#if !MULTIPLAYER_TOOLS
using System.Collections;
using NUnit.Framework;
using Unity.Netcode.Components;
using Unity.Netcode.TestHelpers.Runtime;
using UnityEngine;
using UnityEngine.TestTools;
namespace Unity.Netcode.RuntimeTests
{
internal class TransformInterpolationObject : NetworkTransform
{
public static bool TestComplete = false;
// Set the minimum threshold which we will use as our margin of error
#if UNITY_EDITOR
public const float MinThreshold = 0.005f;
#else
// Add additional room for error on console tests
public const float MinThreshold = 0.009999f;
#endif
private const int k_TargetLocalSpaceToggles = 10;
public bool CheckPosition;
public bool IsMoving;
public bool IsFixed;
private float m_FrameRateFractional;
private bool m_CurrentLocalSpace;
private int m_LocalSpaceToggles;
private int m_LastFrameCount;
public bool ReachedTargetLocalSpaceTransitionCount()
{
TestComplete = m_LocalSpaceToggles >= k_TargetLocalSpaceToggles;
return TestComplete;
}
protected override void OnInitialize(ref NetworkTransformState replicatedState)
{
m_LocalSpaceToggles = 0;
m_FrameRateFractional = 1.0f / Application.targetFrameRate;
PositionThreshold = MinThreshold;
SetMaxInterpolationBound(1.0f);
base.OnInitialize(ref replicatedState);
}
private int m_StartFrameCount;
public void StartMoving()
{
m_StartFrameCount = Time.frameCount;
IsMoving = true;
}
public void StopMoving()
{
IsMoving = false;
}
private const int k_MaxThresholdFailures = 4;
private int m_ExceededThresholdCount;
private void Update()
{
base.OnUpdate();
if (!IsSpawned || TestComplete)
{
return;
}
// Check the position of the nested object on the client
if (CheckPosition)
{
if (transform.position.y < -MinThreshold || transform.position.y > Application.targetFrameRate + MinThreshold)
{
// Temporary work around for this test.
// Really, this test needs to be completely re-written.
m_ExceededThresholdCount++;
// If we haven't corrected ourselves within the maximum number of updates then throw an error.
if (m_ExceededThresholdCount > k_MaxThresholdFailures)
{
Debug.LogError($"Interpolation failure. transform.position.y is {transform.position.y}. Should be between 0.0 and 100.0. Current threshold is [+/- {MinThreshold}].");
}
}
else
{
// If corrected, then reset our count
m_ExceededThresholdCount = 0;
}
}
// Move the nested object on the server
if (IsMoving)
{
Assert.True(CanCommitToTransform, $"Using non-authority instance to update transform!");
if (m_LastFrameCount == Time.frameCount)
{
Debug.Log($"Detected duplicate frame update count {Time.frameCount}. Ignoring this update.");
return;
}
m_LastFrameCount = Time.frameCount;
// Leaving this here for reference.
// If a system is running at a slower frame rate than expected, then the below code could toggle
// the local to world space value at a higher frequency which might not provide enough updates to
// handle interpolating between the transitions.
//var y = Time.realtimeSinceStartup % 10.0f;
//// change the space between local and global every second
//GetComponent<NetworkTransform>().InLocalSpace = ((int)y % 2 == 0);
// Reduce the total frame count down to the frame rate
var y = (Time.frameCount - m_StartFrameCount) % Application.targetFrameRate;
// change the space between local and global every time we hit the expected number of frames
// (or every second if running at the target frame rate)
InLocalSpace = y == 0 ? !InLocalSpace : InLocalSpace;
if (m_CurrentLocalSpace != InLocalSpace)
{
m_LocalSpaceToggles++;
m_CurrentLocalSpace = InLocalSpace;
}
transform.position = new Vector3(0.0f, (y * m_FrameRateFractional), 0.0f);
}
// On the server, make sure to keep the parent object at a fixed position
if (IsFixed)
{
Assert.True(CanCommitToTransform, $"Using non-authority instance to update transform!");
transform.position = new Vector3(1000.0f, 1000.0f, 1000.0f);
}
}
}
internal class TransformInterpolationTests : NetcodeIntegrationTest
{
protected override int NumberOfClients => 1;
private GameObject m_PrefabToSpawn;
private NetworkObject m_SpawnedAsNetworkObject;
private NetworkObject m_SpawnedObjectOnClient;
private NetworkObject m_BaseAsNetworkObject;
private NetworkObject m_BaseOnClient;
protected override void OnServerAndClientsCreated()
{
m_PrefabToSpawn = CreateNetworkObjectPrefab("InterpTestObject");
var networkTransform = m_PrefabToSpawn.AddComponent<TransformInterpolationObject>();
}
private IEnumerator RefreshNetworkObjects()
{
var clientId = m_ClientNetworkManagers[0].LocalClientId;
yield return WaitForConditionOrTimeOut(() => s_GlobalNetworkObjects.ContainsKey(clientId) &&
s_GlobalNetworkObjects[clientId].ContainsKey(m_BaseAsNetworkObject.NetworkObjectId) &&
s_GlobalNetworkObjects[clientId].ContainsKey(m_SpawnedAsNetworkObject.NetworkObjectId));
Assert.False(s_GlobalTimeoutHelper.TimedOut, $"Timed out waiting for client side {nameof(NetworkObject)} ID of {m_SpawnedAsNetworkObject.NetworkObjectId}");
m_BaseOnClient = s_GlobalNetworkObjects[clientId][m_BaseAsNetworkObject.NetworkObjectId];
// make sure the objects are set with the right network manager
m_BaseOnClient.NetworkManagerOwner = m_ClientNetworkManagers[0];
m_SpawnedObjectOnClient = s_GlobalNetworkObjects[clientId][m_SpawnedAsNetworkObject.NetworkObjectId];
// make sure the objects are set with the right network manager
m_SpawnedObjectOnClient.NetworkManagerOwner = m_ClientNetworkManagers[0];
}
[UnityTest]
public IEnumerator TransformInterpolationTest()
{
TransformInterpolationObject.TestComplete = false;
// create an object
var spawnedObject = Object.Instantiate(m_PrefabToSpawn);
var baseObject = Object.Instantiate(m_PrefabToSpawn);
baseObject.GetComponent<NetworkObject>().NetworkManagerOwner = m_ServerNetworkManager;
baseObject.GetComponent<NetworkObject>().Spawn();
m_SpawnedAsNetworkObject = spawnedObject.GetComponent<NetworkObject>();
m_SpawnedAsNetworkObject.NetworkManagerOwner = m_ServerNetworkManager;
m_BaseAsNetworkObject = baseObject.GetComponent<NetworkObject>();
m_BaseAsNetworkObject.NetworkManagerOwner = m_ServerNetworkManager;
m_SpawnedAsNetworkObject.TrySetParent(baseObject);
m_SpawnedAsNetworkObject.Spawn();
yield return RefreshNetworkObjects();
m_SpawnedAsNetworkObject.TrySetParent(baseObject);
var spawnedObjectNetworkTransform = spawnedObject.GetComponent<TransformInterpolationObject>();
baseObject.GetComponent<TransformInterpolationObject>().IsFixed = true;
spawnedObject.GetComponent<TransformInterpolationObject>().StartMoving();
const float maxPlacementError = 0.01f;
// Wait for the base object to place itself on both instances
while (m_BaseOnClient.transform.position.y < 1000 - maxPlacementError ||
m_BaseOnClient.transform.position.y > 1000 + maxPlacementError ||
baseObject.transform.position.y < 1000 - maxPlacementError ||
baseObject.transform.position.y > 1000 + maxPlacementError)
{
yield return new WaitForSeconds(0.01f);
}
m_SpawnedObjectOnClient.GetComponent<TransformInterpolationObject>().CheckPosition = true;
// Test that interpolation works correctly for ~10 seconds or 10 local to world space transitions while moving
// Increasing this duration gives you the opportunity to go check in the Editor how the objects are setup
// and how they move
var timeOutHelper = new TimeoutFrameCountHelper(10);
yield return WaitForConditionOrTimeOut(spawnedObjectNetworkTransform.ReachedTargetLocalSpaceTransitionCount, timeOutHelper);
VerboseDebug($"[TransformInterpolationTest] Wait condition reached or timed out. Frame Count ({timeOutHelper.GetFrameCount()}) | Time Elapsed ({timeOutHelper.GetTimeElapsed()})");
AssertOnTimeout($"Failed to reach desired local to world space transitions in the given time!", timeOutHelper);
}
}
}
#endif