blooblib/vec2.go

63 lines
1.2 KiB
Go

package bloob
import (
"golang.org/x/exp/constraints"
"math"
)
type Number interface {
constraints.Integer | constraints.Float
}
type Vec2[T Number] struct {
X, Y T
}
type Vec2i = Vec2[int]
func Add[T Number](a, b Vec2[T]) Vec2[T] {
return Vec2[T]{X: a.X + b.X, Y: a.Y + b.Y}
}
func AddScalar[T Number](a Vec2[T], b T) Vec2[T] {
return Vec2[T]{X: a.X + b, Y: a.Y + b}
}
func Sub[T Number](a, b Vec2[T]) Vec2[T] {
return Vec2[T]{X: a.X - b.X, Y: a.Y - b.Y}
}
func SubScalar[T Number](a Vec2[T], b T) Vec2[T] {
return Vec2[T]{X: a.X - b, Y: a.Y - b}
}
func Mul[T Number](a, b Vec2[T]) Vec2[T] {
return Vec2[T]{X: a.X * b.X, Y: a.Y * b.Y}
}
func MulScalar[T Number](a Vec2[T], b T) Vec2[T] {
return Vec2[T]{X: a.X * b, Y: a.Y * b}
}
func Div[T Number](a, b Vec2[T]) Vec2[T] {
return Vec2[T]{X: a.X / b.X, Y: a.Y / b.Y}
}
func DivScalar[T Number](a Vec2[T], b T) Vec2[T] {
return Vec2[T]{X: a.X / b, Y: a.Y / b}
}
func (a Vec2[T]) Size() T {
return a.X * a.Y
}
func Dot[T Number](a, b Vec2[T]) T {
return a.X*b.X + a.Y*b.Y
}
func (a Vec2[T]) Mag() float64 {
return math.Sqrt(float64(a.MagSqr()))
}
func (a Vec2[T]) MagSqr() T {
return a.X*a.X + a.Y*a.Y
}