File size: 15,364 Bytes
38dbb2a | 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 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 | """
Whole-scene voxelization exporter.
"""
import bpy
import json
import numpy as np
from pathlib import Path
from collections import defaultdict
# ββ Parameters ββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
VOXEL_SIZE = 0.25
# Sub-voxel sampling density. A triangle is sampled so that no two
# consecutive samples are further apart than VOXEL_SIZE / SAMPLES_PER_EDGE.
# 3 empirically gives conservative coverage with reasonable runtime.
SAMPLES_PER_EDGE = 3
# ββ Environment βββββββββββββββββββββββββββββββββββββββββββββββββββββββ
scene = bpy.context.scene
cam = scene.camera
frame_start = scene.frame_start
frame_end = scene.frame_end
OUT_DIR = Path(bpy.path.abspath("//")) / "voxel_export_data"
# ββ Helpers βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
def is_dynamic(ob):
"""Armature-driven, shape-keyed, or animated meshes are dynamic."""
for mod in ob.modifiers:
if mod.type == 'ARMATURE':
return True
if ob.data.shape_keys is not None:
return True
if ob.animation_data is not None:
return True
return False
def _world_triangles(ob, dg):
"""
Extract triangles from the evaluated mesh in world space.
Returns
-------
tris_world : (T, 3, 3) world-space triangle vertices
tri_vert_ids: (T, 3) indices into the evaluated mesh vertex array
"""
ob_e = ob.evaluated_get(dg)
me = ob_e.to_mesh()
me.calc_loop_triangles()
n_verts = len(me.vertices)
coords = np.empty(n_verts * 3, dtype=np.float64)
if n_verts:
me.vertices.foreach_get("co", coords)
coords = coords.reshape(-1, 3)
n_tri = len(me.loop_triangles)
tri_vert_ids = np.empty(n_tri * 3, dtype=np.int32)
if n_tri:
me.loop_triangles.foreach_get("vertices", tri_vert_ids)
tri_vert_ids = tri_vert_ids.reshape(-1, 3)
mat = np.array(ob_e.matrix_world)
coords_world = (mat[:3, :3] @ coords.T).T + mat[:3, 3] if n_verts else coords
if n_tri:
tris_world = coords_world[tri_vert_ids]
else:
tris_world = np.empty((0, 3, 3), dtype=np.float64)
ob_e.to_mesh_clear()
return tris_world, tri_vert_ids
def _barycentric_grid(n):
"""
Stratified barycentric samples (w, u, v) on the canonical triangle with
n+1 samples along each parametric direction (u, v).
For n=1 we include the three vertices plus the centroid so tiny
triangles still contribute 4 samples.
"""
if n <= 1:
w = np.array([1.0, 0.0, 0.0, 1.0 / 3.0])
u = np.array([0.0, 1.0, 0.0, 1.0 / 3.0])
v = np.array([0.0, 0.0, 1.0, 1.0 / 3.0])
return np.stack([w, u, v], axis=1)
ug, vg = np.meshgrid(
np.linspace(0.0, 1.0, n + 1),
np.linspace(0.0, 1.0, n + 1),
indexing='ij',
)
uu = ug.ravel()
vv = vg.ravel()
keep = uu + vv <= 1.0 + 1e-9
uu = uu[keep]
vv = vv[keep]
ww = 1.0 - uu - vv
return np.stack([ww, uu, vv], axis=1)
def _sample_tris(tris, spacing):
"""
Dense barycentric sampling of a triangle soup.
The sampling rate adapts to the longest edge so every voxel a triangle
passes through receives at least one sample (up to the spacing tolerance).
Returns
-------
pts : (M, 3) world-space sample positions
tri_ids : (M,) which triangle each sample belongs to
bary : (M, 3) (w, u, v) barycentric coordinates per sample
"""
if tris.shape[0] == 0:
return (np.empty((0, 3), dtype=np.float64),
np.empty(0, dtype=np.int64),
np.empty((0, 3), dtype=np.float64))
e1 = tris[:, 1] - tris[:, 0]
e2 = tris[:, 2] - tris[:, 0]
e3 = tris[:, 2] - tris[:, 1]
max_edge = np.maximum.reduce([
np.linalg.norm(e1, axis=1),
np.linalg.norm(e2, axis=1),
np.linalg.norm(e3, axis=1),
])
n_per = np.maximum(1, np.ceil(max_edge / max(spacing, 1e-9)).astype(int))
pts_all = []
tri_ids_all = []
bary_all = []
for n in np.unique(n_per):
sel = np.where(n_per == n)[0]
bary = _barycentric_grid(int(n)) # (S, 3)
sub_tris = tris[sel] # (K, 3, 3)
# (K, S, 3) = sum_i bary[s,i] * sub_tris[k,i,:]
pts = np.einsum('si,kij->ksj', bary, sub_tris)
K, S, _ = pts.shape
pts_all.append(pts.reshape(-1, 3))
tri_ids_all.append(np.repeat(sel, S))
bary_all.append(np.tile(bary, (K, 1)))
return (np.concatenate(pts_all, axis=0),
np.concatenate(tri_ids_all, axis=0),
np.concatenate(bary_all, axis=0))
# ββ Static voxelization (whole scene, single grid) ββββββββββββββββββββ
def voxelize_static_scene(static_objects, dg, voxel_size):
"""
Voxelize every static mesh into a single shared voxel grid.
Each occupied voxel is attributed to exactly one object (the one that
contributed the most surface samples to that cell), so the returned
per-object arrays partition the scene's voxels with no overlaps.
Returns
-------
per_obj_centers : dict[name -> (N, 3) float32] voxel-center positions
grid_info : dict with {'origin', 'cell_size'}
"""
if not static_objects:
return {}, {"origin": [0.0, 0.0, 0.0], "cell_size": float(voxel_size)}
obj_tris = {ob.name: _world_triangles(ob, dg)[0] for ob in static_objects}
all_tris = [t for t in obj_tris.values() if t.shape[0] > 0]
if not all_tris:
empty = {n: np.empty((0, 3), dtype=np.float32) for n in obj_tris}
return empty, {"origin": [0.0, 0.0, 0.0], "cell_size": float(voxel_size)}
# Compute global origin from scene AABB, snapped to the voxel grid.
cat_pts = np.concatenate([t.reshape(-1, 3) for t in all_tris], axis=0)
origin = np.floor(cat_pts.min(axis=0) / voxel_size) * voxel_size
spacing = voxel_size / SAMPLES_PER_EDGE
# For every object, count how many samples land in each voxel.
counts_per_obj = {}
for name, tris in obj_tris.items():
if tris.shape[0] == 0:
counts_per_obj[name] = {}
continue
pts, _, _ = _sample_tris(tris, spacing)
keys = np.floor((pts - origin) / voxel_size).astype(np.int64)
uniq, counts = np.unique(keys, axis=0, return_counts=True)
counts_per_obj[name] = {tuple(k): int(c) for k, c in zip(uniq, counts)}
# Assign each voxel to the object with the highest sample count.
# Ties resolved by iteration order (stable across runs given same scene).
winner_count = {}
winner_name = {}
for name, counter in counts_per_obj.items():
for k, c in counter.items():
if k not in winner_count or c > winner_count[k]:
winner_count[k] = c
winner_name[k] = name
# Group voxel keys by winning object, emit centers at grid cell centers.
keys_by_obj = defaultdict(list)
for k, name in winner_name.items():
keys_by_obj[name].append(k)
per_obj_centers = {}
for name in obj_tris:
keys = keys_by_obj.get(name, [])
if not keys:
per_obj_centers[name] = np.empty((0, 3), dtype=np.float32)
continue
ks = np.array(keys, dtype=np.int64)
order = np.lexsort((ks[:, 2], ks[:, 1], ks[:, 0]))
ks = ks[order]
centers = origin + (ks + 0.5) * voxel_size
per_obj_centers[name] = centers.astype(np.float32)
grid_info = {"origin": origin.tolist(), "cell_size": float(voxel_size)}
return per_obj_centers, grid_info
# ββ Dynamic voxelization (per-object, aligned to global grid) βββββββββ
def voxelize_dynamic_mesh(ob, dg, voxel_size, origin):
"""
Build frame-stable voxel groups for a dynamic mesh aligned to the global
grid. Barycentric samples are cached so that each frame we can recompute
sample world positions from the current evaluated mesh and average them
per voxel group, yielding voxel centers that deform with the mesh while
keeping a stable per-voxel ID across frames.
"""
tris, tri_vert_ids = _world_triangles(ob, dg)
empty_state = {
"tri_vert_ids": tri_vert_ids,
"sample_tri_ids": np.empty(0, dtype=np.int64),
"sample_bary": np.empty((0, 3), dtype=np.float64),
"sorted_keys": [],
"voxel_groups": {},
"initial_centers": np.empty((0, 3), dtype=np.float32),
}
if tris.shape[0] == 0:
return empty_state
pts, sample_tri_ids, sample_bary = _sample_tris(tris, voxel_size / SAMPLES_PER_EDGE)
if pts.shape[0] == 0:
return empty_state
keys = np.floor((pts - origin) / voxel_size).astype(np.int64)
groups = defaultdict(list)
for i in range(keys.shape[0]):
groups[tuple(keys[i])].append(i)
sorted_keys = sorted(groups.keys())
voxel_groups = {k: np.asarray(groups[k], dtype=np.int64) for k in sorted_keys}
initial_centers = np.empty((len(sorted_keys), 3), dtype=np.float32)
for i, k in enumerate(sorted_keys):
initial_centers[i] = pts[voxel_groups[k]].mean(axis=0)
return {
"tri_vert_ids": tri_vert_ids,
"sample_tri_ids": sample_tri_ids,
"sample_bary": sample_bary,
"sorted_keys": sorted_keys,
"voxel_groups": voxel_groups,
"initial_centers": initial_centers,
}
def compute_dynamic_centers(ob, dg, state):
"""Recompute dynamic voxel centers from the current frame's evaluated mesh."""
sorted_keys = state["sorted_keys"]
if len(sorted_keys) == 0:
return np.empty((0, 3), dtype=np.float32)
tri_vert_ids = state["tri_vert_ids"]
sample_tri_ids = state["sample_tri_ids"]
sample_bary = state["sample_bary"]
voxel_groups = state["voxel_groups"]
ob_e = ob.evaluated_get(dg)
me = ob_e.to_mesh()
n_verts = len(me.vertices)
coords = np.empty(n_verts * 3, dtype=np.float64)
if n_verts:
me.vertices.foreach_get("co", coords)
coords = coords.reshape(-1, 3)
mat = np.array(ob_e.matrix_world)
coords_world = (mat[:3, :3] @ coords.T).T + mat[:3, 3] if n_verts else coords
ob_e.to_mesh_clear()
tri_verts_world = coords_world[tri_vert_ids] # (T, 3, 3)
sample_tris = tri_verts_world[sample_tri_ids] # (S, 3, 3)
sample_pts = np.einsum('si,sij->sj', sample_bary, sample_tris)
centers = np.empty((len(sorted_keys), 3), dtype=np.float32)
for i, k in enumerate(sorted_keys):
inds = voxel_groups[k]
centers[i] = sample_pts[inds].mean(axis=0)
return centers
# ββ Camera ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
def extract_camera_data():
"""Extract 4x4 extrinsics and intrinsics from the active scene camera."""
mat = [list(row) for row in cam.matrix_world]
cam_data = cam.data
intrinsics = {
"sensor_width": cam_data.sensor_width,
"sensor_height": cam_data.sensor_height,
"sensor_fit": cam_data.sensor_fit,
"focal_length": cam_data.lens,
"resolution_x": scene.render.resolution_x,
"resolution_y": scene.render.resolution_y,
}
return mat, intrinsics
# ββ Driver ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
def run():
OUT_DIR.mkdir(exist_ok=True, parents=True)
# ββ Step 1: frame 1 β classify & voxelize ββββββββββββββββββββββββ
scene.frame_set(frame_start)
dg = bpy.context.evaluated_depsgraph_get()
meshes = [ob for ob in scene.objects if ob.type == 'MESH']
static_objs = [ob for ob in meshes if not is_dynamic(ob)]
dynamic_objs = [ob for ob in meshes if is_dynamic(ob)]
print(f"[init] meshes: {len(static_objs)} static, {len(dynamic_objs)} dynamic")
static_centers, grid_info = voxelize_static_scene(static_objs, dg, VOXEL_SIZE)
origin = np.array(grid_info["origin"], dtype=np.float64)
dyn_state = {}
for ob in dynamic_objs:
st = voxelize_dynamic_mesh(ob, dg, VOXEL_SIZE, origin)
dyn_state[ob.name] = st
print(f"[init] dynamic {ob.name}: "
f"{len(st['sorted_keys'])} voxels, "
f"{len(st['sample_tri_ids'])} samples")
for name, centers in static_centers.items():
print(f"[init] static {name}: {centers.shape[0]} voxels")
# ββ Step 2: objects_info / static npz ββββββββββββββββββββββββββββ
objects_info = {}
for ob in static_objs:
objects_info[ob.name] = {
"type": "static",
"voxel_size": float(VOXEL_SIZE),
"grid_info": grid_info,
}
for ob in dynamic_objs:
objects_info[ob.name] = {
"type": "dynamic",
"voxel_size": float(VOXEL_SIZE),
"grid_info": grid_info,
}
static_npz = "static.npz"
np.savez_compressed(str(OUT_DIR / static_npz),
**{n: c for n, c in static_centers.items()})
total_static = sum(c.shape[0] for c in static_centers.values())
print(f"[static] saved {total_static} voxels across "
f"{len(static_centers)} static objects -> {static_npz}")
# ββ Step 3: per-frame dynamic centers + camera βββββββββββββββββββ
frames_meta = []
for f in range(frame_start, frame_end + 1):
scene.frame_set(f)
dg = bpy.context.evaluated_depsgraph_get()
frame_centers = {}
for ob in dynamic_objs:
frame_centers[ob.name] = compute_dynamic_centers(ob, dg, dyn_state[ob.name])
npz_name = f"frame_{f:04d}.npz"
np.savez_compressed(str(OUT_DIR / npz_name), **frame_centers)
extrinsics, intrinsics = extract_camera_data()
frames_meta.append({
"frame": f,
"camera_extrinsics": extrinsics,
"camera_intrinsics": intrinsics,
"data_file": npz_name,
})
total = sum(c.shape[0] for c in frame_centers.values()) + total_static
print(f"[frame {f:04d}] exported {total} voxels "
f"({len(frame_centers)} dynamic + {len(static_centers)} static)")
# ββ Metadata βββββββββββββββββββββββββββββββββββββββββββββββββββββ
metadata = {
"voxel_size": float(VOXEL_SIZE),
"global_grid": grid_info,
"objects_info": objects_info,
"static_data_file": static_npz,
"frames": frames_meta,
}
with open(str(OUT_DIR / "metadata.json"), "w") as fp:
json.dump(metadata, fp, indent=2)
print(f"[done] exported {len(frames_meta)} frames to {OUT_DIR}")
if __name__ == "__main__":
run()
|