def fix_mesh(mesh, resolution): bbox_min, bbox_max = mesh.bbox diag_len = norm(bbox_max - bbox_min) target_len = diag_len * resolution rospy.loginfo("\tTarget resolution: {} mm".format(target_len)) count = 0 mesh, __ = pymesh.remove_degenerated_triangles(mesh, 100) mesh, __ = pymesh.split_long_edges(mesh, target_len) num_vertices = mesh.num_vertices while True: mesh, __ = pymesh.collapse_short_edges(mesh, 1e-6) mesh, __ = pymesh.collapse_short_edges(mesh, target_len, preserve_feature=True) mesh, __ = pymesh.remove_obtuse_triangles(mesh, 150.0, 100) if mesh.num_vertices == num_vertices: break num_vertices = mesh.num_vertices rospy.loginfo("\t#vertices: {}".format(num_vertices)) count += 1 if count > 2: break mesh = pymesh.resolve_self_intersection(mesh) mesh, __ = pymesh.remove_duplicated_faces(mesh) mesh = pymesh.compute_outer_hull(mesh) mesh, __ = pymesh.remove_duplicated_faces(mesh) mesh, __ = pymesh.remove_obtuse_triangles(mesh, 179.0, 5) mesh, __ = pymesh.remove_isolated_vertices(mesh) return mesh
def fix_meshes(mesh, detail="normal"): meshCopy = mesh # copy/pasta of pymesh script fix_mesh from qnzhou, see pymesh on GitHub bbox_min, bbox_max = mesh.bbox diag_len = np.linalg.norm(bbox_max - bbox_min) if detail == "normal": target_len = diag_len * 5e-3 elif detail == "high": target_len = diag_len * 2.5e-3 elif detail == "low": target_len = diag_len * 1e-2 count = 0 mesh, __ = pymesh.remove_degenerated_triangles(mesh, 100) mesh, __ = pymesh.split_long_edges(mesh, target_len) num_vertices = mesh.num_vertices while True: mesh, __ = pymesh.collapse_short_edges(mesh, 1e-6) mesh, __ = pymesh.collapse_short_edges(mesh, target_len, preserve_feature=True) mesh, __ = pymesh.remove_obtuse_triangles(mesh, 150.0, 100) if mesh.num_vertices == num_vertices: break num_vertices = mesh.num_vertices count += 1 if count > 10: break mesh = pymesh.resolve_self_intersection(mesh) mesh, __ = pymesh.remove_duplicated_faces(mesh) mesh = pymesh.compute_outer_hull(mesh) mesh, __ = pymesh.remove_duplicated_faces(mesh) mesh, __ = pymesh.remove_obtuse_triangles(mesh, 179.0, 5) mesh, __ = pymesh.remove_isolated_vertices(mesh) if is_mesh_broken(mesh, meshCopy) is True: if detail == "high": print( f'The function fix_meshes broke mesh, trying with lower details settings' ) fix_meshes(mesh, detail="normal") if detail == "normal": print( f'The function fix_meshes broke mesh, trying with lower details settings' ) fix_meshes(mesh, detail="low") if detail == "low": print( f'The function fix_meshes broke mesh, no lower settings can be applied, no fix was done' ) return meshCopy else: return mesh
def carve_mesh(target_mesh, block, N, batch_size, out_name, initial_N=0, save_intermediate=True, debug=False): name, ext = os.path.splitext(out_name); tree = pymesh.AABBTree(); tree.load_mesh(target_mesh); dodecahedron = pymesh.generate_dodecahedron(1.0, np.zeros(3)); vertices = dodecahedron.vertices; faces = dodecahedron.faces; for i in range(initial_N, N, batch_size): pts = block.vertices; squared_dist, face_indices, closest_pts = \ tree.look_up_with_closest_points(pts); n = np.min([batch_size, N-i, len(pts)]); indices = np.argsort(squared_dist)[::-1][:n]; radii = np.sqrt(squared_dist[indices]); centers = pts[indices, :]; to_remove = [pymesh.form_mesh( np.dot(pymesh.Quaternion(numpy.random.rand(4)).to_matrix(), vertices.T * r).T + p, faces) for r,p in zip(radii, centers)]; to_remove = pymesh.merge_meshes(to_remove); if debug: pymesh.save_mesh("deubg_block.msh", block); pymesh.save_mesh("deubg_cut.msh", to_remove); block = pymesh.boolean(block, to_remove, "difference", engine="igl"); block, __ = pymesh.collapse_short_edges(block, 1e-12, False); if save_intermediate: pymesh.save_mesh("{}_{:06}{}".format(name, i, ext), block); return block;
def clean_up_mesh(mesh, tol): new_mesh, _ = pymesh.remove_isolated_vertices(mesh) new_mesh, _ = pymesh.remove_duplicated_vertices(new_mesh) new_mesh, _ = pymesh.remove_duplicated_faces(new_mesh) new_mesh, _ = pymesh.remove_degenerated_triangles(new_mesh) new_mesh, _ = pymesh.collapse_short_edges(new_mesh, rel_threshold=0.2) return new_mesh
def fix_mesh(mesh, detail=5e-3): # "normal": 5e-3 # "high": 2.5e-3 # "low": 2e-2 # "vlow": 2.5e-2 bbox_min, bbox_max = mesh.bbox diag_len = np.linalg.norm(bbox_max - bbox_min) if detail is None: detail = 5e-3 target_len = diag_len * detail print("Target resolution: {} mm".format(target_len)) count = 0 mesh, __ = pymesh.remove_degenerated_triangles(mesh, 100) mesh, __ = pymesh.split_long_edges(mesh, target_len) num_vertices = mesh.num_vertices while True: mesh, __ = pymesh.collapse_short_edges(mesh, 1e-4) mesh, __ = pymesh.collapse_short_edges(mesh, target_len, preserve_feature=True) mesh, __ = pymesh.remove_isolated_vertices(mesh) mesh, __ = pymesh.remove_duplicated_vertices(mesh, tol=1e-4) mesh, __ = pymesh.remove_duplicated_faces(mesh) mesh, __ = pymesh.remove_degenerated_triangles(mesh) mesh, __ = pymesh.remove_isolated_vertices(mesh) mesh, __ = pymesh.remove_obtuse_triangles(mesh, 150.0, 100) if mesh.num_vertices == num_vertices: break num_vertices = mesh.num_vertices print("fix #v: {}".format(num_vertices)) count += 1 if count > 10: break mesh = pymesh.resolve_self_intersection(mesh) mesh, __ = pymesh.remove_duplicated_faces(mesh) mesh = pymesh.compute_outer_hull(mesh) mesh, __ = pymesh.remove_duplicated_faces(mesh) mesh, __ = pymesh.remove_obtuse_triangles(mesh, 179.0, 5) mesh, __ = pymesh.remove_isolated_vertices(mesh) return mesh
def fix_mesh(mesh, detail="normal"): bbox_min, bbox_max = mesh.bbox diag_len = norm(bbox_max - bbox_min) if detail == "normal": target_len = diag_len * 1e-2 elif detail == "high": target_len = diag_len * 5e-3 elif detail == "low": target_len = diag_len * 0.03 print("Target resolution: {} mm".format(target_len)) count = 0 mesh, __ = pymesh.remove_degenerated_triangles(mesh, 100) mesh, __ = pymesh.split_long_edges(mesh, target_len) num_vertices = mesh.num_vertices while True: mesh, __ = pymesh.collapse_short_edges(mesh, 1e-6) mesh, __ = pymesh.collapse_short_edges(mesh, target_len, preserve_feature=True) mesh, __ = pymesh.remove_obtuse_triangles(mesh, 150.0, 100) if mesh.num_vertices == num_vertices: break num_vertices = mesh.num_vertices print("#v: {}".format(num_vertices)) count += 1 if count > 10: break mesh = pymesh.resolve_self_intersection(mesh) mesh, __ = pymesh.remove_duplicated_faces(mesh) mesh = pymesh.compute_outer_hull(mesh) mesh, __ = pymesh.remove_duplicated_faces(mesh) mesh, __ = pymesh.remove_obtuse_triangles(mesh, 179.0, 5) mesh, __ = pymesh.remove_isolated_vertices(mesh) return mesh
def refine_mesh(mesh, cycles, long_threshold, **kwargs): """ kwargs can be: abs_threshold, rel_threshold, preserve_feature """ for i in range(cycles): mesh, _ = pymesh.split_long_edges(mesh, long_threshold) mesh, _ = pymesh.collapse_short_edges(mesh, **kwargs) return mesh
def fix_mesh(mesh, detail="normal"): bbox_min, bbox_max = mesh.bbox; diag_len = norm(bbox_max - bbox_min); if detail == "normal": target_len = diag_len * 1e-2; #target_len = diag_len * 5e-3; elif detail == "enormal": target_len = diag_len * 5e-3 elif detail == "high": target_len = diag_len * 3e-3 #target_len = diag_len * 2.5e-3; elif detail == "low": target_len = diag_len * 1e-2; elif detail == "ehigh": target_len = diag_len * 1e-3; print("Target resolution: {} mm".format(target_len)); count = 0; mesh, __ = pymesh.remove_degenerated_triangles(mesh, 100); mesh, __ = pymesh.split_long_edges(mesh, target_len); num_vertices = mesh.num_vertices; while True: #mesh, __ = pymesh.collapse_short_edges(mesh, 1e-6); if detail == "low": mesh, __ = pymesh.collapse_short_edges(mesh, target_len, preserve_feature=False); else: mesh, __ = pymesh.collapse_short_edges(mesh, target_len, preserve_feature=True); mesh, __ = pymesh.remove_obtuse_triangles(mesh, 150.0, 100); if mesh.num_vertices == num_vertices: break; num_vertices = mesh.num_vertices; print("#v: {}".format(num_vertices)); count += 1; if count > 10: break; mesh = pymesh.resolve_self_intersection(mesh); mesh, __ = pymesh.remove_duplicated_faces(mesh); mesh = pymesh.compute_outer_hull(mesh); mesh, __ = pymesh.remove_duplicated_faces(mesh); mesh, __ = pymesh.remove_obtuse_triangles(mesh, 179.0, 5); mesh, __ = pymesh.remove_isolated_vertices(mesh); return mesh;
def fix_mesh(mesh, target_len): bbox_min, bbox_max = mesh.bbox diag_len = np.linalg.norm(bbox_max - bbox_min) count = 0 print(" remove degenerated triangles") mesh, __ = pymesh.remove_degenerated_triangles(mesh, 100) print(" split long edges") mesh, __ = pymesh.split_long_edges(mesh, target_len) num_vertices = mesh.num_vertices while True: print(" pass %d" % count) print(" collapse short edges #1") mesh, __ = pymesh.collapse_short_edges(mesh, 1e-6) print(" collapse short edges #2") mesh, __ = pymesh.collapse_short_edges(mesh, target_len, preserve_feature=True) print(" remove obtuse triangles") mesh, __ = pymesh.remove_obtuse_triangles(mesh, 150.0, 100) print(" %d of %s vertices." % (num_vertices, mesh.num_vertices)) if mesh.num_vertices == num_vertices: break num_vertices = mesh.num_vertices count += 1 if count > 10: break print(" resolve self intersection") mesh = pymesh.resolve_self_intersection(mesh) print(" remove duplicated faces") mesh, __ = pymesh.remove_duplicated_faces(mesh) print(" computer outer hull") mesh = pymesh.compute_outer_hull(mesh) print(" remove duplicated faces") mesh, __ = pymesh.remove_duplicated_faces(mesh) print(" remove obtuse triangles") mesh, __ = pymesh.remove_obtuse_triangles(mesh, 179.0, 5) print(" remove isolated vertices") mesh, __ = pymesh.remove_isolated_vertices(mesh) return mesh
def __fix_mesh(self, mesh, improvement_thres=0.8): mesh, __ = pymesh.split_long_edges(mesh, self.mesh_target_len) num_vertices = len(mesh.vertices) for __ in range(10): mesh, __ = pymesh.collapse_short_edges(mesh, 1e-6) mesh, __ = pymesh.collapse_short_edges( mesh, self.mesh_target_len, preserve_feature=True ) mesh, __ = pymesh.remove_obtuse_triangles(mesh, 150.0, 100) if len(mesh.vertices) < num_vertices * improvement_thres: break mesh = pymesh.resolve_self_intersection(mesh) mesh, __ = pymesh.collapse_short_edges(mesh, 1e-6) mesh, __ = pymesh.remove_duplicated_faces(mesh) mesh, __ = pymesh.remove_duplicated_faces(mesh) mesh, __ = pymesh.remove_obtuse_triangles(mesh, 179.0, 5) mesh, __ = pymesh.remove_isolated_vertices(mesh) return mesh
def fix_mesh(mesh, target_len): bbox_min, bbox_max = mesh.bbox diag_len = np.linalg.norm(bbox_max - bbox_min) print("running downsample mesh to len %.3f" % target_len) count = 0 mesh, __ = pymesh.split_long_edges(mesh, target_len) num_vertices = mesh.num_vertices while True: mesh, __ = pymesh.collapse_short_edges(mesh, 1e-6) mesh, __ = pymesh.collapse_short_edges(mesh, target_len, preserve_feature=True) if mesh.num_vertices == num_vertices: break num_vertices = mesh.num_vertices count += 1 if count > 10: break return mesh
def old_fix_mesh(vertices, faces, detail="normal"): bbox_min = np.amin(vertices, axis=0) bbox_max = np.amax(vertices, axis=0) diag_len = norm(bbox_max - bbox_min) if detail == "normal": target_len = diag_len * 5e-3 elif detail == "high": target_len = diag_len * 2.5e-3 elif detail == "low": target_len = diag_len * 1e-2 print("Target resolution: {} mm".format(target_len)) count = 0 vertices, faces = pymesh.split_long_edges(vertices, faces, target_len) num_vertices = len(vertices) while True: vertices, faces = pymesh.collapse_short_edges(vertices, faces, 1e-6) vertices, faces = pymesh.collapse_short_edges(vertices, faces, target_len, preserve_feature=True) vertices, faces = pymesh.remove_obtuse_triangles( vertices, faces, 150.0, 100) if num_vertices == len(vertices): break num_vertices = len(vertices) print("#v: {}".format(num_vertices)) count += 1 if count > 10: break vertices, faces = pymesh.resolve_self_intersection(vertices, faces) vertices, faces = pymesh.remove_duplicated_faces(vertices, faces) vertices, faces, _ = pymesh.compute_outer_hull(vertices, faces, False) vertices, faces = pymesh.remove_duplicated_faces(vertices, faces) vertices, faces = pymesh.remove_obtuse_triangles(vertices, faces, 179.0, 5) vertices, faces, voxels = pymesh.remove_isolated_vertices(vertices, faces) return vertices, faces
def fix_mesh(mesh, detail="normal"): bbox_min, bbox_max = mesh.bbox; diag_len = norm(bbox_max - bbox_min); if detail == "normal": target_len = diag_len * 5e-3; elif detail == "high": target_len = diag_len * 2.5e-3; elif detail == "low": target_len = diag_len * 1e-2; print("Target resolution: {} mm".format(target_len)); count = 0; mesh, __ = pymesh.remove_degenerated_triangles(mesh, 100); mesh, __ = pymesh.split_long_edges(mesh, target_len); num_vertices = mesh.num_vertices; while True: mesh, __ = pymesh.collapse_short_edges(mesh, 1e-6); mesh, __ = pymesh.collapse_short_edges(mesh, target_len, preserve_feature=True); mesh, __ = pymesh.remove_obtuse_triangles(mesh, 150.0, 100); if mesh.num_vertices == num_vertices: break; num_vertices = mesh.num_vertices; print("#v: {}".format(num_vertices)); count += 1; if count > 10: break; mesh = pymesh.resolve_self_intersection(mesh); mesh, __ = pymesh.remove_duplicated_faces(mesh); mesh = pymesh.compute_outer_hull(mesh); mesh, __ = pymesh.remove_duplicated_faces(mesh); mesh, __ = pymesh.remove_obtuse_triangles(mesh, 179.0, 5); mesh, __ = pymesh.remove_isolated_vertices(mesh); return mesh;
def fix_mesh(mesh): mesh, __ = pymesh.remove_degenerated_triangles(mesh, 100) log_mesh(mesh, "Remove degenerate faces") mesh, __ = pymesh.collapse_short_edges(mesh, MIN_RES, preserve_feature=True) log_mesh(mesh, "Collapse short edges") mesh = pymesh.resolve_self_intersection(mesh) mesh, __ = pymesh.remove_duplicated_faces(mesh) log_mesh(mesh, "Remove self intersections") mesh = pymesh.compute_outer_hull(mesh) mesh, __ = pymesh.remove_duplicated_faces(mesh) log_mesh(mesh, "New hull, remove duplicates") mesh, __ = pymesh.remove_obtuse_triangles(mesh, 179.5, 5) log_mesh(mesh, "Remote obtuse faces") mesh, __ = pymesh.remove_isolated_vertices(mesh) log_mesh(mesh, "Remove isolated vertices") return mesh
def execute(self, context): scene = context.scene pymesh_props = scene.pymesh obj_a = context.active_object mesh_a = import_object(context, obj_a) pymesh_r, info = pymesh.remove_degenerated_triangles(mesh_a) pymesh_r, info = pymesh.remove_obtuse_triangles(pymesh_r) pymesh_r, info = pymesh.remove_duplicated_faces(pymesh_r) pymesh_r, info = pymesh.collapse_short_edges(pymesh_r) pymesh_r, info = pymesh.remove_duplicated_vertices(pymesh_r) pymesh_r, info = pymesh.remove_isolated_vertices(pymesh_r) off_name = "Py.Clean." + obj_a.name mesh_r = export_mesh(context, pymesh_r, off_name) add_to_scene(context, mesh_r) return {'FINISHED'}
def filter(self): mesh = pymesh.form_mesh(self.mesh.points.values, self.mesh.cells.values) mesh, _ = pymesh.remove_degenerated_triangles(mesh, self.max_iterations) mesh, _ = pymesh.split_long_edges(mesh, self.size) num_vertices = mesh.num_vertices for _ in range(self.max_iterations): mesh, _ = pymesh.collapse_short_edges(mesh, self.size, preserve_feature=True) mesh, _ = pymesh.remove_obtuse_triangles(mesh, self.max_angle, self.max_iterations) if mesh.num_vertices == num_vertices: break num_vertices = mesh.num_vertices return self.mesh.mesh_class()(mesh, parents=[self.mesh])
def remeshing_and_texture(reconstruction_dir): texture_mesh(reconstruction_dir, 0) print_header("Remeshing the model") length = 1.0 while 1: print( "Trying to resize mesh and texture. Current edge collapse threshold " + str(length) + ".") start = time.time() mesh = pymesh.load_mesh(reconstruction_dir + "/scene_dense_mesh_refine.ply") mesh, info = pymesh.collapse_short_edges(mesh, rel_threshold=float(length)) if len(mesh.vertices) > 1000 and length < 4: pymesh.save_mesh( reconstruction_dir + "/remesh_" + str(length) + ".ply", mesh) end = time.time() print("Elapsed time: %d sec" % (end - start) + "\n") texture_mesh(reconstruction_dir, length) length += 0.5 else: print("Can't texture mapping on resized mesh with threshold " + str(length) + "!") return -1
polyfile = sys.argv[1] meshfile = sys.argv[2] trilineleng = float(sys.argv[3]) trilineshortleng = float(sys.argv[4]) x = json.loads(open(polyfile).readline()) vertices = numpy.array(x[0]) faces = numpy.array(x[1]) mesh = pymesh.form_mesh(vertices, faces) #mesh, info = pymesh.remove_degenerated_triangles(mesh, 100) preserve_feature = False # see https://github.com/PyMesh/PyMesh/issues/289 mesh, info = pymesh.split_long_edges(mesh, trilineleng) mesh, info = pymesh.collapse_short_edges(mesh, trilineshortleng, preserve_feature=preserve_feature) mesh, info = pymesh.split_long_edges(mesh, trilineleng) mesh, info = pymesh.collapse_short_edges(mesh, trilineshortleng, preserve_feature=preserve_feature) #print(info) fout = open("temp.txt", "w") print("writing %d verts and %d faces" % (len(mesh.vertices), len(mesh.faces))) fout.write(json.dumps([mesh.vertices.tolist(), mesh.faces.flatten().tolist()])) fout.close() shutil.move("temp.txt", meshfile) # then for the flattener
def regularise_mesh(mesh, tol): """Takes mesh & resizes triangles to tol size""" mesh, __ = pymesh.remove_degenerated_triangles(mesh, 100) mesh, _info = pymesh.split_long_edges(mesh, tol) mesh, __ = pymesh.collapse_short_edges(mesh, 1e-6) mesh, _info = pymesh.collapse_short_edges(mesh, tol, preserve_feature=True)
# In[56]: # rescale so it has vol equiv sphere radius of 1 new_squannit = cor_volume(squannit) p = plt_mesh_square(new_squannit.vertices, new_squannit.faces, xmax) # In[57]: xrot = np.array([1, 0, 0]) vrot = rotate_vertices(new_squannit.vertices, xrot, np.pi / 2) p = plt_mesh_square(vrot, new_squannit.faces, xmax) # In[69]: # reduce the number of faces to something reasonable short_squannit1, info = pymesh.collapse_short_edges( new_squannit, 0.219) # if bigger then fewer faces nf_mesh(short_squannit1) meshplot.plot(short_squannit1.vertices, short_squannit1.faces) short_squannit2, info = pymesh.collapse_short_edges( new_squannit, 0.17) # if bigger then fewer faces nf_mesh(short_squannit2) meshplot.plot(short_squannit2.vertices, short_squannit2.faces) # In[70]: p = plt_mesh_square(short_squannit2.vertices, short_squannit2.faces, xmax) # In[71]: xrot = np.array([1, 0, 0]) vrot = rotate_vertices(short_squannit2.vertices, xrot, np.pi / 2)
def fix_meshes(mesh, detail="normal"): """ A pipeline to optimise and fix mesh based on pymesh Mesh object. 1. A box is created around the mesh. 2. A target length is found based on diagonal of the mesh box. 3. You can choose between 3 level of details, normal details settings seems to be a good compromise between final mesh size and sufficient number of vertices. It highly depends on your final goal. 4. Remove degenerated triangles aka collinear triangles composed of 3 aligned points. The number of iterations is 5 and should remove all degenerated triangles 5. Remove isolated vertices, not connected to any faces or edges 6. Remove self intersection edges and faces which is not realistic 7. Remove duplicated faces 8. The removing of duplicated faces can leave some vertices alone, we will removed them 9. The calculation of outer hull volume is useful to be sure that the mesh is still ok 10. Remove obtuse triangles > 179 who is not realistic and increase computation time 11. We will remove potential duplicated faces again 12. And duplicated vertices again 13. Finally we will look if the mesh is broken or not. If yes we will try lower settings, if the lowest settings broke the mesh we will return the initial mesh. If not, we will return the optimised mesh. :param mesh: Pymesh Mesh object to optimise :param detail: string 'high', 'normal' or 'low' ('normal' as default), or float/int Settings to choose the targeting minimum length of edges :return: Pymesh Mesh object An optimised mesh or not depending on detail settings and mesh quality """ meshCopy = mesh # copy/pasta of pymesh script fix_mesh from qnzhou, see pymesh on GitHub bbox_min, bbox_max = mesh.bbox diag_len = np.linalg.norm(bbox_max - bbox_min) if detail == "normal": target_len = diag_len * 5e-3 elif detail == "high": target_len = diag_len * 2.5e-3 elif detail == "low": target_len = diag_len * 1e-2 elif detail is float or detail is int and detail > 0: target_len = diag_len * detail else: print( 'Details settings is invalid, must be "low", "normal", "high" or positive int or float' ) quit() count = 0 mesh, __ = pymesh.remove_degenerated_triangles(mesh, 5) mesh, __ = pymesh.split_long_edges(mesh, target_len) num_vertices = mesh.num_vertices while True: mesh, __ = pymesh.collapse_short_edges(mesh, target_len, preserve_feature=True) mesh, info = pymesh.remove_obtuse_triangles(mesh, 179.0, 5) if mesh.num_vertices == num_vertices: break num_vertices = mesh.num_vertices count += 1 if count > 10: break mesh, __ = pymesh.remove_duplicated_vertices(mesh) mesh, __ = pymesh.remove_isolated_vertices(mesh) mesh = pymesh.resolve_self_intersection(mesh) mesh, __ = pymesh.remove_duplicated_faces(mesh) mesh, __ = pymesh.remove_duplicated_vertices(mesh) mesh = pymesh.compute_outer_hull(mesh) mesh, __ = pymesh.remove_obtuse_triangles(mesh, 179.0, 5) mesh, __ = pymesh.remove_duplicated_faces(mesh) mesh, __ = pymesh.remove_isolated_vertices(mesh) if is_mesh_broken(mesh, meshCopy) is True: if detail == "high": print( f'The function fix_meshes broke mesh, trying with lower details settings' ) fix_meshes(meshCopy, detail="normal") return mesh if detail == "normal": print( f'The function fix_meshes broke mesh, trying with lower details settings' ) mesh = fix_meshes(meshCopy, detail="low") return mesh if detail == "low": print( f'The function fix_meshes broke mesh, no lower settings can be applied, no fix was done' ) return meshCopy else: return mesh
def symmetrize(verts, faces, eps=1e-3): """ verts: N,3 (x,y,z) tensor faces: F,3 (0,1,2) tensor Modifies mesh to make it symmetric about y-z plane - Cut mesh into half - Copy left half into right half - merge, remove duplicate vertices """ # Snap vertices close to centre to centre verts_centre_mask = (verts[:,0].abs() < eps) verts[verts_centre_mask, 0] = 0 # import pymesh pmesh = pymesh.form_mesh(verts.numpy(), faces.numpy()) pymesh.save_mesh(f'csm_mesh/debug/1.obj', pmesh) # Categorize vertices into left (-1), centre(0), right(1) verts_side = torch.sign(verts[:,0]) # Categorize faces into left (-1), centre(0), right(1) face_verts_side = torch.index_select(verts_side, 0, faces.view(-1)) face_verts_side = face_verts_side.contiguous().view(faces.shape[0], 3) face_left_mask = (face_verts_side[:,0]==-1) & (face_verts_side[:,1]==-1) & (face_verts_side[:,2]==-1) face_right_mask = (face_verts_side[:,0]==1) & (face_verts_side[:,1]==1) & (face_verts_side[:,2]==1) face_intesects_yz = (~face_left_mask) & (~face_right_mask) # Split intersecting faces new_verts = [] new_faces = [] for f in face_intesects_yz.nonzero().squeeze(1): i0, i1, i2 = faces[f] if verts_side[i0]==verts_side[i1]: i0, i1, i2 = i2, i0, i1 elif verts_side[i2]==verts_side[i1]: i0, i1, i2 = i0, i1, i2 elif verts_side[i0]==verts_side[i2]: i0, i1, i2 = i1, i0, i2 elif verts_side[i0]==-1: i0, i1, i2 = i0, i1, i2 elif verts_side[i1]==-1: i0, i1, i2 = i1, i0, i2 elif verts_side[i2]==-1: i0, i1, i2 = i2, i0, i1 else: import ipdb; ipdb.set_trace() # yz axis intersects i0->i1 & i0->i2 assert(verts_side[i0] != verts_side[i1]) assert(verts_side[i0] != verts_side[i2]) v0 = verts[i0] v1 = verts[i1] v2 = verts[i2] v_n1 = (v0 * v1[0] - v1 * v0[0])/(v1[0] - v0[0]) v_n2 = (v0 * v2[0] - v2 * v0[0])/(v2[0] - v0[0]) i_n1 = verts.shape[0] + len(new_verts) i_n2 = verts.shape[0] + len(new_verts) + 1 new_verts.append(v_n1) new_verts.append(v_n2) new_faces.append((i0, i_n1, i_n2)) new_faces.append((i1, i_n1, i_n2)) new_faces.append((i1, i2, i_n2)) new_verts = torch.stack(new_verts, dim=0) new_faces = torch.tensor(new_faces, dtype=faces.dtype, device=faces.device) verts = torch.cat([verts, new_verts], dim=0) faces = torch.index_select(faces, 0, (~face_intesects_yz).nonzero().squeeze(1)) faces = torch.cat([faces, new_faces], dim=0) # import pymesh pmesh = pymesh.form_mesh(verts.numpy(), faces.numpy()) pymesh.save_mesh(f'csm_mesh/debug/2.obj', pmesh) # Merge vertices that are very close together vertex_mapping = [] verts_new = [] for v_id in range(verts.shape[0]): if v_id==0: vertex_mapping.append(0) verts_new.append(verts[0]) continue min_d, min_idx = (verts[0:v_id] - verts[v_id]).norm(dim=-1).min(dim=0) if min_d < eps: vertex_mapping.append(vertex_mapping[min_idx]) else: vertex_mapping.append(len(verts_new)) verts_new.append(verts[v_id]) assert(len(vertex_mapping)==verts.shape[0]) vertex_mapping = torch.tensor(vertex_mapping, dtype=faces.dtype, device=faces.device) verts = torch.stack(verts_new, dim=0) faces = vertex_mapping[faces] # Remove degenerate faces faces_degenerate = (faces[:,0]==faces[:,1]) | (faces[:,0]==faces[:,2]) | (faces[:,2]==faces[:,1]) faces = torch.index_select(faces, 0, (~faces_degenerate).nonzero().squeeze(1)) # import pymesh pmesh = pymesh.form_mesh(verts.numpy(), faces.numpy()) pymesh.save_mesh(f'csm_mesh/debug/3.obj', pmesh) # Delete faces that lie on right side (verts_side==1) verts_centre_mask = (verts[:,0].abs() < eps) verts[verts_centre_mask, 0] = 0 verts_side = torch.sign(verts[:,0]) face_verts_side = torch.index_select(verts_side, 0, faces.view(-1)) face_verts_side = face_verts_side.contiguous().view(faces.shape[0], 3) face_right_mask = (face_verts_side[:,0]==1) | (face_verts_side[:,1]==1) | (face_verts_side[:,2]==1) faces = torch.index_select(faces, 0, (~face_right_mask).nonzero().squeeze(1)) # import pymesh pmesh = pymesh.form_mesh(verts.numpy(), faces.numpy()) pymesh.save_mesh(f'csm_mesh/debug/4.obj', pmesh) # Flip mesh, merge faces_flip = faces + verts.shape[0] faces = torch.cat([faces, faces_flip], dim=0) verts_flip = verts * torch.tensor([-1,1,1], dtype=verts.dtype, device=verts.device) vertex_mapping_flip = torch.arange(verts.shape[0], dtype=faces.dtype, device=faces.device) vertex_mapping_flip[~verts_centre_mask] += verts.shape[0] vertex_mapping = torch.arange(verts.shape[0], dtype=faces.dtype, device=faces.device) vertex_mapping = torch.cat([vertex_mapping, vertex_mapping_flip], dim=0) verts = torch.cat([verts, verts_flip], dim=0) faces = vertex_mapping[faces] # import pymesh pmesh = pymesh.form_mesh(verts.numpy(), faces.numpy()) pymesh.save_mesh(f'csm_mesh/debug/5.obj', pmesh) pymesh.save_mesh(f'csm_mesh/debug/5.8.obj', pmesh) numv = pmesh.num_vertices while True: pmesh, __ = pymesh.collapse_short_edges(pmesh, rel_threshold=0.4) verts = torch.as_tensor(pmesh.vertices, dtype=verts.dtype, device=verts.device) faces = torch.as_tensor(pmesh.faces, dtype=faces.dtype, device=faces.device) verts_centre_mask = (verts[:,0].abs() < 1e-3) verts[verts_centre_mask, 0] = 0 pmesh = pymesh.form_mesh(verts.numpy(), faces.numpy()) pmesh, __ = pymesh.remove_isolated_vertices(pmesh) pmesh, __ = pymesh.remove_duplicated_vertices(pmesh, tol=eps) pmesh, __ = pymesh.remove_duplicated_faces(pmesh) pmesh, __ = pymesh.remove_degenerated_triangles(pmesh) pmesh, __ = pymesh.remove_isolated_vertices(pmesh) # pmesh, __ = pymesh.remove_obtuse_triangles(pmesh, 120.0, 100) pmesh, __ = pymesh.collapse_short_edges(pmesh, 1e-2) pmesh, __ = pymesh.remove_duplicated_vertices(pmesh, tol=eps) if pmesh.num_vertices==numv: break numv = pmesh.num_vertices pymesh.save_mesh(f'csm_mesh/debug/5.9.obj', pmesh) verts = torch.as_tensor(pmesh.vertices, dtype=verts.dtype, device=verts.device) faces = torch.as_tensor(pmesh.faces, dtype=faces.dtype, device=faces.device) # Remove unused vertices vertices_used = torch.unique(faces.view(-1)) vertex_mapping = torch.zeros((verts.shape[0], ), dtype=faces.dtype, device=faces.device) vertex_mapping[vertices_used] = torch.arange(vertices_used.shape[0], dtype=faces.dtype, device=faces.device) faces = vertex_mapping[faces] verts = verts[vertices_used] # import pymesh pmesh = pymesh.form_mesh(verts.numpy(), faces.numpy()) pymesh.save_mesh(f'csm_mesh/debug/6.obj', pmesh) return verts, faces