geom/rectangle.go

60 lines
1.6 KiB
Go
Raw Normal View History

package geom
// Rectangle represents a 2-dimensional surface with as boundaries Min (inclusive) and Max (exclusive).
type Rectangle struct {
Min, Max Point
}
// Rect is a shorthand function to create a rectangle.
func Rect(x0, y0, x1, y1 int) Rectangle {
if x0 > x1 {
x0, x1 = x1, x0
}
if y0 > y1 {
y0, y1 = y1, y0
}
return Rectangle{Point{x0, y0}, Point{x1, y1}}
}
// RectRel is a shorthand function to create a rectangle specifying its width and height instead of a second coordinate.
func RectRel(x, y, w, h int) Rectangle {
return Rectangle{Point{x, y}, Point{x + w, y + h}}
}
// Add translates rectangle r by point p.
func (r Rectangle) Add(p Point) Rectangle {
return Rectangle{
Point{r.Min.X + p.X, r.Min.Y + p.Y},
Point{r.Max.X + p.X, r.Max.Y + p.Y},
}
}
// Dx returns the width of r.
func (r Rectangle) Dx() int {
return r.Max.X - r.Min.X
}
// Dy returns the height of r.
func (r Rectangle) Dy() int {
return r.Max.Y - r.Min.Y
}
// Size returns the size of the rectangle.
func (r Rectangle) Size() Point {
return Point{r.Max.X - r.Min.X, r.Max.Y - r.Min.Y}
}
// Sub translates rectangle r in the opposite direction of point p.
func (r Rectangle) Sub(p Point) Rectangle {
return Rectangle{
Point{r.Min.X - p.X, r.Min.Y - p.Y},
Point{r.Max.X - p.X, r.Max.Y - p.Y},
}
}
// ToF returns the floating point representation of r.
func (r Rectangle) ToF() RectangleF { return RectangleF{Min: r.Min.ToF(), Max: r.Max.ToF()} }
// ToF32 returns the floating point representation of r.
func (r Rectangle) ToF32() RectangleF32 { return RectangleF32{Min: r.Min.ToF32(), Max: r.Max.ToF32()} }