2022-12-25 10:44:29 +00:00
package resolv
2023-03-02 02:22:27 +00:00
import "math"
2022-12-25 10:44:29 +00:00
// Vector is the definition of a row vector that contains scalars as
// 64 bit floats
type Vector [ ] float64
// Axis is an integer enum type that describes vector axis
type Axis int
const (
// the consts below are used to represent vector axis, they are useful
// to lookup values within the vector.
2023-03-02 02:22:27 +00:00
X Axis = 0
Y Axis = 1
Z Axis = 2
2022-12-25 10:44:29 +00:00
)
func ( v Vector ) Magnitude2 ( ) float64 {
2023-03-02 02:22:27 +00:00
var result float64 = 0.
2022-12-25 10:44:29 +00:00
for _ , scalar := range v {
result += scalar * scalar
}
return result
}
// Unit returns a direction vector with the length of one.
func ( v Vector ) Unit ( ) Vector {
2023-03-02 02:22:27 +00:00
l2 := v . Magnitude2 ( )
if l2 < 1e-16 {
2022-12-25 10:44:29 +00:00
return v
}
2023-03-02 02:22:27 +00:00
l := math . Sqrt ( l2 )
//inv := FastInvSqrt64(l2) // "Fast Inverse Square Root" is arch dependent, it's by far non-trivial to use it in Golang as well as make it feasible in the transpiled JavaScript.
2023-03-01 10:20:54 +00:00
for i := 0 ; i < len ( v ) ; i ++ {
2022-12-25 10:44:29 +00:00
v [ i ] = v [ i ] / l
2023-03-02 02:22:27 +00:00
//v[i] = v[i] * inv
2022-12-25 10:44:29 +00:00
}
return v
}
// X is corresponding to doing a v[0] lookup, if index 0 does not exist yet, a
// 0 will be returned instead
2023-03-02 02:22:27 +00:00
func ( v Vector ) GetX ( ) float64 {
2022-12-25 10:44:29 +00:00
if len ( v ) < 1 {
return 0.
}
return v [ X ]
}
// Y is corresponding to doing a v[1] lookup, if index 1 does not exist yet, a
// 0 will be returned instead
2023-03-02 02:22:27 +00:00
func ( v Vector ) GetY ( ) float64 {
2022-12-25 10:44:29 +00:00
if len ( v ) < 2 {
return 0.
}
return v [ Y ]
}
// Z is corresponding to doing a v[2] lookup, if index 2 does not exist yet, a
// 0 will be returned instead
2023-03-02 02:22:27 +00:00
func ( v Vector ) GetZ ( ) float64 {
2022-12-25 10:44:29 +00:00
if len ( v ) < 3 {
return 0.
}
return v [ Z ]
}