2020-11-13 07:46:31 -07:00
|
|
|
import math
|
|
|
|
|
|
|
|
ZERO = (0, 0)
|
|
|
|
|
2020-11-14 11:10:04 -07:00
|
|
|
|
2020-11-13 07:46:31 -07:00
|
|
|
def dot(x1, y1, x2, y2):
|
2020-11-14 11:10:04 -07:00
|
|
|
"""Returns the dot product of two vectors."""
|
2020-11-13 07:46:31 -07:00
|
|
|
return (x1 * x2) + (y1 * y2)
|
|
|
|
|
2020-11-14 11:10:04 -07:00
|
|
|
|
2020-11-13 07:46:31 -07:00
|
|
|
def length(x, y):
|
2020-11-14 11:10:04 -07:00
|
|
|
"""Returns the magnitude of a vector."""
|
2020-11-13 07:46:31 -07:00
|
|
|
return math.sqrt((x * x) + (y * y))
|
|
|
|
|
|
|
|
def normalize(x, y):
|
2020-11-14 11:10:04 -07:00
|
|
|
"""Returns the unit vector pointed in the same direction as [x, y]."""
|
2020-11-13 07:46:31 -07:00
|
|
|
_len = length(x, y)
|
|
|
|
return x / _len, y / _len
|
|
|
|
|
2020-11-14 11:10:04 -07:00
|
|
|
|
|
|
|
def lnormal(x, y):
|
|
|
|
"""Returns the left-hand normal of a vector."""
|
2020-11-16 02:05:13 -07:00
|
|
|
return y, -x
|
2020-11-14 11:10:04 -07:00
|
|
|
|
|
|
|
|
|
|
|
def rnormal(x, y):
|
|
|
|
"""Returns the right-hand normal of a vector."""
|
2020-11-16 02:05:13 -07:00
|
|
|
return -y, x
|
2020-11-14 11:10:04 -07:00
|
|
|
|
|
|
|
|
|
|
|
def reverse(x, y):
|
|
|
|
"""Returns a vector pointing in the opposite direction."""
|
|
|
|
return -x, -y
|
|
|
|
|
|
|
|
|
2020-11-13 07:46:31 -07:00
|
|
|
def scale(x, y, factor):
|
2020-11-14 11:10:04 -07:00
|
|
|
"""Scale a vector by a given factor."""
|
2020-11-13 07:46:31 -07:00
|
|
|
return x * factor, y * factor
|
|
|
|
|
2020-11-14 11:10:04 -07:00
|
|
|
|
2020-11-13 07:46:31 -07:00
|
|
|
def add(x1, y1, x2, y2):
|
2020-11-14 11:10:04 -07:00
|
|
|
"""Add two vectors."""
|
2020-11-13 07:46:31 -07:00
|
|
|
return x1 + x2, y1 + y2
|
|
|
|
|
2020-11-14 11:10:04 -07:00
|
|
|
|
2020-11-13 07:46:31 -07:00
|
|
|
def sub(x1, y1, x2, y2):
|
2020-11-14 11:10:04 -07:00
|
|
|
"""Subtract a vector from another."""
|
2020-11-13 07:46:31 -07:00
|
|
|
return x1 - x2, y1 - y2
|
|
|
|
|
2020-11-14 11:10:04 -07:00
|
|
|
|
2020-11-13 07:46:31 -07:00
|
|
|
def vmin(x1, y1, x2, y2):
|
2020-11-14 11:10:04 -07:00
|
|
|
"""Return the minimum [x, y] components of the given vectors."""
|
2020-11-13 07:46:31 -07:00
|
|
|
return min(x1, x2), min(y1, y2)
|
|
|
|
|
2020-11-14 11:10:04 -07:00
|
|
|
|
2020-11-13 07:46:31 -07:00
|
|
|
def vmax(x1, y1, x2, y2):
|
2020-11-14 11:10:04 -07:00
|
|
|
"""Return the maximum [x, y] components of the given vectors."""
|
2020-11-13 07:46:31 -07:00
|
|
|
return max(x1, x2), max(y1, y2)
|
2020-11-14 11:10:04 -07:00
|
|
|
|
|
|
|
|
2020-11-15 07:56:13 -07:00
|
|
|
def is_colinear(x1, y1, x2, y2):
|
|
|
|
"""Returns whether two unit vectors are pointed in the same or
|
|
|
|
opposite directions."""
|
2020-11-15 02:34:17 -07:00
|
|
|
return math.isclose(abs(dot(x1, y1, x2, y2)), 1, rel_tol=1e-05)
|