Skip to content

Instantly share code, notes, and snippets.

@Jummit
Created November 3, 2020 07:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Jummit/f21dab760ec40a5abbaca681c85bd102 to your computer and use it in GitHub Desktop.
Save Jummit/f21dab760ec40a5abbaca681c85bd102 to your computer and use it in GitHub Desktop.
Join duplicate vertices of a mesh in Godot
static func _join_duplicates(mesh : Mesh) -> Dictionary:
var data_tool := MeshDataTool.new()
if not data_tool.create_from_surface(_deindex(mesh), 0) == OK:
return {}
var old_vertex_ids := {}
var ordered_vertices := []
for vertex_id in data_tool.get_vertex_count():
var vertex := data_tool.get_vertex(vertex_id)
old_vertex_ids[vertex] = vertex_id
ordered_vertices.append(vertex)
ordered_vertices.sort()
var surface_tool := SurfaceTool.new()
surface_tool.begin(Mesh.PRIMITIVE_TRIANGLES)
surface_tool.index()
var vertex_ids := {}
var original_face_ids := {}
var current_id := 0
var last_vertex : Vector3 = ordered_vertices.front()
var id : int = old_vertex_ids[ordered_vertices.front()]
surface_tool.add_color(Color(id))
surface_tool.add_vertex(last_vertex)
for vertex in ordered_vertices:
if not last_vertex.is_equal_approx(vertex):
id = old_vertex_ids[vertex]
surface_tool.add_color(Color(id))
surface_tool.add_vertex(vertex)
current_id += 1
last_vertex = vertex
vertex_ids[vertex] = current_id
var last_face_id := 0
for vertex_id in data_tool.get_vertex_count():
var vertex := data_tool.get_vertex(vertex_id)
if vertex_id % 3 == 0:
original_face_ids[last_face_id] = data_tool.get_vertex_faces(vertex_id)[0]
last_face_id += 1
surface_tool.add_index(vertex_ids[vertex])
return {
mesh = surface_tool.commit(),
original_face_ids = original_face_ids}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment