< Summary - ReFlex - Library

Information
Class: Implementation.Components.InteractionManager
Assembly: ReFlex.Core.Implementation
File(s): D:\a\reflex\reflex\library\src\Core\Implementation\Components\InteractionManager.cs
Line coverage
87%
Covered lines: 417
Uncovered lines: 59
Coverable lines: 476
Total lines: 767
Line coverage: 87.6%
Branch coverage
61%
Covered branches: 155
Total branches: 253
Branch coverage: 61.2%
Method coverage

Feature is only available for sponsors

Upgrade to PRO version

Metrics

MethodBranch coverage Crap Score Cyclomatic complexity Line coverage
.ctor(...)100%44100%
GetTimestampSeconds()100%210%
get_Interactions()50%22100%
get_PredictionHorizonSeconds()0%620%
set_PredictionHorizonSeconds(...)50%22100%
get_UseVelocityPrediction()0%620%
set_UseVelocityPrediction(...)50%22100%
get_NumFramesForPrediction()0%620%
set_NumFramesForPrediction(...)50%22100%
get_UseSecondDerivation()0%620%
set_UseSecondDerivation(...)50%22100%
get_SecondDerivationMagnitude()0%620%
set_SecondDerivationMagnitude(...)50%22100%
get_Type()50%22100%
set_Type(...)100%11100%
CreateObserver(...)40%6562.5%
ComputeZeroPlaneDistance()100%210%
ReadObserverRasters(...)50%22100%
UpdateObserver(...)100%4497.82%
OnHistoryUpdated(...)66.66%66100%
get_Distance()0%620%
set_Distance(...)50%2280%
get_MinDistance()0%620%
set_MinDistance(...)50%2280%
get_MaxDistance()0%620%
set_MaxDistance(...)50%2280%
get_MinAngle()0%620%
set_MinAngle(...)0%620%
get_MinConfidence()0%620%
set_MinConfidence(...)100%22100%
get_MaxConfidence()0%620%
set_MaxConfidence(...)50%2280%
get_InteractionHistorySize()0%620%
set_InteractionHistorySize(...)50%2280%
get_NumSmoothingFrames()0%620%
set_NumSmoothingFrames(...)50%2280%
get_UseMinimumCostAssignment()100%210%
set_UseMinimumCostAssignment(...)100%22100%
get_AssignmentMissCost()100%210%
set_AssignmentMissCost(...)66.66%66100%
get_AssignmentBirthCost()100%210%
set_AssignmentBirthCost(...)66.66%66100%
get_ConfidenceGainPerSecond()100%210%
set_ConfidenceGainPerSecond(...)50%66100%
get_ConfidenceDecayPerSecond()100%210%
set_ConfidenceDecayPerSecond(...)50%66100%
get_ContactRetentionSeconds()0%620%
set_ContactRetentionSeconds(...)50%6683.33%
get_ObservationTimeoutSeconds()0%620%
set_ObservationTimeoutSeconds(...)50%66100%
get_TouchMergeDistance2D()0%620%
set_TouchMergeDistance2D(...)100%22100%
get_DepthScale()0%620%
set_DepthScale(...)0%620%
get_FilterType()50%22100%
set_FilterType(...)50%22100%
get_ExtremumTypeCheckNumSamples()50%22100%
set_ExtremumTypeCheckNumSamples(...)100%22100%
get_ExtremumMergeRadius()0%620%
set_ExtremumMergeRadius(...)50%22100%
get_ExtremumTypeCheckRadius()50%22100%
set_ExtremumTypeCheckRadius(...)100%22100%
get_ExtremumTypeCheckFittingPercentage()50%22100%
set_ExtremumTypeCheckFittingPercentage(...)100%22100%
get_ExtremumTypeCheckMethod()50%22100%
set_ExtremumTypeCheckMethod(...)100%22100%
get_PointCloud()100%210%
set_PointCloud(...)100%210%
get_VectorField()100%11100%
set_VectorField(...)100%210%
get_InputDistance()100%11100%
get_UseObservationSnapshots()0%620%
set_UseObservationSnapshots(...)75%44100%
Init(...)100%11100%
OnTrackingStateChanged(...)100%11100%
ResetTracking()75%88100%
AdvanceTime()50%22100%
Update()87.5%323292.85%
OnObservationReady(...)100%22100%
OnSnapshotSourceReady(...)83.33%66100%
RecycleSnapshot(...)100%1212100%
OnNewVelocities(...)83.33%1212100%
Dispose()100%88100%
OnNewInteractions(...)66.66%66100%
RemoveClusteredInteractions(...)87.5%8895.45%

File(s)

D:\a\reflex\reflex\library\src\Core\Implementation\Components\InteractionManager.cs

