github.com/unidoc/unidoc@v2.2.0+incompatible/pdf/contentstream/draw/vector.go (about) 1 /* 2 * This file is subject to the terms and conditions defined in 3 * file 'LICENSE.md', which is part of this source code package. 4 */ 5 6 package draw 7 8 import "math" 9 10 type Vector struct { 11 Dx float64 12 Dy float64 13 } 14 15 func NewVector(dx, dy float64) Vector { 16 v := Vector{} 17 v.Dx = dx 18 v.Dy = dy 19 return v 20 } 21 22 func NewVectorBetween(a Point, b Point) Vector { 23 v := Vector{} 24 v.Dx = b.X - a.X 25 v.Dy = b.Y - a.Y 26 return v 27 } 28 29 func NewVectorPolar(length float64, theta float64) Vector { 30 v := Vector{} 31 32 v.Dx = length * math.Cos(theta) 33 v.Dy = length * math.Sin(theta) 34 return v 35 } 36 37 func (v Vector) Add(other Vector) Vector { 38 v.Dx += other.Dx 39 v.Dy += other.Dy 40 return v 41 } 42 43 func (v Vector) Rotate(phi float64) Vector { 44 mag := v.Magnitude() 45 angle := v.GetPolarAngle() 46 47 return NewVectorPolar(mag, angle+phi) 48 } 49 50 // Change the sign of the vector: -vector. 51 func (this Vector) Flip() Vector { 52 mag := this.Magnitude() 53 theta := this.GetPolarAngle() 54 55 this.Dx = mag * math.Cos(theta+math.Pi) 56 this.Dy = mag * math.Sin(theta+math.Pi) 57 return this 58 } 59 60 func (v Vector) FlipY() Vector { 61 v.Dy = -v.Dy 62 return v 63 } 64 65 func (v Vector) FlipX() Vector { 66 v.Dx = -v.Dx 67 return v 68 } 69 70 func (this Vector) Scale(factor float64) Vector { 71 mag := this.Magnitude() 72 theta := this.GetPolarAngle() 73 74 this.Dx = factor * mag * math.Cos(theta) 75 this.Dy = factor * mag * math.Sin(theta) 76 return this 77 } 78 79 func (this Vector) Magnitude() float64 { 80 return math.Sqrt(math.Pow(this.Dx, 2.0) + math.Pow(this.Dy, 2.0)) 81 } 82 83 func (this Vector) GetPolarAngle() float64 { 84 return math.Atan2(this.Dy, this.Dx) 85 }