scoop:scoop.ui.style:0.1.0
src/cache/border_regions.scoop
Selected production source · src/cache/border_regions.scoop
1
package scoop.ui.style3
import scoop.graphics.*5
/** Distances to each box edge, divided by its width, partition every rounded join. */6
internal fun borderRegions(bounds: Rect, edges: BorderEdges): Array<Array<Point>> {7
val widths = [edges.left.width, edges.top.width, edges.right.width, edges.bottom.width]8
var largest = 0.09
for (width in widths)10
largest = themeMax(largest, width)11
if (largest == 0.0)12
return [[], [], [], []]13
val maximum = largest14
val normalized = Array<Double>(4L) { index -> widths[index] / maximum }15
val distances =16
[17
BorderPlane(1.0, 0.0, 0.0),18
BorderPlane(0.0, 1.0, 0.0),19
BorderPlane(-1.0, 0.0, bounds.width),20
BorderPlane(0.0, -1.0, bounds.height)21
]22
val rectangle =23
[24
Point(0.0, 0.0),25
Point(bounds.width, 0.0),26
Point(bounds.width, bounds.height),27
Point(0.0, bounds.height)28
]29
return Array<Array<Point>>(4L) {30
edge ->31
if (widths[edge] == 0.0)32
return@Array []33
var polygon = rectangle34
val current = distances[edge]35
for (other in 0L ..< 4L) {36
if (edge == other || widths[other] == 0.0)37
continue38
val compare = distances[other]39
val plane =40
BorderPlane(41
current.x * normalized[other] - compare.x * normalized[edge],42
current.y * normalized[other] - compare.y * normalized[edge],43
current.c * normalized[other] - compare.c * normalized[edge]44
)45
polygon = clipBorderRegion(polygon, plane)46
}47
val points = polygon48
Array<Point>(points.size) {49
index -> Point(bounds.x + points[index].x, bounds.y + points[index].y)50
}51
}52
}54
private struct BorderPlane(val x: Double, val y: Double, val c: Double) {55
fun distance(point: Point): Double = x * point.x + y * point.y + c56
}58
private fun clipBorderRegion(polygon: Array<Point>, plane: BorderPlane): Array<Point> {59
if (polygon.size == 0L)60
return polygon61
val result = ArrayList<Point>()62
var previous = polygon[polygon.size - 1L]63
var before = plane.distance(previous)64
for (point in polygon) {65
val after = plane.distance(point)66
if ((before <= 0.0) != (after <= 0.0)) {67
val t = before / (before - after)68
result.add(69
Point(70
previous.x + (point.x - previous.x) * t,71
previous.y + (point.y - previous.y) * t72
)73
)74
}75
if (after <= 0.0)76
result.add(point)77
previous = point78
before = after79
}80
return result.toArray()81
}