diff --git a/orx-shapes/src/commonMain/kotlin/primitives/RectangleIntersection.kt b/orx-shapes/src/commonMain/kotlin/primitives/RectangleIntersection.kt new file mode 100644 index 00000000..801c1733 --- /dev/null +++ b/orx-shapes/src/commonMain/kotlin/primitives/RectangleIntersection.kt @@ -0,0 +1,23 @@ +package org.openrndr.extra.shapes.primitives + +import org.openrndr.shape.Rectangle +import kotlin.math.max +import kotlin.math.min + +/** + * Find intersection of [this] and [other] + * @return a rectangle shaped intersection or [Rectangle.EMPTY] when the intersection is empty. + */ +fun Rectangle.intersection(other: Rectangle) : Rectangle = if (this.intersects(other)) { + val tn = this.normalized + val on = other.normalized + + val left = max(tn.corner.x, on.corner.x) + val right = min(tn.corner.x + tn.width, on.corner.x + on.width) + val top = max(tn.corner.y, on.corner.y) + val bottom = min(tn.corner.y + tn.height, on.corner.y + on.height) + + Rectangle(left, top, right - left, bottom - top) +} else { + Rectangle.EMPTY +} \ No newline at end of file diff --git a/orx-shapes/src/jvmDemo/kotlin/primitives/DemoRectangleIntersection01.kt b/orx-shapes/src/jvmDemo/kotlin/primitives/DemoRectangleIntersection01.kt new file mode 100644 index 00000000..38ada841 --- /dev/null +++ b/orx-shapes/src/jvmDemo/kotlin/primitives/DemoRectangleIntersection01.kt @@ -0,0 +1,39 @@ +package primitives + +import org.openrndr.application +import org.openrndr.color.ColorRGBa +import org.openrndr.extra.shapes.primitives.intersection + +/** + * Demonstrate rectangle-rectangle intersection + */ +fun main() { + application { + configure { + width = 720 + height = 720 + } + program { + val h = drawer.bounds.offsetEdges(-100.0, -10.0) + val v = drawer.bounds.offsetEdges(-10.0, -100.0) + + extend { + drawer.clear(ColorRGBa.WHITE) + + /** + * Find intersection + */ + val i = h.intersection(v) + drawer.fill = ColorRGBa.RED + drawer.rectangle(h) + + drawer.fill = ColorRGBa.BLUE + drawer.rectangle(v) + + drawer.fill = ColorRGBa.BLACK + drawer.stroke = ColorRGBa.WHITE + drawer.rectangle(i) + } + } + } +} \ No newline at end of file