forces.dart 1.84 KB
Newer Older
Matt Perry's avatar
Matt Perry committed
1 2 3 4 5
// Copyright 2015 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

import 'package:newton/newton.dart';
6

7 8
export 'package:newton/newton.dart' show SpringDescription;

Florian Loitsch's avatar
Florian Loitsch committed
9
/// A factory for simulations.
Matt Perry's avatar
Matt Perry committed
10
abstract class Force {
11 12
  const Force();

13
  /// Creates a new physics simulation with the given initial conditions.
14
  Simulation release(double position, double velocity);
Matt Perry's avatar
Matt Perry committed
15 16
}

Florian Loitsch's avatar
Florian Loitsch committed
17
/// A factory for spring-based physics simulations.
Matt Perry's avatar
Matt Perry committed
18
class SpringForce extends Force {
19
  const SpringForce(this.spring, { this.left: 0.0, this.right: 1.0 });
20

Florian Loitsch's avatar
Florian Loitsch committed
21
  /// The description of the spring to be used in the created simulations.
Matt Perry's avatar
Matt Perry committed
22
  final SpringDescription spring;
23

Florian Loitsch's avatar
Florian Loitsch committed
24
  /// Where to put the spring's resting point when releasing left.
25
  final double left;
26

Florian Loitsch's avatar
Florian Loitsch committed
27
  /// Where to put the spring's resting point when releasing right.
28
  final double right;
Matt Perry's avatar
Matt Perry committed
29

Florian Loitsch's avatar
Florian Loitsch committed
30
  /// How pricely to terminate the simulation.
31 32 33 34
  ///
  /// We overshoot the target by this distance, but stop the simulation when
  /// the spring gets within this distance (regardless of how fast it's moving).
  /// This causes the spring to settle a bit faster than it otherwise would.
35
  static const Tolerance tolerance = const Tolerance(
36 37 38 39
    velocity: double.INFINITY,
    distance: 0.01
  );

40
  Simulation release(double position, double velocity) {
41 42
    double target = velocity < 0.0 ? this.left - tolerance.distance
                                   : this.right + tolerance.distance;
43 44
    return new SpringSimulation(spring, position, target, velocity)
      ..tolerance = tolerance;
Matt Perry's avatar
Matt Perry committed
45 46 47
  }
}

48 49 50 51 52 53
final SpringDescription _kDefaultSpringDesc = new SpringDescription.withDampingRatio(
  mass: 1.0,
  springConstant: 500.0,
  ratio: 1.0
);

Florian Loitsch's avatar
Florian Loitsch committed
54
/// A spring force with reasonable default values.
Matt Perry's avatar
Matt Perry committed
55
final SpringForce kDefaultSpringForce = new SpringForce(_kDefaultSpringDesc);