perf: sqr distance checks

This commit is contained in:
mischa 2024-10-17 10:52:02 +02:00
parent 808c9988a1
commit 51c767affc

View File

@ -96,6 +96,10 @@ public class NetworkTransformHybrid2022 : NetworkBehaviour
[Range(0.00_01f, 1f)] // disallow 0 division. 1mm to 1m precision is enough range. [Range(0.00_01f, 1f)] // disallow 0 division. 1mm to 1m precision is enough range.
public float scalePrecision = 0.01f; // 1 cm public float scalePrecision = 0.01f; // 1 cm
// squared values for faster distance checks
float positionPrecisionSqr;
float scalePrecisionSqr;
// selective sync ////////////////////////////////////////////////////// // selective sync //////////////////////////////////////////////////////
[Header("Selective Sync & interpolation")] [Header("Selective Sync & interpolation")]
public bool syncPosition = true; public bool syncPosition = true;
@ -127,6 +131,10 @@ protected virtual void OnValidate()
// use sendRate instead of syncInterval for now // use sendRate instead of syncInterval for now
syncInterval = 0; syncInterval = 0;
// cache squared precisions
positionPrecisionSqr = positionPrecision * positionPrecision;
scalePrecisionSqr = scalePrecision * scalePrecision;
// obsolete clientAuthority compatibility: // obsolete clientAuthority compatibility:
// if it was used, then set the new SyncDirection automatically. // if it was used, then set the new SyncDirection automatically.
// if it wasn't used, then don't touch syncDirection. // if it wasn't used, then don't touch syncDirection.
@ -181,15 +189,18 @@ protected virtual void ApplySnapshot(TransformSnapshot interpolated)
} }
// check if position / rotation / scale changed since last _full reliable_ sync. // check if position / rotation / scale changed since last _full reliable_ sync.
// squared comparisons for performance
protected virtual bool Changed(TransformSnapshot current) protected virtual bool Changed(TransformSnapshot current)
{ {
if (syncPosition && Vector3.Distance(last.position, current.position) >= positionPrecision) // if (syncPosition && Vector3.Distance(last.position, current.position) >= positionPrecision)
if (syncPosition && (current.position - last.position).sqrMagnitude >= positionPrecisionSqr)
return true; return true;
if (syncRotation && Quaternion.Angle(last.rotation, current.rotation) >= rotationPrecision) if (syncRotation && Quaternion.Angle(last.rotation, current.rotation) >= rotationPrecision)
return true; return true;
if (syncScale && Vector3.Distance(last.scale, current.scale) >= scalePrecision) // if (syncScale && Vector3.Distance(last.scale, current.scale) >= scalePrecision)
if (syncScale && (current.scale - last.scale).sqrMagnitude >= scalePrecisionSqr)
return true; return true;
return false; return false;