scoop:scoop.surface:0.1.0
src/shared/animation/easing.scoop
Selected production source · src/shared/animation/easing.scoop
1
package scoop.surface3
import scoop.math.abs4
import scoop.math.max5
import scoop.math.min7
/** A unit-time cubic Bézier curve. X controls are monotonic; Y controls may overshoot. */8
public class Easing private constructor(9
private val x1: Double,10
private val y1: Double,11
private val x2: Double,12
private val y2: Double13
) {14
public fun transform(fraction: Double): Double {15
requireAnimation(fraction.isFinite(), "non-finite easing fraction")16
val x = min(1.0, max(0.0, fraction))17
if (x1 == y1 && x2 == y2)18
return x19
return cubic(parameter(x), y1, y2)20
}21
internal fun slope(fraction: Double): Double {22
if (x1 == y1 && x2 == y2)23
return 1.024
val t = parameter(fraction)25
val dx = derivative(t, x1, x2)26
if (abs(dx) > 0.000000000001)27
return derivative(t, y1, y2) / dx28
val before = max(0.0, fraction - 0.000001)29
val after = min(1.0, fraction + 0.000001)30
return (transform(after) - transform(before)) / (after - before)31
}32
private fun parameter(x: Double): Double {33
if (x <= 0.0)34
return 0.035
if (x >= 1.0)36
return 1.037
var low = 0.038
var high = 1.039
for (index in 0 ..< 48) {40
val middle = (low + high) * 0.541
if (cubic(middle, x1, x2) < x)42
low = middle43
else44
high = middle45
}46
return (low + high) * 0.547
}48
public companion object {49
public val Linear: Easing = Easing(0.0, 0.0, 1.0, 1.0)50
public val EaseIn: Easing = Easing(0.42, 0.0, 1.0, 1.0)51
public val EaseOut: Easing = Easing(0.0, 0.0, 0.58, 1.0)52
public val EaseInOut: Easing = Easing(0.42, 0.0, 0.58, 1.0)53
public fun cubicBezier(x1: Double, y1: Double, x2: Double, y2: Double): Easing {54
requireAnimation(55
x1.isFinite() &&56
y1.isFinite() &&57
x2.isFinite() &&58
y2.isFinite() &&59
x1 >=60
0.0 &&61
x1 <=62
1.0 &&63
x2 >=64
0.0 &&65
x2 <=66
1.0,67
"invalid cubic Bézier controls"68
)69
return Easing(x1, y1, x2, y2)70
}71
}72
}74
private fun cubic(t: Double, a: Double, b: Double): Double {75
val q = 1.0 - t76
return (3.0 * q * q * t) * a + (3.0 * q * t * t) * b + t * t * t77
}79
private fun derivative(t: Double, a: Double, b: Double): Double {80
val q = 1.0 - t81
return 3.0 * q * q * a + 6.0 * q * t * (b - a) + 3.0 * t * t * (1.0 - b)82
}