distancePointToPolygon function
Requirements.Utilities.distancePointToPolygon
· source
Return minimum distance between a point and a polygon
Extends Modelica.Icons.Function
Syntax
(distance, polygonPoint) = distancePointToPolygon(polygon, point);
Description
This function computes the minimum distance of a point to a polygon.
The polygon is defined by a set of points polygon[:,2], where polygon[i,1] is the x-coordinate of polygon point i and polygon[i,2] is the y-coordinate. The last point of the polygon can be identical to the first point, so polygon[1,:] = polygon[end,:]. If this is not the case, the function assumes that the last point polygon[end,:] is connected implicitely to the first point polygon[1,:].
The goal is to compute the minimum distance of the vector input point to polygon, where point[1] is the x-coordinate and point[2] the y-coordinate.
The function returns the minimum distance as distance.
If distance > 0, then point is inside of the polygon.
If distance < 0, then point is outside of the polygon.
If distance = 0, then point is on the polygon.
Furthermore, the point polygonPoint[2] is returned, which is a point
on polygon (either on an edge or a vertex of the polygon)
that is closest to input argument point.
Algorithm
For every edge from polygon[i,:] to polygon[i+1,:] (and from the last point back to the first) the
closest point on the edge is p1 + lambda*(p2 - p1), with lambda the projection of
point - p1 onto the edge, limited to 0 ≤ lambda ≤ 1 (an edge whose squared length is below
100*Modelica.Constants.eps is treated as the point p1). The least of these distances is returned, with its sign
taken from isInsidePolygon, which reports a
point on the polygon as inside, so its distance is +0 (it was -0 on some edges before 2026-12-03). The polygon needs at
least 2 points (assert). The polygon need not be convex; for a self-intersecting polygon the sign follows
the even-odd rule of isInsidePolygon.
Use
The signed distance is the margin of the region checks of the library: ChecksInFixedWindow.WithinDomain (a point of two signals inside a polygonal domain) and LinearAnalysis.regionMargins, used by LinearAnalysis.EigenvaluesWithinRegion (every eigenvalue inside a polygon of the complex plane).
Revisions
2026-12-03, Model Based Innovation LLC: a point on the polygon gets distance +0 on every edge (isInsidePolygon reports it as inside).
Inputs
| Name | Type | Description |
|---|---|---|
polygon[…] input | Real | Polygon points (x,y) |
point[…] input | Real | Point inside, outside or on polygon |
Outputs
| Name | Type | Description |
|---|---|---|
distance output | Real | Minimum distance of point to polygon |
polygonPoint[…] output | Real | Point on polygon that is closest to point |