Andrew's Monotone Chain and Incremental Construction for 2D and 3D Convex Hulls
Convex hulls are workhorse geometry primitives for collision detection, bounding-volume generation, and model simplification. Having a clean, numerically stable implementation of both the 2D monotone chain and the 3D incremental method means an engineer can drop them into a physics engine or mesh tool without debugging edge-case orientation bugs.
Two foundational convex hull algorithms get a direct, code-forward treatment. For 2D point sets, Andrew's Monotone Chain sorts by x-coordinate, then walks left-to-right for the lower hull and right-to-left for the upper hull, discarding points that break convexity via cross-product checks. The result is a numerically stable O(n log n) implementation that avoids the polar-angle pitfalls of Graham Scan.
The 3D approach switches to incremental construction. It first finds the four points that maximize tetrahedron volume, builds outward-facing triangular faces, then processes every remaining point. For each point outside the current hull, the algorithm identifies visible faces, extracts the horizon edges where visible and invisible faces meet, deletes the visible faces, and stitches new triangles from the horizon to the point. A final outward-normal pass keeps all face orientations consistent.
Both implementations are shown in full TypeScript, with helper functions for cross products, orientation tests, deduplication, and centroid calculation. The 3D code includes a validation routine that checks every vertex lies inside or on every face.
Andrew's Monotone Chain is preferred in production graphics code over Graham Scan specifically because coordinate sorting sidesteps the floating-point instability of polar-angle comparisons.
The 3D incremental algorithm's use of a maximum-volume initial tetrahedron is a practical heuristic that reduces the chance of degenerate starting configurations, though the code still guards against collinear and coplanar point sets.
Tracking face visibility via a sorted vertex-ID key rather than geometric hashing is a robust pattern that avoids floating-point equality checks when identifying shared edges and faces.