| | | 1 | | using System; |
| | | 2 | | using System.Collections.Generic; |
| | | 3 | | using System.Diagnostics; |
| | | 4 | | using System.Linq; |
| | | 5 | | using NLog; |
| | | 6 | | using ReFlex.Core.Common.Components; |
| | | 7 | | using ReFlex.Core.Common.Util; |
| | | 8 | | using ReFlex.Core.Filtering.Components; |
| | | 9 | | using ReFlex.Core.Interactivity.Util; |
| | | 10 | | using Math = System.Math; |
| | | 11 | | |
| | | 12 | | namespace ReFlex.Core.Interactivity.Components |
| | | 13 | | { |
| | | 14 | | public class InteractionSmoothingBehaviour |
| | | 15 | | { |
| | 2 | 16 | | private static readonly Logger Logger = LogManager.GetCurrentClassLogger(); |
| | | 17 | | |
| | | 18 | | #region Fields |
| | | 19 | | |
| | 688 | 20 | | private List<InteractionFrame> _interactionFrames = new List<InteractionFrame>(); |
| | | 21 | | |
| | | 22 | | private sealed class Track |
| | | 23 | | { |
| | 18398 | 24 | | public Interaction LastMeasurement { get; set; } |
| | 13562 | 25 | | public List<(double Time, Interaction Measurement)> Samples { get; } = new(); |
| | 3606 | 26 | | public Interaction Smoothed { get; set; } |
| | 600 | 27 | | public ButterworthFilter Butterworth { get; set; } |
| | 16196 | 28 | | public int LastSeenFrame { get; set; } |
| | 7700 | 29 | | public double LastSeenTime { get; set; } |
| | 8914 | 30 | | public double LastDetectedAt { get; set; } |
| | 4172 | 31 | | public double ConfidenceUpdatedAt { get; set; } |
| | 9374 | 32 | | public float Confidence { get; set; } |
| | 9604 | 33 | | public Point3 MatchingPosition { get; set; } |
| | | 34 | | } |
| | | 35 | | |
| | 688 | 36 | | private readonly Dictionary<int, Track> _tracks = new(); |
| | | 37 | | private int _numFramesHistory; |
| | | 38 | | private int _numFramesSmoothing; |
| | 688 | 39 | | private int _requestedNumFramesForPrediction = 3; |
| | 688 | 40 | | private float _secondDerivationMagnitude = .5f; |
| | 688 | 41 | | private double _contactRetentionSeconds = .1; |
| | | 42 | | |
| | | 43 | | private double? _timestampSeconds; |
| | | 44 | | private double? _processedTimestampSeconds; |
| | | 45 | | private double? _observationTimeoutSeconds; |
| | 688 | 46 | | private double _predictionHorizonSeconds = .05; |
| | 688 | 47 | | private float _confidenceDecayPerSecond = 30; |
| | 688 | 48 | | private float _confidenceGainPerSecond = 30; |
| | | 49 | | public const float DefaultAssignmentMissCost = .5f; |
| | | 50 | | public const float DefaultAssignmentBirthCost = .5f; |
| | 688 | 51 | | private float _assignmentMissCost = DefaultAssignmentMissCost; |
| | 688 | 52 | | private float _assignmentBirthCost = DefaultAssignmentBirthCost; |
| | 688 | 53 | | private int _frameId = 0; |
| | 688 | 54 | | private int _maxTouchId = 0; |
| | 688 | 55 | | private FilterType _type = FilterType.None; |
| | | 56 | | private IPointFilter _filter; |
| | | 57 | | |
| | 688 | 58 | | private float _depthScale = 500f; |
| | | 59 | | |
| | | 60 | | #endregion |
| | | 61 | | |
| | | 62 | | #region Properties |
| | | 63 | | |
| | | 64 | | /// <summary> |
| | | 65 | | /// Strict Manhattan-distance gate in sensor pixels. The legacy helper named |
| | | 66 | | /// Point3.Squared2DDistance computes |dx| + |dy|, not squared Euclidean distance. |
| | | 67 | | /// </summary> |
| | 3930 | 68 | | public float TouchMergeDistance2D { get; set; } = 64f; |
| | | 69 | | |
| | | 70 | | /// <summary>Use global minimum-cost assignment; false restores greedy one-to-one matching. |
| | | 71 | | /// Changing this strategy preserves all existing contact state and history.</summary> |
| | 3058 | 72 | | public bool UseMinimumCostAssignment { get; set; } = true; |
| | | 73 | | |
| | | 74 | | /// <summary>Cost of leaving a live track unmatched for one observation. Distances are |
| | | 75 | | /// normalized by TouchMergeDistance2D; this does not change retention or confidence.</summary> |
| | | 76 | | public float AssignmentMissCost |
| | | 77 | | { |
| | 3842 | 78 | | get => _assignmentMissCost; |
| | 288 | 79 | | set => _assignmentMissCost = float.IsFinite(value) && value >= 0 |
| | 288 | 80 | | ? value : throw new ArgumentOutOfRangeException(nameof(value)); |
| | | 81 | | } |
| | | 82 | | |
| | | 83 | | /// <summary>Cost of starting a new track, in the same normalized units as AssignmentMissCost.</summary> |
| | | 84 | | public float AssignmentBirthCost |
| | | 85 | | { |
| | 3650 | 86 | | get => _assignmentBirthCost; |
| | 290 | 87 | | set => _assignmentBirthCost = float.IsFinite(value) && value >= 0 |
| | 290 | 88 | | ? value : throw new ArgumentOutOfRangeException(nameof(value)); |
| | | 89 | | } |
| | | 90 | | |
| | | 91 | | /// <summary>Maximum stored frames; zero disables tracking and smoothing.</summary> |
| | | 92 | | public int NumFramesHistory |
| | | 93 | | { |
| | 12346 | 94 | | get => _numFramesHistory; |
| | | 95 | | set |
| | 834 | 96 | | { |
| | 834 | 97 | | _numFramesHistory = Math.Max(0, value); |
| | 834 | 98 | | NumFramesSmoothing = _numFramesSmoothing; |
| | 834 | 99 | | UpdateInteractionFramesList(); |
| | 834 | 100 | | if (_numFramesHistory == 0) |
| | 26 | 101 | | _tracks.Clear(); |
| | 834 | 102 | | UpdateFilterType(_type); |
| | 834 | 103 | | } |
| | | 104 | | } |
| | | 105 | | |
| | | 106 | | public int NumFramesSmoothing |
| | | 107 | | { |
| | 6442 | 108 | | get => _numFramesSmoothing; |
| | | 109 | | set |
| | 1388 | 110 | | { |
| | 1388 | 111 | | var bounded = Math.Clamp(value, 0, NumFramesHistory); |
| | 1388 | 112 | | if (_numFramesSmoothing != bounded) |
| | 1554 | 113 | | foreach (var track in _tracks.Values) track.Butterworth = null; |
| | 1388 | 114 | | _numFramesSmoothing = bounded; |
| | 1388 | 115 | | UpdateFilterType(_type); |
| | 1388 | 116 | | } |
| | | 117 | | } |
| | | 118 | | |
| | | 119 | | private static double ValidateContactRetention(double value) => |
| | 1064 | 120 | | double.IsFinite(value) && value >= 0 ? value : |
| | 1064 | 121 | | throw new ArgumentOutOfRangeException(nameof(value), "Contact retention must be finite and non-negative |
| | | 122 | | |
| | | 123 | | /// <summary>Maximum elapsed seconds since the last measurement, inclusive; independent of history capacity.</su |
| | | 124 | | public double ContactRetentionSeconds |
| | | 125 | | { |
| | 5622 | 126 | | get => _contactRetentionSeconds; |
| | 750 | 127 | | set => _contactRetentionSeconds = ValidateContactRetention(value); |
| | | 128 | | } |
| | | 129 | | |
| | | 130 | | /// <summary>Timeout without a completed sensor observation. Standalone callers retain the |
| | | 131 | | /// legacy retention deadline unless they explicitly configure a separate observation timeout.</summary> |
| | | 132 | | public double ObservationTimeoutSeconds |
| | | 133 | | { |
| | 5392 | 134 | | get => _observationTimeoutSeconds ?? ContactRetentionSeconds; |
| | 314 | 135 | | set => _observationTimeoutSeconds = ValidateContactRetention(value); |
| | | 136 | | } |
| | | 137 | | |
| | 2826 | 138 | | public bool UseVelocityForMapping { get; set; } |
| | 2546 | 139 | | public bool UseSecondDerivation { get; set; } |
| | | 140 | | /// <summary>Effective sample capacity. Preserve the requested value so history growth restores it.</summary> |
| | | 141 | | public int NumFramesForPrediction |
| | | 142 | | { |
| | 4156 | 143 | | get => Math.Min(_requestedNumFramesForPrediction, NumFramesHistory); |
| | 154 | 144 | | set => _requestedNumFramesForPrediction = Math.Max(2, value); |
| | | 145 | | } |
| | | 146 | | public float SecondDerivationMagnitude |
| | | 147 | | { |
| | 1226 | 148 | | get => _secondDerivationMagnitude; |
| | 56 | 149 | | set => _secondDerivationMagnitude = float.IsFinite(value) && value >= 0 && value <= 1 |
| | 56 | 150 | | ? value : throw new ArgumentOutOfRangeException(nameof(value)); |
| | | 151 | | } |
| | | 152 | | |
| | | 153 | | /// <summary>Explicit diagnostic forecast horizon; matching always uses the actual frame time.</summary> |
| | | 154 | | public double PredictionHorizonSeconds |
| | | 155 | | { |
| | 792 | 156 | | get => _predictionHorizonSeconds; |
| | 144 | 157 | | set => _predictionHorizonSeconds = double.IsFinite(value) && value >= 0 && value <= 1 |
| | 144 | 158 | | ? value : throw new ArgumentOutOfRangeException(nameof(value)); |
| | | 159 | | } |
| | | 160 | | |
| | | 161 | | /// <summary>Loss of confidence per second without measurements; zero disables decay.</summary> |
| | | 162 | | public float ConfidenceDecayPerSecond |
| | | 163 | | { |
| | 750 | 164 | | get => _confidenceDecayPerSecond; |
| | 102 | 165 | | set => _confidenceDecayPerSecond = float.IsFinite(value) && value >= 0 |
| | 102 | 166 | | ? value : throw new ArgumentOutOfRangeException(nameof(value)); |
| | | 167 | | } |
| | | 168 | | |
| | | 169 | | /// <summary>Confirmation gained per observed second; missing intervals never earn confidence.</summary> |
| | | 170 | | public float ConfidenceGainPerSecond |
| | | 171 | | { |
| | 1806 | 172 | | get => _confidenceGainPerSecond; |
| | 84 | 173 | | set => _confidenceGainPerSecond = float.IsFinite(value) && value >= 0 |
| | 84 | 174 | | ? value : throw new ArgumentOutOfRangeException(nameof(value)); |
| | | 175 | | } |
| | | 176 | | |
| | 792 | 177 | | public int CurrentFrameId => _frameId; |
| | 508 | 178 | | public int CurrentMaxId => _maxTouchId; |
| | | 179 | | |
| | | 180 | | /// <summary>Saturation ceiling only. Reaching it never ends a measured contact.</summary> |
| | 4064 | 181 | | public int MaxConfidence { get; set; } |
| | | 182 | | |
| | | 183 | | public float DepthScale |
| | | 184 | | { |
| | 0 | 185 | | get => _depthScale; |
| | 332 | 186 | | set => _depthScale = float.IsFinite(value) && value > 0 |
| | 332 | 187 | | ? value : throw new ArgumentOutOfRangeException(nameof(value), "Depth scale must be finite and positive. |
| | | 188 | | } |
| | | 189 | | |
| | 2194 | 190 | | public InteractionFrame[] InteractionsFramesCache => _interactionFrames |
| | 20870 | 191 | | .Select(frame => new InteractionFrame(frame.FrameId, |
| | 47686 | 192 | | frame.Interactions.Select(interaction => new Interaction(interaction)).ToList(), frame.TimestampSeconds) |
| | | 193 | | |
| | | 194 | | #endregion |
| | | 195 | | |
| | | 196 | | #region Constructor |
| | | 197 | | |
| | 688 | 198 | | public InteractionSmoothingBehaviour(int numFramesHistory) |
| | 688 | 199 | | { |
| | 688 | 200 | | NumFramesHistory = numFramesHistory; |
| | 688 | 201 | | } |
| | | 202 | | |
| | | 203 | | #endregion |
| | | 204 | | |
| | | 205 | | #region public Methods |
| | | 206 | | |
| | | 207 | | public void Reset() |
| | 14 | 208 | | { |
| | 14 | 209 | | _frameId = 0; |
| | 14 | 210 | | _timestampSeconds = null; |
| | 14 | 211 | | _processedTimestampSeconds = null; |
| | 14 | 212 | | _maxTouchId = 0; |
| | 14 | 213 | | _interactionFrames.Clear(); |
| | 14 | 214 | | _tracks.Clear(); |
| | 14 | 215 | | } |
| | | 216 | | |
| | | 217 | | public void UpdateFilterType(FilterType type) |
| | 2640 | 218 | | { |
| | 2640 | 219 | | if (_type != type) |
| | 210 | 220 | | foreach (var track in _tracks.Values) track.Butterworth = null; |
| | 2640 | 221 | | _type = type; |
| | | 222 | | |
| | 2640 | 223 | | switch (type) |
| | | 224 | | { |
| | | 225 | | case FilterType.MovingAverage: |
| | 46 | 226 | | _filter = new SimpleMovingAverageFilter(Math.Max(1, NumFramesSmoothing)); |
| | 46 | 227 | | break; |
| | | 228 | | case FilterType.WeightedMovingAverage: |
| | 14 | 229 | | _filter = new WeightedMovingAverageFilter(Math.Max(1, NumFramesSmoothing)); |
| | 14 | 230 | | break; |
| | | 231 | | case FilterType.PolynomialFit: |
| | 6 | 232 | | _filter = new PolynomialFitFilter(); |
| | 6 | 233 | | break; |
| | | 234 | | case FilterType.WeightedPolynomialFit: |
| | 2 | 235 | | _filter = new WeightedPolynomialFitFilter(); |
| | 2 | 236 | | break; |
| | | 237 | | case FilterType.SavitzkyGolay: |
| | 16 | 238 | | { |
| | 16 | 239 | | var sidePoints = Math.Max(0, (NumFramesSmoothing - 1) / 2); |
| | 16 | 240 | | var order = Math.Min(sidePoints, 3); |
| | 16 | 241 | | _filter = new SavitzkyGolayFilter(sidePoints, order); |
| | 16 | 242 | | break; |
| | | 243 | | } |
| | | 244 | | case FilterType.Butterworth: |
| | 8 | 245 | | _filter = new ButterworthFilter(); |
| | 8 | 246 | | break; |
| | | 247 | | default: |
| | 2548 | 248 | | _filter = null; |
| | 2548 | 249 | | break; |
| | | 250 | | } |
| | | 251 | | |
| | 2640 | 252 | | Logger.Info($"switched Interaction Processing Smoothing Filter to {_filter?.GetType().FullName ?? "None\""}" |
| | 2640 | 253 | | } |
| | | 254 | | |
| | | 255 | | public InteractionFrame Update(IList<Interaction> rawInteractions) => |
| | 12 | 256 | | Update(rawInteractions, (double)Stopwatch.GetTimestamp() / Stopwatch.Frequency); |
| | | 257 | | |
| | | 258 | | /// <summary> |
| | | 259 | | /// Process one observation frame at a strictly increasing monotonic timestamp in seconds. |
| | | 260 | | /// Callers with capture timestamps may supply them here. Invalid times are rejected before |
| | | 261 | | /// mutating tracking state; Interaction.Time remains the legacy wall-clock field. |
| | | 262 | | /// </summary> |
| | | 263 | | public InteractionFrame Update(IList<Interaction> rawInteractions, double timestampSeconds) |
| | 2084 | 264 | | => Update(rawInteractions, timestampSeconds, timestampSeconds); |
| | | 265 | | |
| | | 266 | | /// <summary>Motion uses capture time; liveness and confidence decay use completion time. |
| | | 267 | | /// Slow but continuously successful observations must not look like missing detections.</summary> |
| | | 268 | | public InteractionFrame Update(IList<Interaction> rawInteractions, double timestampSeconds, double processedTime |
| | 2304 | 269 | | { |
| | 2304 | 270 | | if (!double.IsFinite(timestampSeconds) || |
| | 2304 | 271 | | (_timestampSeconds.HasValue && timestampSeconds <= _timestampSeconds.Value)) |
| | 8 | 272 | | throw new ArgumentOutOfRangeException(nameof(timestampSeconds), "Frame times must be finite and strictly |
| | 2296 | 273 | | if (!double.IsFinite(processedTimestampSeconds) || processedTimestampSeconds < timestampSeconds || |
| | 2296 | 274 | | (_processedTimestampSeconds.HasValue && processedTimestampSeconds < _processedTimestampSeconds.Value)) |
| | 0 | 275 | | throw new ArgumentOutOfRangeException(nameof(processedTimestampSeconds)); |
| | 2296 | 276 | | _timestampSeconds = timestampSeconds; |
| | 2296 | 277 | | _processedTimestampSeconds = processedTimestampSeconds; |
| | 2296 | 278 | | _frameId++; |
| | | 279 | | |
| | | 280 | | // Only internal copies are assigned IDs or retained in the tracking history. |
| | 5214 | 281 | | var candidates = rawInteractions.Take(20).Select(item => new Interaction(item)).ToList(); |
| | 2296 | 282 | | var mappedInteractionIds = MapClosestInteraction(candidates); |
| | 2296 | 283 | | var newFrame = new InteractionFrame(_frameId, mappedInteractionIds, timestampSeconds); |
| | | 284 | | |
| | | 285 | | // With history disabled, still publish current measurements, using fresh IDs each frame. |
| | 2296 | 286 | | if (NumFramesHistory == 0) |
| | 32 | 287 | | { |
| | 32 | 288 | | _tracks.Clear(); |
| | 32 | 289 | | return newFrame; |
| | | 290 | | } |
| | | 291 | | |
| | 2264 | 292 | | _interactionFrames.Add(newFrame); |
| | 2264 | 293 | | UpdateInteractionFramesList(); |
| | 2264 | 294 | | var result = new InteractionFrame(_frameId, timestampSeconds); |
| | 15464 | 295 | | foreach (var pair in _tracks.OrderBy(pair => pair.Key).ToArray()) |
| | 3382 | 296 | | { |
| | 3382 | 297 | | var missingFrames = _frameId - pair.Value.LastSeenFrame; |
| | 3382 | 298 | | if (IsExpired(pair.Value, processedTimestampSeconds, _frameId)) |
| | 0 | 299 | | { |
| | | 300 | | // Ended tracks are removed permanently, even while their measurements remain cached. |
| | 0 | 301 | | _tracks.Remove(pair.Key); |
| | 0 | 302 | | continue; |
| | | 303 | | } |
| | | 304 | | |
| | 3382 | 305 | | var smoothed = missingFrames == 0 ? SmoothInteraction(pair.Key) |
| | 3382 | 306 | | : new Interaction(pair.Value.Smoothed ?? pair.Value.LastMeasurement); |
| | 6272 | 307 | | if (missingFrames == 0) pair.Value.Smoothed = new Interaction(smoothed); |
| | 3382 | 308 | | if (smoothed == null) |
| | 0 | 309 | | continue; |
| | 3382 | 310 | | if (missingFrames > 0) |
| | 492 | 311 | | { |
| | 492 | 312 | | DecayConfidence(pair.Value, processedTimestampSeconds); |
| | 492 | 313 | | smoothed.TrackingState = InteractionTrackingState.Lost; |
| | 492 | 314 | | } |
| | 3382 | 315 | | smoothed.Confidence = pair.Value.Confidence; |
| | 3382 | 316 | | result.Interactions.Add(smoothed); |
| | 3382 | 317 | | } |
| | | 318 | | |
| | 2264 | 319 | | return result; |
| | 2296 | 320 | | } |
| | | 321 | | |
| | | 322 | | /// <summary>Age publication without inventing a sensor observation or changing the measured |
| | | 323 | | /// sample clock. Expiry is permanent; confidence during sensor gaps is projected from live state.</summary> |
| | | 324 | | public InteractionFrame OutputAt(double timestampSeconds, bool markLost = true) |
| | 264 | 325 | | { |
| | 264 | 326 | | if (!double.IsFinite(timestampSeconds) || (_processedTimestampSeconds.HasValue && timestampSeconds < _proces |
| | 0 | 327 | | throw new ArgumentOutOfRangeException(nameof(timestampSeconds)); |
| | 264 | 328 | | var output = new InteractionFrame(_frameId, timestampSeconds); |
| | 1276 | 329 | | foreach (var pair in _tracks.OrderBy(pair => pair.Key).ToArray()) |
| | 242 | 330 | | { |
| | 242 | 331 | | var track = pair.Value; |
| | 242 | 332 | | if (IsExpired(track, timestampSeconds, _frameId)) |
| | 18 | 333 | | { |
| | 18 | 334 | | _tracks.Remove(pair.Key); |
| | 18 | 335 | | continue; |
| | | 336 | | } |
| | 224 | 337 | | var item = new Interaction(track.Smoothed ?? track.LastMeasurement); |
| | 224 | 338 | | if (markLost || track.LastSeenFrame != _frameId) |
| | 222 | 339 | | { |
| | 222 | 340 | | item.TrackingState = InteractionTrackingState.Lost; |
| | 222 | 341 | | item.Confidence = Math.Max(0, track.Confidence - (float)(ConfidenceDecayPerSecond * |
| | 222 | 342 | | (timestampSeconds - track.ConfidenceUpdatedAt))); |
| | 222 | 343 | | } |
| | 2 | 344 | | else item.Confidence = track.Confidence; |
| | 224 | 345 | | output.Interactions.Add(item); |
| | 224 | 346 | | } |
| | 264 | 347 | | return output; |
| | 264 | 348 | | } |
| | | 349 | | |
| | | 350 | | #endregion |
| | | 351 | | |
| | | 352 | | /// <summary> |
| | | 353 | | /// order list of frames by frame id descending and remove old frames |
| | | 354 | | /// </summary> |
| | | 355 | | private void UpdateInteractionFramesList() |
| | 3098 | 356 | | { |
| | 3098 | 357 | | if (_interactionFrames.Count > NumFramesHistory) |
| | 908 | 358 | | { |
| | | 359 | | try |
| | 908 | 360 | | { |
| | 12032 | 361 | | _interactionFrames = _interactionFrames.OrderByDescending(frame => frame.FrameId) |
| | 908 | 362 | | .Take(NumFramesHistory).ToList(); |
| | 908 | 363 | | } |
| | 0 | 364 | | catch (Exception e) |
| | 0 | 365 | | { |
| | 0 | 366 | | Logger.Error(e, $"Exception catched in {GetType()}.{nameof(this.UpdateInteractionFramesList)}."); |
| | 0 | 367 | | } |
| | | 368 | | |
| | 908 | 369 | | } |
| | 3098 | 370 | | } |
| | | 371 | | |
| | | 372 | | /// <summary> |
| | | 373 | | /// replaces the frame in the cache with the updated frame (if FrameId is existing, otherwise, nothing is change |
| | | 374 | | /// </summary> |
| | | 375 | | /// <param name="updatedFrame">Frame containing updated values</param> |
| | | 376 | | public void UpdateCachedFrame(InteractionFrame updatedFrame) |
| | 0 | 377 | | { |
| | 0 | 378 | | var frameIdxToBeReplaced = _interactionFrames.FindIndex((f) => f.FrameId == updatedFrame.FrameId); |
| | 0 | 379 | | if (frameIdxToBeReplaced < 0) |
| | 0 | 380 | | return; |
| | | 381 | | |
| | | 382 | | // _interactionFrames[frameIdxToBeReplaced] = updatedFrame; |
| | 0 | 383 | | _interactionFrames[frameIdxToBeReplaced].Interactions.ForEach((interaction) => |
| | 0 | 384 | | { |
| | 0 | 385 | | var updatedInteraction = |
| | 0 | 386 | | updatedFrame.Interactions.FirstOrDefault((update) => update.TouchId == interaction.TouchId); |
| | 0 | 387 | | if (updatedInteraction != null) |
| | 0 | 388 | | { |
| | 0 | 389 | | interaction.Confidence = updatedInteraction.Confidence; |
| | 0 | 390 | | if (_tracks.TryGetValue(interaction.TouchId, out var track) && track.LastSeenFrame == updatedFrame.FrameId |
| | 0 | 391 | | track.Confidence = Math.Clamp(updatedInteraction.Confidence, 0, Math.Max(0, MaxConfidence)); |
| | 0 | 392 | | interaction.ExtremumDescription = new Interaction(updatedInteraction).ExtremumDescription; |
| | 0 | 393 | | |
| | 0 | 394 | | } |
| | 0 | 395 | | }); |
| | 0 | 396 | | } |
| | | 397 | | |
| | | 398 | | /// <summary> |
| | | 399 | | /// Apply smoothing according to chosen filter type. |
| | | 400 | | /// Extracts touches of a given id from frames history and sends them to smoothing algorithm |
| | | 401 | | /// </summary> |
| | | 402 | | /// <param name="touchId">the id of the touch, which should be smoothed</param> |
| | | 403 | | /// <returns>Interaction (last entry in history) with smoothed position</returns> |
| | | 404 | | private Interaction SmoothInteraction(int touchId) |
| | 2890 | 405 | | { |
| | 2890 | 406 | | var track = _tracks[touchId]; |
| | | 407 | | // A type transition starts a new smoothing segment; motion in XY may remain continuous. |
| | 2890 | 408 | | var samples = track.Samples.AsEnumerable().Reverse() |
| | 10364 | 409 | | .TakeWhile(sample => sample.Measurement.Type == track.LastMeasurement.Type).Reverse().ToArray(); |
| | 10362 | 410 | | var interactionsHistory = samples.Select(sample => new Interaction(sample.Measurement)).ToList(); |
| | 2890 | 411 | | var smooth = new Interaction(track.LastMeasurement); |
| | 2890 | 412 | | if (_type == FilterType.Butterworth && NumFramesSmoothing > 0) |
| | 286 | 413 | | { |
| | 286 | 414 | | track.Butterworth ??= new ButterworthFilter(); |
| | 286 | 415 | | smooth.Position = track.Butterworth.ProcessSample(track.LastMeasurement.Position, track.LastSeenTime); |
| | 286 | 416 | | if (Math.Sign(smooth.Position.Z) != Math.Sign(track.LastMeasurement.Position.Z)) |
| | 0 | 417 | | smooth.Position.Z = track.LastMeasurement.Position.Z; |
| | 286 | 418 | | return smooth; |
| | | 419 | | } |
| | | 420 | | |
| | 8690 | 421 | | var raw = interactionsHistory.Select(interaction => interaction.Position).ToList(); |
| | | 422 | | |
| | 2604 | 423 | | if (NumFramesSmoothing > 0 && |
| | 2604 | 424 | | smooth != null && raw.Count >= NumFramesSmoothing && |
| | 2604 | 425 | | _type != FilterType.None && _filter != null) |
| | 140 | 426 | | { |
| | 820 | 427 | | var framesForSmoothing = raw.TakeLast(NumFramesSmoothing).Select(point => new Point3(point)).ToList(); |
| | 820 | 428 | | framesForSmoothing.ForEach(p => p.Z *= _depthScale); |
| | 820 | 429 | | var timestamps = samples.Select(sample => sample.Time).TakeLast(NumFramesSmoothing).ToArray(); |
| | 140 | 430 | | var filtered = _filter is Base2DFilter temporalFilter |
| | 140 | 431 | | ? temporalFilter.Process(framesForSmoothing, timestamps) |
| | 140 | 432 | | : _filter.Process(framesForSmoothing); |
| | 140 | 433 | | smooth.Position = new Point3(filtered.Last()); |
| | 140 | 434 | | smooth.Position.Z /= _depthScale; |
| | 140 | 435 | | if (Math.Sign(smooth.Position.Z) != Math.Sign(track.LastMeasurement.Position.Z)) |
| | 0 | 436 | | smooth.Position.Z = track.LastMeasurement.Position.Z; |
| | 140 | 437 | | } |
| | | 438 | | |
| | 2604 | 439 | | return smooth; |
| | 2890 | 440 | | } |
| | | 441 | | |
| | | 442 | | |
| | | 443 | | |
| | | 444 | | /// <summary> |
| | | 445 | | /// One-to-one assignment to forecasts using the selected minimum-cost or legacy greedy strategy. |
| | | 446 | | /// A candidate and a track may each participate in only one pair. Unmatched candidates |
| | | 447 | | /// start new tracks; unmatched tracks may bridge the configured elapsed time. |
| | | 448 | | /// With prediction disabled or insufficient samples, falls back to the last measurement. |
| | | 449 | | /// </summary> |
| | | 450 | | private List<Interaction> MapClosestInteraction(List<Interaction> candidates) |
| | 2296 | 451 | | { |
| | | 452 | | // Explicitly missing detections use contact retention. A sensor/processing gap uses |
| | | 453 | | // its separate timeout, measured since the last successful completion, not capture. |
| | 7012 | 454 | | foreach (var id in _tracks.Where(pair => |
| | 2372 | 455 | | IsExpired(pair.Value, _processedTimestampSeconds.Value, _frameId - 1)) |
| | 2358 | 456 | | .Select(pair => pair.Key).ToArray()) |
| | 62 | 457 | | _tracks.Remove(id); |
| | | 458 | | |
| | 12724 | 459 | | foreach (var candidate in candidates) |
| | 2918 | 460 | | candidate.TouchId = -1; |
| | | 461 | | |
| | 11508 | 462 | | foreach (var track in _tracks.Values) |
| | 2310 | 463 | | track.MatchingPosition = Predict(track, _timestampSeconds.Value); |
| | | 464 | | |
| | 4606 | 465 | | var targets = _tracks.Select(pair => (TouchId: pair.Key, Position: pair.Value.MatchingPosition)).ToArray(); |
| | 2296 | 466 | | var assignedIds = UseMinimumCostAssignment |
| | 2296 | 467 | | ? MinimumCostContactAssignment.Assign(candidates, targets, TouchMergeDistance2D, AssignmentMissCost, Ass |
| | 2296 | 468 | | : GreedyContactAssignment.Assign(candidates, targets, TouchMergeDistance2D); |
| | 10428 | 469 | | for (var index = 0; index < candidates.Count; index++) |
| | 2918 | 470 | | { |
| | 2918 | 471 | | var touchId = assignedIds[index]; |
| | 2918 | 472 | | if (touchId < 0) |
| | 1100 | 473 | | continue; |
| | 1818 | 474 | | var candidate = candidates[index]; |
| | 1818 | 475 | | candidate.TouchId = touchId; |
| | 1818 | 476 | | candidate.TrackingState = InteractionTrackingState.Confirmed; |
| | 1818 | 477 | | var track = _tracks[touchId]; |
| | | 478 | | // Continue decay through the last lost interval before recovering. A new detection |
| | | 479 | | // gains confidence only over continuously observed intervals, never over a lost interval. |
| | 1818 | 480 | | if (track.LastSeenFrame < _frameId - 1) |
| | 24 | 481 | | DecayConfidence(track, _processedTimestampSeconds.Value); |
| | 1818 | 482 | | var gain = track.LastSeenFrame == _frameId - 1 |
| | 1818 | 483 | | ? ConfidenceGainPerSecond * (_timestampSeconds.Value - track.LastSeenTime) : 0; |
| | 1818 | 484 | | candidate.Confidence = (float)Math.Min(track.Confidence + gain, Math.Max(0, MaxConfidence)); |
| | 1818 | 485 | | } |
| | | 486 | | |
| | 12724 | 487 | | foreach (var candidate in candidates) |
| | 2918 | 488 | | { |
| | 2918 | 489 | | if (candidate.TouchId < 0) |
| | 1100 | 490 | | { |
| | 1100 | 491 | | AssignMaxId(candidate); |
| | 1100 | 492 | | candidate.TrackingState = InteractionTrackingState.Tentative; |
| | 1100 | 493 | | candidate.Confidence = Math.Clamp(candidate.Confidence, 0, Math.Max(0, MaxConfidence)); |
| | 1100 | 494 | | } |
| | 2918 | 495 | | var matchingPosition = _tracks.TryGetValue(candidate.TouchId, out var previous) |
| | 2918 | 496 | | ? previous.MatchingPosition : candidate.Position; |
| | 2918 | 497 | | var current = previous ?? new Track(); |
| | 2918 | 498 | | if (previous != null && previous.LastMeasurement.Type != candidate.Type) |
| | 2 | 499 | | current.Butterworth = null; |
| | 2918 | 500 | | current.LastMeasurement = candidate; |
| | 2918 | 501 | | current.LastSeenFrame = _frameId; |
| | 2918 | 502 | | current.LastSeenTime = _timestampSeconds.Value; |
| | 2918 | 503 | | current.LastDetectedAt = _processedTimestampSeconds.Value; |
| | 2918 | 504 | | current.Confidence = candidate.Confidence; |
| | 2918 | 505 | | current.ConfidenceUpdatedAt = _processedTimestampSeconds.Value; |
| | 2918 | 506 | | current.MatchingPosition = (Point3)matchingPosition.Copy(); |
| | 2918 | 507 | | current.Samples.Add((_timestampSeconds.Value, new Interaction(candidate))); |
| | 2918 | 508 | | var capacity = Math.Max(1, Math.Max(NumFramesSmoothing, NumFramesForPrediction)); |
| | 2918 | 509 | | if (current.Samples.Count > capacity) |
| | 1258 | 510 | | current.Samples.RemoveRange(0, current.Samples.Count - capacity); |
| | 2918 | 511 | | _tracks[candidate.TouchId] = current; |
| | 2918 | 512 | | } |
| | 3720 | 513 | | return candidates.OrderBy(candidate => candidate.TouchId).ToList(); |
| | 2296 | 514 | | } |
| | | 515 | | |
| | | 516 | | private bool IsExpired(Track track, double now, int latestObservationFrame) |
| | 5996 | 517 | | => now > track.LastDetectedAt + (track.LastSeenFrame == latestObservationFrame |
| | 5996 | 518 | | ? ObservationTimeoutSeconds : ContactRetentionSeconds); |
| | | 519 | | |
| | | 520 | | private void DecayConfidence(Track track, double timestampSeconds) |
| | 516 | 521 | | { |
| | 516 | 522 | | track.Confidence = Math.Max(0, track.Confidence - (float)(ConfidenceDecayPerSecond * |
| | 516 | 523 | | (timestampSeconds - track.ConfidenceUpdatedAt))); |
| | 516 | 524 | | track.ConfidenceUpdatedAt = timestampSeconds; |
| | 516 | 525 | | } |
| | | 526 | | |
| | | 527 | | private Point3 Predict(Track track, double targetTime) |
| | 2324 | 528 | | { |
| | 2324 | 529 | | if (!UseVelocityForMapping) |
| | 1366 | 530 | | return (Point3)track.LastMeasurement.Position.Copy(); |
| | 958 | 531 | | var motion = ContactMotion.Estimate(track.Samples, track.LastSeenTime, NumFramesForPrediction, UseSecondDeri |
| | 958 | 532 | | var forecast = ContactMotion.Forecast(track.LastMeasurement.Position, motion, |
| | 958 | 533 | | SecondDerivationMagnitude, (float)(targetTime - track.LastSeenTime)); |
| | 958 | 534 | | return UseSecondDerivation ? forecast.PredictedPositionAdvanced : forecast.PredictedPositionBasic; |
| | 2324 | 535 | | } |
| | | 536 | | |
| | | 537 | | /// <summary> |
| | | 538 | | /// Atomic diagnostics for this output frame. Positions use the uncalibrated sensor raster; |
| | | 539 | | /// forecasts have an explicit time horizon, matching positions were used at this frame timestamp. |
| | | 540 | | /// Never combines asynchronously delivered interaction/velocity messages in the frontend. |
| | | 541 | | /// </summary> |
| | | 542 | | public List<InteractionVelocity> GetVelocities(InteractionFrame output) |
| | 318 | 543 | | { |
| | 318 | 544 | | var result = new List<InteractionVelocity>(); |
| | 318 | 545 | | if (!UseVelocityForMapping) |
| | 90 | 546 | | return result; |
| | 1212 | 547 | | foreach (var interaction in output.Interactions) |
| | 264 | 548 | | { |
| | 264 | 549 | | if (!_tracks.TryGetValue(interaction.TouchId, out var track)) |
| | 2 | 550 | | continue; |
| | 262 | 551 | | var motion = ContactMotion.Estimate(track.Samples, track.LastSeenTime, NumFramesForPrediction, UseSecond |
| | 262 | 552 | | var item = ContactMotion.Forecast(track.LastMeasurement.Position, motion, |
| | 262 | 553 | | SecondDerivationMagnitude, (float)(output.TimestampSeconds + PredictionHorizonSeconds - track.LastSe |
| | 262 | 554 | | item.TouchId = interaction.TouchId; |
| | 262 | 555 | | item.FrameId = _frameId; |
| | 262 | 556 | | item.LastMeasuredFrameId = track.LastSeenFrame; |
| | 262 | 557 | | item.TimestampSeconds = output.TimestampSeconds; |
| | 262 | 558 | | item.LastMeasuredTimestampSeconds = track.LastSeenTime; |
| | 262 | 559 | | item.PredictionTimestampSeconds = output.TimestampSeconds + PredictionHorizonSeconds; |
| | 262 | 560 | | item.PredictionHorizonSeconds = PredictionHorizonSeconds; |
| | 262 | 561 | | item.Confidence = interaction.Confidence; |
| | 262 | 562 | | item.SampleCount = motion.Count; |
| | 262 | 563 | | item.IsPredicted = interaction.TrackingState == InteractionTrackingState.Lost; |
| | 262 | 564 | | item.UseSecondDerivation = UseSecondDerivation; |
| | 262 | 565 | | item.SmoothedPosition = (Point3)interaction.Position.Copy(); |
| | 262 | 566 | | item.MatchingPosition = !item.IsPredicted |
| | 262 | 567 | | ? (Point3)track.MatchingPosition.Copy() : Predict(track, output.TimestampSeconds); |
| | 262 | 568 | | result.Add(item); |
| | 262 | 569 | | } |
| | 228 | 570 | | return result; |
| | 318 | 571 | | } |
| | | 572 | | |
| | | 573 | | /// <summary> |
| | | 574 | | /// Assigns a new id to the given point and increments current maximum touch id. |
| | | 575 | | /// </summary> |
| | | 576 | | /// <param name="interaction">the touch point which should get a new unique id</param> |
| | | 577 | | private void AssignMaxId(Interaction interaction) |
| | 1100 | 578 | | { |
| | 1100 | 579 | | interaction.TouchId = _maxTouchId; |
| | 1100 | 580 | | _maxTouchId++; |
| | 1100 | 581 | | } |
| | | 582 | | |
| | | 583 | | } |
| | | 584 | | } |