velocity_tracker.dart 8.85 KB
Newer Older
Ian Hickson's avatar
Ian Hickson committed
1
// Copyright 2014 The Flutter Authors. All rights reserved.
2 3 4
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

5
import 'dart:ui' show Offset;
6

7 8
import 'package:flutter/foundation.dart';

9 10
import 'lsq_solver.dart';

11
export 'dart:ui' show Offset;
12

13
/// A velocity in two dimensions.
14
@immutable
15
class Velocity {
16 17 18
  /// Creates a velocity.
  ///
  /// The [pixelsPerSecond] argument must not be null.
19 20 21
  const Velocity({
    @required this.pixelsPerSecond,
  }) : assert(pixelsPerSecond != null);
22 23

  /// A velocity that isn't moving at all.
24
  static const Velocity zero = Velocity(pixelsPerSecond: Offset.zero);
25 26 27 28

  /// The number of pixels per second of velocity in the x and y directions.
  final Offset pixelsPerSecond;

29
  /// Return the negation of a velocity.
30
  Velocity operator -() => Velocity(pixelsPerSecond: -pixelsPerSecond);
31 32

  /// Return the difference of two velocities.
33
  Velocity operator -(Velocity other) {
34
    return Velocity(
35 36
        pixelsPerSecond: pixelsPerSecond - other.pixelsPerSecond);
  }
37 38

  /// Return the sum of two velocities.
39
  Velocity operator +(Velocity other) {
40
    return Velocity(
41 42 43
        pixelsPerSecond: pixelsPerSecond + other.pixelsPerSecond);
  }

44 45 46 47 48 49 50 51 52 53 54 55 56 57 58
  /// Return a velocity whose magnitude has been clamped to [minValue]
  /// and [maxValue].
  ///
  /// If the magnitude of this Velocity is less than minValue then return a new
  /// Velocity with the same direction and with magnitude [minValue]. Similarly,
  /// if the magnitude of this Velocity is greater than maxValue then return a
  /// new Velocity with the same direction and magnitude [maxValue].
  ///
  /// If the magnitude of this Velocity is within the specified bounds then
  /// just return this.
  Velocity clampMagnitude(double minValue, double maxValue) {
    assert(minValue != null && minValue >= 0.0);
    assert(maxValue != null && maxValue >= 0.0 && maxValue >= minValue);
    final double valueSquared = pixelsPerSecond.distanceSquared;
    if (valueSquared > maxValue * maxValue)
59
      return Velocity(pixelsPerSecond: (pixelsPerSecond / pixelsPerSecond.distance) * maxValue);
60
    if (valueSquared < minValue * minValue)
61
      return Velocity(pixelsPerSecond: (pixelsPerSecond / pixelsPerSecond.distance) * minValue);
62 63 64
    return this;
  }

65
  @override
66
  bool operator ==(Object other) {
67 68
    return other is Velocity
        && other.pixelsPerSecond == pixelsPerSecond;
69 70
  }

71
  @override
72 73
  int get hashCode => pixelsPerSecond.hashCode;

74
  @override
75 76 77
  String toString() => 'Velocity(${pixelsPerSecond.dx.toStringAsFixed(1)}, ${pixelsPerSecond.dy.toStringAsFixed(1)})';
}

78 79 80
/// A two dimensional velocity estimate.
///
/// VelocityEstimates are computed by [VelocityTracker.getVelocityEstimate]. An
81
/// estimate's [confidence] measures how well the velocity tracker's position
82 83 84 85 86 87
/// data fit a straight line, [duration] is the time that elapsed between the
/// first and last position sample used to compute the velocity, and [offset]
/// is similarly the difference between the first and last positions.
///
/// See also:
///
88 89
///  * [VelocityTracker], which computes [VelocityEstimate]s.
///  * [Velocity], which encapsulates (just) a velocity vector and provides some
90 91 92
///    useful velocity operations.
class VelocityEstimate {
  /// Creates a dimensional velocity estimate.
93 94
  ///
  /// [pixelsPerSecond], [confidence], [duration], and [offset] must not be null.
95
  const VelocityEstimate({
96 97 98 99
    @required this.pixelsPerSecond,
    @required this.confidence,
    @required this.duration,
    @required this.offset,
100 101 102 103
  }) : assert(pixelsPerSecond != null),
       assert(confidence != null),
       assert(duration != null),
       assert(offset != null);
104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122

  /// The number of pixels per second of velocity in the x and y directions.
  final Offset pixelsPerSecond;

  /// A value between 0.0 and 1.0 that indicates how well [VelocityTracker]
  /// was able to fit a straight line to its position data.
  ///
  /// The value of this property is 1.0 for a perfect fit, 0.0 for a poor fit.
  final double confidence;

  /// The time that elapsed between the first and last position sample used
  /// to compute [pixelsPerSecond].
  final Duration duration;

  /// The difference between the first and last position sample used
  /// to compute [pixelsPerSecond].
  final Offset offset;

  @override
123
  String toString() => 'VelocityEstimate(${pixelsPerSecond.dx.toStringAsFixed(1)}, ${pixelsPerSecond.dy.toStringAsFixed(1)}; offset: $offset, duration: $duration, confidence: ${confidence.toStringAsFixed(1)})';
124 125 126
}

