| | | 1 | | using System; |
| | | 2 | | using System.Collections.Generic; |
| | | 3 | | using System.Diagnostics; |
| | | 4 | | using System.Linq; |
| | | 5 | | using System.Threading.Tasks; |
| | | 6 | | using ReFlex.Core.Common.Components; |
| | | 7 | | using ReFlex.Core.Common.Interfaces; |
| | | 8 | | using ReFlex.Core.Common.Util; |
| | | 9 | | using ReFlex.Core.Interactivity.Interfaces; |
| | | 10 | | using ReFlex.Core.Interactivity.Util; |
| | | 11 | | using Math = System.Math; |
| | | 12 | | |
| | | 13 | | namespace ReFlex.Core.Interactivity.Components |
| | | 14 | | { |
| | | 15 | | public abstract class InteractionObserverBase : IInteractionObserver, IPerformanceReporter |
| | | 16 | | { |
| | | 17 | | #region Fields |
| | | 18 | | |
| | 258 | 19 | | private readonly Stopwatch _stopWatch = new(); |
| | | 20 | | |
| | | 21 | | // Configuration access shares the frame/publication lock. Never hold it across Analyze awaits. |
| | 258 | 22 | | private readonly object _trackingSync = new(); |
| | | 23 | | private readonly InteractionSmoothingBehaviour _smoothingBehaviour; |
| | 258 | 24 | | private int _numSmoothingFrames = 5; |
| | 258 | 25 | | private int _historySize = 25; |
| | 258 | 26 | | private double _contactRetentionSeconds = .1; |
| | 258 | 27 | | private float _touchMergeDistance2d = 64f; |
| | 258 | 28 | | private float _depthScale = 100.0f; |
| | | 29 | | private FilterType _filterType; |
| | | 30 | | private float _maxConfidence; |
| | 258 | 31 | | private float _extremumMergeRadius = ExtremumConsolidator.DefaultRadius; |
| | | 32 | | private int _extremumTypeCheckRadius; |
| | | 33 | | private int _extremumTypeCheckNumSamples; |
| | | 34 | | |
| | 258 | 35 | | private Tuple<int, int>[] _fixedSamples = Array.Empty<Tuple<int, int>>(); |
| | 258 | 36 | | private Tuple<int, int>[] _stochasticSamples = Array.Empty<Tuple<int, int>>(); |
| | | 37 | | |
| | | 38 | | #endregion |
| | | 39 | | |
| | | 40 | | #region Properties |
| | | 41 | | |
| | | 42 | | /// <summary> |
| | | 43 | | /// Gets or sets the distance. |
| | | 44 | | /// </summary> |
| | | 45 | | /// <value> |
| | | 46 | | /// The distance. |
| | | 47 | | /// </value> |
| | 2088 | 48 | | public float Distance { get; set; } |
| | | 49 | | |
| | | 50 | | /// <summary> |
| | | 51 | | /// Gets or sets the minimum depth. |
| | | 52 | | /// </summary> |
| | | 53 | | /// <value> |
| | | 54 | | /// The maximum depth. |
| | | 55 | | /// </value> |
| | 1266 | 56 | | public float MinDistance { get; set; } |
| | | 57 | | |
| | | 58 | | /// <summary> |
| | | 59 | | /// Gets or sets the maximum depth. |
| | | 60 | | /// </summary> |
| | | 61 | | /// <value> |
| | | 62 | | /// The maximum depth. |
| | | 63 | | /// </value> |
| | 490 | 64 | | public float MaxDistance { get; set; } |
| | | 65 | | |
| | | 66 | | /// <summary> |
| | | 67 | | /// defines how many points should be checked to determine the type of the extremum |
| | | 68 | | /// </summary> |
| | | 69 | | public int ExtremumTypeCheckNumSamples |
| | | 70 | | { |
| | 578146 | 71 | | get => _extremumTypeCheckNumSamples; |
| | | 72 | | set |
| | 186 | 73 | | { |
| | 186 | 74 | | if (_extremumTypeCheckNumSamples == value) |
| | 22 | 75 | | return; |
| | 164 | 76 | | _extremumTypeCheckNumSamples = value; |
| | 164 | 77 | | UpdateSamples(); |
| | 186 | 78 | | } |
| | | 79 | | } |
| | | 80 | | |
| | | 81 | | /// <summary> |
| | | 82 | | /// The pixel radius in which the points are sampled for deriving the type of the local extremum |
| | | 83 | | /// </summary> |
| | | 84 | | public int ExtremumTypeCheckRadius |
| | | 85 | | { |
| | 330456 | 86 | | get => _extremumTypeCheckRadius; |
| | | 87 | | set |
| | 186 | 88 | | { |
| | 186 | 89 | | if (_extremumTypeCheckRadius == value) |
| | 20 | 90 | | return; |
| | 166 | 91 | | _extremumTypeCheckRadius = value; |
| | 166 | 92 | | UpdateSamples(); |
| | 186 | 93 | | } |
| | | 94 | | } |
| | | 95 | | |
| | | 96 | | /// <summary> |
| | | 97 | | /// Which ratio of "correctly aligned" points should match to distinguish between Undefined or Minimum/Maximum ? |
| | | 98 | | /// </summary> |
| | 356 | 99 | | public float ExtremumTypeCheckFittingPercentage { get; set; } |
| | | 100 | | |
| | | 101 | | /// <summary> |
| | | 102 | | /// Defines how neighboring the points are sampled for determining the type of extremum. |
| | | 103 | | /// </summary> |
| | 834 | 104 | | public ExtremumTypeCheckMethod ExtremumTypeCheckMethod { get; set; } |
| | | 105 | | |
| | | 106 | | /// <summary>Euclidean radius in sensor pixels for consolidating same-type extrema before ID assignment; zero di |
| | | 107 | | public float ExtremumMergeRadius |
| | | 108 | | { |
| | 960 | 109 | | get { lock (_trackingSync) return _extremumMergeRadius; } |
| | 248 | 110 | | set { lock (_trackingSync) _extremumMergeRadius = ExtremumConsolidator.ValidateRadius(value); } |
| | | 111 | | } |
| | | 112 | | |
| | | 113 | | public double PredictionHorizonSeconds |
| | | 114 | | { |
| | 24 | 115 | | get { lock (_trackingSync) return _smoothingBehaviour.PredictionHorizonSeconds; } |
| | 224 | 116 | | set { lock (_trackingSync) _smoothingBehaviour.PredictionHorizonSeconds = value; } |
| | | 117 | | } |
| | | 118 | | |
| | | 119 | | public bool UseVelocityPrediction |
| | | 120 | | { |
| | 48 | 121 | | get { lock (_trackingSync) return _smoothingBehaviour.UseVelocityForMapping; } |
| | 304 | 122 | | set { lock (_trackingSync) _smoothingBehaviour.UseVelocityForMapping = value; } |
| | | 123 | | } |
| | | 124 | | public int NumFramesForPrediction |
| | | 125 | | { |
| | 24 | 126 | | get { lock (_trackingSync) return _smoothingBehaviour.NumFramesForPrediction; } |
| | 232 | 127 | | set { lock (_trackingSync) _smoothingBehaviour.NumFramesForPrediction = value; } |
| | | 128 | | } |
| | | 129 | | public bool UseSecondDerivation |
| | | 130 | | { |
| | 24 | 131 | | get { lock (_trackingSync) return _smoothingBehaviour.UseSecondDerivation; } |
| | 224 | 132 | | set { lock (_trackingSync) _smoothingBehaviour.UseSecondDerivation = value; } |
| | | 133 | | } |
| | | 134 | | public float SecondDerivationMagnitude |
| | | 135 | | { |
| | 24 | 136 | | get { lock (_trackingSync) return _smoothingBehaviour.SecondDerivationMagnitude; } |
| | 224 | 137 | | set { lock (_trackingSync) _smoothingBehaviour.SecondDerivationMagnitude = value; } |
| | | 138 | | } |
| | | 139 | | |
| | | 140 | | public int InteractionHistorySize |
| | | 141 | | { |
| | 3032 | 142 | | get { lock (_trackingSync) return _smoothingBehaviour?.NumFramesHistory ?? _historySize; } |
| | | 143 | | set |
| | 120 | 144 | | { |
| | 120 | 145 | | lock (_trackingSync) |
| | 120 | 146 | | { |
| | 120 | 147 | | _historySize = Math.Max(0, value); |
| | 120 | 148 | | if (_smoothingBehaviour != null) |
| | 120 | 149 | | { |
| | 120 | 150 | | _smoothingBehaviour.NumFramesHistory = _historySize; |
| | | 151 | | // update depending smoothing/filter values |
| | 120 | 152 | | NumSmoothingFrames = _numSmoothingFrames; |
| | 120 | 153 | | } |
| | 120 | 154 | | } |
| | 120 | 155 | | } |
| | | 156 | | } |
| | | 157 | | |
| | | 158 | | public int NumSmoothingFrames |
| | | 159 | | { |
| | 96 | 160 | | get { lock (_trackingSync) return _smoothingBehaviour?.NumFramesSmoothing ?? _numSmoothingFrames; } |
| | | 161 | | set |
| | 492 | 162 | | { |
| | 492 | 163 | | lock (_trackingSync) |
| | 492 | 164 | | { |
| | 492 | 165 | | _numSmoothingFrames = Math.Clamp(value, 0, InteractionHistorySize); |
| | 492 | 166 | | if (_smoothingBehaviour != null) |
| | 492 | 167 | | _smoothingBehaviour.NumFramesSmoothing = _numSmoothingFrames; |
| | 492 | 168 | | } |
| | 492 | 169 | | } |
| | | 170 | | } |
| | | 171 | | |
| | | 172 | | private static double ValidateContactRetention(double value) => |
| | 326 | 173 | | double.IsFinite(value) && value >= 0 ? value : |
| | 326 | 174 | | throw new ArgumentOutOfRangeException(nameof(value), "Contact retention must be finite and non-negative |
| | | 175 | | |
| | | 176 | | public bool UseMinimumCostAssignment |
| | | 177 | | { |
| | 24 | 178 | | get { lock (_trackingSync) return _smoothingBehaviour.UseMinimumCostAssignment; } |
| | 232 | 179 | | set { lock (_trackingSync) _smoothingBehaviour.UseMinimumCostAssignment = value; } |
| | | 180 | | } |
| | | 181 | | |
| | | 182 | | public float AssignmentMissCost |
| | | 183 | | { |
| | 24 | 184 | | get { lock (_trackingSync) return _smoothingBehaviour.AssignmentMissCost; } |
| | 232 | 185 | | set { lock (_trackingSync) _smoothingBehaviour.AssignmentMissCost = value; } |
| | | 186 | | } |
| | | 187 | | |
| | | 188 | | public float AssignmentBirthCost |
| | | 189 | | { |
| | 32 | 190 | | get { lock (_trackingSync) return _smoothingBehaviour.AssignmentBirthCost; } |
| | 240 | 191 | | set { lock (_trackingSync) _smoothingBehaviour.AssignmentBirthCost = value; } |
| | | 192 | | } |
| | | 193 | | |
| | | 194 | | public float ConfidenceGainPerSecond |
| | | 195 | | { |
| | 48 | 196 | | get { lock (_trackingSync) return _smoothingBehaviour.ConfidenceGainPerSecond; } |
| | 242 | 197 | | set { lock (_trackingSync) _smoothingBehaviour.ConfidenceGainPerSecond = value; } |
| | | 198 | | } |
| | | 199 | | public float ConfidenceDecayPerSecond |
| | | 200 | | { |
| | 48 | 201 | | get { lock (_trackingSync) return _smoothingBehaviour.ConfidenceDecayPerSecond; } |
| | 242 | 202 | | set { lock (_trackingSync) _smoothingBehaviour.ConfidenceDecayPerSecond = value; } |
| | | 203 | | } |
| | | 204 | | |
| | | 205 | | public double ContactRetentionSeconds |
| | | 206 | | { |
| | 120 | 207 | | get { lock (_trackingSync) return _smoothingBehaviour?.ContactRetentionSeconds ?? _contactRetentionSeconds; |
| | | 208 | | set |
| | 326 | 209 | | { |
| | 326 | 210 | | lock (_trackingSync) |
| | 326 | 211 | | { |
| | 326 | 212 | | _contactRetentionSeconds = ValidateContactRetention(value); |
| | 320 | 213 | | if (_smoothingBehaviour != null) |
| | 320 | 214 | | _smoothingBehaviour.ContactRetentionSeconds = _contactRetentionSeconds; |
| | 320 | 215 | | } |
| | 320 | 216 | | } |
| | | 217 | | } |
| | | 218 | | |
| | | 219 | | /// <summary>Maximum sensor/processing silence and acceptable observation age, in seconds.</summary> |
| | | 220 | | public double ObservationTimeoutSeconds |
| | | 221 | | { |
| | 376 | 222 | | get { lock (_trackingSync) return _smoothingBehaviour.ObservationTimeoutSeconds; } |
| | 1256 | 223 | | set { lock (_trackingSync) _smoothingBehaviour.ObservationTimeoutSeconds = value; } |
| | | 224 | | } |
| | | 225 | | |
| | | 226 | | public float TouchMergeDistance2D |
| | | 227 | | { |
| | 24 | 228 | | get { lock (_trackingSync) return _touchMergeDistance2d; } |
| | | 229 | | set |
| | 352 | 230 | | { |
| | 352 | 231 | | lock (_trackingSync) |
| | 352 | 232 | | { |
| | 352 | 233 | | _touchMergeDistance2d = value; |
| | 352 | 234 | | if (_smoothingBehaviour != null) |
| | 352 | 235 | | _smoothingBehaviour.TouchMergeDistance2D = value; |
| | 352 | 236 | | } |
| | 352 | 237 | | } |
| | | 238 | | } |
| | | 239 | | |
| | | 240 | | public float DepthScale |
| | | 241 | | { |
| | 0 | 242 | | get { lock (_trackingSync) return _depthScale; } |
| | | 243 | | set |
| | 314 | 244 | | { |
| | 314 | 245 | | lock (_trackingSync) |
| | 314 | 246 | | { |
| | 314 | 247 | | if (_smoothingBehaviour != null) |
| | 314 | 248 | | _smoothingBehaviour.DepthScale = value; |
| | 314 | 249 | | _depthScale = value; |
| | 314 | 250 | | } |
| | 314 | 251 | | } |
| | | 252 | | } |
| | | 253 | | |
| | | 254 | | public FilterType FilterType |
| | | 255 | | { |
| | 32 | 256 | | get { lock (_trackingSync) return _filterType; } |
| | | 257 | | set |
| | 356 | 258 | | { |
| | 356 | 259 | | lock (_trackingSync) |
| | 356 | 260 | | { |
| | 356 | 261 | | _filterType = value; |
| | 356 | 262 | | if (_smoothingBehaviour != null) |
| | 356 | 263 | | _smoothingBehaviour.UpdateFilterType(_filterType); |
| | 356 | 264 | | } |
| | 356 | 265 | | } |
| | | 266 | | } |
| | | 267 | | |
| | | 268 | | |
| | | 269 | | /// <summary> |
| | | 270 | | /// Gets or sets the minimum angle. |
| | | 271 | | /// </summary> |
| | | 272 | | /// <value> |
| | | 273 | | /// The minimum angle. |
| | | 274 | | /// </value> |
| | 84 | 275 | | public virtual float MinAngle { get; set; } |
| | | 276 | | |
| | | 277 | | /// <summary> |
| | | 278 | | /// Gets or sets the minimum confidence. |
| | | 279 | | /// </summary> |
| | | 280 | | /// <value> |
| | | 281 | | /// The minimum confidence. |
| | | 282 | | /// </value> |
| | 394 | 283 | | public virtual float MinConfidence { get; set; } |
| | | 284 | | |
| | | 285 | | /// <summary> |
| | | 286 | | /// Gets or sets the maximum confidence. |
| | | 287 | | /// </summary> |
| | | 288 | | /// <value> |
| | | 289 | | /// The maximum confidence. |
| | | 290 | | /// </value> |
| | | 291 | | public virtual float MaxConfidence |
| | | 292 | | { |
| | 1520 | 293 | | get { lock (_trackingSync) return _maxConfidence; } |
| | | 294 | | set |
| | 364 | 295 | | { |
| | 364 | 296 | | lock (_trackingSync) |
| | 364 | 297 | | { |
| | 364 | 298 | | _maxConfidence = value; |
| | 364 | 299 | | if (_smoothingBehaviour != null) |
| | 364 | 300 | | _smoothingBehaviour.MaxConfidence = (int) MaxConfidence; |
| | 364 | 301 | | } |
| | 364 | 302 | | } |
| | | 303 | | } |
| | | 304 | | |
| | 2280 | 305 | | public bool MeasurePerformance { get; set; } |
| | | 306 | | |
| | 240 | 307 | | protected int FrameId { get; private set; } |
| | | 308 | | |
| | | 309 | | #region Abstract Members |
| | | 310 | | |
| | | 311 | | public abstract ObserverType Type { get; } |
| | | 312 | | public abstract PointCloud3 PointCloud { get; set; } |
| | | 313 | | public abstract VectorField2 VectorField { get; set; } |
| | | 314 | | |
| | | 315 | | public event EventHandler<IList<Interaction>> NewInteractions; |
| | | 316 | | public event EventHandler<IList<InteractionVelocity>> NewVelocities; |
| | | 317 | | |
| | | 318 | | public event EventHandler<PerformanceDataItem> PerformanceDataUpdated; |
| | | 319 | | |
| | | 320 | | public event EventHandler<IList<InteractionFrame>> InteractionHistoryUpdated; |
| | | 321 | | |
| | | 322 | | #endregion |
| | | 323 | | |
| | | 324 | | #region Constructor |
| | | 325 | | |
| | 258 | 326 | | protected InteractionObserverBase() |
| | 258 | 327 | | { |
| | 258 | 328 | | _smoothingBehaviour = new InteractionSmoothingBehaviour(InteractionHistorySize); |
| | 258 | 329 | | ObservationTimeoutSeconds = 1; |
| | 258 | 330 | | NumSmoothingFrames = _numSmoothingFrames; |
| | 258 | 331 | | ContactRetentionSeconds = _contactRetentionSeconds; |
| | 258 | 332 | | TouchMergeDistance2D = _touchMergeDistance2d; |
| | 258 | 333 | | DepthScale = _depthScale; |
| | 258 | 334 | | MaxConfidence = _maxConfidence; |
| | 258 | 335 | | FilterType = _filterType; |
| | 258 | 336 | | } |
| | | 337 | | |
| | | 338 | | #endregion |
| | | 339 | | |
| | | 340 | | public void UpdateFrameId(int frameId) |
| | 0 | 341 | | { |
| | 0 | 342 | | FrameId = frameId; |
| | 0 | 343 | | } |
| | | 344 | | |
| | | 345 | | #endregion |
| | | 346 | | |
| | | 347 | | protected abstract Task<Tuple<IEnumerable<Interaction>, ProcessPerformance>> Analyze(ProcessPerformance performa |
| | | 348 | | |
| | 0 | 349 | | protected virtual Task ReportPerformance(ProcessPerformance performance) => Task.CompletedTask; |
| | | 350 | | |
| | | 351 | | protected virtual Task<ProcessingResult> CheckInitialState() |
| | 94 | 352 | | { |
| | 94 | 353 | | return Task.FromResult(new ProcessingResult(ProcessServiceStatus.Available)); |
| | 94 | 354 | | } |
| | | 355 | | |
| | | 356 | | private double? _observationTime; |
| | | 357 | | |
| | | 358 | | public async Task<ProcessingResult> Update(TrackingObservation observation) |
| | 92 | 359 | | { |
| | 92 | 360 | | PointCloud = observation.PointCloud; |
| | 92 | 361 | | VectorField = observation.VectorField; |
| | 92 | 362 | | _observationTime = observation.TimestampSeconds; |
| | 184 | 363 | | try { return await Update(); } |
| | 276 | 364 | | finally { _observationTime = null; } |
| | 90 | 365 | | } |
| | | 366 | | |
| | | 367 | | public void AdvanceTime(double timestampSeconds) |
| | 36 | 368 | | { |
| | 72 | 369 | | lock (_trackingSync) Publish(_smoothingBehaviour.OutputAt(timestampSeconds)); |
| | 36 | 370 | | } |
| | | 371 | | |
| | | 372 | | private void Publish(InteractionFrame frame) |
| | 262 | 373 | | { |
| | 262 | 374 | | var selected = SelectSmoothedInteractions(frame.Interactions).ToList(); |
| | 262 | 375 | | var published = ApplyConfidenceFilter(selected).ToList(); |
| | 540 | 376 | | var publishedIds = published.Select(item => item.TouchId).ToHashSet(); |
| | 556 | 377 | | var selectedIds = selected.Select(item => item.TouchId).ToHashSet(); |
| | | 378 | | // Diagnostics include hidden tracks and are captured before any external callbacks. |
| | 262 | 379 | | var velocities = _smoothingBehaviour.GetVelocities(frame); |
| | 1198 | 380 | | foreach (var velocity in velocities) |
| | 206 | 381 | | { |
| | 206 | 382 | | velocity.Width = PointCloud?.SizeX ?? 0; |
| | 206 | 383 | | velocity.Height = PointCloud?.SizeY ?? 0; |
| | 206 | 384 | | velocity.IsPublished = publishedIds.Contains(velocity.TouchId); |
| | 206 | 385 | | velocity.SuppressionReason = velocity.IsPublished ? "" : |
| | 206 | 386 | | selectedIds.Contains(velocity.TouchId) ? "confidence" : "observer-selection"; |
| | 206 | 387 | | } |
| | 262 | 388 | | OnNewInteractions(published); |
| | 262 | 389 | | NewVelocities?.Invoke(this, velocities); |
| | 262 | 390 | | } |
| | | 391 | | |
| | | 392 | | public virtual async Task<ProcessingResult> Update() |
| | 242 | 393 | | { |
| | 242 | 394 | | var processResult = await CheckInitialState(); |
| | | 395 | | |
| | 242 | 396 | | if (processResult.ServiceStatus != ProcessServiceStatus.Available) |
| | 14 | 397 | | { |
| | 14 | 398 | | AdvanceTime(GetTimestampSeconds()); |
| | 14 | 399 | | UpdatePerformanceMetrics(new ProcessPerformance(), DateTime.Now.Ticks); |
| | 14 | 400 | | return processResult; |
| | | 401 | | } |
| | | 402 | | |
| | 228 | 403 | | var timestampSeconds = _observationTime ?? GetTimestampSeconds(); |
| | 228 | 404 | | var observationCloud = PointCloud; |
| | 228 | 405 | | var processingDateTime = DateTime.Now.Ticks; |
| | | 406 | | |
| | 228 | 407 | | if (MeasurePerformance) |
| | 2 | 408 | | { |
| | 2 | 409 | | _stopWatch.Start(); |
| | 2 | 410 | | } |
| | | 411 | | |
| | 228 | 412 | | var processed = await Analyze(processResult.PerformanceMeasurement); |
| | | 413 | | |
| | 226 | 414 | | var candidates = processed.Item1; |
| | 226 | 415 | | var perfItem = processed.Item2; |
| | | 416 | | |
| | 226 | 417 | | if (MeasurePerformance) |
| | 2 | 418 | | { |
| | 2 | 419 | | _stopWatch.Stop(); |
| | 2 | 420 | | perfItem.Update = _stopWatch.Elapsed - perfItem.Preparation; |
| | 2 | 421 | | _stopWatch.Reset(); |
| | 2 | 422 | | } |
| | | 423 | | |
| | 226 | 424 | | if (MeasurePerformance) |
| | 2 | 425 | | { |
| | 2 | 426 | | _stopWatch.Start(); |
| | 2 | 427 | | } |
| | | 428 | | |
| | 226 | 429 | | var interactions = ConvertDepthValue(candidates.ToList()); |
| | | 430 | | |
| | 226 | 431 | | if (MeasurePerformance) |
| | 2 | 432 | | { |
| | 2 | 433 | | _stopWatch.Stop(); |
| | 2 | 434 | | perfItem.ConvertDepthValue = _stopWatch.Elapsed; |
| | 2 | 435 | | _stopWatch.Reset(); |
| | 2 | 436 | | } |
| | | 437 | | |
| | 226 | 438 | | if (MeasurePerformance) |
| | 2 | 439 | | { |
| | 2 | 440 | | _stopWatch.Start(); |
| | 2 | 441 | | } |
| | | 442 | | |
| | 226 | 443 | | var processedInteractions = ComputeExtremumType(interactions, observationCloud.AsJaggedArray()); |
| | | 444 | | |
| | 226 | 445 | | var cleanedUpInteractions = RemoveExtremumsBetweenTouches(processedInteractions); |
| | | 446 | | |
| | 226 | 447 | | if (MeasurePerformance) |
| | 2 | 448 | | { |
| | 2 | 449 | | _stopWatch.Stop(); |
| | 2 | 450 | | perfItem.ComputeExtremumType = _stopWatch.Elapsed; |
| | 2 | 451 | | _stopWatch.Reset(); |
| | 2 | 452 | | } |
| | | 453 | | |
| | | 454 | | |
| | 226 | 455 | | if (MeasurePerformance) |
| | 2 | 456 | | { |
| | 2 | 457 | | _stopWatch.Start(); |
| | 2 | 458 | | } |
| | | 459 | | |
| | | 460 | | Task reportTask; |
| | 226 | 461 | | lock (_trackingSync) |
| | 226 | 462 | | { |
| | 226 | 463 | | var measurements = ConsolidateExtrema(cleanedUpInteractions); |
| | 226 | 464 | | var processedAt = Math.Max(timestampSeconds, GetTimestampSeconds()); |
| | | 465 | | // Reject an actually late result before it can mutate or revive tracking state. |
| | 226 | 466 | | var frame = _observationTime.HasValue && processedAt > timestampSeconds + ObservationTimeoutSeconds |
| | 226 | 467 | | ? _smoothingBehaviour.OutputAt(processedAt) |
| | 226 | 468 | | : ComputeSmoothingValue(measurements, timestampSeconds, processedAt); |
| | | 469 | | |
| | 226 | 470 | | if (MeasurePerformance) |
| | 2 | 471 | | { |
| | 2 | 472 | | _stopWatch.Stop(); |
| | 2 | 473 | | perfItem.Smoothing = _stopWatch.Elapsed; |
| | 2 | 474 | | _stopWatch.Reset(); |
| | 2 | 475 | | } |
| | | 476 | | |
| | | 477 | | // Populate optional remote stage timings before publishing the shared dictionary. |
| | 226 | 478 | | reportTask = MeasurePerformance ? ReportPerformance(perfItem) : Task.CompletedTask; |
| | 226 | 479 | | processResult.PerformanceMeasurement = perfItem; |
| | 226 | 480 | | UpdatePerformanceMetrics(perfItem, processingDateTime); |
| | | 481 | | |
| | 226 | 482 | | Publish(frame); |
| | 226 | 483 | | } |
| | | 484 | | |
| | 226 | 485 | | await reportTask; |
| | | 486 | | |
| | 226 | 487 | | return processResult; |
| | 240 | 488 | | } |
| | | 489 | | |
| | | 490 | | /// <summary>Limits the smoothed output without changing the tracking history.</summary> |
| | | 491 | | protected virtual IEnumerable<Interaction> SelectSmoothedInteractions(IEnumerable<Interaction> interactions) |
| | 256 | 492 | | => interactions; |
| | | 493 | | |
| | | 494 | | protected virtual IList<Interaction> ConsolidateExtrema(IList<Interaction> interactions) |
| | 226 | 495 | | => ExtremumConsolidator.Consolidate(interactions, ExtremumMergeRadius); |
| | | 496 | | |
| | | 497 | | /// <summary>Monotonic observation time captured before Analyze, including remote work.</summary> |
| | 74 | 498 | | protected virtual double GetTimestampSeconds() => (double)Stopwatch.GetTimestamp() / Stopwatch.Frequency; |
| | | 499 | | |
| | | 500 | | protected InteractionFrame ComputeSmoothingValue(IList<Interaction> rawInteractions, double? timestampSeconds = |
| | | 501 | | double? processedTimestampSeconds = null) |
| | 220 | 502 | | { |
| | 220 | 503 | | var capturedAt = timestampSeconds ?? GetTimestampSeconds(); |
| | 220 | 504 | | var result = _smoothingBehaviour.Update(rawInteractions, capturedAt, processedTimestampSeconds ?? capturedAt |
| | 220 | 505 | | InteractionHistoryUpdated?.Invoke(this, _smoothingBehaviour.InteractionsFramesCache); |
| | | 506 | | |
| | 220 | 507 | | return result; |
| | 220 | 508 | | } |
| | | 509 | | |
| | | 510 | | protected virtual ExtremumDescription ComputeExtremumType(Point3[][] pointsArray, int xPos, int yPos) |
| | 486 | 511 | | { |
| | 486 | 512 | | if (ExtremumTypeCheckMethod == ExtremumTypeCheckMethod.Global) |
| | 352 | 513 | | { |
| | | 514 | | // Global skips neighbourhood validation, but retains the same sensor-depth |
| | | 515 | | // convention as the spatial classifier: pushes are minima, pulls maxima. |
| | 352 | 516 | | var depth = pointsArray[xPos][yPos].Z; |
| | 352 | 517 | | var type = !float.IsFinite(depth) || depth == Distance ? ExtremumType.Undefined |
| | 352 | 518 | | : depth < Distance ? ExtremumType.Minimum : ExtremumType.Maximum; |
| | 352 | 519 | | return new ExtremumDescription |
| | 352 | 520 | | { |
| | 352 | 521 | | Type = type, |
| | 352 | 522 | | NumFittingPoints = type == ExtremumType.Undefined ? 0 : ExtremumTypeCheckNumSamples, |
| | 352 | 523 | | PercentageFittingPoints = type == ExtremumType.Undefined ? 0 : 1.0f |
| | 352 | 524 | | }; |
| | | 525 | | } |
| | | 526 | | |
| | 134 | 527 | | var xMax = pointsArray.Length - 1; |
| | 134 | 528 | | var yMax = xMax > 0 ? pointsArray[0].Length - 1 : 0; |
| | | 529 | | |
| | | 530 | | // refZ is the absolute distance from sensor |
| | 134 | 531 | | var refZ = Math.Abs(pointsArray[xPos][yPos].Z); |
| | | 532 | | |
| | 134 | 533 | | var numCloser = 0; |
| | 134 | 534 | | var numFarther = 0; |
| | | 535 | | |
| | | 536 | | Tuple<int, int>[] samples; |
| | 134 | 537 | | switch (ExtremumTypeCheckMethod) |
| | | 538 | | { |
| | | 539 | | case ExtremumTypeCheckMethod.StochasticStatic: |
| | 30 | 540 | | samples = _stochasticSamples; |
| | 30 | 541 | | break; |
| | | 542 | | case ExtremumTypeCheckMethod.StochasticDynamic: |
| | 30 | 543 | | samples = GenerateSamples(); |
| | 30 | 544 | | break; |
| | | 545 | | case ExtremumTypeCheckMethod.Global: |
| | 0 | 546 | | throw new ArgumentException("invalid Method 'Global' at this point."); |
| | | 547 | | case ExtremumTypeCheckMethod.FixedRadius: |
| | | 548 | | default: |
| | 74 | 549 | | samples = _fixedSamples; |
| | 74 | 550 | | break; |
| | | 551 | | } |
| | | 552 | | |
| | 329260 | 553 | | for (var i = 0; i < samples.Length; i++) |
| | 164496 | 554 | | { |
| | 164496 | 555 | | var sample = GetSample(pointsArray, xPos, yPos, samples, i, xMax, yMax); |
| | 164496 | 556 | | if (Math.Abs(sample.Z) > refZ) |
| | 98756 | 557 | | numFarther++; |
| | | 558 | | else |
| | 65740 | 559 | | numCloser++; |
| | 164496 | 560 | | } |
| | | 561 | | |
| | | 562 | | |
| | 134 | 563 | | var ratioMax = ExtremumTypeCheckNumSamples > 0 ? (float)numCloser / ExtremumTypeCheckNumSamples : 0; |
| | 134 | 564 | | var ratioMin = ExtremumTypeCheckNumSamples > 0 ? (float)numFarther / ExtremumTypeCheckNumSamples : 0; |
| | | 565 | | |
| | 134 | 566 | | if (numCloser > numFarther && ratioMax > ExtremumTypeCheckFittingPercentage) |
| | 52 | 567 | | { |
| | 52 | 568 | | return new ExtremumDescription |
| | 52 | 569 | | { |
| | 52 | 570 | | Type = ExtremumType.Maximum, |
| | 52 | 571 | | NumFittingPoints = numCloser, |
| | 52 | 572 | | PercentageFittingPoints = ratioMax |
| | 52 | 573 | | }; |
| | | 574 | | } |
| | | 575 | | |
| | 82 | 576 | | if (numFarther > numCloser && ratioMin > ExtremumTypeCheckFittingPercentage) |
| | 50 | 577 | | { |
| | 50 | 578 | | return new ExtremumDescription |
| | 50 | 579 | | { |
| | 50 | 580 | | Type = ExtremumType.Minimum, |
| | 50 | 581 | | NumFittingPoints = numFarther, |
| | 50 | 582 | | PercentageFittingPoints = ratioMin |
| | 50 | 583 | | }; |
| | | 584 | | } |
| | | 585 | | |
| | 32 | 586 | | return new ExtremumDescription |
| | 32 | 587 | | { |
| | 32 | 588 | | Type = ExtremumType.Undefined, |
| | 32 | 589 | | NumFittingPoints = Math.Max(numCloser, numFarther), |
| | 32 | 590 | | PercentageFittingPoints = Math.Max(ratioMin, ratioMax) |
| | 32 | 591 | | }; |
| | | 592 | | |
| | 486 | 593 | | } |
| | | 594 | | |
| | | 595 | | protected List<Interaction> ConvertDepthValue(List<Interaction> interactions) |
| | 234 | 596 | | { |
| | 234 | 597 | | var result = new List<Interaction>(); |
| | | 598 | | |
| | 1510 | 599 | | foreach (var item in interactions) |
| | 404 | 600 | | { |
| | 404 | 601 | | if (item?.Position == null || !float.IsFinite(item.Position.Z) || |
| | 404 | 602 | | Math.Abs(item.Position.Z - Distance) <= MinDistance) |
| | 24 | 603 | | continue; |
| | | 604 | | |
| | 380 | 605 | | if (item.Position.Z < Distance) |
| | 364 | 606 | | { |
| | 364 | 607 | | item.Type = InteractionType.Push; |
| | 364 | 608 | | var depth = (Distance - item.Position.Z - MinDistance) / (MinDistance - MaxDistance); |
| | | 609 | | |
| | 364 | 610 | | if (depth > 0) |
| | 0 | 611 | | continue; |
| | | 612 | | |
| | 364 | 613 | | if (depth < -1) |
| | 0 | 614 | | depth = -1; |
| | | 615 | | |
| | 364 | 616 | | item.Position.Z = depth; |
| | 364 | 617 | | } |
| | | 618 | | else |
| | 16 | 619 | | { |
| | 16 | 620 | | item.Type = InteractionType.Pull; |
| | 16 | 621 | | var depth = (item.Position.Z - MinDistance - Distance) / (MaxDistance - MinDistance); |
| | | 622 | | |
| | 16 | 623 | | if (depth < 0) |
| | 0 | 624 | | continue; |
| | | 625 | | |
| | 16 | 626 | | if (depth > 1) |
| | 0 | 627 | | depth = 1; |
| | | 628 | | |
| | 16 | 629 | | item.Position.Z = depth; |
| | 16 | 630 | | } |
| | | 631 | | |
| | 380 | 632 | | result.Add(item); |
| | 380 | 633 | | } |
| | | 634 | | |
| | 234 | 635 | | return result; |
| | 234 | 636 | | } |
| | | 637 | | |
| | | 638 | | protected IEnumerable<Interaction> ApplyConfidenceFilter(IEnumerable<Interaction> interactions) |
| | 262 | 639 | | { |
| | 556 | 640 | | return interactions.ToArray().Where(item => item.Confidence > MinConfidence); |
| | 262 | 641 | | } |
| | | 642 | | |
| | | 643 | | protected List<Interaction> ComputeExtremumType(List<Interaction> interactions, Point3[][] pointsArray) |
| | 226 | 644 | | { |
| | 226 | 645 | | interactions.ForEach(interaction => |
| | 598 | 646 | | interaction.ExtremumDescription = ComputeExtremumType(pointsArray, (int)interaction.Position.X, (int)int |
| | | 647 | | |
| | 226 | 648 | | return interactions; |
| | 226 | 649 | | } |
| | | 650 | | |
| | | 651 | | /// <summary> |
| | | 652 | | /// generic approach: removes all maximums below the surface and all minimums above the surface. Removal is base |
| | | 653 | | /// Points witch <see cref="ExtremumType.Undefined"/> are also removed. |
| | | 654 | | /// </summary> |
| | | 655 | | /// <param name="interactions">the list of preprocessed interactions with valid ExtremumDescription</param> |
| | | 656 | | /// <returns></returns> |
| | | 657 | | protected List<Interaction> RemoveExtremumsBetweenTouches(List<Interaction> interactions) |
| | 226 | 658 | | { |
| | 226 | 659 | | return interactions.Where((touch) => |
| | 226 | 660 | | // invalid or undefined ExtremumType |
| | 372 | 661 | | touch.ExtremumDescription != null && touch.ExtremumDescription.Type != ExtremumType.Undefined && |
| | 372 | 662 | | // minimums below the surface |
| | 372 | 663 | | ((touch.Position.Z < 0 && touch.ExtremumDescription.Type == ExtremumType.Minimum) || |
| | 372 | 664 | | // maximums above the surface |
| | 372 | 665 | | (touch.Position.Z > 0 && touch.ExtremumDescription.Type == ExtremumType.Maximum)) |
| | 226 | 666 | | |
| | 226 | 667 | | ).ToList(); |
| | 226 | 668 | | } |
| | | 669 | | |
| | | 670 | | protected void UpdatePerformanceMetrics(ProcessPerformance perfItem, long startTime) |
| | 240 | 671 | | { |
| | 240 | 672 | | var pData = new PerformanceDataItem |
| | 240 | 673 | | { |
| | 240 | 674 | | FrameId = Convert.ToInt32(FrameId), |
| | 240 | 675 | | FrameStart = startTime, |
| | 240 | 676 | | FrameEnd = DateTime.Now.Ticks, |
| | 240 | 677 | | Process = perfItem, |
| | 240 | 678 | | Stage = PerformanceDataStage.ProcessingData |
| | 240 | 679 | | }; |
| | | 680 | | |
| | 240 | 681 | | PerformanceDataUpdated?.Invoke(this, pData); |
| | 240 | 682 | | } |
| | | 683 | | |
| | 262 | 684 | | protected void OnNewInteractions(List<Interaction> args) => NewInteractions?.Invoke(this, args); |
| | | 685 | | |
| | | 686 | | /// <summary> |
| | | 687 | | /// Calculates the average distance for the currently stored PointCloud. |
| | | 688 | | /// </summary> |
| | | 689 | | /// <returns></returns> |
| | | 690 | | public float CalculateAverageDistance() |
| | 0 | 691 | | { |
| | 0 | 692 | | var sum = 0f; |
| | 0 | 693 | | var points = PointCloud?.AsArray(); |
| | | 694 | | |
| | 0 | 695 | | if (points == null) |
| | 0 | 696 | | return sum; |
| | | 697 | | |
| | 0 | 698 | | var numValidSamples = 0; |
| | | 699 | | |
| | 0 | 700 | | for (var i = 0; i < points.Length; ++i) |
| | 0 | 701 | | { |
| | 0 | 702 | | if (!points[i].IsValid || points[i].IsFiltered) |
| | 0 | 703 | | continue; |
| | | 704 | | |
| | 0 | 705 | | numValidSamples++; |
| | 0 | 706 | | sum += points[i].Z; |
| | 0 | 707 | | } |
| | | 708 | | |
| | 0 | 709 | | return (float) decimal.Round((decimal) (sum / numValidSamples), 2); |
| | 0 | 710 | | } |
| | | 711 | | |
| | | 712 | | private static Point3 GetSample(Point3[][] pointsArray, int xPos, int yPos, Tuple<int, int>[] samples, int i, in |
| | 164496 | 713 | | { |
| | 164496 | 714 | | var xIdx = xPos + samples[i].Item1; |
| | 164496 | 715 | | xIdx = Math.Min(Math.Max(xIdx, 0), xMax); |
| | | 716 | | |
| | 164496 | 717 | | var yIdx = yPos + samples[i].Item2; |
| | 164496 | 718 | | yIdx = Math.Min(Math.Max(yIdx, 0), yMax); |
| | 164496 | 719 | | var sample = pointsArray[xIdx][yIdx]; |
| | | 720 | | |
| | 164496 | 721 | | return sample; |
| | 164496 | 722 | | } |
| | | 723 | | |
| | | 724 | | private Tuple<int, int>[] GenerateSamples() |
| | 360 | 725 | | { |
| | 360 | 726 | | var result = new List<Tuple<int, int>>(); |
| | | 727 | | |
| | 360 | 728 | | var rnd = new Random(); |
| | | 729 | | |
| | 360 | 730 | | var min = (int)Math.Floor(0.5f * ExtremumTypeCheckRadius); |
| | 360 | 731 | | var max = ExtremumTypeCheckRadius; |
| | 360 | 732 | | var range = max - min; |
| | | 733 | | |
| | 494416 | 734 | | for (var i = 0; i < ExtremumTypeCheckNumSamples; i++) |
| | 246848 | 735 | | { |
| | | 736 | | // One draw per axis encodes both magnitude and sign. Map [-range, -1] |
| | | 737 | | // to [-(max - 1), -min] and [0, range - 1] to [min, max - 1]. |
| | 246848 | 738 | | var x = rnd.Next(-range, range); |
| | 246848 | 739 | | var y = rnd.Next(-range, range); |
| | | 740 | | // A 0/-1 sign mask avoids an unpredictable branch for each axis. |
| | 246848 | 741 | | var xSign = x >> 31; |
| | 246848 | 742 | | var ySign = y >> 31; |
| | 246848 | 743 | | var xStochastic = x + (min ^ xSign) - 2 * xSign; |
| | 246848 | 744 | | var yStochastic = y + (min ^ ySign) - 2 * ySign; |
| | | 745 | | |
| | 246848 | 746 | | result.Add(new Tuple<int, int>(xStochastic, yStochastic)); |
| | 246848 | 747 | | } |
| | | 748 | | |
| | 360 | 749 | | return result.ToArray(); |
| | 360 | 750 | | } |
| | | 751 | | |
| | | 752 | | private void UpdateSamples() |
| | 330 | 753 | | { |
| | 330 | 754 | | var samplesFixed = new List<Tuple<int, int>>(); |
| | | 755 | | |
| | 330388 | 756 | | for (var i = 0; i < ExtremumTypeCheckNumSamples; i++) |
| | 164864 | 757 | | { |
| | 164864 | 758 | | var p = (double)i / ExtremumTypeCheckNumSamples; |
| | 164864 | 759 | | var xFixed = (int) Math.Floor(ExtremumTypeCheckRadius * Math.Cos(p * 2 * Math.PI)); |
| | 164864 | 760 | | var yFixed = (int) Math.Floor(ExtremumTypeCheckRadius * Math.Sin(p * 2 * Math.PI)); |
| | | 761 | | |
| | 164864 | 762 | | samplesFixed.Add(new Tuple<int, int>(xFixed, yFixed)); |
| | 164864 | 763 | | } |
| | 330 | 764 | | _fixedSamples = samplesFixed.ToArray(); |
| | | 765 | | |
| | 330 | 766 | | _stochasticSamples = GenerateSamples(); |
| | 330 | 767 | | } |
| | | 768 | | |
| | | 769 | | |
| | | 770 | | } |
| | | 771 | | } |