How to return the coordinates of the respective 3 vertexes of a DelaunayMesh's face?
Finding the correct triangle is a very delicate business. See for example:
pts1 = BlockRandom[SeedRandom[1]; RandomReal[1, {30, 2}]];
R = DelaunayMesh[pts1];
redPt = {0.68, 0.75};
idx = Nearest[MeshCoordinates[R] -> Automatic, redPt, 3];
r = Max@Nearest[MeshCoordinates[R] -> "Distance", redPt, 3];
i = Position[Through[(RegionMember /@ MeshPrimitives[R, 2])[redPt]],
True][[1, 1]];
Show[
HighlightMesh[R, Join[Thread[{0, idx}], {{2, i}}]],
Graphics[{
Red, Point@redPt,
Circle[redPt, r]
}],
PlotRange -> All
]
Fortunately, there seems to be a built-in but undocumented function for this task:
j = Region`Mesh`MeshNearestCellIndex[R, redPt];
MeshPrimitives[R, j]
Show[
HighlightMesh[R, j],
Graphics[{Red, Point[redPt]}]
]
Polygon[{{0.925275, 0.578056}, {0.767697, 0.973336}, {0.544772, 0.562659}}]
Update: As noted by Henrik and Rahul the original answer is not the correct approach. An alternative method that gives the correct polygon containing redPt
is based on using Graphics`PolygonUtils`InPolygonQ
:
ClearAll[f]
f[r_, p_] := Pick[#, Graphics`PolygonUtils`InPolygonQ[#, p] & /@ #] &@
MeshPrimitives[r, 2];
Show[plot1,
Graphics[{PointSize[Large], Point@redPt, Opacity[.5, Red], f[plot1, redPt]}]]
To get the coordinates, use
f[plot1, redPt][[1, 1]]
{{0.67033, 0.84245}, {0.620283, 0.648944}, {0.829905, 0.700287}}
Using Henrik's example (R
):
Show[R, Graphics[{PointSize[Large], Point@redPt, Opacity[.5, Red], f[R, redPt]}]]
Original (incorrect) answer:
Nearest[MeshCoordinates[plot1], redPts, 3]