blob: 393eafd7692da08424dad18ea8fcc5ddc354d48c [file] [log] [blame]
Guido van Rossumc6360141990-10-13 19:23:40 +00001# 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#
10error = 'rect.error'
11
12
13# The empty rectangle.
14#
15empty = (0, 0), (0, 0)
16
17
18# Check if a rectangle is empty.
19#
Guido van Rossume7113b61993-03-29 11:30:50 +000020def is_empty(r):
21 (left, top), (right, bottom) = r
Guido van Rossumc6360141990-10-13 19:23:40 +000022 return left >= right or top >= bottom
23
24
25# Compute the intersection or two or more rectangles.
26# This works with a list or tuple argument.
27#
28def intersect(list):
29 if not list: raise error, 'intersect called with empty list'
30 if is_empty(list[0]): return empty
31 (left, top), (right, bottom) = list[0]
32 for rect in list[1:]:
Guido van Rossum124eb941990-10-26 13:44:32 +000033 if is_empty(rect):
34 return empty
35 (l, t), (r, b) = rect
36 if left < l: left = l
37 if top < t: top = t
38 if right > r: right = r
39 if bottom > b: bottom = b
Guido van Rossume7113b61993-03-29 11:30:50 +000040 if is_empty(((left, top), (right, bottom))):
Guido van Rossum124eb941990-10-26 13:44:32 +000041 return empty
Guido van Rossumc6360141990-10-13 19:23:40 +000042 return (left, top), (right, bottom)
43
44
45# Compute the smallest rectangle containing all given rectangles.
46# This works with a list or tuple argument.
47#
48def union(list):
Sjoerd Mullender4fddf331993-08-25 14:09:01 +000049 (left, top), (right, bottom) = list[0]
Guido van Rossumc6360141990-10-13 19:23:40 +000050 for (l, t), (r, b) in list[1:]:
Guido van Rossume7113b61993-03-29 11:30:50 +000051 if not is_empty(((l, t), (r, b))):
Guido van Rossumc6360141990-10-13 19:23:40 +000052 if l < left: left = l
53 if t < top: top = t
54 if r > right: right = r
55 if b > bottom: bottom = b
56 res = (left, top), (right, bottom)
57 if is_empty(res):
58 return empty
59 return res
60
61
62# Check if a point is in a rectangle.
63#
64def pointinrect((h, v), ((left, top), (right, bottom))):
65 return left <= h < right and top <= v < bottom
66
67
68# Return a rectangle that is dh, dv inside another
69#
70def inset(((left, top), (right, bottom)), (dh, dv)):
71 left = left + dh
72 top = top + dv
73 right = right - dh
74 bottom = bottom - dv
75 r = (left, top), (right, bottom)
76 if is_empty(r):
77 return empty
78 else:
79 return r
80
81
82# Conversions between rectangles and 'geometry tuples',
83# given as origin (h, v) and dimensions (width, height).
84#
85def rect2geom((left, top), (right, bottom)):
86 return (left, top), (right-left, bottom-top)
87
88def geom2rect((h, v), (width, height)):
89 return (h, v), (h+width, v+height)