diff --git a/spatial/r3/vector.go b/spatial/r3/vector.go index 2ecf0256..f10c2c08 100644 --- a/spatial/r3/vector.go +++ b/spatial/r3/vector.go @@ -38,6 +38,15 @@ func (p Vec) Dot(q Vec) float64 { return p.X*q.X + p.Y*q.Y + p.Z*q.Z } +// Cross returns the cross product p×q. +func (p Vec) Cross(q Vec) Vec { + return Vec{ + p.Y*q.Z - p.Z*q.Y, + p.Z*q.X - p.X*q.Z, + p.X*q.Y - p.Y*q.X, + } +} + // Box is a 3D bounding box. type Box struct { Min, Max Vec diff --git a/spatial/r3/vector_test.go b/spatial/r3/vector_test.go index 161a3f0d..0966a0d5 100644 --- a/spatial/r3/vector_test.go +++ b/spatial/r3/vector_test.go @@ -112,3 +112,26 @@ func TestDot(t *testing.T) { }) } } + +func TestCross(t *testing.T) { + for _, test := range []struct { + v1, v2, want Vec + }{ + {Vec{1, 0, 0}, Vec{1, 0, 0}, Vec{0, 0, 0}}, + {Vec{1, 0, 0}, Vec{0, 1, 0}, Vec{0, 0, 1}}, + {Vec{0, 1, 0}, Vec{1, 0, 0}, Vec{0, 0, -1}}, + {Vec{1, 2, 3}, Vec{-4, 5, -6}, Vec{-27, -6, 13}}, + {Vec{1, 2, 3}, Vec{1, 2, 3}, Vec{}}, + {Vec{1, 2, 3}, Vec{2, 3, 4}, Vec{-1, 2, -1}}, + } { + t.Run("", func(t *testing.T) { + got := test.v1.Cross(test.v2) + if got != test.want { + t.Fatalf( + "error: %v × %v = %v, want %v", + test.v1, test.v2, got, test.want, + ) + } + }) + } +}