using System.Buffers;
namespace Chronos.Core.Motion;
/// Summary of a motion field's vector magnitudes (pixels per frame).
public readonly record struct MotionStatistics(
double MeanMagnitude,
double MedianMagnitude,
double P95Magnitude,
double MaxMagnitude,
double MeanU,
double MeanV,
double ReliableFraction);
///
/// Dense motion vectors (full-resolution pixels per frame) on a regular grid: node (i, j) describes the
/// pixel at (i·Step, j·Step). A vector (u, v) at p means the content at p in the first frame is found at
/// p + (u, v) in the second. holds the forward–backward consistency error in pixels
/// (NaN when not checked). Storage is pooled; dispose the field when done.
///
public sealed class MotionField : IDisposable
{
private float[]? _u;
private float[]? _v;
private float[]? _error;
public MotionField(int imageWidth, int imageHeight, int step)
{
ArgumentOutOfRangeException.ThrowIfNegativeOrZero(imageWidth);
ArgumentOutOfRangeException.ThrowIfNegativeOrZero(imageHeight);
ArgumentOutOfRangeException.ThrowIfNegativeOrZero(step);
ImageWidth = imageWidth;
ImageHeight = imageHeight;
Step = step;
Columns = (imageWidth - 1) / step + 1;
Rows = (imageHeight - 1) / step + 1;
var n = Columns * Rows;
_u = ArrayPool.Shared.Rent(n);
_v = ArrayPool.Shared.Rent(n);
_error = ArrayPool.Shared.Rent(n);
U.Clear();
V.Clear();
Error.Fill(float.NaN);
}
public int ImageWidth { get; }
public int ImageHeight { get; }
/// Grid spacing in full-resolution pixels.
public int Step { get; }
public int Columns { get; }
public int Rows { get; }
public int Count => Columns * Rows;
/// Horizontal components, row-major over the grid.
public Span U => Storage(_u);
/// Vertical components, row-major over the grid.
public Span V => Storage(_v);
/// Forward–backward error |w(p) + w'(p + w(p))| in pixels; NaN when unchecked.
public Span Error => Storage(_error);
/// True when has been filled by a forward–backward check.
public bool HasConsistency { get; internal set; }
/// Bilinearly interpolated vector at a full-resolution pixel-centre position (clamped to the grid).
public (float U, float V) Sample(double x, double y)
{
var gx = (float)(x / Step);
var gy = (float)(y / Step);
return (PlaneOps.Bilinear(U, Columns, Rows, gx, gy), PlaneOps.Bilinear(V, Columns, Rows, gx, gy));
}
/// Bilinearly interpolated forward–backward error (NaN when unchecked).
public float SampleError(double x, double y) =>
HasConsistency ? PlaneOps.Bilinear(Error, Columns, Rows, (float)(x / Step), (float)(y / Step)) : float.NaN;
/// Counts of vector magnitudes in equal bins over [0, max]; larger values land in the last bin.
public int[] MagnitudeHistogram(int bins, double maxMagnitude)
{
ArgumentOutOfRangeException.ThrowIfNegativeOrZero(bins);
if (!(maxMagnitude > 0)) throw new ArgumentOutOfRangeException(nameof(maxMagnitude));
var histogram = new int[bins];
var u = U;
var v = V;
var scale = bins / maxMagnitude;
for (var i = 0; i < u.Length; i++)
{
var m = double.Sqrt((double)u[i] * u[i] + (double)v[i] * v[i]);
histogram[int.Min(bins - 1, (int)(m * scale))]++;
}
return histogram;
}
/// Magnitude statistics; vectors with a forward–backward error above px count as unreliable.
public MotionStatistics Statistics(double reliableError = 1.0)
{
var n = Count;
var magnitudes = ArrayPool.Shared.Rent(n);
try
{
var u = U;
var v = V;
var error = Error;
double sum = 0, su = 0, sv = 0, max = 0;
var reliable = 0;
for (var i = 0; i < n; i++)
{
var m = float.Sqrt(u[i] * u[i] + v[i] * v[i]);
magnitudes[i] = m;
sum += m;
su += u[i];
sv += v[i];
max = double.Max(max, m);
if (!HasConsistency || error[i] <= reliableError) reliable++;
}
var span = magnitudes.AsSpan(0, n);
var median = PlaneOps.Median(span);
var p95 = PlaneOps.Select(span, int.Min(n - 1, (int)double.Ceiling(0.95 * n) - 1));
return new MotionStatistics(sum / n, median, p95, max, su / n, sv / n, reliable / (double)n);
}
finally
{
ArrayPool.Shared.Return(magnitudes);
}
}
/// Sets every vector to (u, v).
public void Fill(float u, float v)
{
U.Fill(u);
V.Fill(v);
}
public void Dispose()
{
Return(ref _u);
Return(ref _v);
Return(ref _error);
}
private Span Storage(float[]? array) => (array ?? throw new ObjectDisposedException(nameof(MotionField))).AsSpan(0, Count);
private static void Return(ref float[]? array)
{
var a = Interlocked.Exchange(ref array, null);
if (a is not null) ArrayPool.Shared.Return(a);
}
}