adze/chop/voxel.py

89 lines
2.5 KiB
Python

from typing import Tuple
import numpy
from . import poly_t, plane_t
from .split import split
from .moments import get_moments, number_of_moments
try:
# Check if running with line_profiler
profile
except NameError:
def profile(f):
return f
@profile
def voxelize(poly: poly_t,
d: numpy.ndarray,
box: numpy.ndarray = None,
order: int = 0
) -> numpy.ndarray:
'''
Voxelize a Schelegel-representation polyhedron
'''
box = get_box(poly, d) if box is None else numpy.array(box, dtype=int)
d = numpy.array(d)
grid_shape = box[1] - box[0]
dest_grid = numpy.zeros((*grid_shape, number_of_moments(order)), dtype=float)
if poly is None or poly['vertices'].shape[0] == 0 or (grid_shape <= 0).any():
return dest_grid
# Stack-based recursive split
stack = [(poly, box)]
while stack:
c_poly, c_box = stack.pop()
# Base case 1: moments are 0 for this region
if c_poly['vertices'].shape[0] == 0:
continue
box_size = c_box[1] - c_box[0]
split_axis = box_size.argmax()
max_dist = box_size[split_axis]
# Base case 2: calculate moments for single voxel
if max_dist == 1:
moments = get_moments(c_poly, order)
offset = (c_box[0] - box[0])
dest_grid[offset[0], offset[1], offset[2], :] += moments
continue
# Recursion case: split along longest side
n = numpy.zeros(3)
n[split_axis] = -1
split_ind = c_box[0][split_axis] + max_dist // 2
plane = (n, d[split_axis] * split_ind)
children = split(c_poly, plane)
split_plane = c_box.copy()
split_plane[:, split_axis] = split_ind
stack.append((children[0], numpy.vstack((c_box[0], split_plane[1])) ))
stack.append((children[1], numpy.vstack((split_plane[0], c_box[1])) ))
return dest_grid
def get_box(poly: poly_t, d: numpy.ndarray) -> numpy.ndarray:
min_box = numpy.floor(numpy.min(poly['vertices'], axis=0) / d)
max_box = numpy.ceil(numpy.max(poly['vertices'], axis=0) / d)
return numpy.array((min_box, max_box), dtype=int)
def clamp_box(poly: poly_t,
box: numpy.ndarray,
clampbox: numpy.ndarray,
d: numpy.ndarray
) -> Tuple[poly_t, numpy.ndarray]:
faces = box_faces_from_verts(clampbox)
for face in faces:
poly = clip(poly, face)
box = get_box(poly, d)
return poly, box