File size: 5,358 Bytes
aadc8c0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
"""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