#Creating custom meshes through C++

1 messages · Page 1 of 1 (latest)

slender halo
#

I've got a marching cubes program written in gdscript, but its very slow. I've made a gdextension to do this much faster, but I cant figure out how to set a mesh.

Ive looked at the header files of MeshInstance3D, ArrayMesh, Array, and I cant figure out how to do it.
Is there any documentation on c++ extensions?

This is the code I've got so far (pretty much a copy of the godot code);

PackedVector3Array vertices;
PackedVector3Array normals;

indices.resize(3);
vertices.resize(3);
normals.resize(3);
indices[0] = 0;
indices[1] = 1;
indices[2] = 2;
vertices[0] = Vector3(0.0, 0.0, 0.0);
vertices[1] = Vector3(1.0, 0.0, 0.0);
vertices[2] = Vector3(0.0, 1.0, 0.0);
normals[0] = Vector3(0.0, 0.0, 1.0);
normals[1] = Vector3(0.0, 0.0, 1.0);
normals[2] = Vector3(0.0, 0.0, 1.0);

Array meshArrays;
meshArrays.resize(Mesh::ArrayType::ARRAY_MAX);
meshArrays[Mesh::ArrayType::ARRAY_INDEX] = indices;
meshArrays[Mesh::ArrayType::ARRAY_VERTEX] = vertices;
meshArrays[Mesh::ArrayType::ARRAY_NORMAL] = normals;

ArrayMesh mesh;
mesh.add_surface_from_arrays(Mesh::PrimitiveType::PRIMITIVE_TRIANGLES, meshArrays);

((MeshInstance3D*)get_child(0))->set_mesh(&mesh);

Thanks!

unreal cypress
# slender halo I've got a marching cubes program written in gdscript, but its very slow. I've m...
// Create the arrays as you already have
PackedInt32Array indices;
PackedVector3Array vertices;
PackedVector3Array normals;

indices.resize(3);
vertices.resize(3);
normals.resize(3);
indices[0] = 0;
indices[1] = 1;
indices[2] = 2;
vertices[0] = Vector3(0.0, 0.0, 0.0);
vertices[1] = Vector3(1.0, 0.0, 0.0);
vertices[2] = Vector3(0.0, 1.0, 0.0);
normals[0] = Vector3(0.0, 0.0, 1.0);
normals[1] = Vector3(0.0, 0.0, 1.0);
normals[2] = Vector3(0.0, 0.0, 1.0);

// Create the mesh array
Array mesh_arrays;
mesh_arrays.resize(Mesh::ARRAY_MAX);
mesh_arrays[Mesh::ARRAY_VERTEX] = vertices;
mesh_arrays[Mesh::ARRAY_NORMAL] = normals;
mesh_arrays[Mesh::ARRAY_INDEX] = indices;

// Create ArrayMesh using Ref<> (reference-counted pointer)
Ref<ArrayMesh> mesh;
mesh.instantiate();
mesh->add_surface_from_arrays(Mesh::PRIMITIVE_TRIANGLES, mesh_arrays);

// Get the MeshInstance3D and set the mesh
MeshInstance3D *mesh_instance = Object::cast_to<MeshInstance3D>(get_child(0));
if (mesh_instance) {
    mesh_instance->set_mesh(mesh);
}```

The header files are the primary documentation for C++ API, as the online docs mostly cover gdscript.

1. Use Ref<ArrayMesh> instead of ArrayMesh - Godot uses reference-counted smart pointers for resources

2. Call instantiate() to create the actual mesh object

3. Use Object::cast_to<>() for safe type casting instead of C-style cast

4. Pass the Ref<ArrayMesh> directly to set_mesh() - it handles the reference counting