From 2a8c17c33c724bf04bd099d7519e2b8516b3df39 Mon Sep 17 00:00:00 2001
From: faiface <faiface@ksp.sk>
Date: Wed, 5 Jul 2017 19:51:54 +0200
Subject: [PATCH] add Rect.Intersect

---
 geometry.go | 20 +++++++++++++++++---
 1 file changed, 17 insertions(+), 3 deletions(-)

diff --git a/geometry.go b/geometry.go
index 56283a9..1c61477 100644
--- a/geometry.go
+++ b/geometry.go
@@ -160,8 +160,8 @@ type Rect struct {
 // Note that the returned rectangle is not automatically normalized.
 func R(minX, minY, maxX, maxY float64) Rect {
 	return Rect{
-		Min: V(minX, minY),
-		Max: V(maxX, maxY),
+		Min: Vec{minX, minY},
+		Max: Vec{maxX, maxY},
 	}
 }
 
@@ -257,7 +257,7 @@ func (r Rect) Contains(u Vec) bool {
 	return r.Min.X <= u.X && u.X <= r.Max.X && r.Min.Y <= u.Y && u.Y <= r.Max.Y
 }
 
-// Union returns a minimal Rect which covers both r and s. Rects r and s should be normalized.
+// Union returns the minimal Rect which covers both r and s. Rects r and s must be normalized.
 func (r Rect) Union(s Rect) Rect {
 	return R(
 		math.Min(r.Min.X, s.Min.X),
@@ -267,6 +267,20 @@ func (r Rect) Union(s Rect) Rect {
 	)
 }
 
+// Intersect returns the maximal Rect which is covered by both r and s. Rects r and s must be normalized.
+func (r Rect) Intersect(s Rect) Rect {
+	t := R(
+		math.Min(r.Max.X, s.Max.X),
+		math.Min(r.Max.Y, s.Max.Y),
+		math.Max(r.Min.X, s.Min.X),
+		math.Max(r.Min.Y, s.Min.Y),
+	)
+	if t.Min.X >= t.Max.X || t.Min.Y >= t.Max.Y {
+		return Rect{}
+	}
+	return t
+}
+
 // Matrix is a 3x2 affine matrix that can be used for all kinds of spatial transforms, such
 // as movement, scaling and rotations.
 //
-- 
GitLab