Skip to content
bcs99 edited this page Mar 30, 2022 · 1 revision

Program and shader object

ObjectTK provides a base class for shader programs which does all the work to get shaders up and running while also simplifying interop with uniforms, vertex attributes, etc. Also included is functionality similar to GLSW, which enables multiple shaders per file and provides "#include" pre-processing.

The following example uses the #include statement in a rather stupid way, just for demonstration.

-- Version
#version 140

-- Vertex
#include ExampleShader.Version
in vec3 InPosition;
uniform mat4 ModelViewProjectionMatrix;

void main()
{
    gl_Position = ModelViewProjectionMatrix * vec4(InPosition,1);
}

-- Fragment
#include ExampleShader.Version
out vec4 FragColor;

void main()
{
    FragColor = vec4(1);
}

The corresponding type should look like this:

[VertexShaderSource("ExampleShader.Vertex")]
[FragmentShaderSource("ExampleShader.Fragment")]
public class ExampleProgram
    : Program
{
    [VertexAttrib(3, VertexAttribPointerType.Float)]
    public VertexAttrib InPosition { get; protected set; }

    public Uniform<Matrix4> ModelViewProjectionMatrix { get; protected set; }
}

// initialize program (create shaders, load and compile shader sources, link program, error checking)
var program = ProgramFactory.Create<ExampleProgram>();

Buffer object

ObjectTK also provides a generic type which encapsulates all the work necessary to set up, update, clear and copy buffer objects.

// create some vertices
var vertices = new[] { new Vector3(-1,-1,0), new Vector3(1,-1,0), new Vector3(0,1,0) };

// create buffer object and upload vertex data
var vbo = new Buffer<Vector3>();
vbo.Init(BufferTarget.ArrayBuffer, vertices);

Vertex array object

To simplify set up of vertex attributes the vertex array provides methods to bind buffer objects to specific vertex attributes. When called without further arguments the buffer is bound according to parameters specified on the VertexAttribAttribute (3 components of type float in this case).

var vao = new VertexArray();
vao.Bind();
vao.BindAttribute(program.InPosition, vbo);

Render

Once the program type is set up its usage is straight forward. Activate the program, set any uniforms, bind the vertex array and draw:

program.Use();
program.ModelViewProjectionMatrix.Set(ModelView*Projection);
vao.Bind();
vao.DrawArrays(PrimitiveType.Triangles, vbo.ElementCount);
Clone this wiki locally