github.com/gopherd/gonum@v0.0.4/spatial/r3/vector.go (about) 1 // Copyright ©2019 The Gonum Authors. 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 r3 6 7 import "math" 8 9 // Vec is a 3D vector. 10 type Vec struct { 11 X, Y, Z float64 12 } 13 14 // Add returns the vector sum of p and q. 15 func Add(p, q Vec) Vec { 16 return Vec{ 17 X: p.X + q.X, 18 Y: p.Y + q.Y, 19 Z: p.Z + q.Z, 20 } 21 } 22 23 // Sub returns the vector sum of p and -q. 24 func Sub(p, q Vec) Vec { 25 return Vec{ 26 X: p.X - q.X, 27 Y: p.Y - q.Y, 28 Z: p.Z - q.Z, 29 } 30 } 31 32 // Scale returns the vector p scaled by f. 33 func Scale(f float64, p Vec) Vec { 34 return Vec{ 35 X: f * p.X, 36 Y: f * p.Y, 37 Z: f * p.Z, 38 } 39 } 40 41 // Dot returns the dot product p·q. 42 func Dot(p, q Vec) float64 { 43 return p.X*q.X + p.Y*q.Y + p.Z*q.Z 44 } 45 46 // Cross returns the cross product p×q. 47 func Cross(p, q Vec) Vec { 48 return Vec{ 49 p.Y*q.Z - p.Z*q.Y, 50 p.Z*q.X - p.X*q.Z, 51 p.X*q.Y - p.Y*q.X, 52 } 53 } 54 55 // Rotate returns a new vector, rotated by alpha around the provided axis. 56 func Rotate(p Vec, alpha float64, axis Vec) Vec { 57 return NewRotation(alpha, axis).Rotate(p) 58 } 59 60 // Norm returns the Euclidean norm of p 61 // |p| = sqrt(p_x^2 + p_y^2 + p_z^2). 62 func Norm(p Vec) float64 { 63 return math.Hypot(p.X, math.Hypot(p.Y, p.Z)) 64 } 65 66 // Norm2 returns the Euclidean squared norm of p 67 // |p|^2 = p_x^2 + p_y^2 + p_z^2. 68 func Norm2(p Vec) float64 { 69 return p.X*p.X + p.Y*p.Y + p.Z*p.Z 70 } 71 72 // Unit returns the unit vector colinear to p. 73 // Unit returns {NaN,NaN,NaN} for the zero vector. 74 func Unit(p Vec) Vec { 75 if p.X == 0 && p.Y == 0 && p.Z == 0 { 76 return Vec{X: math.NaN(), Y: math.NaN(), Z: math.NaN()} 77 } 78 return Scale(1/Norm(p), p) 79 } 80 81 // Cos returns the cosine of the opening angle between p and q. 82 func Cos(p, q Vec) float64 { 83 return Dot(p, q) / (Norm(p) * Norm(q)) 84 } 85 86 // Box is a 3D bounding box. 87 type Box struct { 88 Min, Max Vec 89 }