scoop:scoop.ui.component:0.1.0
src/chart/curve.scoop
Selected production source · src/chart/curve.scoop
1
package scoop.ui.component3
import scoop.graphics.*4
import scoop.math.*6
internal fun chartRuns(samples: Array<ChartSample?>, connect: Boolean): Array<Array<ChartSample>> {7
val result = ArrayList<Array<ChartSample>>()8
var run = ArrayList<ChartSample>()9
for (sample in samples)10
when (sample) {11
case Some(val value) -> run.add(value)12
case None -> if (!connect && run.size > 0L) {13
result.add(run.toArray());14
run = ArrayList<ChartSample>()15
}16
}17
if (run.size > 0L)18
result.add(run.toArray())19
return result.toArray()20
}22
/** Steffen tangents as used by d3-shape's monotone curve. See LICENSE-D3. */23
internal fun chartSlope(left: Point, middle: Point, right: Point): Double {24
val h0 = middle.x - left.x;25
val h1 = right.x - middle.x26
if (h0 == 0.0 || h1 == 0.0 || h0 + h1 == 0.0)27
return 0.028
val s0 = (middle.y - left.y) / h0;29
val s1 = (right.y - middle.y) / h130
val p = (s0 * h1 + s1 * h0) / (h0 + h1)31
val sign0 =32
if (s0 < 0.0)33
-1.034
else35
1.036
val sign1 =37
if (s1 < 0.0)38
-1.039
else40
1.041
return (sign0 + sign1) * upperBound(upperBound(abs(s0), abs(s1)), abs(p) * 0.5)42
}44
internal fun chartTrace(45
path: PathBuilder,46
points: Array<Point>,47
curve: ChartCurve,48
horizontal: Boolean,49
move: Boolean = true50
) {51
if (points.size == 0L)52
return53
val values =54
Array<Point>(points.size) {55
at -> if (horizontal)56
Point(points[at].y, points[at].x)57
else58
points[at]59
}60
fun mapped(point: Point): Point =61
if (horizontal)62
Point(point.y, point.x)63
else64
point65
if (move)66
path.moveTo(points[0L])67
else68
path.lineTo(points[0L])69
var monotone = curve == ChartCurve.Monotone && values.size > 2L70
val delta =71
if (values.size > 1L)72
values[1L].x - values[0L].x73
else74
0.075
for (at in 1L ..< values.size)76
if ((values[at].x - values[at - 1L].x) * delta <= 0.0)77
monotone = false78
val slopes = MutableArray<Double>(values.size) { _ -> 0.0 }79
if (monotone) {80
for (at in 1L ..< values.size - 1L)81
slopes[at] = chartSlope(values[at - 1L], values[at], values[at + 1L])82
slopes[0L] =83
(3.0 * (values[1L].y - values[0L].y) / (values[1L].x - values[0L].x) - slopes[1L]) / 2.084
val last = values.size - 1L85
slopes[last] =86
(87
3.0 *88
(values[last].y - values[last - 1L].y) /89
(values[last].x - values[last - 1L].x) -90
slopes[last - 1L]91
) /92
2.093
}94
for (at in 1L ..< values.size) {95
val left = values[at - 1L];96
val right = values[at]97
if (monotone) {98
val dx = (right.x - left.x) / 3.099
path.cubicTo(100
mapped(Point(left.x + dx, left.y + dx * slopes[at - 1L])),101
mapped(Point(right.x - dx, right.y - dx * slopes[at])),102
mapped(right)103
)104
} else105
if (curve == ChartCurve.Step) {106
val middle = left.x / 2.0 + right.x / 2.0107
path.lineTo(mapped(Point(middle, left.y)))108
path.lineTo(mapped(Point(middle, right.y)))109
path.lineTo(mapped(right))110
} else111
path.lineTo(mapped(right))112
}113
}