I implemented the intersection of two (convex) polygons in C++. It finds the polygon in the intersection like in this image.
Looking for any and all feedback. I left the logic for line intersection and point containment out.
#include <algorithm>#include <cmath>#include <iostream>#include <optional>using std::atan2;using std::move;using std::optional;using std::vector;using std::sort;struct Point { double x; double y;};struct LineSegment { Point u; Point v;};// Returns the intersection point of l1 and l2 if it exists, nullopt otherwise.// Unimplemented.optional<Point> lineIntersection(const LineSegment& l1, const LineSegment& l2);class Polygon {public: Polygon(const vector<Point>& points) : points_{points} {}; Polygon(const vector<Point>&& points) : points_{move(points)} {}; // Returns true if point is in Polygon, false otherwise. // Unimplemented. bool contains(const Point& point) const; static Polygon intersect(const Polygon& p1, const Polygon& p2) { vector<Point> points; for (size_t i = 0; i < p1.points_.size(); ++i) { // Add points of p1 contained in p2. if (p2.contains(p1.points_[i])) { points.emplace_back(p1.points_[i]); } for (size_t j = 0; j < p2.points_.size(); ++j) { // Add points of intersection. auto intersection = lineIntersection( LineSegment{p1.points_[i], p1.points_[(i+1) % p1.points_.size()]}, LineSegment{p2.points_[j], p2.points_[(j+1) % p2.points_.size()]}); if (intersection != nullopt) { points.emplace_back(move(intersection.value())); } } } // Add points of p2 contained in p1. for (size_t i = 0; i < p2.points_.size(); ++i) { if (p1.contains(p2.points_[i])) { points.emplace_back(p2.points_[i]); } } // Sort into counter-clockwise order. sort(points.begin(), points.end(), [](Point a, Point b){ return atan2(a.y, a.x) > atan2(b.y, b.x); }); return Polygon{points}; }private: vector<Point> points_;};