Just | 470b505 | 2000-01-16 20:37:11 +0000 | [diff] [blame] | 1 | # |
Just | deb3b63 | 2000-01-26 19:32:45 +0000 | [diff] [blame] | 2 | # Various array and rectangle tools |
Just | 470b505 | 2000-01-16 20:37:11 +0000 | [diff] [blame] | 3 | # |
| 4 | |
| 5 | import Numeric |
| 6 | |
| 7 | |
| 8 | def calcBounds(array): |
| 9 | """Calculate the bounding rectangle of a 2D array. |
| 10 | Returns a 4-tuple: |
| 11 | smallest x, smallest y, largest x, largest y. |
| 12 | """ |
| 13 | if len(array) == 0: |
| 14 | return 0, 0, 0, 0 |
| 15 | xmin, ymin = Numeric.minimum.reduce(array) |
| 16 | xmax, ymax = Numeric.maximum.reduce(array) |
| 17 | return xmin, ymin, xmax, ymax |
| 18 | |
Just | 470b505 | 2000-01-16 20:37:11 +0000 | [diff] [blame] | 19 | def pointsInRect(array, rect): |
| 20 | """Find out which points or array are inside rect. |
| 21 | Returns an array with a boolean for each point. |
| 22 | """ |
| 23 | if len(array) < 1: |
| 24 | return [] |
| 25 | lefttop = rect[:2] |
| 26 | rightbottom = rect[2:] |
| 27 | condition = Numeric.logical_and( |
| 28 | Numeric.greater(array, lefttop), |
| 29 | Numeric.less(array, rightbottom)) |
| 30 | return Numeric.logical_and.reduce(condition, -1) |
| 31 | |
Just | deb3b63 | 2000-01-26 19:32:45 +0000 | [diff] [blame] | 32 | def vectorLength(vector): |
| 33 | return Numeric.sqrt(vector[0]**2 + vector[1]**2) |
| 34 | |
| 35 | def asInt16(array): |
| 36 | "Round and cast to 16 bit integer." |
| 37 | return Numeric.floor(array + 0.5).astype(Numeric.Int16) |
| 38 | |
Just | 470b505 | 2000-01-16 20:37:11 +0000 | [diff] [blame] | 39 | |
| 40 | def normRect((l, t, r, b)): |
| 41 | """XXX doc""" |
| 42 | return min(l, r), min(t, b), max(l, r), max(t, b) |
| 43 | |
| 44 | def scaleRect((l, t, r, b), x, y): |
| 45 | return l * x, t * y, r * x, b * y |
| 46 | |
| 47 | def offsetRect((l, t, r, b), dx, dy): |
| 48 | return l+dx, t+dy, r+dx, b+dy |
Just | be7163c | 2000-01-18 22:29:39 +0000 | [diff] [blame] | 49 | |
| 50 | def insetRect((l, t, r, b), dx, dy): |
| 51 | return l+dx, t+dy, r-dx, b-dy |
| 52 | |
| 53 | def sectRect((l1, t1, r1, b1), (l2, t2, r2, b2)): |
| 54 | l, t, r, b = max(l1, l2), max(t1, t2), min(r1, r2), min(b1, b2) |
| 55 | if l >= r or t >= b: |
| 56 | return 0, (0, 0, 0, 0) |
| 57 | return 1, (l, t, r, b) |
| 58 | |
Just | 02a739a | 2000-01-23 19:10:27 +0000 | [diff] [blame] | 59 | def unionRect((l1, t1, r1, b1), (l2, t2, r2, b2)): |
| 60 | l, t, r, b = min(l1, l2), min(t1, t2), max(r1, r2), max(b1, b2) |
| 61 | return (l, t, r, b) |
| 62 | |
| 63 | def rectCenter((l, t, r, b)): |
| 64 | return (l+r)/2, (t+b)/2 |
| 65 | |
Just | b3026ba | 2000-01-22 00:26:07 +0000 | [diff] [blame] | 66 | def intRect(rect): |
| 67 | rect = Numeric.array(rect) |
| 68 | l, t = Numeric.floor(rect[:2]) |
| 69 | r, b = Numeric.ceil(rect[2:]) |
| 70 | return tuple(Numeric.array((l, t, r, b)).astype(Numeric.Int)) |
Just | be7163c | 2000-01-18 22:29:39 +0000 | [diff] [blame] | 71 | |