Skip to content

Commit

Permalink
style: running code cleanup on all files
Browse files Browse the repository at this point in the history
  • Loading branch information
James-Frowen committed Sep 25, 2022
1 parent 65cfdb8 commit aefde61
Show file tree
Hide file tree
Showing 8 changed files with 115 additions and 116 deletions.
33 changes: 16 additions & 17 deletions Assets/NetworkPositionSync/Runtime/InterpolationTime.cs
Original file line number Diff line number Diff line change
Expand Up @@ -60,43 +60,42 @@ namespace JamesFrowen.PositionSync
/// </remarks>
public class InterpolationTime
{
static readonly ILogger logger = LogFactory.GetLogger<InterpolationTime>();
private static readonly ILogger logger = LogFactory.GetLogger<InterpolationTime>();
private bool intialized;

bool intialized;
/// <summary>
/// The time value that the client uses to interpolate
/// </summary>
float _clientTime;
private float _clientTime;

/// <summary>
/// The client will multiply deltaTime by this scale time value each frame
/// </summary>
float clientScaleTime;

readonly ExponentialMovingAverage diffAvg;
private float clientScaleTime;
private readonly ExponentialMovingAverage diffAvg;

/// <summary>
/// How much above the goalOffset difference are we allowed to go before changing the timescale
/// </summary>
readonly float positiveThreshold;
private readonly float positiveThreshold;

/// <summary>
/// How much below the goalOffset difference are we allowed to go before changing the timescale
/// </summary>
readonly float negativeThreshold;

readonly float fastScale = 1.01f;
const float normalScale = 1f;
readonly float slowScale = 0.99f;
private readonly float negativeThreshold;
private readonly float fastScale = 1.01f;
private const float normalScale = 1f;
private readonly float slowScale = 0.99f;

/// <summary>
/// Is the difference between previous time and new time too far apart?
/// If so, reset the client time.
/// </summary>
readonly float _skipAheadThreshold;

float _clientDelay;
private readonly float _skipAheadThreshold;
private float _clientDelay;

// Used for debug purposes. Move along...
float _latestServerTime;
private float _latestServerTime;

/// <summary>
/// Timer that follows server time
Expand Down Expand Up @@ -192,7 +191,7 @@ public void OnMessage(float serverTime)
}

// Calculate the difference.
float diff = serverTime - _clientTime;
var diff = serverTime - _clientTime;

// Are we falling behind?
if (serverTime - _clientTime > _skipAheadThreshold)
Expand Down
30 changes: 15 additions & 15 deletions Assets/NetworkPositionSync/Runtime/SnapshotBuffer.cs
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@ public interface ISnapshotInterpolator<T>
}
public class SnapshotBuffer<T>
{
static readonly ILogger logger = LogFactory.GetLogger<SnapshotBuffer<T>>();
private static readonly ILogger logger = LogFactory.GetLogger<SnapshotBuffer<T>>();

internal struct Snapshot
{
Expand All @@ -54,8 +54,8 @@ public Snapshot(T state, double time) : this()
}
}

readonly List<Snapshot> buffer = new List<Snapshot>();
readonly ISnapshotInterpolator<T> interpolator;
private readonly List<Snapshot> buffer = new List<Snapshot>();
private readonly ISnapshotInterpolator<T> interpolator;

internal IReadOnlyList<Snapshot> DebugBuffer => buffer;

Expand All @@ -75,12 +75,12 @@ public int SnapshotCount
get => buffer.Count;
}

Snapshot First
private Snapshot First
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
get => buffer[0];
}
Snapshot Last
private Snapshot Last
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
get => buffer[buffer.Count - 1];
Expand Down Expand Up @@ -134,17 +134,17 @@ public T GetLinearInterpolation(double now)
}

