From e7e02c66622edaf50914f51dc66fc770f47b304d Mon Sep 17 00:00:00 2001 From: mischa Date: Fri, 15 Mar 2024 13:00:43 +0800 Subject: [PATCH] perf: PredictedRigidbody MoveTowardsCustom --- .../PredictedRigidbody/PredictedRigidbody.cs | 26 ++++++++++++++++++- .../Examples/BenchmarkPrediction/Readme.md | 1 + 2 files changed, 26 insertions(+), 1 deletion(-) diff --git a/Assets/Mirror/Components/PredictedRigidbody/PredictedRigidbody.cs b/Assets/Mirror/Components/PredictedRigidbody/PredictedRigidbody.cs index cfa90823c..46bd3ec45 100644 --- a/Assets/Mirror/Components/PredictedRigidbody/PredictedRigidbody.cs +++ b/Assets/Mirror/Components/PredictedRigidbody/PredictedRigidbody.cs @@ -347,7 +347,31 @@ protected virtual void SmoothFollowPhysicsCopy() // sooner we need to catch the fuck up // float positionStep = (distance * distance) * interpolationSpeed; float positionStep = distance * positionInterpolationSpeed; - Vector3 newPosition = Vector3.MoveTowards(currentPosition, physicsPosition, positionStep * deltaTime); + + // simple and slow version with MoveTowards, which recalculates delta and delta.sqrMagnitude: + // Vector3 newPosition = Vector3.MoveTowards(currentPosition, physicsPosition, positionStep * deltaTime); + // faster version copied from MoveTowards: + // this increases Prediction Benchmark Client's FPS from 615 -> 640. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + static Vector3 MoveTowardsCustom( + Vector3 current, + Vector3 target, + Vector3 _delta, // pass this in since we already calculated it + float _sqrDistance, // pass this in since we already calculated it + float _distance, // pass this in since we already calculated it + float maxDistanceDelta) + { + if (_sqrDistance == 0.0 || maxDistanceDelta >= 0.0 && _sqrDistance <= maxDistanceDelta * maxDistanceDelta) + return target; + + return new Vector3( + current.x + (_delta.x / _distance) * maxDistanceDelta, + current.y + (_delta.y / _distance) * maxDistanceDelta, + current.z + (_delta.z / _distance) * maxDistanceDelta); + } + + Vector3 newPosition = MoveTowardsCustom(currentPosition, physicsPosition, delta, sqrDistance, distance, positionStep * deltaTime); + // smoothly interpolate to the target rotation. // Quaternion.RotateTowards doesn't seem to work at all, so let's use SLerp. diff --git a/Assets/Mirror/Examples/BenchmarkPrediction/Readme.md b/Assets/Mirror/Examples/BenchmarkPrediction/Readme.md index 207bf5795..cd0ed609a 100644 --- a/Assets/Mirror/Examples/BenchmarkPrediction/Readme.md +++ b/Assets/Mirror/Examples/BenchmarkPrediction/Readme.md @@ -19,3 +19,4 @@ Predicted: 2024-03-13: 580 FPS Client, 1700 FPS Server // micro optimizations 2024-03-14: 590 FPS Client, 1700 FPS Server // UpdateGhosting() every 4th frame 2024-03-14: 615 FPS Client, 1700 FPS Server // predictedRigidbodyTransform.GetPositionAndRotation() + 2024-03-15: 625 FPS Client, 1700 FPS Server // Vector3.MoveTowardsCustom()