Skip to content

Commit

Permalink
feat(math): more math functions
Browse files Browse the repository at this point in the history
  • Loading branch information
johanhenriksson committed Oct 18, 2024
1 parent 5e7c558 commit 3c3cb8c
Show file tree
Hide file tree
Showing 5 changed files with 55 additions and 2 deletions.
43 changes: 43 additions & 0 deletions math/math32.go
Original file line number Diff line number Diff line change
Expand Up @@ -175,3 +175,46 @@ func Snap(f, multiple float32) float32 {
func Pow(f, x float32) float32 {
return float32(math.Pow(float64(f), float64(x)))
}

// NextPow2 returns the next power of 2 greater than n, or n if its a power of 2.
func NextPow2(n uint) uint {
n--
n |= n >> 1
n |= n >> 2
n |= n >> 4
n |= n >> 8
n |= n >> 16
n++
return n
}

// Ilog2 returns the uint32 value that is log2(v).
func Ilog2(v uint32) uint32 {
boolToUInt32 := func(b bool) uint32 {
if b {
return 1
}
return 0
}

var r, shift uint32
r = boolToUInt32(v > 0xffff) << 4
v >>= r
shift = boolToUInt32(v > 0xff) << 3
v >>= shift
r |= shift
shift = boolToUInt32(v > 0xf) << 2
v >>= shift
r |= shift
shift = boolToUInt32(v > 0x3) << 1
v >>= shift
r |= shift
r |= (v >> 1)
return r
}

func ApproxEqual[F constraints.Float](v, v2 F) bool {
epsilon := F(0.0001)
d := v - v2
return d*d < epsilon*epsilon
}
5 changes: 5 additions & 0 deletions math/vec2/operations.go
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,11 @@ func Distance(a, b T) float32 {
return a.Sub(b).Length()
}

// DistanceSqr returns the squared euclidian distance between two points.
func DistanceSqr(a, b T) float32 {
return a.Sub(b).LengthSqr()
}

func Min(a, b T) T {
return T{
X: math.Min(a.X, b.X),
Expand Down
2 changes: 1 addition & 1 deletion math/vec2/vec2.go
Original file line number Diff line number Diff line change
Expand Up @@ -116,7 +116,7 @@ func (v T) Div(v2 T) T {

func (v T) ApproxEqual(v2 T) bool {
epsilon := float32(0.0001)
return Distance(v, v2) < epsilon
return DistanceSqr(v, v2) < epsilon*epsilon
}

func (v T) String() string {
Expand Down
5 changes: 5 additions & 0 deletions math/vec3/operations.go
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,11 @@ func Distance(a, b T) float32 {
return a.Sub(b).Length()
}

// DistanceSqr returns the squared euclidian distance between two points.
func DistanceSqr(a, b T) float32 {
return a.Sub(b).LengthSqr()
}

func Mid(a, b T) T {
return a.Add(b).Scaled(0.5)
}
Expand Down
2 changes: 1 addition & 1 deletion math/vec3/vec3.go
Original file line number Diff line number Diff line change
Expand Up @@ -197,7 +197,7 @@ func (v T) WithZ(z float32) T {

func (v T) ApproxEqual(v2 T) bool {
epsilon := float32(0.0001)
return Distance(v, v2) < epsilon
return DistanceSqr(v, v2) < epsilon*epsilon
}

func (v T) String() string {
Expand Down

0 comments on commit 3c3cb8c

Please sign in to comment.