Skip to content

Commit

Permalink
Avoid the use of stride tricks to make code more readable (#89)
Browse files Browse the repository at this point in the history
Admittedly this is a style issue, but I feel like stridetricks isn't
very useful in this particular case and it somewhat destroys readability
for me.

While the reshaping is cute, I honestly don't think it helps much with
the python overhead.

I hit this code in trying to implment frustum culling for my application
(though I still haven't succeeded in getting a performance improvement).

Let me know what you think.

I think there is also some complexity in the code due to an attempt at
making it generaizable to beyond a single "aabb" object.

However, I didn't see any tests for this, and so my presumption is that
this is problem and likely the cause of much of the original code
compelxity.
  • Loading branch information
hmaarrfk authored Dec 25, 2024
1 parent c7138c9 commit 4015b5c
Showing 1 changed file with 18 additions and 26 deletions.
44 changes: 18 additions & 26 deletions pylinalg/misc.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
import numpy as np
from numpy.lib.stride_tricks import as_strided


def aabb_to_sphere(aabb, /, *, out=None, dtype=None):
Expand Down Expand Up @@ -73,32 +72,25 @@ def aabb_transform(aabb, matrix, /, *, out=None, dtype=None):
if out is None:
out = np.empty_like(aabb, dtype=dtype)

corners = np.empty((*aabb.shape[:-2], 8, 4), dtype=float)
corners[...] = [1, 2, 3, 4]
size = corners.itemsize

corners_x = as_strided(
corners[..., 0],
shape=(*corners.shape[:-2], 4, 2),
strides=(*corners.strides[:-2], 8 * size, 4 * size),
)
corners_x[:] = aabb[..., :, 0]

corners_y = as_strided(
corners[..., 1],
shape=(*corners.shape[:-2], 2, 2, 2),
strides=(*corners.strides[:-2], 16 * size, 4 * size, 8 * size),
corners = np.full(
aabb.shape[:-2] + (8, 4),
# Fill value of 1 is used for homogeneous coordinates.
fill_value=1.0,
dtype=float,
)
corners_y[:] = aabb[..., :, 1]

corners_z = as_strided(
corners[..., 2],
shape=(*corners.shape[:-2], 4, 2),
strides=(*corners.strides[:-2], 4 * size, 16 * size),
)
corners_z[:] = aabb[..., :, 2]

corners[..., 3] = 1
# x
corners[..., 0::2, 0] = aabb[..., 0, 0]
corners[..., 1::2, 0] = aabb[..., 1, 0]

# y
corners[..., 0::4, 1] = aabb[..., 0, 1]
corners[..., 1::4, 1] = aabb[..., 0, 1]
corners[..., 2::4, 1] = aabb[..., 1, 1]
corners[..., 3::4, 1] = aabb[..., 1, 1]

# z
corners[..., 0:4, 2] = aabb[..., 0, 2]
corners[..., 4:8, 2] = aabb[..., 1, 2]

corners = corners @ matrix
out[..., 0, :] = np.min(corners[..., :-1], axis=-2)
Expand Down

0 comments on commit 4015b5c

Please sign in to comment.