"""From the TRELLIS text ONNX build's pipeline.py (moonbox-dev/TRELLIS-text-xlarge-ONNX): the sparse-op index tables of the latent flow and the mesh decoder (TRELLIS v1 modules, as SAM 3D Objects uses them) and the numpy port of NVIDIA FlexiCubes (Apache-2.0, LICENSE-FlexiCubes.txt) from TRELLIS's copy (MIT).""" from __future__ import annotations import itertools import numpy as np SLAT_NAMES = ["coords64", "nbr64", "coords32", "nbr32", "down_child", "down_cnt", "up_idx"] MESH_NAMES = ["coords64", "win0_fwd", "win0_mask", "win0_bwd", "win4_fwd", "win4_mask", "win4_bwd", "nbr128", "nbr256"] OFF27 = np.array(list(itertools.product((-1, 0, 1), repeat=3)), np.int64) SUB8 = np.array(list(itertools.product((0, 1), repeat=3)), np.int64) WINDOW = 8 def neighbours(xyz, offsets=OFF27): """[N, K] index of each voxel's neighbour at each offset (N where there is none).""" xyz = np.asarray(xyz, np.int64) n = len(xyz) R = int(xyz.max()) + 4 key = lambda p: ((p[:, 0] + 1) * R + (p[:, 1] + 1)) * R + (p[:, 2] + 1) k = key(xyz) order = np.argsort(k, kind="stable") ks = k[order] out = np.full((n, len(offsets)), n, np.int64) for j, o in enumerate(offsets): q = key(xyz + o) pos = np.minimum(np.searchsorted(ks, q), n - 1) hit = ks[pos] == q out[hit, j] = order[pos[hit]] return out def with_batch(xyz): return np.concatenate([np.zeros((len(xyz), 1), np.int32), np.asarray(xyz, np.int32)], 1) def slat_flow_tables(coords): """coords [N, 4] (batch 0, x, y, z at 64^3) -> coords64, nbr64, coords32, nbr32, down_child, down_cnt, up_idx.""" xyz = np.asarray(coords)[:, 1:].astype(np.int64) coarse, inv = np.unique(xyz // 2, axis=0, return_inverse=True) # SparseDownsample's order inv = inv.reshape(-1) m = len(coarse) cnt = np.bincount(inv, minlength=m) order = np.argsort(inv, kind="stable") start = np.concatenate([[0], np.cumsum(cnt)[:-1]]) slot = np.arange(len(xyz)) - start[inv[order]] child = np.full((m, 8), len(xyz), np.int64) child[inv[order], slot] = order return (with_batch(xyz), neighbours(xyz), with_batch(coarse), neighbours(coarse), child, cnt.astype(np.float32)[:, None], inv.astype(np.int64)) def windows(xyz, shift, size=WINDOW): """The Swin partition (calc_window_partition): voxels grouped by window, padded to the fullest window. Returns fwd [W, L] (index, N = padding), mask [W, L] (0 / -inf) and bwd [N] (position in the W * L layout).""" s = np.asarray(xyz, np.int64) + shift nw = (s.max(0) + 1 + size - 1) // size wid = ((s[:, 0] // size) * nw[1] + s[:, 1] // size) * nw[2] + s[:, 2] // size uw, winv, wcnt = np.unique(wid, return_inverse=True, return_counts=True) winv = winv.reshape(-1) L, Wn, n = int(wcnt.max()), len(uw), len(s) order = np.argsort(winv, kind="stable") start = np.concatenate([[0], np.cumsum(wcnt)[:-1]]) slot = np.empty(n, np.int64) slot[order] = np.arange(n) - start[winv[order]] fwd = np.full((Wn, L), n, np.int64) fwd[winv, slot] = np.arange(n) mask = np.where(fwd < n, 0.0, -np.inf).astype(np.float32) return fwd, mask, (winv * L + slot).astype(np.int64) def subdivide(xyz): return ((np.asarray(xyz, np.int64) * 2)[:, None] + SUB8[None]).reshape(-1, 3) def mesh_dec_tables(coords): """coords [N, 4] -> coords64, the two Swin partitions (shift 0, 4), nbr128, nbr256.""" xyz = np.asarray(coords)[:, 1:].astype(np.int64) x128 = subdivide(xyz) x256 = subdivide(x128) return (with_batch(xyz),) + windows(xyz, 0) + windows(xyz, WINDOW // 2) + (neighbours(x128), neighbours(x256)) def mesh_dec_coords256(coords): return with_batch(subdivide(subdivide(np.asarray(coords)[:, 1:]))) CORNERS = np.array([[0, 0, 0], [1, 0, 0], [0, 1, 0], [1, 1, 0], [0, 0, 1], [1, 0, 1], [0, 1, 1], [1, 1, 1]], np.int64) CUBE_EDGES = np.array([0, 1, 1, 5, 4, 5, 0, 4, 2, 3, 3, 7, 6, 7, 2, 6, 2, 0, 3, 1, 7, 5, 6, 4], np.int64) QUAD_SPLIT_1, QUAD_SPLIT_2 = np.array([0, 1, 2, 0, 2, 3]), np.array([0, 1, 3, 3, 1, 2]) def _interp(w, x): """FlexiCubes._linear_interp: zero crossing along each edge (w [E, 2, 1], x [E, 2, C]).""" w2 = np.concatenate([w[:, 1:2], -w[:, 0:1]], 1) return (x * w2).sum(1) / w2.sum(1) def _index_add(n, idx, val): out = np.zeros((n,) + val.shape[1:], np.float32) np.add.at(out, idx, val) return out def flexicubes(feats, xyz, tables, res=256, weight_scale=0.99): """SparseFeatures2Mesh.__call__ (use_color) + FlexiCubes.__call__ (training=False) for one shape. feats [N, 101] (sdf 8, deform 8 x 3, weights 21, colour 8 x 6), xyz [N, 3] at res^3. Returns vertices [V, 3] in [-0.5, 0.5]^3, faces [F, 3], vertex attributes [V, 6] (colour, normal map).""" f32 = np.float32 feats = np.asarray(feats, f32) xyz = np.asarray(xyz, np.int64) n = len(xyz) R = res + 1 sdf = feats[:, 0:8] + f32(-1.0 / res) deform = feats[:, 8:32].reshape(n, 8, 3) weights = feats[:, 32:53] color = feats[:, 53:101].reshape(n, 8, 6) # sparse_cube2verts: every voxel's 8 corners, per-vertex mean over the voxels sharing it vkey = lambda p: (p[..., 0] * R + p[..., 1]) * R + p[..., 2] vid = vkey(xyz[:, None] + CORNERS[None]).reshape(-1) tv, inv = np.unique(vid, return_inverse=True) inv = inv.reshape(-1) attrs = np.concatenate([sdf[..., None], deform, color], -1).reshape(-1, 10) cnt = np.bincount(inv, minlength=len(tv)).astype(f32) vattr = np.stack([np.bincount(inv, attrs[:, c], minlength=len(tv)) for c in range(10)], 1).astype(f32) vattr /= cnt[:, None] def lookup(q): pos = np.minimum(np.searchsorted(tv, q), len(tv) - 1) return pos, tv[pos] == q def sdf_of(q): pos, hit = lookup(q) return np.where(hit, vattr[pos, 0], f32(1.0)) # untouched grid vertices: outside (1) def pos_of(q): pos, hit = lookup(q) d = np.where(hit[..., None], vattr[pos, 1:4], f32(0.0)) g = np.stack([q // (R * R), (q // R) % R, q % R], -1).astype(f32) return g / f32(res) - f32(0.5) + f32((1 - 1e-8) / (res * 2)) * np.tanh(d) def color_of(q): pos, hit = lookup(q) c = np.where(hit[..., None], vattr[pos, 4:10], f32(0.0)) return (1 / (1 + np.exp(-c))).astype(f32) # candidate cubes: those with a corner among the vertices with a negative SDF, in dense (x, y, z) order neg = tv[vattr[:, 0] < 0] nv = np.stack([neg // (R * R), (neg // R) % R, neg % R], -1) cc = (nv[:, None] - CORNERS[None]).reshape(-1, 3) cc = cc[((cc >= 0) & (cc < res)).all(1)] ckey = np.unique((cc[:, 0] * res + cc[:, 1]) * res + cc[:, 2]) cxyz = np.stack([ckey // (res * res), (ckey // res) % res, ckey % res], -1) cube_v = vkey(cxyz[:, None] + CORNERS[None]) # [C, 8] occ = sdf_of(cube_v) < 0 s = occ.sum(1) surf = (s > 0) & (s < 8) ckey, cxyz, cube_v, occ = ckey[surf], cxyz[surf], cube_v[surf], occ[surf] S = len(ckey) if S == 0: return np.zeros((0, 3), f32), np.zeros((0, 3), np.int64), np.zeros((0, 6), f32) # weights: the decoder's per-voxel values where a voxel exists, 0 elsewhere (the dense grid's zeros) ikey = (xyz[:, 0] * res + xyz[:, 1]) * res + xyz[:, 2] io = np.argsort(ikey) pos = np.minimum(np.searchsorted(ikey[io], ckey), n - 1) hit = ikey[io][pos] == ckey w = np.where(hit[:, None], weights[io[pos]], f32(0.0)) beta = np.tanh(w[:, :12]) * f32(weight_scale) + f32(1) alpha = np.tanh(w[:, 12:20]) * f32(weight_scale) + f32(1) gamma = (1 / (1 + np.exp(-w[:, 20]))).astype(f32) * f32(weight_scale) + f32((1 - weight_scale) / 2) # _get_case_id (the C16 / C19 ambiguity resolved against the adjacent cube) case = (occ * (1 << np.arange(8))).sum(1) pc = tables["check_table"][case] to_check = np.nonzero(pc[:, 0] == 1)[0] adj = cxyz[to_check] + pc[to_check, 1:4] within = ((adj >= 0) & (adj < res)).all(1) to_check, adj = to_check[within], adj[within] akey = (adj[:, 0] * res + adj[:, 1]) * res + adj[:, 2] chk_keys = np.sort(ckey[pc[:, 0] == 1]) if len(chk_keys) and len(akey): p = np.minimum(np.searchsorted(chk_keys, akey), len(chk_keys) - 1) flip_case = chk_keys[p] == akey case[to_check[flip_case]] = pc[to_check[flip_case], -1] # _identify_surf_edges edges = cube_v[:, CUBE_EDGES].reshape(-1, 2) big = R ** 3 ue_key, e_inv, e_cnt = np.unique(edges[:, 0] * big + edges[:, 1], return_inverse=True, return_counts=True) e_inv = e_inv.reshape(-1) ue = np.stack([ue_key // big, ue_key % big], 1) mask_edges = (sdf_of(ue) < 0).sum(1) == 1 surf_edges_mask = mask_edges[e_inv] counts = e_cnt[e_inv] mapping = np.full(len(ue), -1, np.int64) mapping[mask_edges] = np.arange(mask_edges.sum()) idx_map = mapping[e_inv] # [S * 12] surf_edges = ue[mask_edges] # _compute_vd alpha12 = alpha[:, CUBE_EDGES].reshape(-1, 2) # [S * 12, 2] se_x = pos_of(surf_edges.reshape(-1)).reshape(-1, 2, 3) se_s = sdf_of(surf_edges.reshape(-1)).reshape(-1, 2, 1) se_c = color_of(surf_edges.reshape(-1)).reshape(-1, 2, 6) num_vd = tables["num_vd_table"][case] eg, eg_vd, eg_cube, vd_gamma = [], [], [], [] total = 0 for num in np.unique(num_vd): cur = num_vd == num ncur = int(cur.sum()) * int(num) g = tables["dmc_table"][case[cur], :num].reshape(-1, num * 7) g_vd = (np.arange(ncur)[:, None].repeat(7, 1) + total).reshape(g.shape) total += ncur g_cube = np.nonzero(cur)[0][:, None].repeat(num * 7, 1) m = g != -1 eg.append(g[m]) eg_vd.append(g_vd[m]) eg_cube.append(g_cube[m]) vd_gamma.append(gamma[cur][:, None].repeat(num, 1).reshape(-1)) eg, eg_vd, eg_cube, vd_gamma = (np.concatenate(v) for v in (eg, eg_vd, eg_cube, vd_gamma)) flat = eg_cube * 12 + eg idx_group = idx_map[flat] sw = se_s[idx_group] * alpha12[flat][:, :, None] ue_group = _interp(sw, se_x[idx_group]) beta_group = beta.reshape(-1)[flat][:, None] beta_sum = _index_add(total, eg_vd, beta_group) vd = _index_add(total, eg_vd, ue_group * beta_group) / beta_sum vd_color = _index_add(total, eg_vd, _interp(sw, se_c[idx_group]) * beta_group) / beta_sum vd_idx_map = np.zeros(S * 12, np.int64) vd_idx_map[flat] = eg_vd # _triangulate (inference: each quad split along the diagonal with the larger gamma product) gm = (counts == 4) & surf_edges_mask group = idx_map[gm] vd_idx = vd_idx_map[gm] order = np.argsort(group, kind="stable") edge_indices = group[order] quad = vd_idx[order].reshape(-1, 4) s_e = sdf_of(surf_edges[edge_indices.reshape(-1, 4)[:, 0]].reshape(-1)).reshape(-1, 2) flip = s_e[:, 0] > 0 quad = np.concatenate([quad[flip][:, [0, 1, 3, 2]], quad[~flip][:, [2, 3, 1, 0]]]) qg = vd_gamma[quad] split = (qg[:, 0] * qg[:, 2]) > (qg[:, 1] * qg[:, 3]) faces = np.where(split[:, None], quad[:, QUAD_SPLIT_1], quad[:, QUAD_SPLIT_2]).reshape(-1, 3) return vd.astype(f32), faces, vd_color.astype(f32)