Skip to content

Commit b2c1cde

Browse files
authored
Merge pull request #1938 from itzpr3d4t0r/rect_clip_simplification+
simplified pg_rect_clip
2 parents b3f2781 + 4eb0e6b commit b2c1cde

File tree

2 files changed

+10
-36
lines changed

2 files changed

+10
-36
lines changed

src_c/rect.c

Lines changed: 6 additions & 36 deletions
Original file line numberDiff line numberDiff line change
@@ -1105,46 +1105,16 @@ pg_rect_clip(pgRectObject *self, PyObject *args)
11051105
return RAISE(PyExc_TypeError, "Argument must be rect style object");
11061106
}
11071107

1108-
/* Left */
1109-
if ((A->x >= B->x) && (A->x < (B->x + B->w))) {
1110-
x = A->x;
1111-
}
1112-
else if ((B->x >= A->x) && (B->x < (A->x + A->w)))
1113-
x = B->x;
1114-
else
1115-
goto nointersect;
1116-
1117-
/* Right */
1118-
if (((A->x + A->w) > B->x) && ((A->x + A->w) <= (B->x + B->w))) {
1119-
w = (A->x + A->w) - x;
1120-
}
1121-
else if (((B->x + B->w) > A->x) && ((B->x + B->w) <= (A->x + A->w)))
1122-
w = (B->x + B->w) - x;
1123-
else
1124-
goto nointersect;
1108+
x = MAX(A->x, B->x);
1109+
y = MAX(A->y, B->y);
1110+
w = MIN(A->x + A->w, B->x + B->w) - x;
1111+
h = MIN(A->y + A->h, B->y + B->h) - y;
11251112

1126-
/* Top */
1127-
if ((A->y >= B->y) && (A->y < (B->y + B->h))) {
1128-
y = A->y;
1113+
if (w <= 0 || h <= 0) {
1114+
return _pg_rect_subtype_new4(Py_TYPE(self), A->x, A->y, 0, 0);
11291115
}
1130-
else if ((B->y >= A->y) && (B->y < (A->y + A->h)))
1131-
y = B->y;
1132-
else
1133-
goto nointersect;
1134-
1135-
/* Bottom */
1136-
if (((A->y + A->h) > B->y) && ((A->y + A->h) <= (B->y + B->h))) {
1137-
h = (A->y + A->h) - y;
1138-
}
1139-
else if (((B->y + B->h) > A->y) && ((B->y + B->h) <= (A->y + A->h)))
1140-
h = (B->y + B->h) - y;
1141-
else
1142-
goto nointersect;
11431116

11441117
return _pg_rect_subtype_new4(Py_TYPE(self), x, y, w, h);
1145-
1146-
nointersect:
1147-
return _pg_rect_subtype_new4(Py_TYPE(self), A->x, A->y, 0, 0);
11481118
}
11491119

11501120
/* clipline() - crops the given line within the rect

test/rect_test.py

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -847,6 +847,10 @@ def test_clip(self):
847847
self.assertEqual(
848848
r1, r1.clip(Rect(r1)), "r1 does not clip an identical rect to itself"
849849
)
850+
self.assertEqual(Rect(1, 2, 0, 0), r1.clip(Rect(3, 0, 2, 2)))
851+
self.assertEqual(Rect(1, 2, 0, 0), r1.clip(Rect(3, 8, 2, 2)))
852+
self.assertEqual(Rect(1, 2, 0, 0), r1.clip(Rect(-2, 8, 2, 2)))
853+
self.assertEqual(Rect(1, 2, 0, 0), r1.clip(Rect(-2, 0, 2, 2)))
850854

851855
def test_clipline(self):
852856
"""Ensures clipline handles four int parameters.

0 commit comments

Comments
 (0)