
"""Draw vertices from numpy arrays."""

import OpenGL.GL as gl
import OpenGL.arrays.vbo as vbo

import glitch

class DrawVertexArray(glitch.Node):
    def __init__(self, mode, array):
        glitch.Node.__init__(self)

        self.mode = mode
        self.array = array
        assert self.array.shape[1] == 2

        if mode == gl.GL_LINES:
            assert self.array.shape[0] % 2 == 0
            # This is 2 * sizeof(float).
            self.stride = 8
        elif mode == gl.GL_TRIANGLES:
            assert self.array.shape[0] % 3 == 0
            self.stride = 8
        else:
            raise ValueError

    def draw(self, ctx):
        buffer = vbo.VBO(self.array)
        buffer.bind()
        gl.glEnableClientState(gl.GL_VERTEX_ARRAY)
        # Three coordinates per vertex, with a stride of sizeof(float) * the
        # number of fields.
        gl.glVertexPointer(2, gl.GL_FLOAT, self.stride, buffer)
        gl.glDrawArrays(self.mode, 0, self.array.shape[0])
        gl.glDisableClientState(gl.GL_VERTEX_ARRAY)
        buffer.unbind()
