Mini Project: A 2D Geometry Toolkit
In this project you will build a small 2D geometry library in plain Python, one tool at a time: a Vec type, distances and angles, polygon area and centroid, a point-in-polygon test, rotations about a pivot, and a convex hull. At the end every tool is tested on one small scene (a house, a garden of trees) and the scene is plotted. It brings together vectors in geometry, coordinate geometry, transformations, collision geometry and convex hulls.
What we are building: about 90 lines of geometry code with a test after every step, ending in a scene report like tree (4, 4): outside and a picture.
| Step | New concepts |
|---|---|
| 1. A vector type | Vec with +, −, scalar ×, dot, cross, length, normalize, rotate |
| 2. Distances and angles | signed angle with atan2(cross, dot), triangle angles |
| 3. Polygon measures | shoelace area and orientation, perimeter, centroid |
| 4. Point in polygon | ray casting for any simple polygon, the "on the edge" case |
| 5. Transformations | rotation about a pivot, translation, what they preserve |
| 6. Hull, scene and plot | convex hull, a full scene test, a Matplotlib picture |
Note: Every step is a complete program, so each block repeats the code from the steps before it. Each step ends with
assertchecks: if a check fails, Python stops with anAssertionError, which is the simplest possible test framework.
Step 1: A vector type
A point and a vector are both a pair ; we use one Vec type for both. A frozen dataclass gives us equality, hashing (so vectors can go in a set) and immutability for free. The 2D cross product is a plain number: positive when is counter-clockwise from . Rotation by is the rotation formula .
import math
from dataclasses import dataclass
@dataclass(frozen=True)
class Vec:
x: float
y: float
def __add__(self, o): return Vec(self.x + o.x, self.y + o.y)
def __sub__(self, o): return Vec(self.x - o.x, self.y - o.y)
def __mul__(self, k): return Vec(self.x * k, self.y * k)
__rmul__ = __mul__
def dot(self, o): return self.x * o.x + self.y * o.y
def cross(self, o): return self.x * o.y - self.y * o.x
def length(self): return math.hypot(self.x, self.y)
def normalized(self):
n = self.length()
if n == 0:
raise ValueError("cannot normalize the zero vector")
return Vec(self.x / n, self.y / n)
def rotated(self, theta): # counter-clockwise, radians
c, s = math.cos(theta), math.sin(theta)
return Vec(c * self.x - s * self.y, s * self.x + c * self.y)
def __repr__(self): # rounded, and no "-0"
return f"Vec({round(self.x, 6) + 0.0:g}, {round(self.y, 6) + 0.0:g})"
u, v = Vec(3, 4), Vec(1, 0)
print("u + v =", u + v, " u - v =", u - v, " 2u =", 2 * u)
print("|u| =", u.length(), " unit u =", u.normalized())
print("u.v =", u.dot(v), " u x v =", u.cross(v), " v x u =", v.cross(u))
print("v rotated 90 deg:", v.rotated(math.pi / 2), " u rotated 180 deg:", u.rotated(math.pi))
assert u.length() == 5
assert (v.rotated(math.pi / 2) - Vec(0, 1)).length() < 1e-12
assert u.cross(v) == -v.cross(u)
print("step 1 tests passed")u + v = Vec(4, 4) u - v = Vec(2, 4) 2u = Vec(6, 8)
|u| = 5.0 unit u = Vec(0.6, 0.8)
u.v = 3 u x v = -4 v x u = 4
v rotated 90 deg: Vec(0, 1) u rotated 180 deg: Vec(-3, -4)
step 1 tests passed
The rotated vectors are printed rounded: the true values contain tiny errors like 6.1e-17 instead of 0, because is not exactly 0 in floating point. That is also why the rotation test compares with a tolerance.
Step 2: Distances and angles
The distance between two points is the length of their difference. For the angle between two vectors, the best formula combines both products: the dot product is and the cross product is , so
This is more accurate than (which loses precision near 0° and 180°) and it tells left from right. A triangle's interior angles must add up to 180°, a good test.
import math
from dataclasses import dataclass
@dataclass(frozen=True)
class Vec:
x: float
y: float
def __add__(self, o): return Vec(self.x + o.x, self.y + o.y)
def __sub__(self, o): return Vec(self.x - o.x, self.y - o.y)
def __mul__(self, k): return Vec(self.x * k, self.y * k)
__rmul__ = __mul__
def dot(self, o): return self.x * o.x + self.y * o.y
def cross(self, o): return self.x * o.y - self.y * o.x
def length(self): return math.hypot(self.x, self.y)
def normalized(self):
n = self.length()
if n == 0:
raise ValueError("cannot normalize the zero vector")
return Vec(self.x / n, self.y / n)
def rotated(self, theta): # counter-clockwise, radians
c, s = math.cos(theta), math.sin(theta)
return Vec(c * self.x - s * self.y, s * self.x + c * self.y)
def __repr__(self): # rounded, and no "-0"
return f"Vec({round(self.x, 6) + 0.0:g}, {round(self.y, 6) + 0.0:g})"
def distance(p, q):
return (q - p).length()
def angle_between(u, v):
"""Signed angle from u to v in radians, in (-pi, pi]."""
return math.atan2(u.cross(v), u.dot(v))
def angle_at(a, b, c):
"""Interior angle ABC at vertex b, in degrees."""
return math.degrees(abs(angle_between(a - b, c - b)))
print("distance (1,2)-(4,6):", distance(Vec(1, 2), Vec(4, 6)))
print("angle x-axis -> y-axis:", math.degrees(angle_between(Vec(1, 0), Vec(0, 1))))
print("angle y-axis -> x-axis:", math.degrees(angle_between(Vec(0, 1), Vec(1, 0))))
A, B, C = Vec(0, 0), Vec(4, 0), Vec(0, 3)
angles = [angle_at(C, A, B), angle_at(A, B, C), angle_at(B, C, A)]
print("triangle angles:", [round(a, 2) for a in angles], " sum:", round(sum(angles), 10))
assert distance(Vec(1, 2), Vec(4, 6)) == 5
assert abs(sum(angles) - 180) < 1e-9
print("step 2 tests passed")distance (1,2)-(4,6): 5.0
angle x-axis -> y-axis: 90.0
angle y-axis -> x-axis: -90.0
triangle angles: [90.0, 36.87, 53.13] sum: 180.0
step 2 tests passed
The 3-4-5 triangle has angles 90°, 36.87° and 53.13°: a right angle at , as the sides along the axes promise.
Step 3: Polygon measures
A polygon is a list of vertices in order. The shoelace formula adds the cross products of consecutive vertices:
The sign tells the orientation: positive for counter-clockwise, negative for clockwise. The centroid (the balance point of the filled shape) uses the same cross products as weights: .
Our test shape is an L-shaped house: a rectangle with a wing on top, so its area must be .
import math
from dataclasses import dataclass
@dataclass(frozen=True)
class Vec:
x: float
y: float
def __add__(self, o): return Vec(self.x + o.x, self.y + o.y)
def __sub__(self, o): return Vec(self.x - o.x, self.y - o.y)
def __mul__(self, k): return Vec(self.x * k, self.y * k)
__rmul__ = __mul__
def dot(self, o): return self.x * o.x + self.y * o.y
def cross(self, o): return self.x * o.y - self.y * o.x
def length(self): return math.hypot(self.x, self.y)
def normalized(self):
n = self.length()
if n == 0:
raise ValueError("cannot normalize the zero vector")
return Vec(self.x / n, self.y / n)
def rotated(self, theta): # counter-clockwise, radians
c, s = math.cos(theta), math.sin(theta)
return Vec(c * self.x - s * self.y, s * self.x + c * self.y)
def __repr__(self): # rounded, and no "-0"
return f"Vec({round(self.x, 6) + 0.0:g}, {round(self.y, 6) + 0.0:g})"
def distance(p, q):
return (q - p).length()
def angle_between(u, v):
"""Signed angle from u to v in radians, in (-pi, pi]."""
return math.atan2(u.cross(v), u.dot(v))
def angle_at(a, b, c):
"""Interior angle ABC at vertex b, in degrees."""
return math.degrees(abs(angle_between(a - b, c - b)))
def signed_area(poly):
"""Shoelace formula: > 0 for counter-clockwise vertices."""
return sum(p.cross(q) for p, q in zip(poly, poly[1:] + poly[:1])) / 2
def perimeter(poly):
return sum(distance(p, q) for p, q in zip(poly, poly[1:] + poly[:1]))
def centroid(poly):
a, cx, cy = signed_area(poly), 0.0, 0.0
for p, q in zip(poly, poly[1:] + poly[:1]):
w = p.cross(q)
cx, cy = cx + (p.x + q.x) * w, cy + (p.y + q.y) * w
return Vec(cx / (6 * a), cy / (6 * a))
house = [Vec(0, 0), Vec(6, 0), Vec(6, 3), Vec(3, 3), Vec(3, 5), Vec(0, 5)]
print("area:", signed_area(house), " reversed:", signed_area(house[::-1]))
print("perimeter:", perimeter(house))
print("centroid:", centroid(house))
tri = [Vec(0, 0), Vec(4, 0), Vec(0, 3)]
print("triangle area:", signed_area(tri), " centroid:", centroid(tri))
assert signed_area(house) == 24 and signed_area(house[::-1]) == -24
assert centroid(house) == Vec(2.625, 2.125)
print("step 3 tests passed")area: 24.0 reversed: -24.0
perimeter: 22.0
centroid: Vec(2.625, 2.125)
triangle area: 6.0 centroid: Vec(1.33333, 1)
step 3 tests passed
Check the centroid by hand: the big rectangle (area 18) balances at , the wing (area 6) at . Their weighted average is . ✓
Step 4: Point in polygon
For a convex polygon "on the left of every edge" would do, but the house is not convex. The ray casting test works for any simple polygon: shoot a ray from the point to the right and count how many edges it crosses. An odd count means inside.
Two details make it robust. The condition (a.y > p.y) != (b.y > p.y) treats each edge as half-open, so a ray through a vertex is counted exactly once. And a point lying exactly on an edge is reported separately as "edge", checked first with the cross product (collinear) and the dot product (between the end points).
import math
from dataclasses import dataclass
@dataclass(frozen=True)
class Vec:
x: float
y: float
def __add__(self, o): return Vec(self.x + o.x, self.y + o.y)
def __sub__(self, o): return Vec(self.x - o.x, self.y - o.y)
def __mul__(self, k): return Vec(self.x * k, self.y * k)
__rmul__ = __mul__
def dot(self, o): return self.x * o.x + self.y * o.y
def cross(self, o): return self.x * o.y - self.y * o.x
def length(self): return math.hypot(self.x, self.y)
def normalized(self):
n = self.length()
if n == 0:
raise ValueError("cannot normalize the zero vector")
return Vec(self.x / n, self.y / n)
def rotated(self, theta): # counter-clockwise, radians
c, s = math.cos(theta), math.sin(theta)
return Vec(c * self.x - s * self.y, s * self.x + c * self.y)
def __repr__(self): # rounded, and no "-0"
return f"Vec({round(self.x, 6) + 0.0:g}, {round(self.y, 6) + 0.0:g})"
def distance(p, q):
return (q - p).length()
def angle_between(u, v):
"""Signed angle from u to v in radians, in (-pi, pi]."""
return math.atan2(u.cross(v), u.dot(v))
def angle_at(a, b, c):
"""Interior angle ABC at vertex b, in degrees."""
return math.degrees(abs(angle_between(a - b, c - b)))
def signed_area(poly):
"""Shoelace formula: > 0 for counter-clockwise vertices."""
return sum(p.cross(q) for p, q in zip(poly, poly[1:] + poly[:1])) / 2
def perimeter(poly):
return sum(distance(p, q) for p, q in zip(poly, poly[1:] + poly[:1]))
def centroid(poly):
a, cx, cy = signed_area(poly), 0.0, 0.0
for p, q in zip(poly, poly[1:] + poly[:1]):
w = p.cross(q)
cx, cy = cx + (p.x + q.x) * w, cy + (p.y + q.y) * w
return Vec(cx / (6 * a), cy / (6 * a))
def point_in_polygon(p, poly, eps=1e-9):
"""'inside', 'outside' or 'edge', by casting a ray to the right."""
inside = False
for a, b in zip(poly, poly[1:] + poly[:1]):
if abs((b - a).cross(p - a)) < eps and (p - a).dot(p - b) <= eps:
return "edge" # collinear and between a and b
if (a.y > p.y) != (b.y > p.y): # the edge straddles the ray's height
x_cross = a.x + (p.y - a.y) * (b.x - a.x) / (b.y - a.y)
if x_cross > p.x:
inside = not inside
return "inside" if inside else "outside"
house = [Vec(0, 0), Vec(6, 0), Vec(6, 3), Vec(3, 3), Vec(3, 5), Vec(0, 5)]
tests = {Vec(1, 1): "inside", Vec(5, 2): "inside", Vec(2, 4): "inside",
Vec(4, 4): "outside", # in the notch of the L
Vec(7, 1): "outside", Vec(3, 4): "edge", Vec(6, 3): "edge",
Vec(1, 3): "inside", # the ray passes through vertex (3, 3)
Vec(-1, 3): "outside"}
for p, expected in tests.items():
got = point_in_polygon(p, house)
print(f"{p}: {got:7} {'ok' if got == expected else 'WRONG'}")
assert got == expected
print("step 4 tests passed")Vec(1, 1): inside ok
Vec(5, 2): inside ok
Vec(2, 4): inside ok
Vec(4, 4): outside ok
Vec(7, 1): outside ok
Vec(3, 4): edge ok
Vec(6, 3): edge ok
Vec(1, 3): inside ok
Vec(-1, 3): outside ok
step 4 tests passed
The point is the tricky one: its ray runs along the edge from to and through the vertex . The half-open rule counts the vertical edge – once and ignores the horizontal edge, so the count is odd and the answer is right.
Step 5: Transformations
Rotating a point about a pivot by means: move to the origin, rotate, move back, that is . Rotations and translations are rigid motions: they keep lengths, angles and areas, and a rotation about the centroid keeps the centroid where it is. Those invariants make excellent tests.
import math
from dataclasses import dataclass
@dataclass(frozen=True)
class Vec:
x: float
y: float
def __add__(self, o): return Vec(self.x + o.x, self.y + o.y)
def __sub__(self, o): return Vec(self.x - o.x, self.y - o.y)
def __mul__(self, k): return Vec(self.x * k, self.y * k)
__rmul__ = __mul__
def dot(self, o): return self.x * o.x + self.y * o.y
def cross(self, o): return self.x * o.y - self.y * o.x
def length(self): return math.hypot(self.x, self.y)
def normalized(self):
n = self.length()
if n == 0:
raise ValueError("cannot normalize the zero vector")
return Vec(self.x / n, self.y / n)
def rotated(self, theta): # counter-clockwise, radians
c, s = math.cos(theta), math.sin(theta)
return Vec(c * self.x - s * self.y, s * self.x + c * self.y)
def __repr__(self): # rounded, and no "-0"
return f"Vec({round(self.x, 6) + 0.0:g}, {round(self.y, 6) + 0.0:g})"
def distance(p, q):
return (q - p).length()
def angle_between(u, v):
"""Signed angle from u to v in radians, in (-pi, pi]."""
return math.atan2(u.cross(v), u.dot(v))
def angle_at(a, b, c):
"""Interior angle ABC at vertex b, in degrees."""
return math.degrees(abs(angle_between(a - b, c - b)))
def signed_area(poly):
"""Shoelace formula: > 0 for counter-clockwise vertices."""
return sum(p.cross(q) for p, q in zip(poly, poly[1:] + poly[:1])) / 2
def perimeter(poly):
return sum(distance(p, q) for p, q in zip(poly, poly[1:] + poly[:1]))
def centroid(poly):
a, cx, cy = signed_area(poly), 0.0, 0.0
for p, q in zip(poly, poly[1:] + poly[:1]):
w = p.cross(q)
cx, cy = cx + (p.x + q.x) * w, cy + (p.y + q.y) * w
return Vec(cx / (6 * a), cy / (6 * a))
def rotate_about(p, pivot, theta):
return pivot + (p - pivot).rotated(theta)
def transform(poly, theta=0.0, pivot=Vec(0, 0), offset=Vec(0, 0)):
return [rotate_about(p, pivot, theta) + offset for p in poly]
house = [Vec(0, 0), Vec(6, 0), Vec(6, 3), Vec(3, 3), Vec(3, 5), Vec(0, 5)]
c = centroid(house)
turned = transform(house, theta=math.radians(30), pivot=c)
moved = transform(house, offset=Vec(10, -2))
print("turned house:", turned[:3], "...")
print(f"area {signed_area(turned):.10f}, perimeter {perimeter(turned):.10f}")
print("centroid after turning:", centroid(turned))
print("centroid after moving :", centroid(moved))
print("corner (6, 0) by 90 deg about (6, 3):", rotate_about(Vec(6, 0), Vec(6, 3), math.pi / 2))
assert abs(signed_area(turned) - 24) < 1e-9 and abs(perimeter(turned) - 22) < 1e-9
assert distance(centroid(turned), c) < 1e-9
print("step 5 tests passed")turned house: [Vec(1.41418, -1.0278), Vec(6.61034, 1.9722), Vec(5.11034, 4.57027)] ...
area 24.0000000000, perimeter 22.0000000000
centroid after turning: Vec(2.625, 2.125)
centroid after moving : Vec(12.625, 0.125)
corner (6, 0) by 90 deg about (6, 3): Vec(9, 3)
step 5 tests passed
A 90° counter-clockwise turn of about : the offset becomes , so the point lands on .
Step 6: Hull, scene and plot
The last tool is the convex hull (Andrew's monotone chain, written with Vec). Then a small scene uses everything: which trees grow inside the house, the hull of all the trees (a fence that encloses them), its area, and the house rotated 30° about its centroid, all drawn with Matplotlib.
import math
from dataclasses import dataclass
@dataclass(frozen=True)
class Vec:
x: float
y: float
def __add__(self, o): return Vec(self.x + o.x, self.y + o.y)
def __sub__(self, o): return Vec(self.x - o.x, self.y - o.y)
def __mul__(self, k): return Vec(self.x * k, self.y * k)
__rmul__ = __mul__
def dot(self, o): return self.x * o.x + self.y * o.y
def cross(self, o): return self.x * o.y - self.y * o.x
def length(self): return math.hypot(self.x, self.y)
def normalized(self):
n = self.length()
if n == 0:
raise ValueError("cannot normalize the zero vector")
return Vec(self.x / n, self.y / n)
def rotated(self, theta): # counter-clockwise, radians
c, s = math.cos(theta), math.sin(theta)
return Vec(c * self.x - s * self.y, s * self.x + c * self.y)
def __repr__(self): # rounded, and no "-0"
return f"Vec({round(self.x, 6) + 0.0:g}, {round(self.y, 6) + 0.0:g})"
def distance(p, q):
return (q - p).length()
def angle_between(u, v):
"""Signed angle from u to v in radians, in (-pi, pi]."""
return math.atan2(u.cross(v), u.dot(v))
def angle_at(a, b, c):
"""Interior angle ABC at vertex b, in degrees."""
return math.degrees(abs(angle_between(a - b, c - b)))
def signed_area(poly):
"""Shoelace formula: > 0 for counter-clockwise vertices."""
return sum(p.cross(q) for p, q in zip(poly, poly[1:] + poly[:1])) / 2
def perimeter(poly):
return sum(distance(p, q) for p, q in zip(poly, poly[1:] + poly[:1]))
def centroid(poly):
a, cx, cy = signed_area(poly), 0.0, 0.0
for p, q in zip(poly, poly[1:] + poly[:1]):
w = p.cross(q)
cx, cy = cx + (p.x + q.x) * w, cy + (p.y + q.y) * w
return Vec(cx / (6 * a), cy / (6 * a))
def point_in_polygon(p, poly, eps=1e-9):
"""'inside', 'outside' or 'edge', by casting a ray to the right."""
inside = False
for a, b in zip(poly, poly[1:] + poly[:1]):
if abs((b - a).cross(p - a)) < eps and (p - a).dot(p - b) <= eps:
return "edge" # collinear and between a and b
if (a.y > p.y) != (b.y > p.y): # the edge straddles the ray's height
x_cross = a.x + (p.y - a.y) * (b.x - a.x) / (b.y - a.y)
if x_cross > p.x:
inside = not inside
return "inside" if inside else "outside"
def rotate_about(p, pivot, theta):
return pivot + (p - pivot).rotated(theta)
def transform(poly, theta=0.0, pivot=Vec(0, 0), offset=Vec(0, 0)):
return [rotate_about(p, pivot, theta) + offset for p in poly]
def convex_hull(points):
pts = sorted(set(points), key=lambda v: (v.x, v.y))
if len(pts) <= 2:
return pts
lower, upper = [], []
for chain, seq in ((lower, pts), (upper, reversed(pts))):
for p in seq:
while len(chain) >= 2 and (chain[-1] - chain[-2]).cross(p - chain[-2]) <= 0:
chain.pop()
chain.append(p)
return lower[:-1] + upper[:-1]
import matplotlib.pyplot as plt
house = [Vec(0, 0), Vec(6, 0), Vec(6, 3), Vec(3, 3), Vec(3, 5), Vec(0, 5)]
trees = [Vec(1, 1), Vec(4, 4), Vec(2, 4), Vec(7, 1), Vec(5, 2), Vec(8, 6), Vec(1, 6), Vec(4, -1)]
for t in trees:
print(f"tree ({t.x:g}, {t.y:g}): {point_in_polygon(t, house)}")
fence = convex_hull(trees)
print("fence:", fence)
print(f"fence area {signed_area(fence)}, length {perimeter(fence):.3f}")
outside = [t for t in trees if point_in_polygon(t, house) == "outside"]
print("all outside trees within the fence:", all(point_in_polygon(t, fence) != "outside" for t in outside))
turned = transform(house, theta=math.radians(30), pivot=centroid(house))
fig, ax = plt.subplots(figsize=(7, 4))
for poly, style, label in [(house, "-", "house"), (turned, "--", "house turned 30°"), (fence, ":", "fence (hull)")]:
xs, ys = zip(*[(p.x, p.y) for p in poly + poly[:1]])
ax.plot(xs, ys, style, label=label)
ax.plot([t.x for t in trees], [t.y for t in trees], "^", color="green", label="trees")
ax.set_xlim(-2, 13); ax.set_aspect("equal")
ax.legend(loc="center right", fontsize=8) # the empty space right of the scene
print("all scene checks done")tree (1, 1): inside
tree (4, 4): outside
tree (2, 4): inside
tree (7, 1): outside
tree (5, 2): inside
tree (8, 6): outside
tree (1, 6): outside
tree (4, -1): outside
fence: [Vec(1, 1), Vec(4, -1), Vec(7, 1), Vec(8, 6), Vec(1, 6)]
fence area 38.5, length 24.310
all outside trees within the fence: True
all scene checks done
The fence is a convex polygon with every tree inside or on it, as a hull must be. Its area is a multiple of because all corners have integer coordinates.
Ideas to extend it
- Add
segments_intersect(orientation tests) and use it to check whether a straight path between two trees passes through the house. - Triangulate the house by ear clipping and check that the triangle areas add up to 24.
- Add
scale_about(p, pivot, k)and check that areas scale by . - Replace floats with
Fractioncoordinates where possible, so that every test except those involving rotations is exact.
Test yourself
Why compute the angle between vectors as instead of ?
- acos is not available in Python
- atan2 gives a signed angle (left vs right) and stays accurate near 0° and 180°
- atan2 returns degrees
- It avoids the dot product
The shoelace formula returns −24 for a polygon. What does that tell you?
- The polygon is invalid
- Its area is −24
- Its vertices are in clockwise order; the area is 24
- It is not convex
A ray from a point to the right crosses the polygon's edges 3 times. Where is the point?
- Inside
- Outside
- On an edge
- It cannot be decided