Guido van Rossum | c636014 | 1990-10-13 19:23:40 +0000 | [diff] [blame] | 1 | # Module 'rect'. |
| 2 | # |
| 3 | # Operations on rectangles. |
| 4 | # There is some normalization: all results return the object 'empty' |
| 5 | # if their result would contain no points. |
| 6 | |
| 7 | |
| 8 | # Exception. |
| 9 | # |
| 10 | error = 'rect.error' |
| 11 | |
| 12 | |
| 13 | # The empty rectangle. |
| 14 | # |
| 15 | empty = (0, 0), (0, 0) |
| 16 | |
| 17 | |
| 18 | # Check if a rectangle is empty. |
| 19 | # |
| 20 | def is_empty((left, top), (right, bottom)): |
| 21 | return left >= right or top >= bottom |
| 22 | |
| 23 | |
| 24 | # Compute the intersection or two or more rectangles. |
| 25 | # This works with a list or tuple argument. |
| 26 | # |
| 27 | def intersect(list): |
| 28 | if not list: raise error, 'intersect called with empty list' |
| 29 | if is_empty(list[0]): return empty |
| 30 | (left, top), (right, bottom) = list[0] |
| 31 | for rect in list[1:]: |
| 32 | if not is_empty(rect): |
| 33 | (l, t), (r, b) = rect |
| 34 | if left < l: left = l |
| 35 | if top < t: top = t |
| 36 | if right > r: right = r |
| 37 | if bottom > b: bottom = b |
| 38 | if is_empty((left, top), (right, bottom)): |
| 39 | return empty |
| 40 | return (left, top), (right, bottom) |
| 41 | |
| 42 | |
| 43 | # Compute the smallest rectangle containing all given rectangles. |
| 44 | # This works with a list or tuple argument. |
| 45 | # |
| 46 | def union(list): |
| 47 | (left, top), (right, bottom) = empty |
| 48 | for (l, t), (r, b) in list[1:]: |
| 49 | if not is_empty((l, t), (r, b)): |
| 50 | if l < left: left = l |
| 51 | if t < top: top = t |
| 52 | if r > right: right = r |
| 53 | if b > bottom: bottom = b |
| 54 | res = (left, top), (right, bottom) |
| 55 | if is_empty(res): |
| 56 | return empty |
| 57 | return res |
| 58 | |
| 59 | |
| 60 | # Check if a point is in a rectangle. |
| 61 | # |
| 62 | def pointinrect((h, v), ((left, top), (right, bottom))): |
| 63 | return left <= h < right and top <= v < bottom |
| 64 | |
| 65 | |
| 66 | # Return a rectangle that is dh, dv inside another |
| 67 | # |
| 68 | def inset(((left, top), (right, bottom)), (dh, dv)): |
| 69 | left = left + dh |
| 70 | top = top + dv |
| 71 | right = right - dh |
| 72 | bottom = bottom - dv |
| 73 | r = (left, top), (right, bottom) |
| 74 | if is_empty(r): |
| 75 | return empty |
| 76 | else: |
| 77 | return r |
| 78 | |
| 79 | |
| 80 | # Conversions between rectangles and 'geometry tuples', |
| 81 | # given as origin (h, v) and dimensions (width, height). |
| 82 | # |
| 83 | def rect2geom((left, top), (right, bottom)): |
| 84 | return (left, top), (right-left, bottom-top) |
| 85 | |
| 86 | def geom2rect((h, v), (width, height)): |
| 87 | return (h, v), (h+width, v+height) |