// edge cases are returned about, if code gets to this for loop then a valid from/to should exist...
for (int i = 0; i < buffer.Count - 1; i++)
for (var i = 0; i < buffer.Count - 1; i++)
{
Snapshot from = buffer[i];
Snapshot to = buffer[i + 1];
double fromTime = buffer[i].time;
double toTime = buffer[i + 1].time;
var from = buffer[i];
var to = buffer[i + 1];
var fromTime = buffer[i].time;
var toTime = buffer[i + 1].time;

// if between times, then use from/to
if (fromTime <= now && now <= toTime)
{
float alpha = (float)Clamp01((now - fromTime) / (toTime - fromTime));
var alpha = (float)Clamp01((now - fromTime) / (toTime - fromTime));
// todo add trace log
if (logger.LogEnabled()) logger.Log($"alpha:{alpha:0.000}");

Expand Down Expand Up @@ -172,7 +172,7 @@ private double Clamp01(double v)
public void RemoveOldSnapshots(double oldTime)
{
// Loop from newest to oldest...
for (int i = buffer.Count - 1; i >= 0; i--)
for (var i = buffer.Count - 1; i >= 0; i--)
{
// Is this one older than oldTime? If so, evict it.
if (buffer[i].time < oldTime)
Expand All @@ -197,12 +197,12 @@ public string ToDebugString(double now)

var builder = new StringBuilder();
builder.AppendLine($"count:{buffer.Count}, minTime:{buffer[0].time:0.000}, maxTime:{buffer[buffer.Count - 1].time:0.000}");
for (int i = 0; i < buffer.Count; i++)
for (var i = 0; i < buffer.Count; i++)
{
if (i != 0)
{
double fromTime = buffer[i - 1].time;
double toTime = buffer[i].time;
var fromTime = buffer[i - 1].time;
var toTime = buffer[i].time;
// if between times, then use from/to
if (fromTime <= now && now <= toTime)
{
Expand Down
76 changes: 38 additions & 38 deletions Assets/NetworkPositionSync/Runtime/SyncPositionBehaviour.cs
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@ namespace JamesFrowen.PositionSync
[AddComponentMenu("Network/SyncPosition/SyncPositionBehaviour")]
public class SyncPositionBehaviour : NetworkBehaviour
{
static readonly ILogger logger = LogFactory.GetLogger<SyncPositionBehaviour>();
private static readonly ILogger logger = LogFactory.GetLogger<SyncPositionBehaviour>();

/// <summary>
/// Checks if object needs syncing to clients
Expand Down Expand Up @@ -93,48 +93,48 @@ internal void ApplyOnClient(TransformState state, float time)
[Header("Synchronization Settings")]

[Tooltip("What transform should be synchronized?")]
[SerializeField] Transform target;
[SerializeField] private Transform target;

[Tooltip("If true, we will use local position and rotation. If false, we use world position and rotation.")]
[SerializeField] bool useLocalSpace = true;
[SerializeField] private bool useLocalSpace = true;

[Header("Authority")]
[Tooltip("Set to true if moves come from owner client, set to false if moves always come from server")]
[SerializeField] bool clientAuthority = false;
[SerializeField] private bool clientAuthority = false;

[Tooltip("Client Authority Sync Interval")]
[SerializeField] float clientSyncRate = 20;
[SerializeField] float ClientFixedSyncInterval => 1 / clientSyncRate;
[SerializeField] private float clientSyncRate = 20;
[SerializeField] private float ClientFixedSyncInterval => 1 / clientSyncRate;

[Tooltip("Debugging")]
[SerializeField] bool showDebugGui = false;

float syncTimer;
[SerializeField] private bool showDebugGui = false;
private float syncTimer;

/// <summary>
/// Set when client with authority updates the server
/// </summary>
bool _needsUpdate;
private bool _needsUpdate;

/// <summary>
/// latest values from client
/// </summary>
TransformState? _latestState;
private TransformState? _latestState;

// values for HasMoved/Rotated
Vector3 lastPosition;
Quaternion lastRotation;
private Vector3 lastPosition;
private Quaternion lastRotation;

// client
internal readonly SnapshotBuffer<TransformState> snapshotBuffer = new SnapshotBuffer<TransformState>(TransformState.CreateInterpolator());

#if DEBUG
ExponentialMovingAverage timeDelayAvg = new ExponentialMovingAverage(100);
void OnGUI()
private ExponentialMovingAverage timeDelayAvg = new ExponentialMovingAverage(100);

private void OnGUI()
{
if (showDebugGui)
{
float delay = _system.TimeSync.LatestServerTime - _system.TimeSync.InterpolationTimeField;
var delay = _system.TimeSync.LatestServerTime - _system.TimeSync.InterpolationTimeField;
timeDelayAvg.Add(delay);
GUILayout.Label($"ServerTime: {_system.TimeSync.LatestServerTime:0.000}");
GUILayout.Label($"InterpTime: {_system.TimeSync.InterpolationTimeField:0.000}");
Expand All @@ -144,7 +144,7 @@ void OnGUI()
}
#endif

void OnValidate()
private void OnValidate()
{
if (target == null)
target = transform;
Expand All @@ -153,7 +153,7 @@ void OnValidate()
/// <summary>
/// server auth or no owner, or host
/// </summary>
bool IsControlledByServer
private bool IsControlledByServer
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
get => !clientAuthority || Owner == null || Owner == Server.LocalPlayer;
Expand All @@ -162,13 +162,13 @@ bool IsControlledByServer
/// <summary>
/// Are we in control of this object when running a client auth setup and we own this object?
/// </summary>
bool IsLocalClientInControl
private bool IsLocalClientInControl
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
get => clientAuthority && HasAuthority;
}

Vector3 Position
private Vector3 Position
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
get
Expand All @@ -185,7 +185,7 @@ Vector3 Position
}
}

Quaternion Rotation
private Quaternion Rotation
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
get
Expand Down Expand Up @@ -227,11 +227,11 @@ internal void ClearNeedsUpdate()
/// </summary>
/// <returns></returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
bool HasMoved()
private bool HasMoved()
{
Vector3 precision = _system.PackSettings.precision;
Vector3 diff = lastPosition - Position;
bool moved = Mathf.Abs(diff.x) > precision.x
var precision = _system.PackSettings.precision;
var diff = lastPosition - Position;
var moved = Mathf.Abs(diff.x) > precision.x
|| Mathf.Abs(diff.y) > precision.y
|| Mathf.Abs(diff.z) > precision.z;

Expand All @@ -247,10 +247,10 @@ bool HasMoved()
/// </summary>
/// <returns></returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
bool HasRotated()
private bool HasRotated()
{
// todo fix?
bool rotated = Quaternion.Angle(lastRotation, Rotation) > 0.001f;
var rotated = Quaternion.Angle(lastRotation, Rotation) > 0.001f;

if (rotated)
{
Expand All @@ -269,9 +269,9 @@ private void Awake()
Identity.OnStopServer.AddListener(OnStopServer);
}

SyncPositionSystem _system;
private SyncPositionSystem _system;

void FindSystem()
private void FindSystem()
{
if (IsServer)
_system = ServerObjectManager.GetComponent<SyncPositionSystem>();
Expand Down Expand Up @@ -311,7 +311,7 @@ public void OnStopServer()
}
#endregion

void Update()
private void Update()
{
if (IsClient)
{
Expand All @@ -329,7 +329,7 @@ void Update()
/// <para>Adds to buffer for interpolation</para>
/// </summary>
/// <param name="state"></param>
void AddSnapShotToBuffer(TransformState state, float serverTime)
private void AddSnapShotToBuffer(TransformState state, float serverTime)
{
// dont apply on local owner
if (IsLocalClientInControl)
Expand All @@ -349,7 +349,7 @@ void AddSnapShotToBuffer(TransformState state, float serverTime)


#region Client Sync Update
void ClientAuthorityUpdate()
private void ClientAuthorityUpdate()
{
// host client doesn't need to update server
if (IsServer) { return; }
Expand Down Expand Up @@ -394,7 +394,7 @@ private void SendMessageToServer()
/// <para>no need to interpolate on server</para>
/// </summary>
/// <param name="state"></param>
void ApplyStateNoInterpolation(TransformState state)
private void ApplyStateNoInterpolation(TransformState state)
{
Position = state.position;
Rotation = state.rotation;
Expand All @@ -403,13 +403,13 @@ void ApplyStateNoInterpolation(TransformState state)


#region Client Interpolation
void ClientInterpolation()
private void ClientInterpolation()
{
if (snapshotBuffer.IsEmpty)
return;

float snapshotTime = _system.TimeSync.InterpolationTimeField;
TransformState state = snapshotBuffer.GetLinearInterpolation(snapshotTime);
var snapshotTime = _system.TimeSync.InterpolationTimeField;
var state = snapshotBuffer.GetLinearInterpolation(snapshotTime);
// todo add trace log
if (logger.LogEnabled())
logger.Log($"p1: {Position.x}, p2: {state.position.x}, delta: {Position.x - state.position.x}");
Expand All @@ -418,7 +418,7 @@ void ClientInterpolation()
Rotation = state.rotation;

// remove snapshots older than 2times sync interval, they will never be used by Interpolation
float removeTime = snapshotTime - (_system.TimeSync.ClientDelay * 1.5f);
var removeTime = snapshotTime - (_system.TimeSync.ClientDelay * 1.5f);
snapshotBuffer.RemoveOldSnapshots(removeTime);
}
#endregion
Expand All @@ -431,7 +431,7 @@ public void Teleport(Vector3 position, Quaternion rotation)
}

[ClientRpc]
void RpcTeleport(Vector3 position, Quaternion rotation)
private void RpcTeleport(Vector3 position, Quaternion rotation)
{
snapshotBuffer.ClearBuffer();
transform.SetPositionAndRotation(position, rotation);
Expand Down
Loading

0 comments on commit aefde61

Please sign in to comment.