Create custom mesh async
Occasionally, you may want to create your own mesh asynchronously. In this example, we will create a simple mesh with a single quad. Let’s first show the code and then explain it:
require engine.gen_geometry.mesh_structures
require engine.serializer.generic_storage
def generate_quad_mesh(width, height : int) : MeshGeometry {
var vertices = [float3(0, 0, 0), float3(0, height, 0), float3(width, height, 0), float3(width, 0, 0)]
var normals = [float3(0, 0, -1), float3(0, 0, -1), float3(0, 0, -1), float3(0, 0, -1)]
var uvs = [float2(0, 0), float2(0, height), float2(width, height), float2(width, 0)]
var triangles = [uint3(0u, 1u, 2u), uint3(2u, 3u, 0u)]
return <- MeshGeometry(vertices <- vertices, normals <- normals, uv <- uvs, triangles <- triangles)
}
[export]
def build(data : string) : MeshGeometry {
let req = GenericStorage(data)
let size = get_or(req, "size", int2())
return <- generate_quad_mesh(size.x, size.y)
}
First, we require the two modules that contain all the types and functions we need. It’s better not to require engine.core here for faster compilation. Then, we define a function that generates a quad mesh. The function takes two parameters, width and height, and returns a Mesh object. Inside the function, we define the vertices and indices of the quad. The vertices are defined as an array of Vertex objects, where each Vertex object contains the position, normal, and texture coordinate of a vertex. The indices are defined as an array of uint3 objects, where each uint3 object contains the indices of the vertices that form a triangle. In any mesh you create, you need to define the vertices and indices that make up the mesh. Finally, we create a Mesh object with the generated vertices and indices and return it.
The build function is necessary for the engine to create the mesh. It takes a string parameter that is actually a GenericStorage object. We extract the size parameter from the GenericStorage object and call the generate_quad_mesh function with the extracted size parameters. We then return the generated MeshData object.
Now let’s show how to generate this mesh with the specified size in your game script:
var req : GenericStorage
set(req, "size", int2(size))
let mesh = generate_mesh("%file/quad_mesh.das", req)
In this code snippet, we first create a GenericStorage object and set the size parameter to the desired width and height of the quad mesh. We then call the generate_mesh function with the path to the script that generates the mesh and the GenericStorage object as parameters. The generate_mesh function will execute the build function and return the generated Mesh object, which you can now use in your game.