package net.shadowfacts.cacao.geometry import java.lang.RuntimeException import kotlin.math.pow /** * Helper class that represents a cubic bezier curve. * * @author shadowfacts */ data class BezierCurve(private val points: Array) { init { if (points.size != 4) { throw RuntimeException("Cubic bezier curve must have exactly four points") } } fun point(time: Double): Point { val x = coordinate(time, Axis.HORIZONTAL) val y = coordinate(time, Axis.VERTICAL) return Point(x, y) } private fun coordinate(t: Double, axis: Axis): Double { // B(t)=(1-t)^3*p0+3(1-t)^2*t*p1+3(1-t)*t^2*p2+t^3*p3 val p0 = points[0][axis] val p1 = points[1][axis] val p2 = points[2][axis] val p3 = points[3][axis] return ((1 - t).pow(3) * p0) + (3 * (1 - t).pow(2) * t * p1) + (3 * (1 - t) * t.pow(2) * p2) + (t.pow(3) * p3) } override fun equals(other: Any?): Boolean { if (this === other) return true if (javaClass != other?.javaClass) return false other as BezierCurve if (!points.contentEquals(other.points)) return false return true } override fun hashCode(): Int { return points.contentHashCode() } }