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 48c6a6121c com.unity.netcode.gameobjects@2.0.0
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] - 2024-09-12

### Added

- Added tooltips for all of the `NetworkObject` component's properties. (#3052)
- Added message size validation to named and unnamed message sending functions for better error messages. (#3049)
- Added "Check for NetworkObject Component" property to the Multiplayer->Netcode for GameObjects project settings. When disabled, this will bypass the in-editor `NetworkObject` check on `NetworkBehaviour` components. (#3031)
- Added `NetworkTransform.SwitchTransformSpaceWhenParented` property that, when enabled, will handle the world to local, local to world, and local to local transform space transitions when interpolation is enabled. (#3013)
- Added `NetworkTransform.TickSyncChildren` that, when enabled, will tick synchronize nested and/or child `NetworkTransform` components to eliminate any potential visual jittering that could occur if the `NetworkTransform` instances get into a state where their state updates are landing on different network ticks. (#3013)
- Added `NetworkObject.AllowOwnerToParent` property to provide the ability to allow clients to parent owned objects when running in a client-server network topology. (#3013)
- Added `NetworkObject.SyncOwnerTransformWhenParented` property to provide a way to disable applying the server's transform information in the parenting message on the client owner instance which can be useful for owner authoritative motion models. (#3013)
- Added `NetcodeEditorBase` editor helper class to provide easier modification and extension of the SDK's components. (#3013)

### Fixed

- Fixed issue where `NetworkAnimator` would send updates to non-observer clients. (#3057)
- Fixed issue where an exception could occur when receiving a universal RPC for a `NetworkObject` that has been despawned. (#3052)
- Fixed issue where a NetworkObject hidden from a client that is then promoted to be session owner was not being synchronized with newly joining clients.(#3051)
- Fixed issue where clients could have a wrong time delta on `NetworkVariableBase` which could prevent from sending delta state updates. (#3045)
- Fixed issue where setting a prefab hash value during connection approval but not having a player prefab assigned could cause an exception when spawning a player. (#3042)
- Fixed issue where the `NetworkSpawnManager.HandleNetworkObjectShow` could throw an exception if one of the `NetworkObject` components to show was destroyed during the same frame. (#3030)
- Fixed issue where the `NetworkManagerHelper` was continuing to check for hierarchy changes when in play mode. (#3026)
- Fixed issue with newly/late joined clients and `NetworkTransform` synchronization of parented `NetworkObject` instances. (#3013)
- Fixed issue with smooth transitions between transform spaces when interpolation is enabled (requires `NetworkTransform.SwitchTransformSpaceWhenParented` to be enabled). (#3013)

### Changed

- Changed `NetworkTransformEditor` now uses `NetworkTransform` as the base type class to assure it doesn't display a foldout group when using the base `NetworkTransform` component class. (#3052)
- Changed `NetworkAnimator.Awake` is now a protected virtual method. (#3052)
- Changed  when invoking `NetworkManager.ConnectionManager.DisconnectClient` during a distributed authority session a more appropriate message is logged. (#3052)
- Changed `NetworkTransformEditor` so it now derives from `NetcodeEditorBase`. (#3013)
- Changed `NetworkRigidbodyBaseEditor` so it now derives from `NetcodeEditorBase`. (#3013)
- Changed `NetworkManagerEditor` so it now derives from `NetcodeEditorBase`. (#3013)
2024-09-12 00:00:00 +00:00

237 lines
9.7 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;
public override void OnUpdate()
{
base.OnUpdate();
// 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;
}
}
}
private void Update()
{
base.OnUpdate();
if (!IsSpawned || !CanCommitToTransform || TestComplete)
{
return;
}
// 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