Geometric types: points, vectors, shapes and shared tables
| Problem | Represent points, vectors, lines, planes, polygons, polyhedra and meshes in one to three dimensions so that shapes can share vertices, change coordinate systems and be transformed in place |
| Devised by | René Descartes (1637), coordinates; Hermann Grassmann (1844) and Josiah Willard Gibbs (1881), vector algebra; Bruce Baumgart (1972), shared-vertex boundary representations for computer models |
| Accuracy | Single precision (f32, about seven significant digits) for the primitive types; the algorithms of the other entries work in f64 on plain arrays |
| Cost | per point lookup in a hash table; for a shape with vertices |
| Read first | Nothing beyond the Preliminaries |
| API | concrete (CoordinateVector1D–3D, FreeVector2D–3D, UnitVector1D–3D, Line1D–3D, Plane1D–3D, Triangle2D–3D, PolygonFace2D–3D, Tetrahedron3D, Mesh2D, SurfaceMesh3D, VolumeMesh3D), GeometryTableRegistry, HashGeometryTable, common (ids and traits), coordinate_systems, transformation_traits |
Overview
Before any geometric algorithm can run, shapes must be written down. The simplest way gives each triangle its own three corner points. But a mesh then stores every shared corner several times, and moving one copy tears the surface. Solid modellers and finite-element codes instead keep each point once and describe shapes by referring to points. The library’s primitive types work that way: points live in a keyed table, and lines, triangles, polygons, tetrahedra and meshes hold the ids of their points together with a shared handle to the table. Transforming a shape rewrites its points in the table, so every other shape using those points follows.
A second distinction runs through the types, that between points (positions) and vectors (displacements). A point plus a vector is a point, and two points differ by a vector, but two points cannot be added. The types make that distinction, and also allow coordinates to be held in polar, spherical or cylindrical form.
This entry describes those types. The algorithms in the other entries of this chapter take plain arrays such as [f64; 3] instead, so they can be used on data from anywhere.
Where it is used
Shared geometric types make the geometry chapters interoperable.
- Writing geometry programs. Points, vectors, planes and polygons that behave consistently let you combine intersection, hull and mesh functions without converting between representations.
- Teaching. The distinction between a point and a vector, and the operations each allows, is clearer when the types enforce it.
History
René Descartes’ La Géométrie (1637) turned geometry into algebra with coordinates. Vectors arrived two centuries later, in Hermann Grassmann’s Ausdehnungslehre (1844) and in Josiah Willard Gibbs’s and Oliver Heaviside’s vector analysis of the 1880s, which separated positions from directed magnitudes. Computer representations of solids began in the 1960s and 1970s. Bruce Baumgart’s winged-edge structure (1972) and the boundary representations of CAD systems store each vertex once and build edges and faces on top, the idea used here. The point/vector distinction became standard through affine geometry in graphics, as in Tony DeRose’s “coordinate-free geometric programming” (1989).
The idea
Points and vectors
For each dimension there are three coordinate types.
- A coordinate vector (
CoordinateVector1D,2D,3D) is a position. - A free vector (
FreeVector2D,3D) is a displacement, with no position. - A unit vector (
UnitVector1D,2D,3D) is a direction, normalised on construction.
Adding a free vector to a coordinate vector moves it; dot and cross products are defined where they make sense. Components are f32 (GeometryMeasure). The zero-dimensional layer is the IsPoint trait that every coordinate type implements.
Lines, planes and polygons
A line (Line1D, 2D, 3D) is a pair of point ids, with a length and a direction from its head to its tail. A plane (Plane2D, 3D) is a point and a unit normal; in 2D it is a line used as a mirror, and Plane1D is a mirror point. A triangle (Triangle2D, 3D) holds three point ids, a polygon face (PolygonFace2D, 3D) any number, and a tetrahedron (Tetrahedron3D) four. They report area, perimeter, centroid, normal or orientation, and the tetrahedron its signed volume. A polygon face splits into triangles as a fan from its first vertex, so it should be convex or at least star-shaped from that vertex.
Meshes
A mesh is a list of face ids into a face table. Mesh2D and SurfaceMesh3D are made of polygon faces and report their faces, edges, normals and total area. VolumeMesh3D is a list of tetrahedra. Its volume is the sum of theirs, and its boundary is the set of tetrahedron faces used exactly once. boundary_triangles returns those faces, and surface_mesh turns them into a SurfaceMesh3D in the caller’s tables.
Keyed tables and the registry
A HashGeometryTable maps ids (PointId, LineId, FaceId, TriangleId, TetrahedronId) to primitives. It is shared between shapes through a reference-counted handle, SharedGeometryTable (Rc<RefCell<…>>), so the tables are single-threaded. The GeometryTableRegistry owns one table of each kind and is the usual starting point. Insert points, then build shapes from their ids and the registry’s handles.
Coordinate systems
Each coordinate type records the system its components are in: Cartesian or polar in 2D; Cartesian, spherical with the inclination from , or cylindrical in 3D. The conversions, applied by set_coordinate_system and converted_to, are the usual ones,
with and back. Changing the system converts the stored components. Arithmetic and lengths always use the Cartesian values, so the result does not depend on the system a point happens to be stored in.
Traits and transformations
Capabilities are traits shared across the types: IsLine, IsPolygon, IsTriangle, IsMesh, HasCentroid, HasMeasure and many more, collected in geometric_traits. The transformation traits change a shape in place:
CanTranslatemoves it by the vector of a line;CanRotateturns it about a line’s axis by Rodrigues’ formula;CanMirrorreflects it in a plane, by ;CanShearapplies , with the length of a line.
Algorithm
The geometric types are built in layers, each referring to the one below by identifier.
- Points. Insert the points into the registry’s point table, each under an id of your choosing.
- Composite shapes. Create lines, faces, triangles and tetrahedra by giving the ids of their points and a handle to the table. A shape stores the ids, not copies of the coordinates. If meshes are to refer to these shapes, insert them into their own tables in turn.
- Measuring and transforming. A method such as a length, an area or a volume looks the ids up in the table at the moment it is called, so it always uses the current positions. Moving a point in the table therefore moves every shape that refers to it.
Implementation
/// Rotates a point around an axis using Rodrigues' rotation formula.
pub(crate) fn rotate_point_around_axis(
point: CoordinateVector3D,
origin: CoordinateVector3D,
axis: &impl IsUnitVector,
angle: GeometryMeasure,
) -> CoordinateVector3D {
let axis = FreeVector3D::new(axis[0], axis[1], axis[2]);
let translated = FreeVector3D::new(point.x() - origin.x(), point.y() - origin.y(), point.z() - origin.z());
let axis_components = axis.cartesian_components();
let cos_theta = angle.cos();
let sin_theta = angle.sin();
let cross = FreeVector3D::new(
axis_components[1] * translated.z() - axis_components[2] * translated.y(),
axis_components[2] * translated.x() - axis_components[0] * translated.z(),
axis_components[0] * translated.y() - axis_components[1] * translated.x(),
);
let dot = axis_components[0] * translated.x()
+ axis_components[1] * translated.y()
+ axis_components[2] * translated.z();
let rotated = translated * cos_theta + cross * sin_theta + axis * (dot * (1.0 - cos_theta));
origin + rotated
}
- Every shape resolves its points on demand; a missing id gives
Noneor zero measures rather than a panic. - With the
serdefeature, ids and primitive types can be serialised.
In practice
//! Points, vectors and primitives sharing a keyed point table.
use lib_jsl_geometry::common::{IsGeometryTable, IsGeometryTableBase, PointId, TriangleId};
use lib_jsl_geometry::concrete::{CoordinateVector3D, FreeVector3D, GeometryTableRegistry, Line3D, Plane3D, Triangle3D, UnitVector3D};
use lib_jsl_geometry::coordinate_systems::CoordinateSystem3D;
use lib_jsl_geometry::one_d::IsLine;
use lib_jsl_geometry::transformation_traits::{CanMirror, CanTranslate};
use lib_jsl_geometry::two_d::IsPolygon;
fn main() {
// Points live once, in the registry's point table, and are referred to by id.
let mut registry = GeometryTableRegistry::new();
for (id, p) in [(1, [0.0, 0.0, 0.0]), (2, [2.0, 0.0, 0.0]), (3, [0.0, 1.0, 0.0]), (4, [0.0, 0.0, 3.0])] {
registry.point_table_mut().insert(PointId(id), CoordinateVector3D::new(p[0], p[1], p[2])).unwrap();
}
let points = registry.point_table().clone();
let mut triangle = Triangle3D::new(PointId(1), PointId(2), PointId(3), points.clone());
registry.triangle_table_mut().insert(TriangleId(1), triangle.clone()).unwrap();
let edge = Line3D::new(PointId(1), PointId(2), points.clone());
println!("triangle area {}, perimeter {:.4}, normal {}", triangle.area(), triangle.perimeter(), triangle.normal());
println!("edge length {}", edge.length());
// Moving the triangle moves its points in the shared table, so the edge follows.
let up = Line3D::new(PointId(1), PointId(4), points.clone());
triangle.translate(&up);
println!("after translating by (0, 0, 3): edge from {} to {}", edge.head().unwrap(), edge.tail().unwrap());
triangle.mirror(&Plane3D::new(CoordinateVector3D::new(0.0, 0.0, 1.0), UnitVector3D::new(0.0, 0.0, 1.0)));
println!("after mirroring in z = 1: edge from {} to {}", edge.head().unwrap(), edge.tail().unwrap());
// Coordinates can be held in another system; arithmetic works on the Cartesian values.
let mut p = CoordinateVector3D::new(1.0, 1.0, 1.0);
p.set_coordinate_system(CoordinateSystem3D::Spherical);
println!("(1, 1, 1) in spherical coordinates: {:?}", p.raw_components());
let q = p + FreeVector3D::new(0.0, 0.0, 1.0);
println!("plus (0, 0, 1): Cartesian {:?}", q.cartesian_components());
}
triangle area 1, perimeter 5.2361, normal UnitVector3D(Cartesian, 0, 0, 1)
edge length 2
after translating by (0, 0, 3): edge from CoordinateVector3D(Cartesian, 0, 0, 3) to CoordinateVector3D(Cartesian, 2, 0, 3)
after mirroring in z = 1: edge from CoordinateVector3D(Cartesian, 0, 0, -1) to CoordinateVector3D(Cartesian, 2, 0, -1)
(1, 1, 1) in spherical coordinates: [1.7320508, 0.9553166, 0.7853982]
plus (0, 0, 1): Cartesian [1.0000001, 1.0000001, 2.0]
The edge was never transformed itself, but it shares points 1 and 2 with the triangle, so it moved with it. The spherical round trip shows single precision: .
Strengths
- Shared vertices: shapes stay connected when transformed, and meshes store each point once.
- Explicit points, vectors and unit vectors, and coordinates in polar, spherical or cylindrical form.
Weaknesses
f32components: about seven digits, too few for large coordinates or accumulated transforms.Rc<RefCell>tables are not thread-safe, and the trait-heavy interface is verbose for simple tasks, for which the array-based algorithms are easier.- Polygon triangulation is a fan, correct only for polygons star-shaped from the first vertex.
Exercises
- Explain why adding two points is meaningless but an affine combination with is not.
- Derive the spherical-to-Cartesian conversion and its inverse, and find where the inverse is singular.
- Show that reflection in a plane, , is an isometry with determinant .
- Give a non-convex polygon whose fan triangulation from its first vertex covers area outside the polygon.
- Show that the boundary of a tetrahedral mesh is the set of faces belonging to exactly one tetrahedron.
Hints and answers
- Adding two points has no meaning as it depends on the origin (translation changes the sum), whereas an affine combination with weights summing to 1 is independent of the origin, since the translation contributes .
- , , ; inversely , , . The inverse is singular at the origin (, undefined) and on the -axis ( undefined).
- The reflection is , with (an isometry) and (one eigenvalue ).
- A polygon with a reflex vertex such as an arrow-head: the fan from a vertex that cannot see all other vertices contains a triangle that lies partly outside the polygon.
- Each interior triangular face is shared by exactly two tetrahedra, while a boundary face belongs to only one; so counting the tetrahedra per face identifies the boundary.
Further reading
- T. DeRose, “A coordinate-free approach to geometric programming”, in Math for SIGGRAPH, SIGGRAPH Course Notes, 1989.
- B. G. Baumgart, “Winged edge polyhedron representation”, Stanford Artificial Intelligence Laboratory report AIM-179, 1972.
- P. J. Schneider and D. H. Eberly, Geometric Tools for Computer Graphics, Morgan Kaufmann, 2003, chapters 2–3.
- M. Mäntylä, An Introduction to Solid Modeling, Computer Science Press, 1988.