glb减面平滑

发布时间:2026/10/15 10:24:47
glb减面平滑 控制目标10万个三角面耗时5s时间。import time import bpy import os import trimesh def count_triangles(obj): 统计物体三角面片数量 if obj.type ! MESH or obj.data is None: return 0 return sum(len(poly.vertices)-2 for poly in obj.data.polygons) def simplify_mesh_target_tri(obj, target_tri100000): bpy.context.view_layer.objects.active obj obj.select_set(True) tri_old count_triangles(obj) print(f物体 {obj.name} 当前三角面: {tri_old}, 目标:{target_tri}) # 如果已经少于目标直接跳过不减面 if tri_old target_tri: print(f{obj.name} 面数已经小于目标跳过减面) return tri_old # 计算比例 ratio target_tri / tri_old # 限制最大ratio1防止异常 ratio min(ratio, 1.0) print(f计算得到减面比例 ratio {ratio:.6f}) mod_decimate obj.modifiers.new(nameDecimate, typeDECIMATE) mod_decimate.decimate_type COLLAPSE # 一次减面 mod_decimate.ratio ratio # 强制三角化避免四边面干扰计数 mod_decimate.use_collapse_triangulate True bpy.ops.object.modifier_apply(modifiermod_decimate.name) tri_new count_triangles(obj) print(f✅ {obj.name} 减面完成最终三角面 {tri_new}) return tri_new def glb_simplify_coarse_target(input_glb_path, output_glb_path, target_tri100000): # 清空场景 bpy.ops.object.select_all(actionSELECT) bpy.ops.object.delete() # 导入GLB bpy.ops.import_scene.gltf(filepathinput_glb_path) obj_list [] for obj in bpy.data.objects: if obj.type MESH and obj.data and len(obj.data.vertices) 0: obj_list.append(obj) total_before 0 for obj in obj_list: tri count_triangles(obj) total_before tri print(f\n 减面前总三角面{total_before} \n) total_after 0 export_target_objs [] for obj in obj_list: final_tri simplify_mesh_target_tri(obj, target_tritarget_tri) if len(obj.data.vertices) 0: print(f警告{obj.name} 减面后顶点为空跳过) continue export_target_objs.append(obj) total_after final_tri print(f\n 减面后总三角面{total_after} ) # 导出前选中处理好的mesh bpy.ops.object.select_all(actionDESELECT) for o in export_target_objs: o.select_set(True) # 导出GLB bpy.ops.export_scene.gltf( filepathoutput_glb_path, export_formatGLB, use_selectionTrue, ) print(f\n导出完成: {output_glb_path}) return total_after # 配置 TARGET_TRI 100000 IN_PATH rE:\project\3d_label\chai_server\0914_1306_0.glb OUT_PATH rfE:\project\3d_label\chai_server\0914_1306_target_{TARGET_TRI//10000}.glb starttime.time() glb_simplify_coarse_target(IN_PATH, OUT_PATH, target_triTARGET_TRI) print(time,time.time()-start) # trimesh校验输出面数 scene trimesh.load(OUT_PATH) geo_keys list(scene.geometry.keys()) if len(geo_keys) 0: raise Exception(GLB里面没有几何体) mesh scene.geometry[geo_keys[0]] print(\n trimesh校验结果 ) print(fvertices shape: {mesh.vertices.shape}, faces shape: {mesh.faces.shape}) print(f三角面片数量(mesh.faces.shape[0]) {mesh.faces.shape[0]}) print(f模型表面积: {mesh.area:.4f})