From 8ad3ad6a188f6d9105fdeded11886f785464ff92 Mon Sep 17 00:00:00 2001 From: Sander Schobers Date: Wed, 14 Nov 2018 10:27:03 +0100 Subject: [PATCH] Added PointF32 implementation of some methods. --- point.go | 6 ++++++ pointf.go | 6 ------ pointf32.go | 43 +++++++++++++++++++++++++++++++++++++++++++ 3 files changed, 49 insertions(+), 6 deletions(-) diff --git a/point.go b/point.go index 7b25eb1..f765121 100644 --- a/point.go +++ b/point.go @@ -2,6 +2,7 @@ package geom import ( _image "image" + "strconv" ) // Point is exposing the standard library image.Point in the geom package. @@ -11,3 +12,8 @@ type Point _image.Point func Pt(x, y int) Point { return Point{x, y} } + +// String formats the point p as a string. +func (p Point) String() string { + return "(" + strconv.Itoa(p.X) + "," + strconv.Itoa(p.Y) + ")" +} diff --git a/pointf.go b/pointf.go index d83180b..48dd030 100644 --- a/pointf.go +++ b/pointf.go @@ -2,7 +2,6 @@ package geom import ( "math" - "strconv" ) // PointF is an X, Y coordinate pair (floating point). @@ -18,11 +17,6 @@ func PtF(x, y float64) PointF { return PointF{X: x, Y: y} } -// String formats the point p as a string. -func (p Point) String() string { - return "(" + strconv.Itoa(p.X) + "," + strconv.Itoa(p.Y) + ")" -} - // To32 transforms the point p into a PointF32. func (p PointF) To32() PointF32 { return PointF32{float32(p.X), float32(p.Y)} diff --git a/pointf32.go b/pointf32.go index 9552f81..844f7a3 100644 --- a/pointf32.go +++ b/pointf32.go @@ -1,5 +1,9 @@ package geom +import ( + "math" +) + // PointF32 is an X, Y coordinate pair (floating point, 32 bits). type PointF32 struct { X, Y float32 @@ -13,6 +17,45 @@ func PtF32(x, y float32) PointF32 { return PointF32{x, y} } +// To64 transforms the point p into a PointF. +func (p PointF32) To64() PointF { + return PointF{float64(p.X), float64(p.Y)} +} + +// 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} +} + +// 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} +} + +// 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 +} + // 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 {