-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathexample.py
More file actions
157 lines (132 loc) · 4.7 KB
/
example.py
File metadata and controls
157 lines (132 loc) · 4.7 KB
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
import torch
import open3d as o3d
import numpy as np
from mc_mixin import _load_mc_ext
# ------------------------------------------------------------
# Config
# ------------------------------------------------------------
RESOLUTIONS = [32, 64, 128, 256]
N_RUNS = 20
SHOW_NORMALS = True
SHOW_MASK = False # True = mostra solo le mesh con mask, False = mostra tutte
# ------------------------------------------------------------
# Grid
# ------------------------------------------------------------
def make_sphere(res):
r = torch.arange(res, dtype=torch.float32)
z, y, x = torch.meshgrid(r, r, r, indexing="ij")
c = res / 2
sdf = ((x - c)**2 + (y - c)**2 + (z - c)**2).sqrt() - res * 0.3
return sdf.cuda()
def make_mask(res):
# crea uno spicchio: solo un quarto del cubo è True
m = torch.zeros(res, res, res, dtype=torch.bool, device="cuda")
m[res//2:, res//2:, :] = True
return m
# ------------------------------------------------------------
# Timing
# ------------------------------------------------------------
def time_cuda(fn):
start = torch.cuda.Event(True)
end = torch.cuda.Event(True)
torch.cuda.synchronize()
start.record()
for _ in range(N_RUNS):
fn()
end.record()
torch.cuda.synchronize()
return start.elapsed_time(end) / N_RUNS
# ------------------------------------------------------------
# Benchmark
# ------------------------------------------------------------
def run(mc):
results = []
for i, res in enumerate(RESOLUTIONS[:4]): # solo 4 sfere
grid = make_sphere(res)
mask = make_mask(res) if SHOW_MASK else torch.Tensor()
# warmup
for _ in range(5):
mc.marching_cubes(grid, 0.0, mask, compute_normals=True)
torch.cuda.synchronize()
out = [None]
def fn():
out[0] = mc.marching_cubes(grid, 0.0, mask, compute_normals=True)
ms = time_cuda(fn)
v, f, n = out[0]
print(f"{res}³ | {'MASK' if SHOW_MASK else 'FULL':4} | {ms:.2f} ms | {v.shape[0]} verts | {f.shape[0]} faces")
results.append({
"res": res,
"mask": SHOW_MASK,
"v": v.cpu(),
"f": f.cpu(),
"n": n.cpu()
})
return results
# ------------------------------------------------------------
# Normals
# ------------------------------------------------------------
def get_normals_lineset(points, normals, length=0.05):
pts = points.numpy()
nrm = normals.numpy()
line_pts = np.concatenate([pts, pts + nrm * length], axis=0)
lines = [[i, i + len(pts)] for i in range(len(pts))]
ls = o3d.geometry.LineSet()
ls.points = o3d.utility.Vector3dVector(line_pts)
ls.lines = o3d.utility.Vector2iVector(lines)
return ls
# ------------------------------------------------------------
# Visualization
# ------------------------------------------------------------
def show(results):
geometries = []
# 4 colori fissi
colors_map = [
[1.0, 0.0, 0.0], # red
[0.0, 1.0, 0.0], # green
[0.0, 0.0, 1.0], # blue
[1.0, 1.0, 0.0], # yellow
]
offset = 0.0
for i, rec in enumerate(results):
v = rec["v"]
f = rec["f"]
n = rec["n"]
if v.shape[0] == 0:
continue
verts = v.numpy()
faces = f.numpy()
norms = n.numpy()
mesh = o3d.geometry.TriangleMesh()
mesh.vertices = o3d.utility.Vector3dVector(verts)
mesh.triangles = o3d.utility.Vector3iVector(faces)
# normalizza tutto a unit cube
bb = mesh.get_axis_aligned_bounding_box()
scale = 1.0 / max(bb.get_extent())
center = bb.get_center()
verts = (verts - center) * scale
norms = norms / np.linalg.norm(norms, axis=1, keepdims=True)
mesh.vertices = o3d.utility.Vector3dVector(verts)
mesh.vertex_normals = o3d.utility.Vector3dVector(norms)
# colore fisso
mesh.paint_uniform_color(colors_map[i % 4])
# shift per layout
shift = np.array([offset, 0, 0])
mesh.translate(shift)
geometries.append(mesh)
# normali
if SHOW_NORMALS:
ls = get_normals_lineset(torch.from_numpy(verts + shift), torch.from_numpy(norms))
geometries.append(ls)
offset += 2.0
o3d.visualization.draw_geometries(geometries, zoom=0.4)
# ------------------------------------------------------------
# Main
# ------------------------------------------------------------
if __name__ == "__main__":
if not torch.cuda.is_available():
raise RuntimeError("CUDA not available")
print(torch.cuda.get_device_name(0))
mc = _load_mc_ext()
results = run(mc)
print("Showing meshes...")
show(results)