I want to generate a simplified mesh from cubes placed in a GridMap in Godot. I came up with the following code, however, the resulting ArrayMesh appears so be invalid, as surface_get_arrays(0).size() will always evaluate to 0. Can anyone point me in the right direction what the issue might be?
func create_combined_cube_mesh(gridmap: GridMap) -> ArrayMesh:
print("Create combined cube mesh...")
var start = Time.get_ticks_msec()
var array_mesh = ArrayMesh.new()
var box_mesh = BoxMesh.new()
box_mesh.size = gridmap.cell_size
var arrays = box_mesh.surface_get_arrays(0)
var vertices = arrays[Mesh.ARRAY_VERTEX]
var indices = arrays[Mesh.ARRAY_INDEX]
var mesh_data = []
mesh_data.resize(Mesh.ARRAY_MAX)
mesh_data[Mesh.ARRAY_VERTEX] = []
mesh_data[Mesh.ARRAY_INDEX] = []
var vertex_offset = 0
for cell in gridmap.get_used_cells():
var transform = gridmap.map_to_local(cell)
for v in vertices:
mesh_data[Mesh.ARRAY_VERTEX].append(v + transform)
for i in indices:
mesh_data[Mesh.ARRAY_INDEX].append(i + vertex_offset)
vertex_offset += vertices.size()
array_mesh.add_surface_from_arrays(Mesh.PRIMITIVE_TRIANGLES, mesh_data)
print(array_mesh.surface_get_arrays(0).size()) // prints 0, but should contain a surface at index 0, as per 1 line above, huh!?
return array_mesh if mesh_data[Mesh.ARRAY_VERTEX].size() > 0 else null
```