Skip to content

Instantly share code, notes, and snippets.

@Lateasusual
Created May 13, 2024 14:22
Show Gist options
  • Save Lateasusual/071d27cc9ac94e3e9b4be26d0086f294 to your computer and use it in GitHub Desktop.
Save Lateasusual/071d27cc9ac94e3e9b4be26d0086f294 to your computer and use it in GitHub Desktop.
@tool
extends EditorScenePostImport
class MeshInstanceList:
var mesh: Mesh
var aabb: AABB
var transforms: Array
# Converts geometry node instances into MultiMeshInstances
func gn_instances_to_mm(parent: Node, scene: Node):
# Allow for multiple different meshes to be instanced from the same object
var mesh_map := Dictionary()
for child: MeshInstance3D in parent.find_children("GN Instance*"):
if child.mesh in mesh_map:
var col : MeshInstanceList = mesh_map[child.mesh]
col.transforms.append(child.transform)
# Merge AABB from all the instances
# TODO splitting instances into local clusters for better culling?
col.aabb = col.aabb.merge(child.transform * child.get_aabb())
else:
var col = MeshInstanceList.new()
col.mesh = child.mesh
col.transforms = [child.transform]
col.aabb = child.transform * child.get_aabb()
mesh_map[child.mesh] = col
child.queue_free()
for col: MeshInstanceList in mesh_map.values():
var mm = MultiMesh.new()
mm.transform_format = MultiMesh.TRANSFORM_3D
mm.mesh = col.mesh
mm.instance_count = len(col.transforms)
for i in range(len(col.transforms)):
mm.set_instance_transform(i, col.transforms[i])
mm.custom_aabb = col.aabb
var mmi = MultiMeshInstance3D.new()
mmi.multimesh = mm
if col.mesh.resource_name.length() > 0:
mmi.name = col.mesh.resource_name
parent.add_child(mmi)
mmi.set_owner(scene)
func process_meshes(scene: Node):
for child in scene.find_children("*"):
# Not sure how to support nested instances yet
if child.name.begins_with("GN Instance"):
continue
gn_instances_to_mm(child, scene)
func _post_import(scene: Node) -> Object:
process_meshes(scene)
return scene
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment