Skip to content
Snippets Groups Projects
geometry.go 8.95 KiB
Newer Older
faiface's avatar
faiface committed
package pixel

import (
	"fmt"
	"math"

	"github.com/go-gl/mathgl/mgl64"
faiface's avatar
faiface committed
)

// Vec is a 2D vector type with X and Y coordinates.
faiface's avatar
faiface committed
//
// Create vectors with the V constructor:
//
//   u := pixel.V(1, 2)
//   v := pixel.V(8, -3)
//
// Use various methods to manipulate them:
faiface's avatar
faiface committed
//
//   w := u.Add(v)
//   fmt.Println(w)        // Vec(9, -1)
//   fmt.Println(u.Sub(v)) // Vec(-7, 5)
//   u = pixel.V(2, 3)
//   v = pixel.V(8, 1)
//   if u.X < 0 {
//	     fmt.Println("this won't happen")
faiface's avatar
faiface committed
//   }
//   x := u.Unit().Dot(v.Unit())
type Vec struct {
	X, Y float64
faiface's avatar
faiface committed
}

// ZV is a zero vector.
var ZV = Vec{0, 0}
// V returns a new 2D vector with the given coordinates.
func V(x, y float64) Vec {
	return Vec{x, y}
faiface's avatar
faiface committed
// String returns the string representation of the vector u.
faiface's avatar
faiface committed
//
//   u := pixel.V(4.5, -1.3)
//   u.String()     // returns "Vec(4.5, -1.3)"
//   fmt.Println(u) // Vec(4.5, -1.3)
faiface's avatar
faiface committed
func (u Vec) String() string {
	return fmt.Sprintf("Vec(%v, %v)", u.X, u.Y)
faiface's avatar
faiface committed
}

// XY returns the components of the vector in two return values.
func (u Vec) XY() (x, y float64) {
	return u.X, u.Y
faiface's avatar
faiface committed
}

// Add returns the sum of vectors u and v.
func (u Vec) Add(v Vec) Vec {
	return Vec{
		u.X + v.X,
		u.Y + v.Y,
	}
faiface's avatar
faiface committed
}

// Sub returns the difference betweeen vectors u and v.
func (u Vec) Sub(v Vec) Vec {
	return Vec{
		u.X - v.X,
		u.Y - v.Y,
	}
}

// Scaled returns the vector u multiplied by c.
func (u Vec) Scaled(c float64) Vec {
	return Vec{u.X * c, u.Y * c}
}

// ScaledXY returns the vector u multiplied by the vector v component-wise.
func (u Vec) ScaledXY(v Vec) Vec {
	return Vec{u.X * v.X, u.Y * v.Y}
faiface's avatar
faiface committed
}

faiface's avatar
faiface committed
// Len returns the length of the vector u.
faiface's avatar
faiface committed
func (u Vec) Len() float64 {
	return math.Hypot(u.X, u.Y)
faiface's avatar
faiface committed
}

faiface's avatar
faiface committed
// Angle returns the angle between the vector u and the x-axis. The result is in range [-Pi, Pi].
faiface's avatar
faiface committed
func (u Vec) Angle() float64 {
	return math.Atan2(u.Y, u.X)
faiface's avatar
faiface committed
}

faiface's avatar
faiface committed
// Unit returns a vector of length 1 facing the direction of u (has the same angle).
faiface's avatar
faiface committed
func (u Vec) Unit() Vec {
	if u.X == 0 && u.Y == 0 {
		return Vec{1, 0}
	return u.Scaled(1 / u.Len())
faiface's avatar
faiface committed
// Rotated returns the vector u rotated by the given angle in radians.
faiface's avatar
faiface committed
func (u Vec) Rotated(angle float64) Vec {
faiface's avatar
faiface committed
	sin, cos := math.Sincos(angle)
	return Vec{
		u.X*cos - u.Y*sin,
		u.X*sin + u.Y*cos,
	}
faiface's avatar
faiface committed
// Dot returns the dot product of vectors u and v.
faiface's avatar
faiface committed
func (u Vec) Dot(v Vec) float64 {
	return u.X*v.X + u.Y*v.Y
faiface's avatar
faiface committed
}

// Cross return the cross product of vectors u and v.
faiface's avatar
faiface committed
func (u Vec) Cross(v Vec) float64 {
	return u.X*v.Y - v.X*u.Y
faiface's avatar
faiface committed
}
faiface's avatar
faiface committed

faiface's avatar
faiface committed
// Map applies the function f to both x and y components of the vector u and returns the modified
faiface's avatar
faiface committed
// vector.
faiface's avatar
faiface committed
//
//   u := pixel.V(10.5, -1.5)
//   v := u.Map(math.Floor)   // v is Vec(10, -2), both components of u floored
faiface's avatar
faiface committed
func (u Vec) Map(f func(float64) float64) Vec {
	return Vec{
		f(u.X),
		f(u.Y),
	}
faiface's avatar
faiface committed
}

faiface's avatar
faiface committed
// Lerp returns a linear interpolation between vectors a and b.
//
faiface's avatar
faiface committed
// This function basically returns a point along the line between a and b and t chooses which one.
faiface's avatar
faiface committed
// If t is 0, then a will be returned, if t is 1, b will be returned. Anything between 0 and 1 will
// return the appropriate point between a and b and so on.
func Lerp(a, b Vec, t float64) Vec {
	return a.Scaled(1 - t).Add(b.Scaled(t))
faiface's avatar
faiface committed
}

// Rect is a 2D rectangle aligned with the axes of the coordinate system. It is defined by two
// points, Min and Max.
faiface's avatar
faiface committed
//
// The invariant should hold, that Max's components are greater or equal than Min's components
// respectively.
faiface's avatar
faiface committed
type Rect struct {
faiface's avatar
faiface committed
}

// R returns a new Rect with given the Min and Max coordinates.
faiface's avatar
faiface committed
//
// Note that the returned rectangle is not automatically normalized.
func R(minX, minY, maxX, maxY float64) Rect {
faiface's avatar
faiface committed
	return Rect{
		Min: V(minX, minY),
		Max: V(maxX, maxY),
faiface's avatar
faiface committed
// String returns the string representation of the Rect.
//
//   r := pixel.R(100, 50, 200, 300)
//   r.String()     // returns "Rect(100, 50, 200, 300)"
//   fmt.Println(r) // Rect(100, 50, 200, 300)
func (r Rect) String() string {
	return fmt.Sprintf("Rect(%v, %v, %v, %v)", r.Min.X, r.Min.Y, r.Max.X, r.Max.Y)
faiface's avatar
faiface committed
}

// Norm returns the Rect in normal form, such that Max is component-wise greater or equal than Min.
func (r Rect) Norm() Rect {
	return Rect{
		Min: Vec{
			math.Min(r.Min.X, r.Max.X),
			math.Min(r.Min.Y, r.Max.Y),
		},
		Max: Vec{
			math.Max(r.Min.X, r.Max.X),
			math.Max(r.Min.Y, r.Max.Y),
		},
faiface's avatar
faiface committed
	}
}

faiface's avatar
faiface committed
// W returns the width of the Rect.
faiface's avatar
faiface committed
func (r Rect) W() float64 {
	return r.Max.X - r.Min.X
faiface's avatar
faiface committed
}

faiface's avatar
faiface committed
// H returns the height of the Rect.
faiface's avatar
faiface committed
func (r Rect) H() float64 {
	return r.Max.Y - r.Min.Y
faiface's avatar
faiface committed
}

faiface's avatar
faiface committed
// Size returns the vector of width and height of the Rect.
faiface's avatar
faiface committed
func (r Rect) Size() Vec {
	return V(r.W(), r.H())
}

faiface's avatar
faiface committed
// Center returns the position of the center of the Rect.
faiface's avatar
faiface committed
func (r Rect) Center() Vec {
	return Lerp(r.Min, r.Max, 0.5)
}

// Moved returns the Rect moved (both Min and Max) by the given vector delta.
func (r Rect) Moved(delta Vec) Rect {
	return Rect{
		Min: r.Min.Add(delta),
		Max: r.Max.Add(delta),
faiface's avatar
faiface committed
// Resized returns the Rect resized to the given size while keeping the position of the given
// anchor.
faiface's avatar
faiface committed
//
//   r.Resized(r.Min, size)      // resizes while keeping the position of the lower-left corner
//   r.Resized(r.Max, size)      // same with the top-right corner
//   r.Resized(r.Center(), size) // resizes around the center
faiface's avatar
faiface committed
//
// This function does not make sense for resizing a rectangle of zero area and will panic. Use
// ResizedMin in the case of zero area.
func (r Rect) Resized(anchor, size Vec) Rect {
	if r.W()*r.H() == 0 {
		panic(fmt.Errorf("(%T).Resize: zero area", r))
	}
	fraction := Vec{size.X / r.W(), size.Y / r.H()}
		Min: anchor.Add(r.Min.Sub(anchor)).ScaledXY(fraction),
		Max: anchor.Add(r.Max.Sub(anchor)).ScaledXY(fraction),
	}
}

// ResizedMin returns the Rect resized to the given size while keeping the position of the Rect's
// Min.
//
// Sizes of zero area are safe here.
func (r Rect) ResizedMin(size Vec) Rect {
	return Rect{
		Min: r.Min,
		Max: r.Min.Add(size),
faiface's avatar
faiface committed
}

// Contains checks whether a vector u is contained within this Rect (including it's borders).
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
faiface's avatar
faiface committed
// Union returns a minimal Rect which covers both r and s. Rects r and s should be normalized.
func (r Rect) Union(s Rect) Rect {
	return R(
		math.Min(r.Min.X, s.Min.X),
		math.Min(r.Min.Y, s.Min.Y),
		math.Max(r.Max.X, s.Max.X),
		math.Max(r.Max.Y, s.Max.Y),
faiface's avatar
faiface committed
	)
}

// Matrix is a 3x3 transformation matrix that can be used for all kinds of spacial transforms, such
// as movement, scaling and rotations.
//
// Matrix has a handful of useful methods, each of which adds a transformation to the matrix. For
// example:
//
faiface's avatar
faiface committed
//   pixel.IM.Moved(pixel.V(100, 200)).Rotated(pixel.ZV, math.Pi/2)
faiface's avatar
faiface committed
// This code creates a Matrix that first moves everything by 100 units horizontally and 200 units
// vertically and then rotates everything by 90 degrees around the origin.
type Matrix [9]float64

faiface's avatar
faiface committed
// IM stands for identity matrix. Does nothing, no transformation.
faiface's avatar
faiface committed
var IM = Matrix(mgl64.Ident3())
faiface's avatar
faiface committed
// String returns a string representation of the Matrix.
//
//   m := pixel.IM
//   fmt.Println(m) // Matrix(1 0 0 | 0 1 0 | 0 0 1)
func (m Matrix) String() string {
	return fmt.Sprintf(
		"Matrix(%v %v %v | %v %v %v | %v %v %v)",
faiface's avatar
faiface committed
		m[0], m[3], m[6],
		m[1], m[4], m[7],
		m[2], m[5], m[8],
// Moved moves everything by the delta vector.
func (m Matrix) Moved(delta Vec) Matrix {
	m3 := mgl64.Mat3(m)
	m3 = mgl64.Translate2D(delta.XY()).Mul3(m3)
	return Matrix(m3)
}

// ScaledXY scales everything around a given point by the scale factor in each axis respectively.
func (m Matrix) ScaledXY(around Vec, scale Vec) Matrix {
	m3 := mgl64.Mat3(m)
	m3 = mgl64.Translate2D(around.Scaled(-1).XY()).Mul3(m3)
	m3 = mgl64.Scale2D(scale.XY()).Mul3(m3)
	m3 = mgl64.Translate2D(around.XY()).Mul3(m3)
	return Matrix(m3)
}

// Scaled scales everything around a given point by the scale factor.
func (m Matrix) Scaled(around Vec, scale float64) Matrix {
	return m.ScaledXY(around, V(scale, scale))
// Rotated rotates everything around a given point by the given angle in radians.
func (m Matrix) Rotated(around Vec, angle float64) Matrix {
	m3 := mgl64.Mat3(m)
	m3 = mgl64.Translate2D(around.Scaled(-1).XY()).Mul3(m3)
	m3 = mgl64.Rotate3DZ(angle).Mul3(m3)
	m3 = mgl64.Translate2D(around.XY()).Mul3(m3)
	return Matrix(m3)
}

faiface's avatar
faiface committed
// Chained adds another Matrix to this one. All tranformations by the next Matrix will be applied
// after the transformations of this Matrix.
func (m Matrix) Chained(next Matrix) Matrix {
	m3 := mgl64.Mat3(m)
	m3 = mgl64.Mat3(next).Mul3(m3)
	return Matrix(m3)
}

// Project applies all transformations added to the Matrix to a vector u and returns the result.
faiface's avatar
faiface committed
//
// Time complexity is O(1).
func (m Matrix) Project(u Vec) Vec {
	m3 := mgl64.Mat3(m)
	proj := m3.Mul3x1(mgl64.Vec3{u.X, u.Y, 1})
	return V(proj.X(), proj.Y())
}

// Unproject does the inverse operation to Project.
faiface's avatar
faiface committed
//
// Time complexity is O(1).
func (m Matrix) Unproject(u Vec) Vec {
	m3 := mgl64.Mat3(m)
	inv := m3.Inv()
	unproj := inv.Mul3x1(mgl64.Vec3{u.X, u.Y, 1})
	return V(unproj.X(), unproj.Y())
}