github.com/searKing/golang/go@v1.2.117/exp/image/point.go (about) 1 // Copyright 2023 The searKing Author. All rights reserved. 2 // Use of this source code is governed by a BSD-style 3 // license that can be found in the LICENSE file. 4 5 package image 6 7 import ( 8 "fmt" 9 "image" 10 11 "github.com/searKing/golang/go/exp/constraints" 12 ) 13 14 // A Point is an X, Y coordinate pair. The axes increase right and down. 15 type Point[E constraints.Number] struct { 16 X, Y E 17 } 18 19 // String returns a string representation of p like "(3,4)". 20 func (p Point[E]) String() string { 21 return fmt.Sprintf("(%v,%v)", p.X, p.Y) 22 } 23 24 // Add returns the vector p+q. 25 func (p Point[E]) Add(q Point[E]) Point[E] { 26 return Point[E]{p.X + q.X, p.Y + q.Y} 27 } 28 29 // Sub returns the vector p-q. 30 func (p Point[E]) Sub(q Point[E]) Point[E] { 31 return Point[E]{p.X - q.X, p.Y - q.Y} 32 } 33 34 // Mul returns the vector p*k. 35 func (p Point[E]) Mul(k E) Point[E] { 36 return Point[E]{p.X * k, p.Y * k} 37 } 38 39 // MulPoint returns the vector p.*k. 40 func (p Point[E]) MulPoint(k Point[E]) Point[E] { 41 return Point[E]{p.X * k.X, p.Y * k.Y} 42 } 43 44 // Div returns the vector p/k. 45 func (p Point[E]) Div(k E) Point[E] { 46 return Point[E]{p.X / k, p.Y / k} 47 } 48 49 // DivPoint returns the vector p./k. 50 func (p Point[E]) DivPoint(k Point[E]) Point[E] { 51 return Point[E]{p.X / k.X, p.Y / k.Y} 52 } 53 54 // In reports whether p is in r. 55 func (p Point[E]) In(r Rectangle[E]) bool { 56 return r.Min.X <= p.X && p.X < r.Max.X && 57 r.Min.Y <= p.Y && p.Y < r.Max.Y 58 } 59 60 // Mod returns the point q in r such that p.X-q.X is a multiple of r's width 61 // and p.Y-q.Y is a multiple of r's height. 62 func (p Point[E]) Mod(r image.Rectangle) image.Point { 63 p2 := p.RoundPoint() 64 return p2.Mod(r) 65 } 66 67 // Eq reports whether p and q are equal. 68 func (p Point[E]) Eq(q Point[E]) bool { 69 return p == q 70 } 71 72 func (p Point[E]) RoundPoint() image.Point { 73 return image.Pt(round(p.X), round(p.Y)) 74 } 75 76 // Pt is shorthand for Point[E]{X, Y}. 77 func Pt[E constraints.Number](X, Y E) Point[E] { 78 return Point[E]{X, Y} 79 } 80 81 func FromPtInt[E constraints.Number](q image.Point) Point[E] { 82 return Point[E]{E(q.X), E(q.Y)} 83 }