Skip to content

Commit cb8c058

Browse files
committed
implementation of contains() in PShape same as in Java mode
1 parent ec42203 commit cb8c058

File tree

1 file changed

+32
-6
lines changed

1 file changed

+32
-6
lines changed

core/src/processing/core/PShape.java

Lines changed: 32 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -2822,22 +2822,48 @@ public boolean isClosed() {
28222822
// . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
28232823

28242824

2825-
// http://www.ecse.rpi.edu/Homepages/wrf/Research/Short_Notes/pnpoly.html
2825+
/**
2826+
* Return true if this x, y coordinate is part of this shape. Only works
2827+
* with PATH shapes or GROUP shapes that contain other GROUPs or PATHs.
2828+
*/
28262829
public boolean contains(float x, float y) {
28272830
if (family == PATH) {
2831+
PVector p = new PVector(x, y);
2832+
if (matrix != null) {
2833+
// apply the inverse transformation matrix to the point coordinates
2834+
PMatrix inverseCoords = matrix.get();
2835+
// TODO why is this called twice? [fry 190724]
2836+
// commit was https://github.com/processing/processing/commit/027fc7a4f8e8d0a435366eae754304eea282512a
2837+
inverseCoords.invert(); // maybe cache this?
2838+
inverseCoords.invert(); // maybe cache this?
2839+
inverseCoords.mult(new PVector(x, y), p);
2840+
}
2841+
2842+
// http://www.ecse.rpi.edu/Homepages/wrf/Research/Short_Notes/pnpoly.html
28282843
boolean c = false;
28292844
for (int i = 0, j = vertexCount-1; i < vertexCount; j = i++) {
2830-
if (((vertices[i][Y] > y) != (vertices[j][Y] > y)) &&
2831-
(x <
2845+
if (((vertices[i][Y] > p.y) != (vertices[j][Y] > p.y)) &&
2846+
(p.x <
28322847
(vertices[j][X]-vertices[i][X]) *
2833-
(y-vertices[i][Y]) /
2834-
(vertices[j][1]-vertices[i][Y]) +
2835-
vertices[i][X])) {
2848+
(y-vertices[i][Y]) /
2849+
(vertices[j][1]-vertices[i][Y]) +
2850+
vertices[i][X])) {
28362851
c = !c;
28372852
}
28382853
}
28392854
return c;
2855+
2856+
} else if (family == GROUP) {
2857+
// If this is a group, loop through children until we find one that
2858+
// contains the supplied coordinates. If a child does not support
2859+
// contains() throw a warning and continue.
2860+
for (int i = 0; i < childCount; i++) {
2861+
if (children[i].contains(x, y)) return true;
2862+
}
2863+
return false;
2864+
28402865
} else {
2866+
// https://github.com/processing/processing/issues/1280
28412867
throw new IllegalArgumentException("The contains() method is only implemented for paths.");
28422868
}
28432869
}

0 commit comments

Comments
 (0)