geom/pointf32.go

71 lines
1.6 KiB
Go
Raw Normal View History

package geom
import (
"math"
)
// PointF32 is an X, Y coordinate pair (floating point, 32 bits).
type PointF32 struct {
X, Y float32
}
// ZeroPtF32 is initialized on (0, 0).
var ZeroPtF32 = PointF32{X: 0, Y: 0}
// PtF32 is a shorthand function to create a point.
func PtF32(x, y float32) PointF32 {
return PointF32{x, y}
}
2018-09-23 07:42:08 +00:00
// Add adds q as a vector to p.
func (p PointF32) Add(q PointF32) PointF32 {
return PointF32{p.X + q.X, p.Y + q.Y}
}
// AngleTo calculates the angle [0..2*Pi) from point p to point q.
func (p PointF32) AngleTo(q PointF32) float32 {
a := float32(math.Atan(float64((p.Y - q.Y) / (p.X - q.X))))
if q.X < p.X {
return a + math.Pi
}
if a < 0 {
a += 2 * math.Pi
}
return a
}
// Distance calculates the distance between points p and q.
func (p PointF32) Distance(q PointF32) float32 {
return float32(math.Sqrt(float64(p.Distance2(q))))
}
// Distance2 calculates the squared distance between points p and q.
func (p PointF32) Distance2(q PointF32) float32 {
dx := q.X - p.X
dy := q.Y - p.Y
return dx*dx + dy*dy
}
2018-09-23 07:42:08 +00:00
// In tests if the point p is inside the rectangle r.
func (p PointF32) In(r RectangleF32) bool {
if p.X < r.Min.X || p.X >= r.Max.X || p.Y < r.Min.Y || p.Y >= r.Max.Y {
return false
}
return true
}
2019-03-06 18:06:08 +00:00
// Invert changes the sign of the components.
func (p PointF32) Invert() PointF32 {
return PointF32{-p.X, -p.Y}
}
2019-03-06 18:06:08 +00:00
// Sub subtracts q as a vector from p.
func (p PointF32) Sub(q PointF32) PointF32 {
return PointF32{p.X - q.X, p.Y - q.Y}
}
// To64 transforms the point p into a PointF.
func (p PointF32) To64() PointF {
return PointF{float64(p.X), float64(p.Y)}
}