class _PointAtTime {
127
  const _PointAtTime(this.point, this.time)
128 129
    : assert(point != null),
      assert(time != null);
130 131

  final Duration time;
132
  final Offset point;
133 134 135 136 137

  @override
  String toString() => '_PointAtTime($point at $time)';
}

138
/// Computes a pointer's velocity based on data from [PointerMoveEvent]s.
139
///
140
/// The input data is provided by calling [addPosition]. Adding data is cheap.
141
///
142 143 144
/// To obtain a velocity, call [getVelocity] or [getVelocityEstimate]. This will
/// compute the velocity based on the data added so far. Only call these when
/// you need to use the velocity, as they are comparatively expensive.
145
///
146 147
/// The quality of the velocity estimation will be better if more data points
/// have been received.
148
class VelocityTracker {
149 150 151 152
  static const int _assumePointerMoveStoppedMilliseconds = 40;
  static const int _historySize = 20;
  static const int _horizonMilliseconds = 100;
  static const int _minSampleSize = 3;
153

154
  // Circular buffer; current sample at _index.
155
  final List<_PointAtTime> _samples = List<_PointAtTime>(_historySize);
156
  int _index = 0;
157

Adam Barth's avatar
Adam Barth committed
158
  /// Adds a position as the given time to the tracker.
159
  void addPosition(Duration time, Offset position) {
160
    _index += 1;
161
    if (_index == _historySize)
162
      _index = 0;
163
    _samples[_index] = _PointAtTime(position, time);
164 165
  }

Adam Barth's avatar
Adam Barth committed
166 167
  /// Returns an estimate of the velocity of the object being tracked by the
  /// tracker given the current information available to the tracker.
168 169 170 171
  ///
  /// Information is added using [addPosition].
  ///
  /// Returns null if there is no data on which to base an estimate.
172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196
  VelocityEstimate getVelocityEstimate() {
    final List<double> x = <double>[];
    final List<double> y = <double>[];
    final List<double> w = <double>[];
    final List<double> time = <double>[];
    int sampleCount = 0;
    int index = _index;

    final _PointAtTime newestSample = _samples[index];
    if (newestSample == null)
      return null;

    _PointAtTime previousSample = newestSample;
    _PointAtTime oldestSample = newestSample;

    // Starting with the most recent PointAtTime sample, iterate backwards while
    // the samples represent continuous motion.
    do {
      final _PointAtTime sample = _samples[index];
      if (sample == null)
        break;

      final double age = (newestSample.time - sample.time).inMilliseconds.toDouble();
      final double delta = (sample.time - previousSample.time).inMilliseconds.abs().toDouble();
      previousSample = sample;
197
      if (age > _horizonMilliseconds || delta > _assumePointerMoveStoppedMilliseconds)
198 199 200
        break;

      oldestSample = sample;
201 202 203
      final Offset position = sample.point;
      x.add(position.dx);
      y.add(position.dy);
204 205
      w.add(1.0);
      time.add(-age);
206
      index = (index == 0 ? _historySize : index) - 1;
207

208
      sampleCount += 1;
209
    } while (sampleCount < _historySize);
210

211
    if (sampleCount >= _minSampleSize) {
212
      final LeastSquaresSolver xSolver = LeastSquaresSolver(time, x, w);
213 214
      final PolynomialFit xFit = xSolver.solve(2);
      if (xFit != null) {
215
        final LeastSquaresSolver ySolver = LeastSquaresSolver(time, y, w);
216 217
        final PolynomialFit yFit = ySolver.solve(2);
        if (yFit != null) {
218 219
          return VelocityEstimate( // convert from pixels/ms to pixels/s
            pixelsPerSecond: Offset(xFit.coefficients[1] * 1000, yFit.coefficients[1] * 1000),
220 221 222 223 224 225 226 227 228 229
            confidence: xFit.confidence * yFit.confidence,
            duration: newestSample.time - oldestSample.time,
            offset: newestSample.point - oldestSample.point,
          );
        }
      }
    }

    // We're unable to make a velocity estimate but we did have at least one
    // valid pointer position.
230
    return VelocityEstimate(
231 232 233 234 235
      pixelsPerSecond: Offset.zero,
      confidence: 1.0,
      duration: newestSample.time - oldestSample.time,
      offset: newestSample.point - oldestSample.point,
    );
236 237
  }

238 239 240 241 242
  /// Computes the velocity of the pointer at the time of the last
  /// provided data point.
  ///
  /// This can be expensive. Only call this when you need the velocity.
  ///
243 244
  /// Returns [Velocity.zero] if there is no data from which to compute an
  /// estimate or if the estimated velocity is zero.
245
  Velocity getVelocity() {
246 247
    final VelocityEstimate estimate = getVelocityEstimate();
    if (estimate == null || estimate.pixelsPerSecond == Offset.zero)
248
      return Velocity.zero;
249
    return Velocity(pixelsPerSecond: estimate.pixelsPerSecond);
250 251
  }
}