Archive CFD workflow 2026-10-12: seiler_pipeline
Browse files- cfd_workflow_20261012/seiler_pipeline/input/chair_1.png +3 -0
- cfd_workflow_20261012/seiler_pipeline/scripts/compute_force_chair.py +259 -0
- cfd_workflow_20261012/seiler_pipeline/scripts/force_web_ui.py +733 -0
- cfd_workflow_20261012/seiler_pipeline/scripts/sample_hunyuan.py +222 -0
- cfd_workflow_20261012/seiler_pipeline/scripts/viewer_hunyuan_web_alternate.py +0 -0
- cfd_workflow_20261012/seiler_pipeline/scripts/viewer_hunyuan_web_physiopt.py +0 -0
cfd_workflow_20261012/seiler_pipeline/input/chair_1.png
ADDED
|
Git LFS Details
|
cfd_workflow_20261012/seiler_pipeline/scripts/compute_force_chair.py
ADDED
|
@@ -0,0 +1,259 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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ot3d.art3d import Poly3DCollection
|
| 6 |
+
import os
|
| 7 |
+
import json
|
| 8 |
+
|
| 9 |
+
|
| 10 |
+
def detect_seat_bbox_auto(mesh_path, up_axis=1, shrink_factor=0.60):
|
| 11 |
+
"""
|
| 12 |
+
Détecte la Bounding Box de l'assise d'une chaise avec calcul automatique de l'épaisseur.
|
| 13 |
+
- shrink_factor: Réduit la taille (X, Z) pour analyser uniquement le "cœur" de l'assise
|
| 14 |
+
et éviter de prendre en compte les pieds sur les côtés. (0.60 = 60% du centre)
|
| 15 |
+
"""
|
| 16 |
+
# 1. Charger le mesh
|
| 17 |
+
mesh = trimesh.load(mesh_path, force='mesh')
|
| 18 |
+
up_vector = np.zeros(3)
|
| 19 |
+
up_vector[up_axis] = 1.0
|
| 20 |
+
bounds_min, bounds_max = mesh.bounds
|
| 21 |
+
mesh.vertices = (mesh.vertices - bounds_min) / (bounds_max - bounds_min)
|
| 22 |
+
|
| 23 |
+
# 2. Filtrer les faces horizontales
|
| 24 |
+
dot_products = np.dot(mesh.face_normals, up_vector)
|
| 25 |
+
horizontal_faces_mask = dot_products > 0.85
|
| 26 |
+
|
| 27 |
+
if not np.any(horizontal_faces_mask):
|
| 28 |
+
return None, None, mesh
|
| 29 |
+
|
| 30 |
+
horizontal_faces = mesh.faces[horizontal_faces_mask]
|
| 31 |
+
horizontal_vertices = mesh.vertices[np.unique(horizontal_faces.flatten())]
|
| 32 |
+
|
| 33 |
+
# 3. Trouver la hauteur principale de l'assise
|
| 34 |
+
heights = horizontal_vertices[:, up_axis]
|
| 35 |
+
hist, bin_edges = np.histogram(heights, bins=30, range=(0, 1))
|
| 36 |
+
peak_bin = np.argmax(hist)
|
| 37 |
+
seat_height_center = (bin_edges[peak_bin] + bin_edges[peak_bin + 1]) / 2.0
|
| 38 |
+
|
| 39 |
+
# 4. Isoler les sommets de la surface de l'assise
|
| 40 |
+
seat_vertices = horizontal_vertices[np.abs(horizontal_vertices[:, up_axis] - seat_height_center) < 0.05]
|
| 41 |
+
if len(seat_vertices) == 0:
|
| 42 |
+
return None, None, mesh
|
| 43 |
+
|
| 44 |
+
# Bounding Box de base de la surface
|
| 45 |
+
min_bounds = np.min(seat_vertices, axis=0)
|
| 46 |
+
max_bounds = np.max(seat_vertices, axis=0)
|
| 47 |
+
|
| 48 |
+
# 5. Réduire vers le centre sur les axes horizontaux
|
| 49 |
+
axes_horizontaux = [i for i in range(3) if i != up_axis]
|
| 50 |
+
for axis in axes_horizontaux:
|
| 51 |
+
center = (max_bounds[axis] + min_bounds[axis]) / 2.0
|
| 52 |
+
length = max_bounds[axis] - min_bounds[axis]
|
| 53 |
+
min_bounds[axis] = center - (length * shrink_factor / 2.0)
|
| 54 |
+
max_bounds[axis] = center + (length * shrink_factor / 2.0)
|
| 55 |
+
|
| 56 |
+
# --- 6. CALCUL AUTOMATIQUE DE L'ÉPAISSEUR ---
|
| 57 |
+
|
| 58 |
+
# On récupère les limites X et Z de notre "colonne" centrale
|
| 59 |
+
min_h1, min_h2 = min_bounds[axes_horizontaux[0]], min_bounds[axes_horizontaux[1]]
|
| 60 |
+
max_h1, max_h2 = max_bounds[axes_horizontaux[0]], max_bounds[axes_horizontaux[1]]
|
| 61 |
+
|
| 62 |
+
# On sélectionne tous les points du mesh complet qui sont dans cette colonne
|
| 63 |
+
col_mask = (mesh.vertices[:, axes_horizontaux[0]] >= min_h1) & \
|
| 64 |
+
(mesh.vertices[:, axes_horizontaux[0]] <= max_h1) & \
|
| 65 |
+
(mesh.vertices[:, axes_horizontaux[1]] >= min_h2) & \
|
| 66 |
+
(mesh.vertices[:, axes_horizontaux[1]] <= max_h2)
|
| 67 |
+
column_vertices = mesh.vertices[col_mask]
|
| 68 |
+
|
| 69 |
+
y_values = column_vertices[:, up_axis]
|
| 70 |
+
|
| 71 |
+
def find_boundary(y_array, direction, gap_threshold=0.04):
|
| 72 |
+
# direction: -1 pour chercher vers le bas, 1 pour chercher vers le haut
|
| 73 |
+
if len(y_array) == 0:
|
| 74 |
+
return seat_height_center
|
| 75 |
+
|
| 76 |
+
# Trier les hauteurs (décroissant si on va vers le bas, croissant si on va vers le haut)
|
| 77 |
+
if direction == -1:
|
| 78 |
+
y_sorted = np.sort(y_array[y_array <= seat_height_center + 0.01])[::-1]
|
| 79 |
+
else:
|
| 80 |
+
y_sorted = np.sort(y_array[y_array >= seat_height_center - 0.01])
|
| 81 |
+
|
| 82 |
+
if len(y_sorted) < 2:
|
| 83 |
+
return y_sorted[0] if len(y_sorted)>0 else seat_height_center
|
| 84 |
+
|
| 85 |
+
# Calculer l'espace (gap) entre chaque point consécutif
|
| 86 |
+
gaps = np.abs(y_sorted[:-1] - y_sorted[1:])
|
| 87 |
+
|
| 88 |
+
# Trouver le premier endroit où le trou est plus grand que notre seuil
|
| 89 |
+
large_gaps = np.where(gaps > gap_threshold)[0]
|
| 90 |
+
|
| 91 |
+
if len(large_gaps) > 0:
|
| 92 |
+
return y_sorted[large_gaps[0]] # On renvoie le point juste avant le vide
|
| 93 |
+
return y_sorted[-1] # Si c'est un bloc plein jusqu'au bout, on prend la fin
|
| 94 |
+
|
| 95 |
+
# 1. Calculer le bas et le haut EXACTS de l'assise
|
| 96 |
+
# (Attention, j'ai remis gap_threshold=0.04 pour le bottom, tu avais mis 0.4 dans ton message,
|
| 97 |
+
# ce qui risquait de faire descendre la boîte jusqu'au sol !)
|
| 98 |
+
seat_bottom_exact = find_boundary(y_values, direction=-1, gap_threshold=0.4)
|
| 99 |
+
seat_top_exact = find_boundary(y_values, direction=1, gap_threshold=0.04)
|
| 100 |
+
|
| 101 |
+
# 2. Définir tes marges (ex: 0.02 = 2% de la hauteur totale de la chaise)
|
| 102 |
+
margin_bottom = 0.02
|
| 103 |
+
margin_top = 0.02
|
| 104 |
+
|
| 105 |
+
# 3. Appliquer les marges tout en restant dans les limites normalisées (0.0 à 1.0)
|
| 106 |
+
seat_bottom = max(0.0, seat_bottom_exact - margin_bottom)
|
| 107 |
+
seat_top = min(1.0, seat_top_exact + margin_top)
|
| 108 |
+
|
| 109 |
+
min_bounds[up_axis] = seat_bottom
|
| 110 |
+
max_bounds[up_axis] = seat_top
|
| 111 |
+
|
| 112 |
+
return min_bounds, max_bounds, mesh
|
| 113 |
+
|
| 114 |
+
|
| 115 |
+
def get_box_faces(min_b, max_b):
|
| 116 |
+
"""Génère les 6 faces d'une Bounding Box 3D pour matplotlib."""
|
| 117 |
+
x0, y0, z0 = min_b
|
| 118 |
+
x1, y1, z1 = max_b
|
| 119 |
+
verts = [
|
| 120 |
+
[x0, y0, z0], [x1, y0, z0], [x1, y1, z0], [x0, y1, z0],
|
| 121 |
+
[x0, y0, z1], [x1, y0, z1], [x1, y1, z1], [x0, y1, z1]
|
| 122 |
+
]
|
| 123 |
+
faces = [
|
| 124 |
+
[verts[0], verts[1], verts[2], verts[3]],
|
| 125 |
+
[verts[4], verts[5], verts[6], verts[7]],
|
| 126 |
+
[verts[0], verts[1], verts[5], verts[4]],
|
| 127 |
+
[verts[2], verts[3], verts[7], verts[6]],
|
| 128 |
+
[verts[1], verts[2], verts[6], verts[5]],
|
| 129 |
+
[verts[0], verts[3], verts[7], verts[4]]
|
| 130 |
+
]
|
| 131 |
+
return faces
|
| 132 |
+
|
| 133 |
+
|
| 134 |
+
def render_chair_bbox(mesh, min_bound, max_bound, output_filename):
|
| 135 |
+
"""Génère 1 seule image contenant les 3 rendus avec correction de l'axe vertical (Y -> Z)."""
|
| 136 |
+
|
| 137 |
+
# 1. Échantillonner le mesh
|
| 138 |
+
num_vertices = len(mesh.vertices)
|
| 139 |
+
step = max(1, num_vertices // 5000)
|
| 140 |
+
sampled_vertices = mesh.vertices[::step]
|
| 141 |
+
|
| 142 |
+
# --- L'ASTUCE EST ICI ---
|
| 143 |
+
# On isole les axes et on échange Y et Z pour l'affichage matplotlib
|
| 144 |
+
x_plot = sampled_vertices[:, 0]
|
| 145 |
+
y_plot = sampled_vertices[:, 2] # La profondeur du mesh devient l'axe Y de matplotlib
|
| 146 |
+
z_plot = sampled_vertices[:, 1] # La hauteur du mesh (Y) devient l'axe vertical Z de matplotlib
|
| 147 |
+
|
| 148 |
+
# 2. Récupérer les faces de la boîte et échanger aussi Y et Z
|
| 149 |
+
box_faces = get_box_faces(min_bound, max_bound)
|
| 150 |
+
box_faces_z_up = []
|
| 151 |
+
for face in box_faces:
|
| 152 |
+
# Pour chaque point [x, y, z], on crée [x, z, y]
|
| 153 |
+
new_face = [[v[0], v[2], v[1]] for v in face]
|
| 154 |
+
box_faces_z_up.append(new_face)
|
| 155 |
+
|
| 156 |
+
# 3. Récupérer les limites et échanger Y et Z
|
| 157 |
+
b = mesh.bounds
|
| 158 |
+
min_x, max_x = b[0][0], b[1][0]
|
| 159 |
+
min_y, max_y = b[0][2], b[1][2] # Ancien Z
|
| 160 |
+
min_z, max_z = b[0][1], b[1][1] # Ancien Y
|
| 161 |
+
|
| 162 |
+
# 4. Définir les vues adaptées (Maintenant que Z est bien en haut)
|
| 163 |
+
views = [
|
| 164 |
+
{"name": "Isométrique", "elev": 20, "azim": -45},
|
| 165 |
+
{"name": "Face", "elev": 0, "azim": -90}, # Regarde l'avant de la chaise
|
| 166 |
+
{"name": "Profil", "elev": 0, "azim": 0} # Regarde le côté
|
| 167 |
+
]
|
| 168 |
+
|
| 169 |
+
fig = plt.figure(figsize=(18, 6))
|
| 170 |
+
|
| 171 |
+
for i, view in enumerate(views, start=1):
|
| 172 |
+
ax = fig.add_subplot(1, 3, i, projection='3d')
|
| 173 |
+
|
| 174 |
+
# A. Dessiner la chaise avec nos axes modifiés
|
| 175 |
+
ax.scatter(
|
| 176 |
+
x_plot, y_plot, z_plot,
|
| 177 |
+
c='gray', s=2, alpha=0.4, marker='.'
|
| 178 |
+
)
|
| 179 |
+
|
| 180 |
+
# B. Dessiner la Bounding Box avec nos axes modifiés
|
| 181 |
+
box_col = Poly3DCollection(box_faces_z_up, alpha=0.4, facecolors='red', edgecolors='darkred')
|
| 182 |
+
ax.add_collection3d(box_col)
|
| 183 |
+
|
| 184 |
+
# C. Cadrage de la caméra
|
| 185 |
+
ax.set_xlim(min_x, max_x)
|
| 186 |
+
ax.set_ylim(min_y, max_y)
|
| 187 |
+
ax.set_zlim(min_z, max_z)
|
| 188 |
+
|
| 189 |
+
# Conserver les proportions
|
| 190 |
+
try:
|
| 191 |
+
ax.set_box_aspect((max_x-min_x, max_y-min_y, max_z-min_z))
|
| 192 |
+
except AttributeError:
|
| 193 |
+
pass
|
| 194 |
+
|
| 195 |
+
# Appliquer l'angle de vue
|
| 196 |
+
ax.view_init(elev=view["elev"], azim=view["azim"])
|
| 197 |
+
ax.set_title(f"Vue : {view['name']}")
|
| 198 |
+
ax.set_axis_off()
|
| 199 |
+
|
| 200 |
+
plt.tight_layout()
|
| 201 |
+
plt.savefig(output_filename, dpi=150, bbox_inches='tight')
|
| 202 |
+
plt.close(fig)
|
| 203 |
+
|
| 204 |
+
|
| 205 |
+
def main():
|
| 206 |
+
parser = argparse.ArgumentParser(description="Batch process chair meshes to extract seat bbox.")
|
| 207 |
+
parser.add_argument("--folder", required=True, help="Input directory containing chair folders.")
|
| 208 |
+
parser.add_argument("--instance-file", required=True, help="File with instance to optimize")
|
| 209 |
+
parser.add_argument("-s", "--shrink", type=float, default=0.60, help="Shrink factor for bbox (default: 0.60).")
|
| 210 |
+
parser.add_argument("-r", "--rotation", choices=['none', 'x_up', 'y_up'], default='y_up', help="Rotation fix (default: y_up).")
|
| 211 |
+
args = parser.parse_args()
|
| 212 |
+
|
| 213 |
+
# Chemins ajustés
|
| 214 |
+
input_folder = f"/scratch/cvlab/home/seiler/physiopt_new/output/hunyuan_gen/{args.folder}"
|
| 215 |
+
output_folder = f"/scratch/cvlab/home/seiler/physiopt_new/output_force/hunyuan_gen/{args.folder}"
|
| 216 |
+
os.makedirs(output_folder, exist_ok=True)
|
| 217 |
+
print(f"Processing folders in: {input_folder}")
|
| 218 |
+
|
| 219 |
+
with open(os.path.join("file_for_exp", args.instance_file), "r") as f:
|
| 220 |
+
instance_optimize = json.load(f)
|
| 221 |
+
count = 0
|
| 222 |
+
|
| 223 |
+
for folder_name in os.listdir(input_folder):
|
| 224 |
+
if folder_name in instance_optimize:
|
| 225 |
+
input_subdir = os.path.join(input_folder, folder_name)
|
| 226 |
+
mesh_file = os.path.join(input_subdir, "generated_mesh.obj")
|
| 227 |
+
|
| 228 |
+
if os.path.isdir(input_subdir) and os.path.exists(mesh_file):
|
| 229 |
+
out_subdir = os.path.join(output_folder, folder_name)
|
| 230 |
+
os.makedirs(out_subdir, exist_ok=True)
|
| 231 |
+
|
| 232 |
+
try:
|
| 233 |
+
# Traitement de la chaise
|
| 234 |
+
min_bounds, max_bounds, mesh = detect_seat_bbox_auto(mesh_file)
|
| 235 |
+
# Construction de l'output force [x_min, x_max, y_min, y_max, z_min, z_max]
|
| 236 |
+
config = {
|
| 237 |
+
"force": [0.0, -300000.0, 0.0],
|
| 238 |
+
"force_region_mode": "bbox",
|
| 239 |
+
"force_bbox_ratio": [
|
| 240 |
+
float(min_bounds[0]), float(max_bounds[0]),
|
| 241 |
+
float(min_bounds[1]), float(max_bounds[1]),
|
| 242 |
+
float(min_bounds[2]), float(max_bounds[2])
|
| 243 |
+
]
|
| 244 |
+
}
|
| 245 |
+
|
| 246 |
+
with open(os.path.join(out_subdir, "force_config.json"), 'w') as f:
|
| 247 |
+
json.dump(config, f, indent=2)
|
| 248 |
+
|
| 249 |
+
render_chair_bbox(mesh, min_bounds, max_bounds, os.path.join(out_subdir, "plot.png"))
|
| 250 |
+
print(f"✅ Success: {folder_name}")
|
| 251 |
+
count += 1
|
| 252 |
+
|
| 253 |
+
except Exception as e:
|
| 254 |
+
print(f"❌ Failed: {folder_name} | Error: {e}")
|
| 255 |
+
|
| 256 |
+
print(f"🎉 Batch processing complete for {count} shapes")
|
| 257 |
+
|
| 258 |
+
if __name__ == "__main__":
|
| 259 |
+
main()
|
cfd_workflow_20261012/seiler_pipeline/scripts/force_web_ui.py
ADDED
|
@@ -0,0 +1,733 @@
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import argparse
|
| 2 |
+
import hashlib
|
| 3 |
+
import json
|
| 4 |
+
import os
|
| 5 |
+
import re
|
| 6 |
+
import shutil
|
| 7 |
+
|
| 8 |
+
import numpy as np
|
| 9 |
+
import gradio as gr
|
| 10 |
+
import trimesh
|
| 11 |
+
|
| 12 |
+
POINT_PREVIEW_MAX = 12000
|
| 13 |
+
POINT_PREVIEW_SIZE_RATIO = 0.004
|
| 14 |
+
ROTATE_X_CCW_90 = trimesh.transformations.rotation_matrix(
|
| 15 |
+
np.deg2rad(270.0), [1.0, 0.0, 0.0]
|
| 16 |
+
)
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
def _normalize_out_path(out_path: str) -> str:
|
| 20 |
+
out_path = (out_path or "").strip()
|
| 21 |
+
if not out_path:
|
| 22 |
+
out_path = "force_config.json"
|
| 23 |
+
if out_path.endswith(os.sep) or os.path.isdir(out_path):
|
| 24 |
+
out_path = os.path.join(out_path, "force_config.json")
|
| 25 |
+
return out_path
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
def _parse_force_lines(text: str):
|
| 29 |
+
forces = []
|
| 30 |
+
for raw_line in (text or "").splitlines():
|
| 31 |
+
line = raw_line.strip()
|
| 32 |
+
if not line or line.startswith("#"):
|
| 33 |
+
continue
|
| 34 |
+
parts = [p for p in re.split(r"[,\s]+", line) if p]
|
| 35 |
+
if len(parts) != 3:
|
| 36 |
+
continue
|
| 37 |
+
try:
|
| 38 |
+
vec = [float(v) for v in parts]
|
| 39 |
+
except Exception:
|
| 40 |
+
continue
|
| 41 |
+
forces.append(vec)
|
| 42 |
+
return forces
|
| 43 |
+
|
| 44 |
+
|
| 45 |
+
def _save_config(
|
| 46 |
+
out_path: str,
|
| 47 |
+
fx: float,
|
| 48 |
+
fy: float,
|
| 49 |
+
fz: float,
|
| 50 |
+
extra_forces_text: str,
|
| 51 |
+
mode: str,
|
| 52 |
+
top_percent: float,
|
| 53 |
+
hr_min: float,
|
| 54 |
+
hr_max: float,
|
| 55 |
+
bx0: float,
|
| 56 |
+
bx1: float,
|
| 57 |
+
by0: float,
|
| 58 |
+
by1: float,
|
| 59 |
+
bz0: float,
|
| 60 |
+
bz1: float,
|
| 61 |
+
brx0: float,
|
| 62 |
+
brx1: float,
|
| 63 |
+
bry0: float,
|
| 64 |
+
bry1: float,
|
| 65 |
+
brz0: float,
|
| 66 |
+
brz1: float,
|
| 67 |
+
force_entries,
|
| 68 |
+
):
|
| 69 |
+
out_path = _normalize_out_path(out_path)
|
| 70 |
+
os.makedirs(os.path.dirname(out_path) or ".", exist_ok=True)
|
| 71 |
+
|
| 72 |
+
force_entries = list(force_entries or [])
|
| 73 |
+
if force_entries:
|
| 74 |
+
entries = force_entries
|
| 75 |
+
else:
|
| 76 |
+
entries = [
|
| 77 |
+
_build_force_entry(
|
| 78 |
+
fx,
|
| 79 |
+
fy,
|
| 80 |
+
fz,
|
| 81 |
+
extra_forces_text,
|
| 82 |
+
mode,
|
| 83 |
+
top_percent,
|
| 84 |
+
hr_min,
|
| 85 |
+
hr_max,
|
| 86 |
+
bx0,
|
| 87 |
+
bx1,
|
| 88 |
+
by0,
|
| 89 |
+
by1,
|
| 90 |
+
bz0,
|
| 91 |
+
bz1,
|
| 92 |
+
brx0,
|
| 93 |
+
brx1,
|
| 94 |
+
bry0,
|
| 95 |
+
bry1,
|
| 96 |
+
brz0,
|
| 97 |
+
brz1,
|
| 98 |
+
)
|
| 99 |
+
]
|
| 100 |
+
|
| 101 |
+
all_forces = _flatten_entry_forces(entries)
|
| 102 |
+
|
| 103 |
+
if len(entries) == 1:
|
| 104 |
+
cfg = dict(entries[0])
|
| 105 |
+
else:
|
| 106 |
+
cfg = {"force_entries": entries}
|
| 107 |
+
if len(all_forces) > 1:
|
| 108 |
+
cfg["forces"] = all_forces
|
| 109 |
+
cfg["force"] = [float(sum(v[i] for v in all_forces)) for i in range(3)]
|
| 110 |
+
elif len(all_forces) == 1:
|
| 111 |
+
cfg["force"] = all_forces[0]
|
| 112 |
+
|
| 113 |
+
with open(out_path, "w") as f:
|
| 114 |
+
json.dump(cfg, f, indent=2)
|
| 115 |
+
|
| 116 |
+
cmd = f"python scripts/viewer_hunyuan_web_alternate.py --latents <latents.pt> --use_physics --force_config {out_path}"
|
| 117 |
+
return f"Saved to {out_path}", json.dumps(cfg, indent=2), cmd
|
| 118 |
+
|
| 119 |
+
|
| 120 |
+
def _toggle_groups(mode: str):
|
| 121 |
+
return (
|
| 122 |
+
gr.update(visible=mode == "top_percent"),
|
| 123 |
+
gr.update(visible=mode == "height_ratio"),
|
| 124 |
+
gr.update(visible=mode == "bbox_abs"),
|
| 125 |
+
gr.update(visible=mode == "bbox_ratio"),
|
| 126 |
+
)
|
| 127 |
+
|
| 128 |
+
|
| 129 |
+
def _build_force_entry(
|
| 130 |
+
fx: float,
|
| 131 |
+
fy: float,
|
| 132 |
+
fz: float,
|
| 133 |
+
extra_forces_text: str,
|
| 134 |
+
mode: str,
|
| 135 |
+
top_percent: float,
|
| 136 |
+
hr_min: float,
|
| 137 |
+
hr_max: float,
|
| 138 |
+
bx0: float,
|
| 139 |
+
bx1: float,
|
| 140 |
+
by0: float,
|
| 141 |
+
by1: float,
|
| 142 |
+
bz0: float,
|
| 143 |
+
bz1: float,
|
| 144 |
+
brx0: float,
|
| 145 |
+
brx1: float,
|
| 146 |
+
bry0: float,
|
| 147 |
+
bry1: float,
|
| 148 |
+
brz0: float,
|
| 149 |
+
brz1: float,
|
| 150 |
+
):
|
| 151 |
+
base_force = [float(fx), float(fy), float(fz)]
|
| 152 |
+
extra_forces = _parse_force_lines(extra_forces_text)
|
| 153 |
+
forces = []
|
| 154 |
+
base_nonzero = any(abs(v) > 0 for v in base_force)
|
| 155 |
+
if base_nonzero or not extra_forces:
|
| 156 |
+
forces.append(base_force)
|
| 157 |
+
forces.extend(extra_forces)
|
| 158 |
+
|
| 159 |
+
entry = {}
|
| 160 |
+
if len(forces) > 1:
|
| 161 |
+
entry["forces"] = forces
|
| 162 |
+
entry["force"] = [float(sum(v[i] for v in forces)) for i in range(3)]
|
| 163 |
+
else:
|
| 164 |
+
entry["force"] = forces[0]
|
| 165 |
+
|
| 166 |
+
if mode == "global":
|
| 167 |
+
entry["force_region_mode"] = "global"
|
| 168 |
+
entry["global_loading"] = True
|
| 169 |
+
elif mode == "top_percent":
|
| 170 |
+
entry["force_region_mode"] = "top_percent"
|
| 171 |
+
entry["force_top_percent"] = float(top_percent)
|
| 172 |
+
elif mode == "height_ratio":
|
| 173 |
+
entry["force_region_mode"] = "height_ratio"
|
| 174 |
+
entry["seat_height_min_ratio"] = float(hr_min)
|
| 175 |
+
entry["seat_height_max_ratio"] = float(hr_max)
|
| 176 |
+
elif mode == "bbox_abs":
|
| 177 |
+
entry["force_region_mode"] = "bbox"
|
| 178 |
+
entry["force_bbox"] = [
|
| 179 |
+
float(bx0),
|
| 180 |
+
float(bx1),
|
| 181 |
+
float(by0),
|
| 182 |
+
float(by1),
|
| 183 |
+
float(bz0),
|
| 184 |
+
float(bz1),
|
| 185 |
+
]
|
| 186 |
+
elif mode == "bbox_ratio":
|
| 187 |
+
entry["force_region_mode"] = "bbox"
|
| 188 |
+
entry["force_bbox_ratio"] = [
|
| 189 |
+
float(brx0),
|
| 190 |
+
float(brx1),
|
| 191 |
+
float(bry0),
|
| 192 |
+
float(bry1),
|
| 193 |
+
float(brz0),
|
| 194 |
+
float(brz1),
|
| 195 |
+
]
|
| 196 |
+
return entry
|
| 197 |
+
|
| 198 |
+
|
| 199 |
+
def _flatten_entry_forces(entries):
|
| 200 |
+
all_forces = []
|
| 201 |
+
for entry in entries:
|
| 202 |
+
if not isinstance(entry, dict):
|
| 203 |
+
continue
|
| 204 |
+
if "forces" in entry and isinstance(entry["forces"], list):
|
| 205 |
+
all_forces.extend(entry["forces"])
|
| 206 |
+
elif "force" in entry:
|
| 207 |
+
all_forces.append(entry["force"])
|
| 208 |
+
return all_forces
|
| 209 |
+
|
| 210 |
+
|
| 211 |
+
def _add_force_entry(
|
| 212 |
+
force_entries,
|
| 213 |
+
fx: float,
|
| 214 |
+
fy: float,
|
| 215 |
+
fz: float,
|
| 216 |
+
extra_forces_text: str,
|
| 217 |
+
mode: str,
|
| 218 |
+
top_percent: float,
|
| 219 |
+
hr_min: float,
|
| 220 |
+
hr_max: float,
|
| 221 |
+
bx0: float,
|
| 222 |
+
bx1: float,
|
| 223 |
+
by0: float,
|
| 224 |
+
by1: float,
|
| 225 |
+
bz0: float,
|
| 226 |
+
bz1: float,
|
| 227 |
+
brx0: float,
|
| 228 |
+
brx1: float,
|
| 229 |
+
bry0: float,
|
| 230 |
+
bry1: float,
|
| 231 |
+
brz0: float,
|
| 232 |
+
brz1: float,
|
| 233 |
+
):
|
| 234 |
+
entries = list(force_entries or [])
|
| 235 |
+
entry = _build_force_entry(
|
| 236 |
+
fx,
|
| 237 |
+
fy,
|
| 238 |
+
fz,
|
| 239 |
+
extra_forces_text,
|
| 240 |
+
mode,
|
| 241 |
+
top_percent,
|
| 242 |
+
hr_min,
|
| 243 |
+
hr_max,
|
| 244 |
+
bx0,
|
| 245 |
+
bx1,
|
| 246 |
+
by0,
|
| 247 |
+
by1,
|
| 248 |
+
bz0,
|
| 249 |
+
bz1,
|
| 250 |
+
brx0,
|
| 251 |
+
brx1,
|
| 252 |
+
bry0,
|
| 253 |
+
bry1,
|
| 254 |
+
brz0,
|
| 255 |
+
brz1,
|
| 256 |
+
)
|
| 257 |
+
entries.append(entry)
|
| 258 |
+
preview = json.dumps(entries, indent=2)
|
| 259 |
+
status = f"✅ Added load location #{len(entries)}"
|
| 260 |
+
return entries, preview, status
|
| 261 |
+
|
| 262 |
+
|
| 263 |
+
def _clear_force_entries():
|
| 264 |
+
return [], "[]", "🧹 Cleared all load locations"
|
| 265 |
+
|
| 266 |
+
|
| 267 |
+
def _copy_to_tmp(mesh_path: str) -> str:
|
| 268 |
+
abs_path = os.path.abspath(os.path.expanduser(mesh_path))
|
| 269 |
+
stat = os.stat(abs_path)
|
| 270 |
+
key = f"{abs_path}|{stat.st_size}|{stat.st_mtime_ns}"
|
| 271 |
+
digest = hashlib.sha256(key.encode("utf-8")).hexdigest()[:16]
|
| 272 |
+
tmp_dir = os.path.join("./tmp", "force_web_ui_cache")
|
| 273 |
+
os.makedirs(tmp_dir, exist_ok=True)
|
| 274 |
+
dst_name = f"{digest}_{os.path.basename(abs_path)}"
|
| 275 |
+
dst_path = os.path.join(tmp_dir, dst_name)
|
| 276 |
+
if not os.path.exists(dst_path):
|
| 277 |
+
shutil.copy2(abs_path, dst_path)
|
| 278 |
+
return dst_path
|
| 279 |
+
|
| 280 |
+
|
| 281 |
+
def _prepare_preview_mesh(mesh, mesh_path: str, rotated: bool):
|
| 282 |
+
"""Export preview mesh to ./tmp as GLB (fallback to original file)."""
|
| 283 |
+
abs_path = os.path.abspath(os.path.expanduser(mesh_path))
|
| 284 |
+
stat = os.stat(abs_path)
|
| 285 |
+
key = f"{abs_path}|{stat.st_size}|{stat.st_mtime_ns}|rotated={int(bool(rotated))}|preview_v1"
|
| 286 |
+
digest = hashlib.sha256(key.encode("utf-8")).hexdigest()[:16]
|
| 287 |
+
tmp_dir = os.path.join("./tmp", "force_web_ui_cache")
|
| 288 |
+
os.makedirs(tmp_dir, exist_ok=True)
|
| 289 |
+
glb_path = os.path.join(tmp_dir, f"{digest}.glb")
|
| 290 |
+
if not os.path.exists(glb_path):
|
| 291 |
+
try:
|
| 292 |
+
mesh_to_export = mesh
|
| 293 |
+
if isinstance(mesh, trimesh.Scene):
|
| 294 |
+
geoms = [g for g in mesh.dump() if isinstance(g, trimesh.Trimesh)]
|
| 295 |
+
if len(geoms) > 0:
|
| 296 |
+
mesh_to_export = trimesh.util.concatenate(geoms)
|
| 297 |
+
mesh_to_export.export(glb_path)
|
| 298 |
+
except Exception:
|
| 299 |
+
return _copy_to_tmp(mesh_path), "⚠️ Preview GLB export failed; using the original file instead"
|
| 300 |
+
return glb_path, None
|
| 301 |
+
|
| 302 |
+
|
| 303 |
+
def _reduce_faces(mesh: trimesh.Trimesh, target_faces: int) -> trimesh.Trimesh:
|
| 304 |
+
if not isinstance(mesh, trimesh.Trimesh) or mesh.faces is None:
|
| 305 |
+
return mesh
|
| 306 |
+
face_count = int(mesh.faces.shape[0])
|
| 307 |
+
if face_count <= target_faces:
|
| 308 |
+
return mesh
|
| 309 |
+
idx = np.linspace(0, face_count - 1, target_faces, dtype=np.int64)
|
| 310 |
+
faces = mesh.faces[idx]
|
| 311 |
+
mesh_small = trimesh.Trimesh(vertices=mesh.vertices, faces=faces, process=False)
|
| 312 |
+
try:
|
| 313 |
+
mesh_small.remove_unreferenced_vertices()
|
| 314 |
+
except Exception:
|
| 315 |
+
pass
|
| 316 |
+
return mesh_small
|
| 317 |
+
|
| 318 |
+
|
| 319 |
+
def _extract_points_and_mesh(loaded):
|
| 320 |
+
if loaded is None:
|
| 321 |
+
return None, None
|
| 322 |
+
if isinstance(loaded, trimesh.Trimesh):
|
| 323 |
+
pts = loaded.vertices if hasattr(loaded, "vertices") else None
|
| 324 |
+
return (np.asarray(pts) if pts is not None else None), loaded
|
| 325 |
+
if isinstance(loaded, trimesh.points.PointCloud):
|
| 326 |
+
pts = loaded.vertices if hasattr(loaded, "vertices") else loaded.points
|
| 327 |
+
return (np.asarray(pts) if pts is not None else None), None
|
| 328 |
+
if isinstance(loaded, trimesh.Scene):
|
| 329 |
+
meshes = []
|
| 330 |
+
points = []
|
| 331 |
+
for geom in loaded.dump():
|
| 332 |
+
if isinstance(geom, trimesh.Trimesh):
|
| 333 |
+
meshes.append(geom)
|
| 334 |
+
elif isinstance(geom, trimesh.points.PointCloud):
|
| 335 |
+
pts = geom.vertices if hasattr(geom, "vertices") else geom.points
|
| 336 |
+
if pts is not None:
|
| 337 |
+
points.append(np.asarray(pts))
|
| 338 |
+
if meshes:
|
| 339 |
+
mesh = trimesh.util.concatenate(meshes)
|
| 340 |
+
pts = mesh.vertices if hasattr(mesh, "vertices") else None
|
| 341 |
+
return (np.asarray(pts) if pts is not None else None), mesh
|
| 342 |
+
if points:
|
| 343 |
+
return np.concatenate(points, axis=0), None
|
| 344 |
+
return None, None
|
| 345 |
+
|
| 346 |
+
|
| 347 |
+
def _rotate_points_and_mesh(points, mesh, enable_rotation: bool):
|
| 348 |
+
if not enable_rotation:
|
| 349 |
+
return points, mesh
|
| 350 |
+
|
| 351 |
+
rot = np.asarray(ROTATE_X_CCW_90, dtype=np.float64)
|
| 352 |
+
|
| 353 |
+
rotated_points = None
|
| 354 |
+
if points is not None:
|
| 355 |
+
rotated_points = trimesh.transform_points(np.asarray(points, dtype=np.float64), rot)
|
| 356 |
+
|
| 357 |
+
rotated_mesh = None
|
| 358 |
+
if mesh is not None:
|
| 359 |
+
rotated_mesh = mesh.copy()
|
| 360 |
+
rotated_mesh.apply_transform(rot)
|
| 361 |
+
|
| 362 |
+
return rotated_points, rotated_mesh
|
| 363 |
+
|
| 364 |
+
|
| 365 |
+
def _make_preview_mesh_from_points(points: np.ndarray):
|
| 366 |
+
if points is None or len(points) == 0:
|
| 367 |
+
return None, "⚠️ The point cloud is empty and cannot be previewed"
|
| 368 |
+
points = np.asarray(points, dtype=np.float32)
|
| 369 |
+
total = int(points.shape[0])
|
| 370 |
+
if total > POINT_PREVIEW_MAX:
|
| 371 |
+
idx = np.linspace(0, total - 1, POINT_PREVIEW_MAX, dtype=np.int64)
|
| 372 |
+
pts = points[idx]
|
| 373 |
+
sample_note = f" (sampled {POINT_PREVIEW_MAX}/{total})"
|
| 374 |
+
else:
|
| 375 |
+
pts = points
|
| 376 |
+
sample_note = f" ({total} pts)"
|
| 377 |
+
min_b = points.min(axis=0)
|
| 378 |
+
max_b = points.max(axis=0)
|
| 379 |
+
max_range = float(np.max(max_b - min_b))
|
| 380 |
+
if not np.isfinite(max_range) or max_range <= 0:
|
| 381 |
+
max_range = 1.0
|
| 382 |
+
point_size = max(max_range * POINT_PREVIEW_SIZE_RATIO, 1e-4)
|
| 383 |
+
try:
|
| 384 |
+
base = trimesh.creation.box(extents=[point_size, point_size, point_size])
|
| 385 |
+
v = base.vertices
|
| 386 |
+
f = base.faces
|
| 387 |
+
num = int(pts.shape[0])
|
| 388 |
+
verts = (v[None, :, :] + pts[:, None, :]).reshape(-1, 3)
|
| 389 |
+
faces = (f[None, :, :] + (np.arange(num) * len(v))[:, None, None]).reshape(-1, 3)
|
| 390 |
+
cloud_mesh = trimesh.Trimesh(vertices=verts, faces=faces, process=False)
|
| 391 |
+
cloud_mesh.visual.face_colors = [120, 120, 120, 100]
|
| 392 |
+
return cloud_mesh, f"✅ Point-cloud preview{sample_note}, point size≈{point_size:.4f}"
|
| 393 |
+
except Exception as e:
|
| 394 |
+
extents = np.maximum(max_b - min_b, 1e-6)
|
| 395 |
+
center = (min_b + max_b) * 0.5
|
| 396 |
+
transform = trimesh.transformations.translation_matrix(center)
|
| 397 |
+
box = trimesh.creation.box(extents=extents, transform=transform)
|
| 398 |
+
box.visual.face_colors = [160, 160, 160, 60]
|
| 399 |
+
return box, f"⚠️ Point-cloud preview failed; using a bounding box instead: {e}"
|
| 400 |
+
|
| 401 |
+
|
| 402 |
+
def _load_mesh(mesh_path: str, z_up: bool):
|
| 403 |
+
mesh_path = (mesh_path or "").strip()
|
| 404 |
+
if not mesh_path:
|
| 405 |
+
return "⚠️ Please enter a mesh path", "", None, None, None
|
| 406 |
+
if not os.path.exists(mesh_path):
|
| 407 |
+
return f"⚠️ Path does not exist: {mesh_path}", "", None, None, None
|
| 408 |
+
try:
|
| 409 |
+
loaded = trimesh.load(mesh_path, force="scene")
|
| 410 |
+
points, mesh = _extract_points_and_mesh(loaded)
|
| 411 |
+
if points is None or len(points) == 0:
|
| 412 |
+
return "⚠️ The mesh is empty or failed to load", "", None, None, None
|
| 413 |
+
points, mesh = _rotate_points_and_mesh(points, mesh, enable_rotation=bool(z_up))
|
| 414 |
+
status_prefix = "✅ Mesh loaded"
|
| 415 |
+
preview_note = None
|
| 416 |
+
target_faces = 100000
|
| 417 |
+
if isinstance(mesh, trimesh.Trimesh) and mesh.faces is not None:
|
| 418 |
+
face_count = int(mesh.faces.shape[0])
|
| 419 |
+
if face_count == 0:
|
| 420 |
+
preview_mesh, preview_note = _make_preview_mesh_from_points(points)
|
| 421 |
+
mesh = preview_mesh
|
| 422 |
+
status_prefix = "✅ Point cloud loaded"
|
| 423 |
+
elif face_count > target_faces:
|
| 424 |
+
try:
|
| 425 |
+
mesh = mesh.simplify_quadratic_decimation(target_faces)
|
| 426 |
+
status_prefix += f" (simplified: {face_count} -> {mesh.faces.shape[0]} faces)"
|
| 427 |
+
except Exception:
|
| 428 |
+
mesh = _reduce_faces(mesh, target_faces)
|
| 429 |
+
if hasattr(mesh, "faces") and mesh.faces is not None:
|
| 430 |
+
status_prefix += f" (sample-based reduction: {face_count} -> {mesh.faces.shape[0]} faces)"
|
| 431 |
+
else:
|
| 432 |
+
status_prefix += f" (⚠️ simplification failed, faces={face_count})"
|
| 433 |
+
elif mesh is None:
|
| 434 |
+
preview_mesh, preview_note = _make_preview_mesh_from_points(points)
|
| 435 |
+
mesh = preview_mesh
|
| 436 |
+
status_prefix = "✅ Point cloud loaded"
|
| 437 |
+
|
| 438 |
+
min_b = points.min(axis=0)
|
| 439 |
+
max_b = points.max(axis=0)
|
| 440 |
+
size = max_b - min_b
|
| 441 |
+
info = (
|
| 442 |
+
f"min: [{min_b[0]:.4f}, {min_b[1]:.4f}, {min_b[2]:.4f}]\n"
|
| 443 |
+
f"max: [{max_b[0]:.4f}, {max_b[1]:.4f}, {max_b[2]:.4f}]\n"
|
| 444 |
+
f"size: [{size[0]:.4f}, {size[1]:.4f}, {size[2]:.4f}]"
|
| 445 |
+
)
|
| 446 |
+
bbox = [float(min_b[0]), float(max_b[0]), float(min_b[1]), float(max_b[1]), float(min_b[2]), float(max_b[2])]
|
| 447 |
+
preview_path, warn = _prepare_preview_mesh(mesh, mesh_path, rotated=bool(z_up))
|
| 448 |
+
status_parts = [status_prefix]
|
| 449 |
+
if z_up:
|
| 450 |
+
status_parts.append("↻ Rotated 90 degrees counterclockwise around the +X axis")
|
| 451 |
+
if warn is not None:
|
| 452 |
+
status_parts.append(warn)
|
| 453 |
+
if preview_note is not None:
|
| 454 |
+
status_parts.append(preview_note)
|
| 455 |
+
status = "\n".join(status_parts)
|
| 456 |
+
return status, info, preview_path, bbox, preview_path
|
| 457 |
+
except Exception as e:
|
| 458 |
+
return f"⚠️ Load failed: {e}", "", None, None, None
|
| 459 |
+
|
| 460 |
+
|
| 461 |
+
def _set_bbox_abs_from_bounds(bounds):
|
| 462 |
+
if not bounds or len(bounds) != 6:
|
| 463 |
+
return [gr.update() for _ in range(6)]
|
| 464 |
+
return [bounds[0], bounds[1], bounds[2], bounds[3], bounds[4], bounds[5]]
|
| 465 |
+
|
| 466 |
+
|
| 467 |
+
def _bbox_from_ratio(bounds, ratio):
|
| 468 |
+
if not bounds or len(bounds) != 6 or not ratio or len(ratio) != 6:
|
| 469 |
+
return None
|
| 470 |
+
x0, x1, y0, y1, z0, z1 = [float(v) for v in bounds]
|
| 471 |
+
rx0, rx1, ry0, ry1, rz0, rz1 = [float(v) for v in ratio]
|
| 472 |
+
return [
|
| 473 |
+
x0 + rx0 * (x1 - x0),
|
| 474 |
+
x0 + rx1 * (x1 - x0),
|
| 475 |
+
y0 + ry0 * (y1 - y0),
|
| 476 |
+
y0 + ry1 * (y1 - y0),
|
| 477 |
+
z0 + rz0 * (z1 - z0),
|
| 478 |
+
z0 + rz1 * (z1 - z0),
|
| 479 |
+
]
|
| 480 |
+
|
| 481 |
+
|
| 482 |
+
def _preview_bbox(
|
| 483 |
+
preview_path: str,
|
| 484 |
+
bounds,
|
| 485 |
+
mode: str,
|
| 486 |
+
bx0: float,
|
| 487 |
+
bx1: float,
|
| 488 |
+
by0: float,
|
| 489 |
+
by1: float,
|
| 490 |
+
bz0: float,
|
| 491 |
+
bz1: float,
|
| 492 |
+
brx0: float,
|
| 493 |
+
brx1: float,
|
| 494 |
+
bry0: float,
|
| 495 |
+
bry1: float,
|
| 496 |
+
brz0: float,
|
| 497 |
+
brz1: float,
|
| 498 |
+
):
|
| 499 |
+
if not preview_path or not os.path.exists(preview_path):
|
| 500 |
+
return gr.update(), "⚠️ Please load a mesh first"
|
| 501 |
+
mode = (mode or "").lower()
|
| 502 |
+
if mode not in ("bbox_abs", "bbox_ratio"):
|
| 503 |
+
return gr.update(), "⚠️ Preview is only available in bbox mode"
|
| 504 |
+
if mode == "bbox_ratio":
|
| 505 |
+
bbox = _bbox_from_ratio(bounds, [brx0, brx1, bry0, bry1, brz0, brz1])
|
| 506 |
+
if bbox is None:
|
| 507 |
+
return gr.update(), "⚠️ bbox_ratio is missing bounds or parameters"
|
| 508 |
+
else:
|
| 509 |
+
bbox = [bx0, bx1, by0, by1, bz0, bz1]
|
| 510 |
+
x0, x1 = sorted([float(bbox[0]), float(bbox[1])])
|
| 511 |
+
y0, y1 = sorted([float(bbox[2]), float(bbox[3])])
|
| 512 |
+
z0, z1 = sorted([float(bbox[4]), float(bbox[5])])
|
| 513 |
+
if x1 - x0 <= 0 or y1 - y0 <= 0 or z1 - z0 <= 0:
|
| 514 |
+
return gr.update(), "⚠️ Invalid bbox size"
|
| 515 |
+
|
| 516 |
+
try:
|
| 517 |
+
base = trimesh.load(preview_path, force="scene")
|
| 518 |
+
scene = base if isinstance(base, trimesh.Scene) else trimesh.Scene(base)
|
| 519 |
+
center = np.array([(x0 + x1) / 2, (y0 + y1) / 2, (z0 + z1) / 2], dtype=np.float64)
|
| 520 |
+
extents = np.array([x1 - x0, y1 - y0, z1 - z0], dtype=np.float64)
|
| 521 |
+
transform = trimesh.transformations.translation_matrix(center)
|
| 522 |
+
box = trimesh.creation.box(extents=extents, transform=transform)
|
| 523 |
+
box.visual.face_colors = [255, 0, 0, 60]
|
| 524 |
+
scene.add_geometry(box, node_name="bbox")
|
| 525 |
+
|
| 526 |
+
stat = os.stat(preview_path)
|
| 527 |
+
key = f"{preview_path}|{stat.st_size}|{stat.st_mtime_ns}|{x0},{x1},{y0},{y1},{z0},{z1}"
|
| 528 |
+
digest = hashlib.sha256(key.encode("utf-8")).hexdigest()[:16]
|
| 529 |
+
tmp_dir = os.path.join("./tmp", "force_web_ui_cache")
|
| 530 |
+
os.makedirs(tmp_dir, exist_ok=True)
|
| 531 |
+
out_path = os.path.join(tmp_dir, f"bbox_{digest}.glb")
|
| 532 |
+
scene.export(out_path)
|
| 533 |
+
return out_path, "✅ Updated bbox preview"
|
| 534 |
+
except Exception as e:
|
| 535 |
+
return gr.update(), f"⚠️ Bbox preview failed: {e}"
|
| 536 |
+
|
| 537 |
+
|
| 538 |
+
def build_ui(default_out: str, z_up: bool):
|
| 539 |
+
with gr.Blocks(title="Force Config UI") as demo:
|
| 540 |
+
gr.Markdown(
|
| 541 |
+
"Set force vector(s) (Y-up) and region. "
|
| 542 |
+
"Use 'Add Force Entry' to create multiple locations; "
|
| 543 |
+
"Save JSON will use entries if any exist."
|
| 544 |
+
)
|
| 545 |
+
|
| 546 |
+
mesh_bounds_state = gr.State(None)
|
| 547 |
+
mesh_preview_state = gr.State(None)
|
| 548 |
+
force_entries_state = gr.State([])
|
| 549 |
+
|
| 550 |
+
out_path = gr.Textbox(label="Output JSON Path", value=default_out)
|
| 551 |
+
mesh_path = gr.Textbox(label="Mesh Path (server)", placeholder="/path/to/mesh.obj")
|
| 552 |
+
with gr.Row():
|
| 553 |
+
load_mesh_btn = gr.Button("Load Mesh")
|
| 554 |
+
fill_bbox_btn = gr.Button("Use Mesh Bounds for BBox")
|
| 555 |
+
mesh_status = gr.Textbox(label="Mesh Status", interactive=False)
|
| 556 |
+
mesh_bounds = gr.Textbox(label="Mesh Bounds", interactive=False)
|
| 557 |
+
mesh_view = gr.Model3D(label="Mesh Preview")
|
| 558 |
+
bbox_status = gr.Textbox(label="BBox Preview Status", interactive=False)
|
| 559 |
+
|
| 560 |
+
if z_up:
|
| 561 |
+
with gr.Row():
|
| 562 |
+
fx = gr.Number(label="Fx (N)", value=0.0)
|
| 563 |
+
fy = gr.Number(label="Fy (N)", value=0.0)
|
| 564 |
+
fz = gr.Number(label="Fz (N)", value=-100000.0)
|
| 565 |
+
else:
|
| 566 |
+
with gr.Row():
|
| 567 |
+
fx = gr.Number(label="Fx (N)", value=0.0)
|
| 568 |
+
fy = gr.Number(label="Fy (N)", value=-100000.0)
|
| 569 |
+
fz = gr.Number(label="Fz (N)", value=0.0)
|
| 570 |
+
extra_forces = gr.Textbox(
|
| 571 |
+
label="Extra Forces (one per line: fx fy fz)",
|
| 572 |
+
placeholder="0 0 -500\n100 0 0",
|
| 573 |
+
lines=3,
|
| 574 |
+
)
|
| 575 |
+
|
| 576 |
+
mode = gr.Radio(
|
| 577 |
+
["global", "top_percent", "height_ratio", "bbox_abs", "bbox_ratio"],
|
| 578 |
+
value="top_percent",
|
| 579 |
+
label="Region Mode",
|
| 580 |
+
)
|
| 581 |
+
|
| 582 |
+
with gr.Group(visible=True) as top_group:
|
| 583 |
+
top_percent = gr.Slider(0.01, 0.5, value=0.05, step=0.01, label="Top Percent")
|
| 584 |
+
|
| 585 |
+
with gr.Group(visible=False) as height_group:
|
| 586 |
+
hr_min = gr.Slider(0.0, 1.0, value=0.3, step=0.01, label="Height Min Ratio")
|
| 587 |
+
hr_max = gr.Slider(0.0, 1.0, value=0.5, step=0.01, label="Height Max Ratio")
|
| 588 |
+
|
| 589 |
+
with gr.Group(visible=False) as bbox_abs_group:
|
| 590 |
+
gr.Markdown("BBox (abs) order: x_min, x_max, y_min, y_max, z_min, z_max")
|
| 591 |
+
with gr.Row():
|
| 592 |
+
bx0 = gr.Number(label="x_min", value=-0.2)
|
| 593 |
+
bx1 = gr.Number(label="x_max", value=0.2)
|
| 594 |
+
by0 = gr.Number(label="y_min", value=0.2)
|
| 595 |
+
by1 = gr.Number(label="y_max", value=0.4)
|
| 596 |
+
bz0 = gr.Number(label="z_min", value=-0.2)
|
| 597 |
+
bz1 = gr.Number(label="z_max", value=0.2)
|
| 598 |
+
|
| 599 |
+
with gr.Group(visible=False) as bbox_ratio_group:
|
| 600 |
+
gr.Markdown("BBox (ratio 0-1) order: x_min, x_max, y_min, y_max, z_min, z_max")
|
| 601 |
+
with gr.Row():
|
| 602 |
+
brx0 = gr.Slider(0.0, 1.0, value=0.4, step=0.01, label="x_min")
|
| 603 |
+
brx1 = gr.Slider(0.0, 1.0, value=0.6, step=0.01, label="x_max")
|
| 604 |
+
bry0 = gr.Slider(0.0, 1.0, value=0.4, step=0.01, label="y_min")
|
| 605 |
+
bry1 = gr.Slider(0.0, 1.0, value=0.6, step=0.01, label="y_max")
|
| 606 |
+
brz0 = gr.Slider(0.0, 1.0, value=0.4, step=0.01, label="z_min")
|
| 607 |
+
brz1 = gr.Slider(0.0, 1.0, value=0.6, step=0.01, label="z_max")
|
| 608 |
+
|
| 609 |
+
save_btn = gr.Button("Save JSON", variant="primary")
|
| 610 |
+
add_force_btn = gr.Button("Add Force Entry")
|
| 611 |
+
clear_force_btn = gr.Button("Clear Force Entries")
|
| 612 |
+
preview_bbox_btn = gr.Button("Preview BBox")
|
| 613 |
+
status = gr.Textbox(label="Status")
|
| 614 |
+
force_entries_preview = gr.Code(label="Force Entries", language="json", value="[]")
|
| 615 |
+
preview = gr.Code(label="JSON Preview", language="json")
|
| 616 |
+
cmd = gr.Textbox(label="Command Preview")
|
| 617 |
+
|
| 618 |
+
mode.change(
|
| 619 |
+
_toggle_groups,
|
| 620 |
+
inputs=mode,
|
| 621 |
+
outputs=[top_group, height_group, bbox_abs_group, bbox_ratio_group],
|
| 622 |
+
)
|
| 623 |
+
load_mesh_btn.click(
|
| 624 |
+
_load_mesh,
|
| 625 |
+
inputs=[mesh_path, gr.State(z_up)],
|
| 626 |
+
outputs=[mesh_status, mesh_bounds, mesh_view, mesh_bounds_state, mesh_preview_state],
|
| 627 |
+
)
|
| 628 |
+
fill_bbox_btn.click(
|
| 629 |
+
_set_bbox_abs_from_bounds,
|
| 630 |
+
inputs=[mesh_bounds_state],
|
| 631 |
+
outputs=[bx0, bx1, by0, by1, bz0, bz1],
|
| 632 |
+
)
|
| 633 |
+
preview_bbox_btn.click(
|
| 634 |
+
_preview_bbox,
|
| 635 |
+
inputs=[
|
| 636 |
+
mesh_preview_state,
|
| 637 |
+
mesh_bounds_state,
|
| 638 |
+
mode,
|
| 639 |
+
bx0,
|
| 640 |
+
bx1,
|
| 641 |
+
by0,
|
| 642 |
+
by1,
|
| 643 |
+
bz0,
|
| 644 |
+
bz1,
|
| 645 |
+
brx0,
|
| 646 |
+
brx1,
|
| 647 |
+
bry0,
|
| 648 |
+
bry1,
|
| 649 |
+
brz0,
|
| 650 |
+
brz1,
|
| 651 |
+
],
|
| 652 |
+
outputs=[mesh_view, bbox_status],
|
| 653 |
+
)
|
| 654 |
+
|
| 655 |
+
add_force_btn.click(
|
| 656 |
+
_add_force_entry,
|
| 657 |
+
inputs=[
|
| 658 |
+
force_entries_state,
|
| 659 |
+
fx,
|
| 660 |
+
fy,
|
| 661 |
+
fz,
|
| 662 |
+
extra_forces,
|
| 663 |
+
mode,
|
| 664 |
+
top_percent,
|
| 665 |
+
hr_min,
|
| 666 |
+
hr_max,
|
| 667 |
+
bx0,
|
| 668 |
+
bx1,
|
| 669 |
+
by0,
|
| 670 |
+
by1,
|
| 671 |
+
bz0,
|
| 672 |
+
bz1,
|
| 673 |
+
brx0,
|
| 674 |
+
brx1,
|
| 675 |
+
bry0,
|
| 676 |
+
bry1,
|
| 677 |
+
brz0,
|
| 678 |
+
brz1,
|
| 679 |
+
],
|
| 680 |
+
outputs=[force_entries_state, force_entries_preview, status],
|
| 681 |
+
)
|
| 682 |
+
clear_force_btn.click(
|
| 683 |
+
_clear_force_entries,
|
| 684 |
+
inputs=[],
|
| 685 |
+
outputs=[force_entries_state, force_entries_preview, status],
|
| 686 |
+
)
|
| 687 |
+
|
| 688 |
+
save_btn.click(
|
| 689 |
+
_save_config,
|
| 690 |
+
inputs=[
|
| 691 |
+
out_path,
|
| 692 |
+
fx,
|
| 693 |
+
fy,
|
| 694 |
+
fz,
|
| 695 |
+
extra_forces,
|
| 696 |
+
mode,
|
| 697 |
+
top_percent,
|
| 698 |
+
hr_min,
|
| 699 |
+
hr_max,
|
| 700 |
+
bx0,
|
| 701 |
+
bx1,
|
| 702 |
+
by0,
|
| 703 |
+
by1,
|
| 704 |
+
bz0,
|
| 705 |
+
bz1,
|
| 706 |
+
brx0,
|
| 707 |
+
brx1,
|
| 708 |
+
bry0,
|
| 709 |
+
bry1,
|
| 710 |
+
brz0,
|
| 711 |
+
brz1,
|
| 712 |
+
force_entries_state,
|
| 713 |
+
],
|
| 714 |
+
outputs=[status, preview, cmd],
|
| 715 |
+
)
|
| 716 |
+
return demo
|
| 717 |
+
|
| 718 |
+
|
| 719 |
+
def main():
|
| 720 |
+
parser = argparse.ArgumentParser(description="Force config web UI")
|
| 721 |
+
parser.add_argument("--out", type=str, default="force_config.json", help="Output JSON path")
|
| 722 |
+
parser.add_argument("--server_name", type=str, default="0.0.0.0", help="Gradio server name")
|
| 723 |
+
parser.add_argument("--server_port", type=int, default=7860, help="Gradio server port")
|
| 724 |
+
parser.add_argument("--share", action="store_true", help="Enable Gradio share link")
|
| 725 |
+
parser.add_argument("--z_up", action="store_true", help="Enable z_up mode")
|
| 726 |
+
args = parser.parse_args()
|
| 727 |
+
|
| 728 |
+
demo = build_ui(args.out, args.z_up)
|
| 729 |
+
demo.launch(server_name=args.server_name, server_port=args.server_port, share=args.share)
|
| 730 |
+
|
| 731 |
+
|
| 732 |
+
if __name__ == "__main__":
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Hunyuan3D-2.1 Shape Generation Script
|
| 3 |
+
Generate a 3D shape and save latent tokens for later physics optimization.
|
| 4 |
+
"""
|
| 5 |
+
|
| 6 |
+
# python scripts/sample_hunyuan.py --image /scratch/cvlab/home/seiler/physiopt_new/input/new_york.png --out_folder /scratch/cvlab/home/seiler/physiopt_new/output/hunyuan_gen/new_york
|
| 7 |
+
|
| 8 |
+
import os
|
| 9 |
+
# os.environ['TORCH_HOME'] = '/mnt/cvlab/scratch/cvlab/home/hantzhan/.torch'
|
| 10 |
+
import sys
|
| 11 |
+
|
| 12 |
+
# Add Hunyuan3D-2.1 to the Python path.
|
| 13 |
+
hunyuan_path = os.path.abspath(os.path.join(os.path.dirname(__file__), "../Hunyuan3D-2.1"))
|
| 14 |
+
print(hunyuan_path)
|
| 15 |
+
if os.path.exists(hunyuan_path):
|
| 16 |
+
sys.path.insert(0, hunyuan_path)
|
| 17 |
+
print(f"✅ Added Hunyuan3D-2.1 to the Python path: {hunyuan_path}")
|
| 18 |
+
else:
|
| 19 |
+
print(f"⚠️ Warning: Hunyuan3D-2.1 path does not exist: {hunyuan_path}")
|
| 20 |
+
print(f" Please make sure Hunyuan3D-2.1 has been cloned to the correct location")
|
| 21 |
+
|
| 22 |
+
sys.path.append("..")
|
| 23 |
+
|
| 24 |
+
import torch
|
| 25 |
+
import trimesh
|
| 26 |
+
import numpy as np
|
| 27 |
+
from PIL import Image
|
| 28 |
+
from argparse import ArgumentParser
|
| 29 |
+
|
| 30 |
+
try:
|
| 31 |
+
from hy3dgen.rembg import BackgroundRemover
|
| 32 |
+
from hy3dgen.shapegen import Hunyuan3DDiTFlowMatchingPipeline
|
| 33 |
+
from hy3dgen.shapegen.models.autoencoders import ShapeVAE
|
| 34 |
+
except ImportError as e:
|
| 35 |
+
print(f"❌ Failed to import the Hunyuan3D modules: {e}")
|
| 36 |
+
print(f"\nPlease set up Hunyuan3D-2.1 with the following steps:")
|
| 37 |
+
print(f"1. cd {os.path.dirname(hunyuan_path)}")
|
| 38 |
+
print(f"2. git clone https://github.com/Tencent/Hunyuan3D-2.git Hunyuan3D-2.1")
|
| 39 |
+
print(f"3. cd Hunyuan3D-2.1")
|
| 40 |
+
print(f"4. pip install -e .")
|
| 41 |
+
sys.exit(1)
|
| 42 |
+
|
| 43 |
+
|
| 44 |
+
if __name__ == "__main__":
|
| 45 |
+
parser = ArgumentParser()
|
| 46 |
+
parser.add_argument("--image", type=str, required=True, help="Input image path")
|
| 47 |
+
parser.add_argument("--out_folder", type=str, default="../out/hunyuan_tmp", help="Output directory")
|
| 48 |
+
parser.add_argument("--seed", type=int, default=42, help="Random seed (base value)")
|
| 49 |
+
parser.add_argument("--num_results", type=int, default=1, help="Number of generated results (different seeds)")
|
| 50 |
+
parser.add_argument("--num_inference_steps", type=int, default=50, help="Number of inference steps")
|
| 51 |
+
parser.add_argument("--guidance_scale", type=float, default=7.5, help="CFG strength")
|
| 52 |
+
parser.add_argument("--model_path", type=str, default="tencent/Hunyuan3D-2.1", help="Model path (using v2.1)")
|
| 53 |
+
parser.add_argument("--subfolder", type=str, default="hunyuan3d-dit-v2-1", help="Model subfolder")
|
| 54 |
+
parser.add_argument("--use_safetensors", action="store_true", help="Use safetensors format (default is ckpt)")
|
| 55 |
+
parser.add_argument("--octree_resolution", type=int, default=384, help="Octree resolution (higher is finer but slower)")
|
| 56 |
+
parser.add_argument("--mc_level", type=float, default=0, help="Marching Cubes threshold")
|
| 57 |
+
args = parser.parse_args()
|
| 58 |
+
|
| 59 |
+
# Create the output directory.
|
| 60 |
+
os.makedirs(args.out_folder, exist_ok=True)
|
| 61 |
+
|
| 62 |
+
# Print configuration details.
|
| 63 |
+
print("\n" + "="*60)
|
| 64 |
+
print("Hunyuan3D-2.1 configuration:")
|
| 65 |
+
print(f" - Model: {args.model_path}/{args.subfolder}")
|
| 66 |
+
print(f" - Model format: {'safetensors' if args.use_safetensors else 'checkpoint (.ckpt)'}")
|
| 67 |
+
print(f" - Inference steps: {args.num_inference_steps} (recommended: 50-100)")
|
| 68 |
+
print(f" - Result count: {args.num_results}")
|
| 69 |
+
print(f" - CFG strength: {args.guidance_scale} (recommended: 7.0-10.0)")
|
| 70 |
+
print(f" - Octree resolution: {args.octree_resolution} (recommended: 384-512)")
|
| 71 |
+
print(f" - MC threshold: {args.mc_level:.6f}")
|
| 72 |
+
print("="*60 + "\n")
|
| 73 |
+
|
| 74 |
+
# ==================== Load the model ====================
|
| 75 |
+
print("🔧 Loading the Hunyuan3D-2.1 model...")
|
| 76 |
+
print(f" Model path: {args.model_path}")
|
| 77 |
+
print(f" Subfolder: {args.subfolder}")
|
| 78 |
+
|
| 79 |
+
try:
|
| 80 |
+
# Use the v2.1 model (newer and stronger).
|
| 81 |
+
# v2.1 uses the .ckpt format, so use_safetensors=False is required.
|
| 82 |
+
pipeline = Hunyuan3DDiTFlowMatchingPipeline.from_pretrained(
|
| 83 |
+
args.model_path,
|
| 84 |
+
subfolder=args.subfolder,
|
| 85 |
+
torch_dtype=torch.float16,
|
| 86 |
+
use_safetensors=args.use_safetensors
|
| 87 |
+
)
|
| 88 |
+
|
| 89 |
+
if pipeline is None:
|
| 90 |
+
raise ValueError("Pipeline loading failed and returned None")
|
| 91 |
+
|
| 92 |
+
print(" ✅ Pipeline loaded successfully")
|
| 93 |
+
|
| 94 |
+
# Note: to() may not return self, so do not reassign pipeline.
|
| 95 |
+
pipeline.to('cuda')
|
| 96 |
+
print(" ✅ Model moved to CUDA (dtype: fp16)")
|
| 97 |
+
|
| 98 |
+
except Exception as e:
|
| 99 |
+
print(f"\n❌ Model loading failed: {e}")
|
| 100 |
+
print(f"\nPossible causes:")
|
| 101 |
+
print(f"1. The model has not been downloaded yet - the first run fetches it from Hugging Face")
|
| 102 |
+
print(f"2. Network issues - make sure huggingface.co is reachable")
|
| 103 |
+
print(f"3. Insufficient disk space")
|
| 104 |
+
print(f"\nSuggested fixes:")
|
| 105 |
+
print(f"1. Set a Hugging Face token if the model requires one:")
|
| 106 |
+
print(f" huggingface-cli login")
|
| 107 |
+
print(f"2. Or download the model manually:")
|
| 108 |
+
print(f" git lfs install")
|
| 109 |
+
print(f" git clone https://huggingface.co/tencent/Hunyuan3D-2.1")
|
| 110 |
+
print(f" Then use --model_path ./Hunyuan3D-2.1 --subfolder hunyuan3d-dit-v2-1")
|
| 111 |
+
print(f"3. Or use the v2.0 model instead:")
|
| 112 |
+
print(f" --model_path tencent/Hunyuan3D-2 --subfolder hunyuan3d-dit-v2-0")
|
| 113 |
+
import traceback
|
| 114 |
+
traceback.print_exc()
|
| 115 |
+
sys.exit(1)
|
| 116 |
+
|
| 117 |
+
# Get the VAE for later mesh generation.
|
| 118 |
+
vae = pipeline.vae
|
| 119 |
+
print(f" ✅ VAE acquired successfully")
|
| 120 |
+
|
| 121 |
+
# ==================== Prepare the input image ====================
|
| 122 |
+
print(f"📷 Loading image: {args.image}")
|
| 123 |
+
image = Image.open(args.image).convert("RGBA")
|
| 124 |
+
|
| 125 |
+
# If this is an RGB image, remove the background with rembg.
|
| 126 |
+
if image.mode == 'RGB':
|
| 127 |
+
print(" Removing background...")
|
| 128 |
+
rembg = BackgroundRemover()
|
| 129 |
+
image = rembg(image)
|
| 130 |
+
|
| 131 |
+
# Save the processed image.
|
| 132 |
+
image.save(os.path.join(args.out_folder, "input_image.png"))
|
| 133 |
+
|
| 134 |
+
# ==================== Generate the 3D shape ====================
|
| 135 |
+
print(f"🎨 Generating a 3D shape (steps={args.num_inference_steps}, cfg={args.guidance_scale})...")
|
| 136 |
+
num_results = max(1, int(args.num_results))
|
| 137 |
+
|
| 138 |
+
for idx in range(num_results):
|
| 139 |
+
sample_seed = args.seed + idx
|
| 140 |
+
sample_out = args.out_folder if num_results == 1 else os.path.join(args.out_folder, f"sample_{idx:02d}")
|
| 141 |
+
os.makedirs(sample_out, exist_ok=True)
|
| 142 |
+
|
| 143 |
+
if num_results > 1:
|
| 144 |
+
image.save(os.path.join(sample_out, "input_image.png"))
|
| 145 |
+
|
| 146 |
+
print(f"\n=== Sample {idx+1}/{num_results} | seed={sample_seed} ===")
|
| 147 |
+
|
| 148 |
+
# Set random seeds.
|
| 149 |
+
torch.manual_seed(sample_seed)
|
| 150 |
+
np.random.seed(sample_seed)
|
| 151 |
+
|
| 152 |
+
# Use the simplified pipeline call, consistent with sample_hunyuan_simple.py.
|
| 153 |
+
# Step 1: generate and save latents.
|
| 154 |
+
latents = pipeline(
|
| 155 |
+
image=image,
|
| 156 |
+
num_inference_steps=args.num_inference_steps,
|
| 157 |
+
guidance_scale=args.guidance_scale,
|
| 158 |
+
generator=torch.Generator(device='cuda').manual_seed(sample_seed),
|
| 159 |
+
output_type='latent', # Return latents only; do not decode to mesh yet.
|
| 160 |
+
)
|
| 161 |
+
|
| 162 |
+
print("✅ Latent generation completed!")
|
| 163 |
+
|
| 164 |
+
# ==================== Save latents for physics optimization ====================
|
| 165 |
+
latents_path = os.path.join(sample_out, "latents.pt")
|
| 166 |
+
|
| 167 |
+
# Save latents and the image.
|
| 168 |
+
save_dict = {
|
| 169 |
+
'latents': latents.cpu() if isinstance(latents, torch.Tensor) else latents,
|
| 170 |
+
'image': np.array(image)
|
| 171 |
+
}
|
| 172 |
+
|
| 173 |
+
torch.save(save_dict, latents_path)
|
| 174 |
+
print(f"✅ Saved latents to: {latents_path}")
|
| 175 |
+
if isinstance(latents, torch.Tensor):
|
| 176 |
+
print(f" - Latents shape: {latents.shape}")
|
| 177 |
+
print(f" - Latents range: [{latents.min().item():.3f}, {latents.max().item():.3f}]")
|
| 178 |
+
|
| 179 |
+
# Step 2: decode latents to a mesh with _export().
|
| 180 |
+
print(f"🎭 Decoding latents into a mesh...")
|
| 181 |
+
print(f" Using parameters: octree_resolution={args.octree_resolution}, mc_level={args.mc_level:.6f}")
|
| 182 |
+
mesh = pipeline._export(
|
| 183 |
+
latents,
|
| 184 |
+
output_type='trimesh',
|
| 185 |
+
box_v=1.01,
|
| 186 |
+
mc_level=args.mc_level,
|
| 187 |
+
num_chunks=20000,
|
| 188 |
+
octree_resolution=args.octree_resolution,
|
| 189 |
+
mc_algo='mc',
|
| 190 |
+
enable_pbar=True
|
| 191 |
+
)[0]
|
| 192 |
+
|
| 193 |
+
print("✅ Decoding completed!")
|
| 194 |
+
|
| 195 |
+
# ==================== Save the mesh ====================
|
| 196 |
+
mesh_path = os.path.join(sample_out, "generated_mesh.obj")
|
| 197 |
+
mesh.export(mesh_path)
|
| 198 |
+
print(f"💾 Saved mesh to: {mesh_path}")
|
| 199 |
+
|
| 200 |
+
# Save GLB as well.
|
| 201 |
+
glb_path = os.path.join(sample_out, "generated_mesh.glb")
|
| 202 |
+
mesh.export(glb_path)
|
| 203 |
+
print(f"💾 Saved GLB to: {glb_path}")
|
| 204 |
+
|
| 205 |
+
# ==================== Print summary statistics ====================
|
| 206 |
+
print("\n📊 Generation summary:")
|
| 207 |
+
print(f" - Vertices: {len(mesh.vertices)}")
|
| 208 |
+
print(f" - Faces: {len(mesh.faces)}")
|
| 209 |
+
if isinstance(latents, torch.Tensor):
|
| 210 |
+
print(f" - Latent shape: {latents.shape}")
|
| 211 |
+
|
| 212 |
+
# Free GPU memory.
|
| 213 |
+
del mesh
|
| 214 |
+
if torch.cuda.is_available():
|
| 215 |
+
torch.cuda.empty_cache()
|
| 216 |
+
|
| 217 |
+
print(f"\n✅ All done! Outputs were saved to: {args.out_folder}")
|
| 218 |
+
if num_results == 1:
|
| 219 |
+
print(f" - You can use latents.pt for physics optimization")
|
| 220 |
+
print(f" - Run: python viewer_hunyuan_web.py --latents {latents_path}")
|
| 221 |
+
else:
|
| 222 |
+
print(f" - Each sample is stored in its own sample_XX subdirectory")
|
cfd_workflow_20261012/seiler_pipeline/scripts/viewer_hunyuan_web_alternate.py
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
cfd_workflow_20261012/seiler_pipeline/scripts/viewer_hunyuan_web_physiopt.py
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|