Last active
February 13, 2017 20:53
-
-
Save daseyb/b51f541fb7d3418ad5365ece9aefebc5 to your computer and use it in GitHub Desktop.
Basic Polygon Offsetting
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Vec2d orthogonal(Vec2d val) { | |
return {-val.y, val.x}; | |
} | |
Vec2d calculateBisector(Vec2d prev, Vec2d curr, Vec2d next) { | |
auto nextDir = (next - curr).normalized(); | |
auto prevDir = (prev - curr).normalized(); | |
Vec3d bisector = (nextDir + prevDir); | |
Vec2d norm = orthogonal(nextDir); | |
// If prev, curr and next are colinear | |
if (bisector.norm() < 0.00001) { | |
// bisector is orthogonal to incoming/outgoing edge | |
bisector = norm; | |
} else { | |
// Otherwise make bisector always points in the right direction. | |
bisector *= sign(Vec2d::dot(norm, bisector)); | |
} | |
bisector.normalize(); | |
return bisector; | |
} | |
bool offsetPolygon(const std::vector<Vec2d>& in, double distance, std::vector<Vec2d>& out) { | |
for (int i = 0; i < in.points().size(); i++) { | |
int prevIndex = i == 0 ? in.points().size() - 2 : i - 1; | |
int nextIndex = (i + 1) % in.points().size(); | |
auto curr = in[i]; | |
auto next = in[nextIndex]; | |
auto prev = in[prevIndex]; | |
Vec2d bisector = calculateBisector(prev, curr, next, up); | |
Vec2d nextEdgeDir = (next - curr).normalized(); | |
double edgeDot = Vec2d::dot(nextEdgeDir, bisector); | |
double edgeFactor = 1.0/sqrt(1.0 - edgeDot * edgeDot); | |
auto offsetPoint = curr + bisector * edgeFactor; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment