[GDNative] Create Mesh with vertices calculated within C++ - which class to inherit from?

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By JSchmalhofer

Hello,

I have a quite complex C++ Library that calculates vertices for a 3D mesh. I think the effort to integrate it as GDNative library will be significantly less than porting it to GDScript, as I only need to pass the vertices-array and index-array to ArrayMesh.add_surface_from_arrays().

So far, I fiddled around with the example code from LucyLavend from here using a MeshInstance node:

extends MeshInstance

var mesh_arr = []
var mesh_vertices = PoolVector3Array()
var mesh_indices = PoolIntArray()

func _ready():
	mesh_arr.resize(Mesh.ARRAY_MAX)
	var idx = 0
	
	mesh_vertices.append(Vector3(-1, -1, 0))
	mesh_indices.append(idx)
	idx += 1
	
	mesh_vertices.append(Vector3(0, 1, 0))
	mesh_indices.append(idx)
	idx += 1
	
	mesh_vertices.append(Vector3(1, -1, 0))
	mesh_indices.append(idx)
	idx += 1
	
	mesh_arr[Mesh.ARRAY_VERTEX] = mesh_vertices
	mesh_arr[Mesh.ARRAY_INDEX] = mesh_indices
	
	mesh.add_surface_from_arrays(Mesh.PRIMITIVE_TRIANGLES, mesh_arr)

However, I am now a little confused on how to transfer this example to a C++ GDNative Library, because the node I use in Godot is a MeshInstance, however the method add_surface_from_arrays is part of the class ArrayMesh. I.e. if I create a C+±class onheriting from MeshInstance, I have no access to the add_surface_from_arrays() method, right?

How would you recommend setting up the classes here?
I first was thinking about creating a C++ class that inherits from the generic class Object and can return a PoolVector3Array and a PoolIntArray for vertices and indices and pass those to a GDScript MeshInstance as above. Does that make sense?
I so far did not manage to pass values from GDNative to GDScript.

Any help is appreciated! Thanks!

Well, I found a possible and working way to approach this. I walked through the basic GDNative C++ Example again and found, that I simply forgot to register my getter and setter functions before. Once done, I can easily access my GDNative Script’s variables, even if they have complexer types such as PoolVector3Array or PoolIntArray.

For my current solution, I choose to inherit my C++ class from Node and fill vertices and indices in proper arrays there. Then I register getter-methods to be able to read them.
I then add a MeshInstance with an ArrayMesh as mesh. As child I add a generic Node with the GDNative script assigned. Using get_node("Node") I am then able to access the child-node, read the arrays using previously mentioned getter-methods and create a new surface for mesh in my MeshInstance (similar as in the GDScript above).

Not sure this is the smartest approach to go, but it works for now.

Happy to discuss better solution approaches.

JSchmalhofer | 2022-05-30 21:07