"""GPU voxel -> SDF pipeline for run_strand2surface (CuPy / CUDA). Mirrors the CPU ``rasterise -> interior-fill -> EDT-SDF -> Gaussian-smooth`` path, but runs the dense regular-grid work on the GPU. Returns a host (NumPy) SDF so marching cubes + remeshing continue on the CPU unchanged. These stages are the part that scales with voxel count (the two Euclidean distance transforms dominate as ``radius`` shrinks), and they map almost 1:1 onto ``cupyx.scipy.ndimage`` -- which is why CuPy beats hand-written kernels here. The isotropic remesh is *not* here: it is serial topological editing and does not belong on the GPU. """ from __future__ import annotations import numpy as np def cupy_available() -> bool: """True if CuPy imports and a CUDA device is visible.""" try: import cupy as cp return cp.cuda.runtime.getDeviceCount() > 0 except Exception: # noqa: BLE001 - any failure means "no usable GPU" return False def _rasterise_gpu(cp, strands, bbox_min, voxel_size, grid_dims): """Boolean occupancy grid from strand polylines, on the GPU. Same bucket-by-step-count DDA as the CPU path: every voxel along every edge is visited so no voxel is skipped. Setting True is idempotent, so the scattered writes need no atomics. """ gx, gy, gz = int(grid_dims[0]), int(grid_dims[1]), int(grid_dims[2]) occ = cp.zeros((gx, gy, gz), dtype=cp.bool_) inv_vs = 1.0 / voxel_size bmin = cp.asarray(np.asarray(bbox_min, dtype=np.float64)) def splat(pts): # pts: (M, 3) float64 on device vi = cp.floor((pts - bmin) * inv_vs).astype(cp.int32) vx = cp.clip(vi[:, 0], 0, gx - 1) vy = cp.clip(vi[:, 1], 0, gy - 1) vz = cp.clip(vi[:, 2], 0, gz - 1) occ[vx, vy, vz] = True singles = [s for s in strands if len(s) == 1] if singles: splat(cp.asarray(np.concatenate(singles, axis=0), dtype=cp.float64)) p0_list = [s[:-1] for s in strands if len(s) >= 2] p1_list = [s[1:] for s in strands if len(s) >= 2] if not p0_list: return occ p0 = cp.asarray(np.concatenate(p0_list, axis=0), dtype=cp.float64) p1 = cp.asarray(np.concatenate(p1_list, axis=0), dtype=cp.float64) diffs = p1 - p0 edge_len_vox = cp.abs(diffs * inv_vs).max(axis=1) n_steps = cp.maximum(cp.ceil(edge_len_vox).astype(cp.int64), 1) max_ns = int(n_steps.max()) chunk_pts = 20_000_000 for ns in range(1, max_ns + 1): mask = n_steps == ns count = int(mask.sum()) if count == 0: continue sub_p0 = p0[mask] sub_diffs = diffs[mask] pts_per_edge = ns + 1 edges_per_chunk = max(chunk_pts // pts_per_edge, 1) t = cp.linspace(0.0, 1.0, pts_per_edge, dtype=cp.float64) for i in range(0, count, edges_per_chunk): cp0 = sub_p0[i:i + edges_per_chunk] cd = sub_diffs[i:i + edges_per_chunk] pts = cp0[:, None, :] + t[None, :, None] * cd[:, None, :] splat(pts.reshape(-1, 3)) return occ def _fill_interior_gpu(cp, cndi, struct, occ, closing_radius, eff_radius_vox): """Morphological close + flood-fill interior chambers, on the GPU.""" if closing_radius > 0: # cupyx only implements iterated morphology with brute_force=True. occ = cndi.binary_closing( occ, structure=struct, iterations=closing_radius, brute_force=True, ) edt = cndi.distance_transform_edt(~occ) solid = edt <= eff_radius_vox empty = ~solid labelled, n_labels = cndi.label(empty, structure=struct) if n_labels <= 1: return occ boundary: set[int] = set() for ax in range(3): for s in (0, solid.shape[ax] - 1): sl = [slice(None)] * 3 sl[ax] = s boundary.update(cp.asnumpy(cp.unique(labelled[tuple(sl)])).tolist()) boundary.discard(0) interior_labels = sorted(set(range(1, n_labels + 1)) - boundary) if not interior_labels: return occ interior_mask = cp.isin(labelled, cp.asarray(interior_labels)) return occ | interior_mask def occupancy_to_sdf( strands, bbox_min, voxel_size, grid_dims, eff_radius_vox, closing_radius, smooth_iterations, radius, ) -> np.ndarray: """Run rasterise -> fill -> EDT/SDF -> smooth on the GPU; return host SDF. Output is a float32 NumPy array matching the CPU ``build_sdf_edt`` + Gaussian-smooth result, ready for ``skimage.marching_cubes``. """ import cupy as cp import cupyx.scipy.ndimage as cndi from scipy.ndimage import generate_binary_structure struct = cp.asarray(generate_binary_structure(3, 1)) occ = _rasterise_gpu(cp, strands, bbox_min, voxel_size, grid_dims) if closing_radius > 0: occ = _fill_interior_gpu( cp, cndi, struct, occ, closing_radius, eff_radius_vox, ) edt = cndi.distance_transform_edt(~occ).astype(cp.float32) sdf = edt * voxel_size - (eff_radius_vox * voxel_size) del occ, edt sigma = (radius * 0.5) / voxel_size if smooth_iterations > 0 and sigma > 0: for _ in range(smooth_iterations): sdf = cndi.gaussian_filter(sdf, sigma=sigma) cp.cuda.Stream.null.synchronize() out = cp.asnumpy(sdf) del sdf cp.get_default_memory_pool().free_all_blocks() return out