namespace Titano.Core.Motion; /// Smoothing of per-frame series (camera paths). internal static class PathSmoother { /// /// Gaussian-weighted local linear regression (degree-1 LOESS with a Gaussian kernel truncated at 3σ): /// each sample is replaced by the value at its own position of a line fitted to its neighbourhood. /// Linear trends (pans) pass unchanged and the ends are not pulled toward the interior, unlike a plain /// Gaussian average. σ ≤ 0 returns a copy. /// public static double[] LocalLinear(ReadOnlySpan values, double sigma) { var n = values.Length; var result = values.ToArray(); if (!(sigma > 0) || n < 2) return result; var radius = (int)double.Ceiling(3 * sigma); Span kernel = radius <= 1024 ? stackalloc double[radius + 1] : new double[radius + 1]; for (var d = 0; d <= radius; d++) kernel[d] = double.Exp(-0.5 * d * d / (sigma * sigma)); for (var k = 0; k < n; k++) { double s0 = 0, s1 = 0, s2 = 0, t0 = 0, t1 = 0; var lo = int.Max(0, k - radius); var hi = int.Min(n - 1, k + radius); for (var j = lo; j <= hi; j++) { var d = j - k; var w = kernel[int.Abs(d)]; s0 += w; s1 += w * d; s2 += w * d * d; t0 += w * values[j]; t1 += w * d * values[j]; } var det = s0 * s2 - s1 * s1; result[k] = det > 1e-12 * s0 * s0 ? (s2 * t0 - s1 * t1) / det : t0 / s0; } return result; } }