1 | 'use strict';
|
---|
2 |
|
---|
3 | function clamp(v, min, max) {
|
---|
4 | return Math.max(min, Math.min(v, max));
|
---|
5 | }
|
---|
6 | const V = {
|
---|
7 | toVector(v, fallback) {
|
---|
8 | if (v === undefined) v = fallback;
|
---|
9 | return Array.isArray(v) ? v : [v, v];
|
---|
10 | },
|
---|
11 | add(v1, v2) {
|
---|
12 | return [v1[0] + v2[0], v1[1] + v2[1]];
|
---|
13 | },
|
---|
14 | sub(v1, v2) {
|
---|
15 | return [v1[0] - v2[0], v1[1] - v2[1]];
|
---|
16 | },
|
---|
17 | addTo(v1, v2) {
|
---|
18 | v1[0] += v2[0];
|
---|
19 | v1[1] += v2[1];
|
---|
20 | },
|
---|
21 | subTo(v1, v2) {
|
---|
22 | v1[0] -= v2[0];
|
---|
23 | v1[1] -= v2[1];
|
---|
24 | }
|
---|
25 | };
|
---|
26 | function rubberband(distance, dimension, constant) {
|
---|
27 | if (dimension === 0 || Math.abs(dimension) === Infinity) return Math.pow(distance, constant * 5);
|
---|
28 | return distance * dimension * constant / (dimension + constant * distance);
|
---|
29 | }
|
---|
30 | function rubberbandIfOutOfBounds(position, min, max, constant = 0.15) {
|
---|
31 | if (constant === 0) return clamp(position, min, max);
|
---|
32 | if (position < min) return -rubberband(min - position, max - min, constant) + min;
|
---|
33 | if (position > max) return +rubberband(position - max, max - min, constant) + max;
|
---|
34 | return position;
|
---|
35 | }
|
---|
36 | function computeRubberband(bounds, [Vx, Vy], [Rx, Ry]) {
|
---|
37 | const [[X0, X1], [Y0, Y1]] = bounds;
|
---|
38 | return [rubberbandIfOutOfBounds(Vx, X0, X1, Rx), rubberbandIfOutOfBounds(Vy, Y0, Y1, Ry)];
|
---|
39 | }
|
---|
40 |
|
---|
41 | exports.V = V;
|
---|
42 | exports.computeRubberband = computeRubberband;
|
---|
43 | exports.rubberbandIfOutOfBounds = rubberbandIfOutOfBounds;
|
---|