|
| 1 | +import numpy as np |
| 2 | +import matplotlib.transforms as mtransforms |
| 3 | + |
| 4 | + |
| 5 | +# These transforms break the assumption that the last row is [0, 0, 0, 1], and is |
| 6 | +# therefore not affine. However, this is required to preserve the order that |
| 7 | +# transforms are performed |
| 8 | +class NonAffine3D(mtransforms.Affine3D): |
| 9 | + pass |
| 10 | + |
| 11 | + |
| 12 | +class WorldTransform(mtransforms.Affine3D): |
| 13 | + def __init__(self, xmin, xmax, ymin, ymax, zmin, zmax, pb_aspect=None): |
| 14 | + dx = xmax - xmin |
| 15 | + dy = ymax - ymin |
| 16 | + dz = zmax - zmin |
| 17 | + if pb_aspect is not None: |
| 18 | + ax, ay, az = pb_aspect |
| 19 | + dx /= ax |
| 20 | + dy /= ay |
| 21 | + dz /= az |
| 22 | + mtx = np.array([ |
| 23 | + [1/dx, 0, 0, -xmin/dx], |
| 24 | + [0, 1/dy, 0, -ymin/dy], |
| 25 | + [0, 0, 1/dz, -zmin/dz], |
| 26 | + [0, 0, 0, 1] |
| 27 | + ]) |
| 28 | + super().__init__(matrix=mtx) |
| 29 | + |
| 30 | + |
| 31 | +class PerspectiveTransform(NonAffine3D): |
| 32 | + def __init__(self, zfront, zback, focal_length): |
| 33 | + e = focal_length |
| 34 | + a = 1 |
| 35 | + b = (zfront + zback) / (zfront - zback) |
| 36 | + c = -2 * (zfront * zback) / (zfront - zback) |
| 37 | + mtx = np.array([[e, 0, 0, 0], |
| 38 | + [0, e/a, 0, 0], |
| 39 | + [0, 0, b, c], |
| 40 | + [0, 0, -1, 0]]) |
| 41 | + super().__init__(matrix=mtx) |
| 42 | + |
| 43 | + |
| 44 | +class OrthographicTransform(NonAffine3D): |
| 45 | + def __init__(self, zfront, zback): |
| 46 | + a = -(zfront + zback) |
| 47 | + b = -(zfront - zback) |
| 48 | + mtx = np.array([[2, 0, 0, 0], |
| 49 | + [0, 2, 0, 0], |
| 50 | + [0, 0, -2, 0], |
| 51 | + [0, 0, a, b]]) |
| 52 | + super().__init__(matrix=mtx) |
| 53 | + |
| 54 | + |
| 55 | +class ViewTransform(mtransforms.Affine3D): |
| 56 | + def __init__(self, u, v, w, E): |
| 57 | + """ |
| 58 | + Return the view transformation matrix. |
| 59 | +
|
| 60 | + Parameters |
| 61 | + ---------- |
| 62 | + u : 3-element numpy array |
| 63 | + Unit vector pointing towards the right of the screen. |
| 64 | + v : 3-element numpy array |
| 65 | + Unit vector pointing towards the top of the screen. |
| 66 | + w : 3-element numpy array |
| 67 | + Unit vector pointing out of the screen. |
| 68 | + E : 3-element numpy array |
| 69 | + The coordinates of the eye/camera. |
| 70 | + """ |
| 71 | + self._u = u |
| 72 | + self._v = v |
| 73 | + self._w = w |
| 74 | + |
| 75 | + Mr = np.eye(4) |
| 76 | + Mt = np.eye(4) |
| 77 | + Mr[:3, :3] = [u, v, w] |
| 78 | + Mt[:3, -1] = -E |
| 79 | + mtx = np.dot(Mr, Mt) |
| 80 | + super().__init__(matrix=mtx) |
0 commit comments