Skip to content

Creating Renderable Models

SMG edited this page Jun 16, 2019 · 3 revisions

Model rendering is done using the GenericMesh class, which greatly simplifies drawing geometry. Simply create a GenericMesh object using a collection of vertices and optional indices to draw the geometry using a custom or generated shader.

Creating a Vertex Struct

The type reference T for GenericMesh refers to the vertex struct. Only value types are allowed to ensure the vertex buffer data is correctly organized. A collection of any value type will work, such as float or char, but the class is designed to work best with custom structs.

A custom struct should contain properties or fields for all the information associated with a vertex. This will always include the position but may contain other information such as texture coordinates or normals. An example struct is provided below.

struct MyVertex
{
    public Vector3 Position { get; set; }

    public Vector3 Normal { get; set; }
}

Creating a GenericMesh Class

After creating the vertex struct, add a custom render mesh class inheriting from GenericMesh. The only methods that need to be overriden are the constructors. Using existing indices is recommended to reduce memory usage and improve performance. In this case, vertex indices will be generated automatically. An example class is provided below.

class MyMesh : GenericMesh<MyVertex>
{
    public MyMesh(List<MyVertex> vertices) : base(vertices, OpenTK.Graphics.OpenGL.PrimitiveType.Triangles)
    {
        // Initialize any additional fields here.
        // The base constructor will load the vertex data into buffers for drawing.
    }
}

Loading Vertex Data

For simplicity of rendering, GenericMesh expects vertex data to be in a specific format. This allows the configuration of vertex attributes to be handled automatically. To improve performance, reduce the number of conversion steps needed to get from the source data to a collection of custom vertex structs.

The order of attributes in the buffer directly maps to the order of the members in the struct. Keep this in mind when using an OpenGL debugger to examine the buffers. The data in the internal vertex buffer for the above example will be structured as follows.

Position0.xyz
Normal0.xyz
Position1.xyz
Normal1.xyz
...

Clone this wiki locally