friction_simulation.dart 5.59 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 6
import 'dart:math' as math;

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

9 10
import 'simulation.dart';
import 'tolerance.dart';
11

Ian Hickson's avatar
Ian Hickson committed
12 13 14 15 16 17
/// A simulation that applies a drag to slow a particle down.
///
/// Models a particle affected by fluid drag, e.g. air resistance.
///
/// The simulation ends when the velocity of the particle drops to zero (within
/// the current velocity [tolerance]).
18
class FrictionSimulation extends Simulation {
Ian Hickson's avatar
Ian Hickson committed
19
  /// Creates a [FrictionSimulation] with the given arguments, namely: the fluid
20 21
  /// drag coefficient _cₓ_, a unitless value; the initial position _x₀_, in the same
  /// length units as used for [x]; and the initial velocity _dx₀_, in the same
Ian Hickson's avatar
Ian Hickson committed
22
  /// velocity units as used for [dx].
23 24 25 26
  FrictionSimulation(
    double drag,
    double position,
    double velocity, {
27
    Tolerance tolerance = Tolerance.defaultTolerance,
28 29 30 31 32
  }) : _drag = drag,
       _dragLog = math.log(drag),
       _x = position,
       _v = velocity,
       super(tolerance: tolerance);
Ian Hickson's avatar
Ian Hickson committed
33

34
  /// Creates a new friction simulation with its fluid drag coefficient (_cₓ_) set so
Ian Hickson's avatar
Ian Hickson committed
35 36 37 38 39 40 41 42 43 44
  /// as to ensure that the simulation starts and ends at the specified
  /// positions and velocities.
  ///
  /// The positions must use the same units as expected from [x], and the
  /// velocities must use the same units as expected from [dx].
  ///
  /// The sign of the start and end velocities must be the same, the magnitude
  /// of the start velocity must be greater than the magnitude of the end
  /// velocity, and the velocities must be in the direction appropriate for the
  /// particle to start from the start position and reach the end position.
Ian Hickson's avatar
Ian Hickson committed
45
  factory FrictionSimulation.through(double startPosition, double endPosition, double startVelocity, double endVelocity) {
46
    assert(startVelocity == 0.0 || endVelocity == 0.0 || startVelocity.sign == endVelocity.sign);
Ian Hickson's avatar
Ian Hickson committed
47 48
    assert(startVelocity.abs() >= endVelocity.abs());
    assert((endPosition - startPosition).sign == startVelocity.sign);
49
    return FrictionSimulation(
Ian Hickson's avatar
Ian Hickson committed
50 51
      _dragFor(startPosition, endPosition, startVelocity, endVelocity),
      startPosition,
52
      startVelocity,
53
      tolerance: Tolerance(velocity: endVelocity.abs()),
54
    );
Ian Hickson's avatar
Ian Hickson committed
55 56
  }

57
  final double _drag;
58
  final double _dragLog;
59 60 61
  final double _x;
  final double _v;

62 63 64 65 66 67 68 69
  // Return the drag value for a FrictionSimulation whose x() and dx() values pass
  // through the specified start and end position/velocity values.
  //
  // Total time to reach endVelocity is just: (log(endVelocity) / log(startVelocity)) / log(_drag)
  // or (log(v1) - log(v0)) / log(D), given v = v0 * D^t per the dx() function below.
  // Solving for D given x(time) is trickier. Algebra courtesy of Wolfram Alpha:
  // x1 = x0 + (v0 * D^((log(v1) - log(v0)) / log(D))) / log(D) - v0 / log(D), find D
  static double _dragFor(double startPosition, double endPosition, double startVelocity, double endVelocity) {
70
    return math.pow(math.e, (startVelocity - endVelocity) / (startPosition - endPosition)) as double;
71 72
  }

73
  @override
74
  double x(double time) => _x + _v * math.pow(_drag, time) / _dragLog - _v / _dragLog;
75

76
  @override
77
  double dx(double time) => _v * math.pow(_drag, time);
78

79
  /// The value of [x] at `double.infinity`.
80 81 82 83
  double get finalX => _x - _v / _dragLog;

  /// The time at which the value of `x(time)` will equal [x].
  ///
84
  /// Returns `double.infinity` if the simulation will never reach [x].
85 86 87 88
  double timeAtX(double x) {
    if (x == _x)
      return 0.0;
    if (_v == 0.0 || (_v > 0 ? (x < _x || x > finalX) : (x > _x || x < finalX)))
89
      return double.infinity;
90 91 92
    return math.log(_dragLog * (x - _x) / _v + 1.0) / _dragLog;
  }

93
  @override
94
  bool isDone(double time) => dx(time).abs() < tolerance.velocity;
95 96 97

  @override
  String toString() => '${objectRuntimeType(this, 'FrictionSimulation')}(cₓ: ${_drag.toStringAsFixed(1)}, x₀: ${_x.toStringAsFixed(1)}, dx₀: ${_v.toStringAsFixed(1)})';
98
}
99

100
/// A [FrictionSimulation] that clamps the modeled particle to a specific range
Ian Hickson's avatar
Ian Hickson committed
101
/// of values.
102 103 104
///
/// Only the position is clamped. The velocity [dx] will continue to report
/// unbounded simulated velocities once the particle has reached the bounds.
105
class BoundedFrictionSimulation extends FrictionSimulation {
Ian Hickson's avatar
Ian Hickson committed
106
  /// Creates a [BoundedFrictionSimulation] with the given arguments, namely:
107 108
  /// the fluid drag coefficient _cₓ_, a unitless value; the initial position _x₀_, in the
  /// same length units as used for [x]; the initial velocity _dx₀_, in the same
Ian Hickson's avatar
Ian Hickson committed
109 110 111 112
  /// velocity units as used for [dx], the minimum value for the position, and
  /// the maximum value for the position. The minimum and maximum values must be
  /// in the same units as the initial position, and the initial position must
  /// be within the given range.
113 114 115 116
  BoundedFrictionSimulation(
    double drag,
    double position,
    double velocity,
Hixie's avatar
Hixie committed
117
    this._minX,
118
    this._maxX,
119 120
  ) : assert(position.clamp(_minX, _maxX) == position),
      super(drag, position, velocity);
121 122 123 124

  final double _minX;
  final double _maxX;

125
  @override
126
  double x(double time) {
127
    return super.x(time).clamp(_minX, _maxX);
128 129
  }

130
  @override
131 132 133 134 135
  bool isDone(double time) {
    return super.isDone(time) ||
      (x(time) - _minX).abs() < tolerance.distance ||
      (x(time) - _maxX).abs() < tolerance.distance;
  }
136 137 138

  @override
  String toString() => '${objectRuntimeType(this, 'BoundedFrictionSimulation')}(cₓ: ${_drag.toStringAsFixed(1)}, x₀: ${_x.toStringAsFixed(1)}, dx₀: ${_v.toStringAsFixed(1)}, x: ${_minX.toStringAsFixed(1)}..${_maxX.toStringAsFixed(1)})';
139
}