| using System; |
| using UnityEngine; |
| namespace OnDeviceAgent.Inference |
| { |
|
|
| public sealed class FloatRingBuffer |
| { |
| readonly float[] m_Buffer; |
| int m_Start; |
| int m_Count; |
|
|
| public FloatRingBuffer(int capacity) |
| { |
| m_Buffer = new float[capacity]; |
| } |
|
|
| public int Count => m_Count; |
| public int Capacity => m_Buffer.Length; |
|
|
| public float this[int index] => m_Buffer[PhysicalIndex(index)]; |
|
|
| public void Clear() |
| { |
| m_Start = 0; |
| m_Count = 0; |
| } |
|
|
| public void Add(float value) |
| { |
| if (m_Count == m_Buffer.Length) |
| { |
| m_Buffer[m_Start] = value; |
| m_Start = (m_Start + 1) % m_Buffer.Length; |
| return; |
| } |
|
|
| m_Buffer[PhysicalIndex(m_Count)] = value; |
| m_Count++; |
| } |
|
|
| public void AddRange(float[] source, int length) |
| { |
| AddRange(source, 0, length); |
| } |
|
|
| public void AddRange(float[] source, int sourceIndex, int length) |
| { |
| if (length >= m_Buffer.Length) |
| { |
| Array.Copy(source, sourceIndex + length - m_Buffer.Length, m_Buffer, 0, m_Buffer.Length); |
| m_Start = 0; |
| m_Count = m_Buffer.Length; |
| return; |
| } |
|
|
| var overflow = m_Count + length - m_Buffer.Length; |
| if (overflow > 0) |
| RemoveFromStart(overflow); |
|
|
| CopyInto(source, sourceIndex, PhysicalIndex(m_Count), length); |
| m_Count += length; |
| } |
|
|
| public void CopyTo(int sourceIndex, float[] destination, int destinationIndex, int length) |
| { |
| var physicalIndex = PhysicalIndex(sourceIndex); |
| var firstLength = Mathf.Min(length, m_Buffer.Length - physicalIndex); |
| Array.Copy(m_Buffer, physicalIndex, destination, destinationIndex, firstLength); |
|
|
| var remaining = length - firstLength; |
| if (remaining > 0) |
| Array.Copy(m_Buffer, 0, destination, destinationIndex + firstLength, remaining); |
| } |
|
|
| public void CopyLatest(int length, float[] destination, int destinationIndex) |
| { |
| CopyTo(m_Count - length, destination, destinationIndex, length); |
| } |
|
|
| public void RemoveFromStart(int length) |
| { |
| m_Start = PhysicalIndex(length); |
| m_Count -= length; |
| } |
|
|
| int PhysicalIndex(int logicalIndex) |
| { |
| var index = m_Start + logicalIndex; |
| return index >= m_Buffer.Length ? index - m_Buffer.Length : index; |
| } |
|
|
| void CopyInto(float[] source, int sourceIndex, int destinationIndex, int length) |
| { |
| var firstLength = Mathf.Min(length, m_Buffer.Length - destinationIndex); |
| Array.Copy(source, sourceIndex, m_Buffer, destinationIndex, firstLength); |
|
|
| var remaining = length - firstLength; |
| if (remaining > 0) |
| Array.Copy(source, sourceIndex + firstLength, m_Buffer, 0, remaining); |
| } |
| } |
| } |
|
|