#LineLine coverage
 1using System;
 2using System.Diagnostics;
 3using System.Threading;
 4using System.Collections.Generic;
 5using System.Linq;
 6using System.Threading.Tasks;
 7using Implementation.Interfaces;
 8using ReFlex.Core.Common.Components;
 9using ReFlex.Core.Common.Interfaces;
 10using ReFlex.Core.Common.Util;
 11using ReFlex.Core.Interactivity.Components;
 12using ReFlex.Core.Interactivity.Interfaces;
 13using ReFlex.Core.Interactivity.Util;
 14using ReFlex.Core.Events;
 15
 16namespace Implementation.Components
 17{
 18    public class InteractionManager : IInteractionManager, IDisposable
 19    {
 20        private IInteractionObserver _interactionObserver;
 3621        private readonly object _publicationSync = new();
 22        private readonly ITrackingManager _trackingManager;
 3623        private readonly object _snapshotSync = new();
 3624        private readonly Stack<TrackingObservation> _spareSnapshots = new(2);
 25        private readonly DepthImageManager _snapshotSource;
 26        private TrackingObservation _pendingObservation;
 27        private TrackingObservation _lastSnapshot;
 28        private bool _disposed;
 3629        private readonly SemaphoreSlim _updateGate = new(1, 1);
 3630        private long _lastSequence = -1;
 3631        private double _lastObservationTime = double.NegativeInfinity;
 032        protected virtual double GetTimestampSeconds() => (double)Stopwatch.GetTimestamp() / Stopwatch.Frequency;
 33        private IList<Interaction> _interactions;
 34        private bool _useVelocityPrediction;
 3635        private double _predictionHorizonSeconds = .05;
 3636        private int _numFramesForPrediction = 3;
 37        private bool _useSecondDerivation;
 3638        private float _secondDerivationMagnitude = .5f;
 39        private readonly IDepthImageManager _depthImageManager;
 40        private readonly IPerformanceAggregator _performanceAggregator;
 41
 42        private readonly IRemoteInteractionProcessorService _service;
 43
 44        private float _distance;
 45        private float _minDistance;
 46        private float _maxDistance;
 47        private float _minAngle;
 48        private int _minConfidence;
 49        private int _maxConfidence;
 50        private int _numSmoothFrames;
 51        private int _interactionHistorySize;
 3652        private double _contactRetentionSeconds = .1;
 3653        private double _observationTimeoutSeconds = 1;
 3654        private bool _useMinimumCostAssignment = true;
 3655        private float _assignmentMissCost = InteractionSmoothingBehaviour.DefaultAssignmentMissCost;
 3656        private float _assignmentBirthCost = InteractionSmoothingBehaviour.DefaultAssignmentBirthCost;
 3657        private float _confidenceGainPerSecond = 30;
 3658        private float _confidenceDecayPerSecond = 30;
 3659        private float _smoothingDistanceSquared = 64f;
 3660        private float _depthScale = 100.0f;
 61        private FilterType _filterType;
 62        private int _extremumTypeCheckNumSamples;
 63        private int _extremumTypeCheckRadius;
 3664        private float _extremumMergeRadius = ExtremumConsolidator.DefaultRadius;
 65        private float _extremumTypeCheckFittingPercentage;
 66        private ExtremumTypeCheckMethod _extremumTypeCheckMethod;
 67
 17268        public IList<Interaction> Interactions => _interactions ?? new List<Interaction>();
 69
 70        public double PredictionHorizonSeconds
 71        {
 072            get => _interactionObserver?.PredictionHorizonSeconds ?? _predictionHorizonSeconds;
 73            set
 274            {
 275                if (_interactionObserver != null) _interactionObserver.PredictionHorizonSeconds = value;
 276                _predictionHorizonSeconds = value;
 277            }
 78        }
 79
 80        public bool UseVelocityPrediction
 81        {
 082            get => _interactionObserver?.UseVelocityPrediction ?? _useVelocityPrediction;
 83            set
 2684            {
 2685                if (_interactionObserver != null) _interactionObserver.UseVelocityPrediction = value;
 2686                _useVelocityPrediction = value;
 2687            }
 88        }
 89
 90        public int NumFramesForPrediction
 91        {
 092            get => _interactionObserver?.NumFramesForPrediction ?? _numFramesForPrediction;
 93            set
 294            {
 295                if (_interactionObserver != null) _interactionObserver.NumFramesForPrediction = value;
 296                _numFramesForPrediction = value;
 297            }
 98        }
 99
 100        public bool UseSecondDerivation
 101        {
 0102            get => _interactionObserver?.UseSecondDerivation ?? _useSecondDerivation;
 103            set
 2104            {
 2105                if (_interactionObserver != null) _interactionObserver.UseSecondDerivation = value;
 2106                _useSecondDerivation = value;
 2107            }
 108        }
 109
 110        public float SecondDerivationMagnitude
 111        {
 0112            get => _interactionObserver?.SecondDerivationMagnitude ?? _secondDerivationMagnitude;
 113            set
 2114            {
 2115                if (_interactionObserver != null) _interactionObserver.SecondDerivationMagnitude = value;
 2116                _secondDerivationMagnitude = value;
 2117            }
 118        }
 119
 120        public ObserverType Type
 121        {
 12122            get => _interactionObserver?.Type ?? ObserverType.None;
 123            set
 44124            {
 44125                lock (_publicationSync)
 44126                lock (_snapshotSync)
 44127                    UpdateObserver(CreateObserver(value));
 44128            }
 129        }
 130
 20131        protected virtual IInteractionObserver CreateObserver(ObserverType type) => type switch
 20132        {
 16133            ObserverType.Remote => new RemoteInteractionProcessor(_service),
 4134            ObserverType.MultiTouch => new MultiInteractionObserver(),
 0135            ObserverType.SingleTouch => new SingleInteractionObserver(),
 0136            ObserverType.None => new NoInteractionObserver(),
 0137            _ => throw new ArgumentOutOfRangeException(nameof(type))
 20138        };
 139
 140        public float ComputeZeroPlaneDistance() =>
 0141            ReadObserverRasters(() => _interactionObserver?.CalculateAverageDistance() ?? 0);
 142
 143        private T ReadObserverRasters<T>(Func<T> read)
 4144        {
 4145            if (_snapshotSource == null) return read();
 4146            return _snapshotSource.ReadRasters(() =>
 4147            {
 8148                lock (_snapshotSync) return read();
 8149            });
 4150        }
 151
 152        private void UpdateObserver(IInteractionObserver observer)
 56153        {
 56154            if (_interactionObserver != null)
 20155            {
 20156                _interactionObserver.NewInteractions -= OnNewInteractions;
 20157                _interactionObserver.NewVelocities -= OnNewVelocities;
 20158                _interactionObserver.InteractionHistoryUpdated -= OnHistoryUpdated;
 20159                _performanceAggregator.UnregisterReporter(_interactionObserver as IPerformanceReporter);
 20160            }
 161
 56162            if (observer == null)
 0163                return;
 164
 56165            observer.Distance = _distance;
 56166            observer.MinDistance = _minDistance;
 56167            observer.MaxDistance = _maxDistance;
 56168            observer.MinConfidence = _minConfidence;
 56169            observer.MaxConfidence = _maxConfidence;
 56170            observer.MinAngle = _minAngle;
 56171            observer.PointCloud = _depthImageManager.PointCloud;
 56172            observer.VectorField = _depthImageManager.VectorField;
 56173            observer.InteractionHistorySize = _interactionHistorySize;
 56174            observer.NumSmoothingFrames = _numSmoothFrames;
 56175            observer.TouchMergeDistance2D = _smoothingDistanceSquared;
 56176            observer.ContactRetentionSeconds = _contactRetentionSeconds;
 56177            observer.ObservationTimeoutSeconds = _observationTimeoutSeconds;
 56178            observer.UseMinimumCostAssignment = _useMinimumCostAssignment;
 56179            observer.AssignmentMissCost = _assignmentMissCost;
 56180            observer.AssignmentBirthCost = _assignmentBirthCost;
 56181            observer.ConfidenceGainPerSecond = _confidenceGainPerSecond;
 56182            observer.ConfidenceDecayPerSecond = _confidenceDecayPerSecond;
 56183            observer.DepthScale = _depthScale;
 56184            observer.FilterType = _filterType;
 56185            observer.PredictionHorizonSeconds = _predictionHorizonSeconds;
 56186            observer.UseVelocityPrediction = _useVelocityPrediction;
 56187            observer.NumFramesForPrediction = _numFramesForPrediction;
 56188            observer.UseSecondDerivation = _useSecondDerivation;
 56189            observer.SecondDerivationMagnitude = _secondDerivationMagnitude;
 56190            observer.ExtremumTypeCheckRadius = _extremumTypeCheckRadius;
 56191            observer.ExtremumMergeRadius = _extremumMergeRadius;
 56192            observer.ExtremumTypeCheckNumSamples = _extremumTypeCheckNumSamples;
 56193            observer.ExtremumTypeCheckFittingPercentage = _extremumTypeCheckFittingPercentage;
 56194            observer.ExtremumTypeCheckMethod = _extremumTypeCheckMethod;
 56195            _interactionObserver = observer;
 196
 56197            _interactionObserver.NewInteractions += OnNewInteractions;
 56198            _interactionObserver.NewVelocities += OnNewVelocities;
 56199            _interactionObserver.InteractionHistoryUpdated += OnHistoryUpdated;
 56200            _performanceAggregator.RegisterReporter(_interactionObserver as IPerformanceReporter);
 56201        }
 202
 203        private void OnHistoryUpdated(object sender, IList<InteractionFrame> e)
 66204        {
 66205            lock (_publicationSync)
 66206            {
 66207                if (_disposed || !ReferenceEquals(sender, _interactionObserver)) return;
 66208                InteractionHistoryUpdated?.Invoke(this, e);
 66209            }
 66210        }
 211
 212        public float Distance
 213        {
 0214            get => _interactionObserver?.Distance ?? 0;
 215            set
 32216            {
 32217                if (_interactionObserver != null)
 0218                    _interactionObserver.Distance = value;
 219
 32220                _distance = value;
 32221            }
 222        }
 223
 224        public float MinDistance
 225        {
 0226            get => _interactionObserver?.MinDistance ?? 0;
 227            set
 32228            {
 32229                if (_interactionObserver != null)
 0230                    _interactionObserver.MinDistance = value;
 231
 32232                _minDistance = value;
 32233            }
 234        }
 235
 236        public float MaxDistance
 237        {
 0238            get => _interactionObserver?.MaxDistance ?? 0;
 239            set
 32240            {
 32241                if (_interactionObserver != null)
 0242                    _interactionObserver.MaxDistance = value;
 243
 32244                _maxDistance = value;
 32245            }
 246        }
 247
 248        public float MinAngle
 249        {
 0250            get => _interactionObserver?.MinAngle ?? 0;
 251            set
 0252            {
 0253                if (_interactionObserver != null)
 0254                    _interactionObserver.MinAngle = value;
 255
 0256                _minAngle = value;
 0257            }
 258        }
 259
 260        public int MinConfidence
 261        {
 0262            get => (int)(_interactionObserver?.MinConfidence ?? 0);
 263            set
 28264            {
 28265                if (_interactionObserver != null)
 4266                    _interactionObserver.MinConfidence = value;
 267
 28268                _minConfidence = value;
 28269            }
 270        }
 271
 272        public int MaxConfidence
 273        {
 0274            get => (int)(_interactionObserver?.MaxConfidence ?? 0);
 275            set
 32276            {
 32277                if (_interactionObserver != null)
 0278                    _interactionObserver.MaxConfidence = value;
 279
 32280                _maxConfidence = value;
 32281            }
 282        }
 283
 284        public int InteractionHistorySize
 285        {
 0286            get => _interactionObserver?.InteractionHistorySize ?? 0;
 287            set
 32288            {
 32289                if (_interactionObserver != null)
 0290                    _interactionObserver.InteractionHistorySize = value;
 291
 32292                _interactionHistorySize = value;
 32293            }
 294        }
 295
 296        public int NumSmoothingFrames
 297        {
 0298            get => _interactionObserver?.NumSmoothingFrames ?? 0;
 299            set
 26300            {
 26301                if (_interactionObserver != null)
 0302                    _interactionObserver.NumSmoothingFrames = value;
 303
 26304                _numSmoothFrames = value;
 26305            }
 306        }
 307
 308        public bool UseMinimumCostAssignment
 309        {
 0310            get => _useMinimumCostAssignment;
 311            set
 4312            {
 6313                if (_interactionObserver != null) _interactionObserver.UseMinimumCostAssignment = value;
 4314                _useMinimumCostAssignment = value;
 4315            }
 316        }
 317
 318        public float AssignmentMissCost
 319        {
 0320            get => _assignmentMissCost;
 321            set
 4322            {
 4323                if (!float.IsFinite(value) || value < 0) throw new ArgumentOutOfRangeException(nameof(value));
 6324                if (_interactionObserver != null) _interactionObserver.AssignmentMissCost = value;
 4325                _assignmentMissCost = value;
 4326            }
 327        }
 328
 329        public float AssignmentBirthCost
 330        {
 0331            get => _assignmentBirthCost;
 332            set
 4333            {
 4334                if (!float.IsFinite(value) || value < 0) throw new ArgumentOutOfRangeException(nameof(value));
 6335                if (_interactionObserver != null) _interactionObserver.AssignmentBirthCost = value;
 4336                _assignmentBirthCost = value;
 4337            }
 338        }
 339
 340        public float ConfidenceGainPerSecond
 341        {
 0342            get => _confidenceGainPerSecond;
 343            set
 2344            {
 2345                if (!float.IsFinite(value) || value < 0) throw new ArgumentOutOfRangeException(nameof(value));
 2346                if (_interactionObserver != null) _interactionObserver.ConfidenceGainPerSecond = value;
 2347                _confidenceGainPerSecond = value;
 2348            }
 349        }
 350
 351        public float ConfidenceDecayPerSecond
 352        {
 0353            get => _confidenceDecayPerSecond;
 354            set
 2355            {
 2356                if (!float.IsFinite(value) || value < 0) throw new ArgumentOutOfRangeException(nameof(value));
 2357                if (_interactionObserver != null) _interactionObserver.ConfidenceDecayPerSecond = value;
 2358                _confidenceDecayPerSecond = value;
 2359            }
 360        }
 361
 362        public double ContactRetentionSeconds
 363        {
 0364            get => _interactionObserver?.ContactRetentionSeconds ?? _contactRetentionSeconds;
 365            set
 26366            {
 26367                if (_interactionObserver != null)
 0368                    _interactionObserver.ContactRetentionSeconds = value;
 369
 26370                _contactRetentionSeconds = double.IsFinite(value) && value >= 0 ? value :
 26371                    throw new ArgumentOutOfRangeException(nameof(value));
 26372            }
 373        }
 374
 375        public double ObservationTimeoutSeconds
 376        {
 0377            get => _interactionObserver?.ObservationTimeoutSeconds ?? _observationTimeoutSeconds;
 378            set
 34379            {
 34380                if (!double.IsFinite(value) || value < 0) throw new ArgumentOutOfRangeException(nameof(value));
 34381                if (_interactionObserver != null) _interactionObserver.ObservationTimeoutSeconds = value;
 34382                _observationTimeoutSeconds = value;
 34383            }
 384        }
 385
 386        public float TouchMergeDistance2D
 387        {
 0388            get => _interactionObserver?.TouchMergeDistance2D ?? 0f;
 389            set
 26390            {
 26391                if (_interactionObserver != null)
 2392                    _interactionObserver.TouchMergeDistance2D = value;
 393
 26394                _smoothingDistanceSquared = value;
 26395            }
 396        }
 397
 398        public float DepthScale
 399        {
 0400            get => _interactionObserver?.DepthScale ?? 0f;
 401            set
 0402            {
 0403                if (_interactionObserver != null)
 0404                    _interactionObserver.DepthScale = value;
 405
 0406                _depthScale = value;
 0407            }
 408        }
 409
 410        public FilterType FilterType {
 6411            get => _interactionObserver?.FilterType ?? _filterType;
 412            set
 6413            {
 6414                if (_interactionObserver != null)
 6415                    _interactionObserver.FilterType = value;
 6416                _filterType = value;
 6417            }
 418        }
 419
 420        public int ExtremumTypeCheckNumSamples
 421        {
 2422            get => _interactionObserver?.ExtremumTypeCheckNumSamples ?? _extremumTypeCheckNumSamples;
 423            set
 28424            {
 28425                if (_interactionObserver != null)
 2426                    _interactionObserver.ExtremumTypeCheckNumSamples = value;
 28427                _extremumTypeCheckNumSamples = value;
 28428            }
 429        }
 430
 431        public float ExtremumMergeRadius
 432        {
 0433            get => _interactionObserver?.ExtremumMergeRadius ?? _extremumMergeRadius;
 434            set
 2435            {
 2436                ExtremumConsolidator.ValidateRadius(value);
 2437                if (_interactionObserver != null) _interactionObserver.ExtremumMergeRadius = value;
 2438                _extremumMergeRadius = value;
 2439            }
 440        }
 441
 442        public int ExtremumTypeCheckRadius
 443        {
 2444            get => _interactionObserver?.ExtremumTypeCheckRadius ?? _extremumTypeCheckRadius;
 445            set
 28446            {
 28447                if (_interactionObserver != null)
 2448                    _interactionObserver.ExtremumTypeCheckRadius = value;
 28449                _extremumTypeCheckRadius = value;
 28450            }
 451        }
 452
 453        public float ExtremumTypeCheckFittingPercentage
 454        {
 2455            get => _interactionObserver?.ExtremumTypeCheckFittingPercentage ?? _extremumTypeCheckFittingPercentage;
 456            set
 4457            {
 4458                if (_interactionObserver != null)
 2459                    _interactionObserver.ExtremumTypeCheckFittingPercentage = value;
 4460                _extremumTypeCheckFittingPercentage = value;
 4461            }
 462        }
 463
 464        public ExtremumTypeCheckMethod ExtremumTypeCheckMethod
 465        {
 2466            get => _interactionObserver?.ExtremumTypeCheckMethod ?? _extremumTypeCheckMethod;
 467            set
 34468            {
 34469                if (_interactionObserver != null)
 2470                    _interactionObserver.ExtremumTypeCheckMethod = value;
 34471                _extremumTypeCheckMethod = value;
 34472            }
 473        }
 474
 475        public PointCloud3 PointCloud
 476        {
 0477            get => ReadObserverRasters(() =>
 0478            {
 0479                var cloud = _interactionObserver?.PointCloud;
 0480                return _snapshotSource == null ? cloud : TrackingObservation.CopyCloud(cloud);
 0481            });
 0482            set => _interactionObserver.PointCloud = value;
 483        }
 484
 485        public VectorField2 VectorField
 486        {
 4487            get => ReadObserverRasters(() =>
 4488            {
 4489                var vectors = _interactionObserver?.VectorField;
 4490                return _snapshotSource == null ? vectors : TrackingObservation.CopyVectors(vectors);
 8491            });
 0492            set => _interactionObserver.VectorField = value;
 493        }
 494
 8495        public float InputDistance { get; set; }
 496
 36497        public InteractionManager(IDepthImageManager depthImageManager, IRemoteInteractionProcessorService service,
 36498            IPerformanceAggregator performanceAggregator, ITrackingManager trackingManager = null)
 36499        {
 36500            _depthImageManager = depthImageManager;
 36501            _service = service;
 36502            _performanceAggregator = performanceAggregator;
 36503            _trackingManager = trackingManager;
 504
 36505            _snapshotSource = depthImageManager as DepthImageManager;
 36506            if (_snapshotSource != null)
 8507                _snapshotSource.SnapshotSourceReady += OnSnapshotSourceReady;
 508            else
 28509                depthImageManager.ObservationReady += OnObservationReady;
 510
 36511            if (_trackingManager != null)
 8512                _trackingManager.TrackingStateChanged += OnTrackingStateChanged;
 36513        }
 514
 515        public bool UseObservationSnapshots
 516        {
 0517            get => _snapshotSource?.UseObservationSnapshots ?? true;
 518            set
 8519            {
 8520                lock (_snapshotSync)
 8521                {
 10522                    if (_snapshotSource == null || _snapshotSource.UseObservationSnapshots == value) return;
 6523                    _snapshotSource.UseObservationSnapshots = value;
 6524                    _pendingObservation = null;
 6525                    _spareSnapshots.Clear();
 6526                }
 8527            }
 528        }
 529
 530        public void Init(ObserverType type)
 8531        {
 8532            Type = type;
 8533        }
 534
 6535        private void OnTrackingStateChanged(object sender, TrackingStateChangedEventArgs args) => ResetTracking();
 536
 537        public void ResetTracking()
 12538        {
 539            // Serialize publication with the reset, without waiting for remote analysis to finish.
 12540            lock (_publicationSync)
 12541            {
 12542                lock (_snapshotSync)
 12543                {
 12544                    if (_disposed) return;
 12545                    UpdateObserver(CreateObserver(Type));
 12546                    _pendingObservation = null;
 12547                    _lastSnapshot = null;
 12548                    _spareSnapshots.Clear();
 12549                    _lastSequence = -1;
 12550                    _lastObservationTime = double.NegativeInfinity;
 12551                    _interactions = new List<Interaction>();
 12552                }
 12553                InteractionsUpdated?.Invoke(this, _interactions);
 12554                VelocitiesUpdated?.Invoke(this, new List<InteractionVelocity>());
 12555                InteractionHistoryUpdated?.Invoke(this, new List<InteractionFrame>());
 12556            }
 12557        }
 558
 10559        public void AdvanceTime() => _interactionObserver?.AdvanceTime(GetTimestampSeconds());
 560
 561        public async Task<ProcessServiceStatus> Update()
 92562        {
 92563            await _updateGate.WaitAsync();
 92564            var reservedRasters = false;
 565            try
 92566            {
 567                IInteractionObserver observer;
 568                TrackingObservation observation;
 92569                lock (_snapshotSync)
 92570                {
 92571                    if (_disposed) return ProcessServiceStatus.Skipped;
 92572                    observer = _interactionObserver;
 92573                    if (observer == null) return ProcessServiceStatus.Error;
 92574                    observation = _pendingObservation;
 92575                    if (observation is { OwnsRasters: false } &&
 92576                        !(reservedRasters = _snapshotSource.TryReserveRasters()))
 0577                    {
 578                        // Retry on the next tick. Age existing contacts while the producer is busy.
 0579                        observation = null;
 0580                    }
 581                    else
 92582                    {
 92583                        _pendingObservation = null;
 584                        // A failed producer update may have already modified the last live pair.
 92585                        if (reservedRasters && observation.Sequence != _snapshotSource.RasterSequence)
 0586                            observation = null;
 92587                    }
 92588                    if (observation == null || observation.Sequence <= _lastSequence ||
 92589                        observation.TimestampSeconds <= _lastObservationTime)
 10590                    {
 10591                        RecycleSnapshot(observation);
 10592                        observation = null;
 10593                    }
 594                    else
 82595                    {
 82596                        _lastSequence = observation.Sequence;
 82597                        _lastObservationTime = observation.TimestampSeconds;
 82598                    }
 92599                }
 92600                if (observation == null)
 10601                {
 10602                    observer.AdvanceTime(GetTimestampSeconds());
 10603                    return ProcessServiceStatus.Skipped;
 604                }
 164605                try { return (await observer.Update(observation)).ServiceStatus; }
 2606                catch (Exception exception)
 2607                {
 2608                    NLog.LogManager.GetCurrentClassLogger().Warn(exception, "Interaction analysis failed; aging active t
 609                    // Transport/analysis failures must age the published list, not leave stale contacts.
 2610                    observer.AdvanceTime(GetTimestampSeconds());
 2611                    return ProcessServiceStatus.Error;
 612                }
 613                finally
 82614                {
 615                    // The observer retains its input for diagnostics and distance calculation.
 616                    // Release the previous pair only after the new update has finished.
 82617                    lock (_snapshotSync)
 82618                    {
 82619                        if (ReferenceEquals(observer, _interactionObserver))
 76620                        {
 76621                            RecycleSnapshot(_lastSnapshot);
 76622                            _lastSnapshot = _disposed || _snapshotSource == null || !observation.OwnsRasters ? null : ob
 76623                        }
 82624                    }
 82625                }
 626            }
 627            finally
 92628            {
 100629                if (reservedRasters) _snapshotSource.ReleaseRasters();
 92630                _updateGate.Release();
 92631            }
 92632        }
 633
 634        private void OnObservationReady(object sender, TrackingObservation observation)
 64635        {
 64636            lock (_snapshotSync)
 64637            {
 128638                if (!_disposed) _pendingObservation = observation;
 64639            }
 64640        }
 641
 642        private void OnSnapshotSourceReady(long sequence, double timestamp, PointCloud3 cloud, VectorField2 vectors)
 30643        {
 30644            lock (_snapshotSync)
 30645            {
 30646                if (_disposed) return;
 30647                if (!_snapshotSource.UseObservationSnapshots)
 8648                {
 8649                    _pendingObservation = new TrackingObservation(sequence, timestamp, cloud, vectors, null, copyRasters
 8650                    return;
 651                }
 652
 653                // A pending pair has no reader. Prefer overwriting it when the consumer lags.
 22654                var spare = _pendingObservation;
 22655                _pendingObservation = null;
 40656                if (spare == null) _spareSnapshots.TryPop(out spare);
 22657                _pendingObservation = new TrackingObservation(sequence, timestamp, cloud, vectors, spare);
 22658            }
 30659        }
 660
 661        // Called under _snapshotSync. Public event observations are never recycled.
 662        private void RecycleSnapshot(TrackingObservation observation)
 86663        {
 86664            if (!_disposed && _snapshotSource is { UseObservationSnapshots: true } &&
 86665                observation is { OwnsRasters: true } && _spareSnapshots.Count < 2)
 10666                _spareSnapshots.Push(observation);
 86667        }
 668
 669        public event EventHandler<IList<Interaction>> InteractionsUpdated;
 670        public event EventHandler<IList<InteractionVelocity>> VelocitiesUpdated;
 671
 672        private void OnNewVelocities(object sender, IList<InteractionVelocity> velocities)
 96673        {
 96674            lock (_publicationSync)
 96675            {
 96676                if (_disposed || !ReferenceEquals(sender, _interactionObserver)) return;
 162677                var publishedIds = Interactions.Select(item => item.TouchId).ToHashSet();
 384678                foreach (var item in velocities)
 48679                {
 48680                    if (item.IsPublished && !publishedIds.Contains(item.TouchId))
 2681                    {
 2682                        item.IsPublished = false;
 2683                        item.SuppressionReason = "cluster";
 2684                    }
 48685                }
 96686                VelocitiesUpdated?.Invoke(this, velocities);
 96687            }
 96688        }
 689
 690        public event EventHandler<IList<InteractionFrame>> InteractionHistoryUpdated;
 691
 692        public void Dispose()
 38693        {
 38694            lock (_publicationSync)
 38695            {
 38696                lock (_snapshotSync)
 38697                {
 40698                    if (_disposed) return;
 36699                    _disposed = true;
 36700                    _pendingObservation = null;
 36701                    _lastSnapshot = null;
 36702                    _spareSnapshots.Clear();
 36703                }
 704
 36705                if (_snapshotSource != null)
 8706                    _snapshotSource.SnapshotSourceReady -= OnSnapshotSourceReady;
 707                else
 28708                    _depthImageManager.ObservationReady -= OnObservationReady;
 709
 36710                if (_interactionObserver != null)
 36711                {
 36712                    _interactionObserver.NewInteractions -= OnNewInteractions;
 36713                    _interactionObserver.NewVelocities -= OnNewVelocities;
 36714                    _interactionObserver.InteractionHistoryUpdated -= OnHistoryUpdated;
 715
 36716                    _performanceAggregator.UnregisterReporter(_interactionObserver as IPerformanceReporter);
 36717                }
 36718                if (_trackingManager != null)
 8719                    _trackingManager.TrackingStateChanged -= OnTrackingStateChanged;
 36720            }
 38721        }
 722
 723        private void OnNewInteractions(object sender, IList<Interaction> interactions)
 96724        {
 96725            lock (_publicationSync)
 96726            {
 96727                if (_disposed || !ReferenceEquals(sender, _interactionObserver)) return;
 96728                lock (interactions)
 96729                {
 164730                    var copy = interactions.Select(interaction => new Interaction(interaction)).ToList();
 96731                    _interactions = RemoveClusteredInteractions(copy);
 96732                }
 733
 96734                InteractionsUpdated?.Invoke(this, _interactions);
 96735            }
 96736        }
 737
 738        private IList<Interaction> RemoveClusteredInteractions(IList<Interaction> rawInteractions)
 98739        {
 98740            var filteredCopy = new List<Interaction>();
 106741            rawInteractions = rawInteractions.OrderBy(item => item.TrackingState == InteractionTrackingState.Lost)
 114742                .ThenByDescending(item => item.Confidence).ThenBy(item => item.TouchId).ToList();
 340743            for (var i = 0; i < rawInteractions.Count; i++)
 72744            {
 72745                var currPt = rawInteractions[i];
 76746                var distances = filteredCopy.Select(inter => Point3.Squared2DDistance(inter.Position, currPt.Position)).
 747
 72748                var addPoint = true;
 749
 144750                for (var j = 0; j < distances.Count; j++)
 4751                {
 4752                    var distance = distances[j];
 4753                    if (distance < InputDistance)
 4754                    {
 4755                        addPoint = false;
 4756                        break;
 757                    }
 0758                }
 72759                if (addPoint)
 68760                    filteredCopy.Add(currPt);
 72761            }
 98762            return filteredCopy;
 98763        }
 764
 765
 766    }
 767}

Methods/Properties

.ctor(Implementation.Interfaces.IDepthImageManager,ReFlex.Core.Interactivity.Interfaces.IRemoteInteractionProcessorService,ReFlex.Core.Common.Interfaces.IPerformanceAggregator,Implementation.Interfaces.ITrackingManager)
GetTimestampSeconds()
get_Interactions()
get_PredictionHorizonSeconds()
set_PredictionHorizonSeconds(System.Double)
get_UseVelocityPrediction()
set_UseVelocityPrediction(System.Boolean)
get_NumFramesForPrediction()
set_NumFramesForPrediction(System.Int32)
get_UseSecondDerivation()
set_UseSecondDerivation(System.Boolean)
get_SecondDerivationMagnitude()
set_SecondDerivationMagnitude(System.Single)
get_Type()
set_Type(ReFlex.Core.Common.Util.ObserverType)
CreateObserver(ReFlex.Core.Common.Util.ObserverType)
ComputeZeroPlaneDistance()
ReadObserverRasters(System.Func`1<T>)
UpdateObserver(ReFlex.Core.Interactivity.Interfaces.IInteractionObserver)
OnHistoryUpdated(System.Object,System.Collections.Generic.IList`1<ReFlex.Core.Common.Components.InteractionFrame>)
get_Distance()
set_Distance(System.Single)
get_MinDistance()
set_MinDistance(System.Single)
get_MaxDistance()
set_MaxDistance(System.Single)
get_MinAngle()
set_MinAngle(System.Single)
get_MinConfidence()
set_MinConfidence(System.Int32)
get_MaxConfidence()
set_MaxConfidence(System.Int32)
get_InteractionHistorySize()
set_InteractionHistorySize(System.Int32)
get_NumSmoothingFrames()
set_NumSmoothingFrames(System.Int32)
get_UseMinimumCostAssignment()
set_UseMinimumCostAssignment(System.Boolean)
get_AssignmentMissCost()
set_AssignmentMissCost(System.Single)
get_AssignmentBirthCost()
set_AssignmentBirthCost(System.Single)
get_ConfidenceGainPerSecond()
set_ConfidenceGainPerSecond(System.Single)
get_ConfidenceDecayPerSecond()
set_ConfidenceDecayPerSecond(System.Single)
get_ContactRetentionSeconds()
set_ContactRetentionSeconds(System.Double)
get_ObservationTimeoutSeconds()
set_ObservationTimeoutSeconds(System.Double)
get_TouchMergeDistance2D()
set_TouchMergeDistance2D(System.Single)
get_DepthScale()
set_DepthScale(System.Single)
get_FilterType()
set_FilterType(ReFlex.Core.Interactivity.Util.FilterType)
get_ExtremumTypeCheckNumSamples()
set_ExtremumTypeCheckNumSamples(System.Int32)
get_ExtremumMergeRadius()
set_ExtremumMergeRadius(System.Single)
get_ExtremumTypeCheckRadius()
set_ExtremumTypeCheckRadius(System.Int32)
get_ExtremumTypeCheckFittingPercentage()
set_ExtremumTypeCheckFittingPercentage(System.Single)
get_ExtremumTypeCheckMethod()
set_ExtremumTypeCheckMethod(ReFlex.Core.Common.Util.ExtremumTypeCheckMethod)
get_PointCloud()
set_PointCloud(ReFlex.Core.Common.Components.PointCloud3)
get_VectorField()
set_VectorField(ReFlex.Core.Common.Components.VectorField2)
get_InputDistance()
get_UseObservationSnapshots()
set_UseObservationSnapshots(System.Boolean)
Init(ReFlex.Core.Common.Util.ObserverType)
OnTrackingStateChanged(System.Object,ReFlex.Core.Events.TrackingStateChangedEventArgs)
ResetTracking()
AdvanceTime()
Update()
OnObservationReady(System.Object,ReFlex.Core.Common.Components.TrackingObservation)
OnSnapshotSourceReady(System.Int64,System.Double,ReFlex.Core.Common.Components.PointCloud3,ReFlex.Core.Common.Components.VectorField2)
RecycleSnapshot(ReFlex.Core.Common.Components.TrackingObservation)
OnNewVelocities(System.Object,System.Collections.Generic.IList`1<ReFlex.Core.Common.Components.InteractionVelocity>)
Dispose()
OnNewInteractions(System.Object,System.Collections.Generic.IList`1<ReFlex.Core.Common.Components.Interaction>)
RemoveClusteredInteractions(System.Collections.Generic.IList`1<ReFlex.Core.Common.Components.Interaction>)