You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

101 lines
3.0 KiB
C#

using UnityEngine;
namespace Fusion.Addons.SimpleKCC
{
public sealed class Vector2Accumulator
{
public float SmoothingWindow;
public bool UseDirectionFilter;
private SmoothVector2 _smoothValues = new SmoothVector2(256);
private Vector2 _accumulatedValue;
private Vector2 _unprocessedValue;
private float _unprocessedDeltaTime;
private int _lastAccumulateFrame;
private int _lastConsumeFrame;
public Vector2 AccumulatedValue => _accumulatedValue;
public Vector2Accumulator()
: this(0f, useDirectionFilter: false)
{
}
public Vector2Accumulator(float smoothingWindow)
: this(smoothingWindow, useDirectionFilter: false)
{
}
public Vector2Accumulator(float smoothingWindow, bool useDirectionFilter)
{
SmoothingWindow = smoothingWindow;
UseDirectionFilter = useDirectionFilter;
}
public void Accumulate(Vector2 value)
{
int frameCount = Time.frameCount;
if (frameCount == _lastAccumulateFrame)
{
return;
}
float unscaledDeltaTime = Time.unscaledDeltaTime;
if (SmoothingWindow > 0f)
{
if (UseDirectionFilter)
{
_smoothValues.FilterValues(value.x < 0f, value.x > 0f, value.y < 0f, value.y > 0f);
}
_smoothValues.AddValue(frameCount, unscaledDeltaTime, value);
value = _smoothValues.CalculateSmoothValue(SmoothingWindow, unscaledDeltaTime);
}
_accumulatedValue += value;
_unprocessedValue = value;
_unprocessedDeltaTime = unscaledDeltaTime;
_lastAccumulateFrame = frameCount;
}
public Vector2 Consume()
{
Vector2 accumulatedValue = _accumulatedValue;
_accumulatedValue = default(Vector2);
_unprocessedValue = default(Vector2);
_unprocessedDeltaTime = 0f;
_lastConsumeFrame = Time.frameCount;
return accumulatedValue;
}
public Vector2 ConsumeTickAligned(NetworkRunner runner)
{
int frameCount = Time.frameCount;
Vector2 vector = _accumulatedValue - _unprocessedValue;
float num = ((_lastConsumeFrame != frameCount) ? runner.LocalAlpha : 0f);
float num2 = (1f - num) * runner.DeltaTime;
Vector2 vector2 = _unprocessedValue * Mathf.Clamp01(num2 / _unprocessedDeltaTime);
vector += vector2;
_unprocessedValue -= vector2;
_unprocessedDeltaTime -= num2;
_accumulatedValue -= vector;
_lastConsumeFrame = frameCount;
return vector;
}
public void Clear()
{
_smoothValues.ClearValues();
_accumulatedValue = default(Vector2);
_unprocessedValue = default(Vector2);
_unprocessedDeltaTime = 0f;
}
}
}