Here's an algorithm for polygon corner expansion:
-
Determine the direction of the corner: Check the orientation of the two adjacent vertices. If they form a clockwise angle, it's a concave corner; counterclockwise is convex.
-
Calculate the expansion angle: Compute the angle between the two adjacent vertices and the desired rounding radius. For concave corners, simply use this angle; for convex corners, supplement it to 180 degrees.
-
Compute the expansion distance: Multiply the rounding radius by the sine of half the expansion angle. This ensures the correct expansion for both convex and concave corners.
-
Create new points:
- For convex corners: Move outward from the vertex along the angle's direction by the expansion distance, then create a new point.
- For concave corners: Move inward from the vertex along the angle's direction by the expansion distance, and create a new point.
- Handle special cases:
- If the expansion distance exceeds half the rounding radius, use the latter to ensure visible curvature.
- When the convex corner expansion distance is close to zero, slightly extend the original vertex position to avoid clipping.
-
Update the polygon: Replace the original vertex with the new point calculated in step 4.
-
Repeat this process for each vertex of the polygon, adjusting the expansion distance and direction accordingly.
Here's a simple code snippet in Python that demonstrates this algorithm:
import math
def expand_polygon_corners(polygon, rounding_radius):
expanded_polygon = []
for i, (x, y) in enumerate(polygon):
x_prev, y_prev = polygon[(i - 1) % len(polygon)]
x_next, y_next = polygon[(i + 1) % len(polygon)]
# Determine corner direction
is_convex = is_ccw(x_prev, y_prev, x, y, x_next, y_next)
# Calculate expansion angle
angle = math.atan2(y_next - y, x_next - x) - math.atan2(y_prev - y, x_prev - x)
if not is_convex:
angle = 180 - angle # Supplement for concave corners
# Compute expansion distance
expansion_dist = rounding_radius * math.sin(angle / 2)
# Apply bounds on expansion distance
expansion_dist = min(expansion_dist, rounding_radius / 2)
# Calculate new point
if is_convex:
x_new = x + expansion_dist * math.cos(angle)
y_new = y + expansion_dist * math.sin(angle)
else:
x_new = x - expansion_dist * math.cos(angle)
y_new = y - expansion_dist * math.sin(angle)
expanded_polygon.append((x_new, y_new))
return expanded_polygon
def is_ccw(x1, y1, x2, y2, x3, y3):
return (x2 - x1) * (y3 - y1) - (y2 - y1) * (x3 - x1) > 0
# Example polygon
polygon = [(0, 0), (10, 0), (5, 5), (0, 10)]
rounding_radius = 2
expanded_polygon = expand_polygon_corners(polygon, rounding_radius)
print(expanded_polygon)
This algorithm should handle both convex and concave corners, expanding them appropriately while ensuring visible rounding and maintaining the original polygon's shape as intended.