Esempio n. 1
0
def setup_copy_vertexbuffer():
    '''
    Create the vertexbuffer object for the copying program
    '''
    # gl.glGenVertexArrays(1, ctypes.byref(copy_vao))
    gl.glGenBuffers(1, ctypes.byref(copy_vertexbuffer))

    loc_position = gl.glGetAttribLocation(copy_program, ctypes.create_string_buffer(b'position'))
    loc_texcoord = gl.glGetAttribLocation(copy_program, ctypes.create_string_buffer(b'texcoord'))

    if loc_position < 0:
        print('Warning: position is not used in the shader')
    if loc_texcoord < 0:
        print('Warning: texcoord is not used in the shader')

    gl.glBindVertexArray(copy_vao)

    gl.glEnableVertexAttribArray(loc_position)
    gl.glEnableVertexAttribArray(loc_texcoord)

    gl.glBindBuffer(gl.GL_ARRAY_BUFFER, copy_vertexbuffer)

    gl.glVertexAttribPointer(loc_position, 2, gl.GL_FLOAT, False, ctypes.sizeof(TEXTURE_VERTEX), ctypes.c_void_p(TEXTURE_VERTEX.position.offset))
    gl.glVertexAttribPointer(loc_texcoord, 2, gl.GL_FLOAT, False, ctypes.sizeof(TEXTURE_VERTEX), ctypes.c_void_p(TEXTURE_VERTEX.texcoord.offset))

    gl.glBindVertexArray(0)
Esempio n. 2
0
def setup_render_vertexbuffer():
    '''
	Create the vertexbuffer object for the rendering program
	'''
    gl.glGenVertexArrays(1, ctypes.byref(render_vao))
    gl.glGenBuffers(1, ctypes.byref(render_vertexbuffer))

    loc_position = gl.glGetAttribLocation(
        render_program, ctypes.create_string_buffer(b'position'))
    loc_color = gl.glGetAttribLocation(render_program,
                                       ctypes.create_string_buffer(b'color'))

    if loc_position < 0:
        print('Warning: position is not used in the shader')
    if loc_color < 0:
        print('Warning: color is not used in the shader')

    gl.glBindVertexArray(render_vao)

    gl.glEnableVertexAttribArray(loc_position)
    gl.glEnableVertexAttribArray(loc_color)

    gl.glBindBuffer(gl.GL_ARRAY_BUFFER, render_vertexbuffer)

    gl.glVertexAttribPointer(loc_position, 2, gl.GL_FLOAT, False,
                             ctypes.sizeof(COLOR_VERTEX),
                             ctypes.c_void_p(COLOR_VERTEX.position.offset))
    gl.glVertexAttribPointer(loc_color, 4, gl.GL_FLOAT, False,
                             ctypes.sizeof(COLOR_VERTEX),
                             ctypes.c_void_p(COLOR_VERTEX.color.offset))

    gl.glBindVertexArray(0)
Esempio n. 3
0
def setup_copy_vertexbuffer():
    '''
	Create the vertexbuffer object for the copying program
	'''
    # gl.glGenVertexArrays(1, ctypes.byref(copy_vao))
    gl.glGenBuffers(1, ctypes.byref(copy_vertexbuffer))

    loc_position = gl.glGetAttribLocation(
        copy_program, ctypes.create_string_buffer(b'position'))
    loc_texcoord = gl.glGetAttribLocation(
        copy_program, ctypes.create_string_buffer(b'texcoord'))

    if loc_position < 0:
        print('Warning: position is not used in the shader')
    if loc_texcoord < 0:
        print('Warning: texcoord is not used in the shader')

    gl.glBindVertexArray(copy_vao)

    gl.glEnableVertexAttribArray(loc_position)
    gl.glEnableVertexAttribArray(loc_texcoord)

    gl.glBindBuffer(gl.GL_ARRAY_BUFFER, copy_vertexbuffer)

    gl.glVertexAttribPointer(loc_position, 2, gl.GL_FLOAT, False,
                             ctypes.sizeof(TEXTURE_VERTEX),
                             ctypes.c_void_p(TEXTURE_VERTEX.position.offset))
    gl.glVertexAttribPointer(loc_texcoord, 2, gl.GL_FLOAT, False,
                             ctypes.sizeof(TEXTURE_VERTEX),
                             ctypes.c_void_p(TEXTURE_VERTEX.texcoord.offset))

    gl.glBindVertexArray(0)
Esempio n. 4
0
def setup_render_vertexbuffer():
    '''
    Create the vertexbuffer object for the rendering program
    '''
    gl.glGenVertexArrays(1, ctypes.byref(render_vao))
    gl.glGenBuffers(1, ctypes.byref(render_vertexbuffer))

    loc_position = gl.glGetAttribLocation(render_program, ctypes.create_string_buffer(b'position'))
    loc_color = gl.glGetAttribLocation(render_program, ctypes.create_string_buffer(b'color'))

    if loc_position < 0:
        print('Warning: position is not used in the shader')
    if loc_color < 0:
        print('Warning: color is not used in the shader')


    gl.glBindVertexArray(render_vao)

    gl.glEnableVertexAttribArray(loc_position)
    gl.glEnableVertexAttribArray(loc_color)

    gl.glBindBuffer(gl.GL_ARRAY_BUFFER, render_vertexbuffer)

    gl.glVertexAttribPointer(loc_position, 2, gl.GL_FLOAT, False, ctypes.sizeof(COLOR_VERTEX), ctypes.c_void_p(COLOR_VERTEX.position.offset))
    gl.glVertexAttribPointer(loc_color, 4, gl.GL_FLOAT, False, ctypes.sizeof(COLOR_VERTEX), ctypes.c_void_p(COLOR_VERTEX.color.offset))

    gl.glBindVertexArray(0)
Esempio n. 5
0
    def _create_device_objects(self):
        # save state
        last_texture = gl.GLint()
        gl.glGetIntegerv(gl.GL_TEXTURE_BINDING_2D, byref(last_texture))
        last_array_buffer = gl.GLint()
        gl.glGetIntegerv(gl.GL_ARRAY_BUFFER_BINDING, byref(last_array_buffer))

        last_vertex_array = gl.GLint()
        gl.glGetIntegerv(gl.GL_VERTEX_ARRAY_BINDING, byref(last_vertex_array))

        self._shader_handle = gl.glCreateProgram()
        # note: no need to store shader parts handles after linking
        vertex_shader = gl.glCreateShader(gl.GL_VERTEX_SHADER)
        fragment_shader = gl.glCreateShader(gl.GL_FRAGMENT_SHADER)

        gl.glShaderSource(vertex_shader, 1, make_string_buffer(self.VERTEX_SHADER_SRC), None)
        gl.glShaderSource(fragment_shader, 1, make_string_buffer(self.FRAGMENT_SHADER_SRC), None)
        gl.glCompileShader(vertex_shader)
        gl.glCompileShader(fragment_shader)

        gl.glAttachShader(self._shader_handle, vertex_shader)
        gl.glAttachShader(self._shader_handle, fragment_shader)

        gl.glLinkProgram(self._shader_handle)

        # note: after linking shaders can be removed
        gl.glDeleteShader(vertex_shader)
        gl.glDeleteShader(fragment_shader)

        self._attrib_location_tex = gl.glGetUniformLocation(self._shader_handle, create_string_buffer(b"Texture"))
        self._attrib_proj_mtx = gl.glGetUniformLocation(self._shader_handle, create_string_buffer(b"ProjMtx"))
        self._attrib_location_position = gl.glGetAttribLocation(self._shader_handle, create_string_buffer(b"Position"))
        self._attrib_location_uv = gl.glGetAttribLocation(self._shader_handle, create_string_buffer(b"UV"))
        self._attrib_location_color = gl.glGetAttribLocation(self._shader_handle, create_string_buffer(b"Color"))

        self._vbo_handle = gl.GLuint()
        gl.glGenBuffers(1, byref(self._vbo_handle))
        self._elements_handle = gl.GLuint()
        gl.glGenBuffers(1, byref(self._elements_handle))

        self._vao_handle = gl.GLuint()
        gl.glGenVertexArrays(1, byref(self._vao_handle))
        gl.glBindVertexArray(self._vao_handle)
        gl.glBindBuffer(gl.GL_ARRAY_BUFFER, self._vbo_handle)

        gl.glEnableVertexAttribArray(self._attrib_location_position)
        gl.glEnableVertexAttribArray(self._attrib_location_uv)
        gl.glEnableVertexAttribArray(self._attrib_location_color)

        gl.glVertexAttribPointer(self._attrib_location_position, 2, gl.GL_FLOAT, gl.GL_FALSE, imgui.VERTEX_SIZE, c_void_p(imgui.VERTEX_BUFFER_POS_OFFSET))
        gl.glVertexAttribPointer(self._attrib_location_uv, 2, gl.GL_FLOAT, gl.GL_FALSE, imgui.VERTEX_SIZE, c_void_p(imgui.VERTEX_BUFFER_UV_OFFSET))
        gl.glVertexAttribPointer(self._attrib_location_color, 4, gl.GL_UNSIGNED_BYTE, gl.GL_TRUE, imgui.VERTEX_SIZE, c_void_p(imgui.VERTEX_BUFFER_COL_OFFSET))

        # restore state

        gl.glBindTexture(gl.GL_TEXTURE_2D, cast((c_int*1)(last_texture), POINTER(c_uint)).contents)
        gl.glBindBuffer(gl.GL_ARRAY_BUFFER, cast((c_int*1)(last_array_buffer), POINTER(c_uint)).contents)
        gl.glBindVertexArray(cast((c_int*1)(last_vertex_array), POINTER(c_uint)).contents)
Esempio n. 6
0
 def draw(self):
     """Draw the object to the display buffer"""
     from pyglet import gl
     gl.glUseProgram(self._program)
     for kind in ('fill', 'line'):
         if self._counts[kind] > 0:
             if kind == 'line':
                 if self._line_width <= 0.0:
                     continue
                 gl.glLineWidth(self._line_width)
                 if self._line_loop:
                     mode = gl.GL_LINE_LOOP
                 else:
                     mode = gl.GL_LINE_STRIP
                 cmd = partial(gl.glDrawArrays, mode, 0, self._counts[kind])
             else:
                 gl.glBindBuffer(gl.GL_ELEMENT_ARRAY_BUFFER,
                                 self._buffers[kind]['index'])
                 cmd = partial(gl.glDrawElements, gl.GL_TRIANGLES,
                               self._counts[kind], gl.GL_UNSIGNED_INT, 0)
             gl.glBindBuffer(gl.GL_ARRAY_BUFFER,
                             self._buffers[kind]['array'])
             loc_pos = gl.glGetAttribLocation(self._program, b'a_position')
             gl.glEnableVertexAttribArray(loc_pos)
             gl.glVertexAttribPointer(loc_pos, 2, gl.GL_FLOAT, gl.GL_FALSE,
                                      0, 0)
             loc_col = gl.glGetUniformLocation(self._program, b'u_color')
             gl.glUniform4f(loc_col, *self._colors[kind])
             cmd()
             # The following line is probably only necessary because
             # Pyglet makes some assumptions about the GL state that
             # it perhaps shouldn't. Without it, Text might not
             # render properly (see #252)
             gl.glDisableVertexAttribArray(loc_pos)
     gl.glUseProgram(0)
Esempio n. 7
0
    def vertex_attrib(self, name, data, size=2, stride=0, offset=0):
        """
        Set vertex attribute data in a shader, lacks the flexibility of
        setting several attributes in one vertex buffer.

        Parameters
        ----------

        name: the attribute name in the shader.

        data: a list of vertex attributes (positions, colors, ...)

        Example: name = "positions", data = [0, 0, 0, 1, 1, 0, 1, 1].
        """
        data_ctype = (gl.GLfloat * len(data))(*data)

        vbo_id = gl.GLuint(0)
        gl.glGenBuffers(1, ct.byref(vbo_id))
        gl.glBindBuffer(gl.GL_ARRAY_BUFFER, vbo_id)
        gl.glBufferData(gl.GL_ARRAY_BUFFER, ct.sizeof(data_ctype), data_ctype,
                        gl.GL_STATIC_DRAW)

        location = gl.glGetAttribLocation(self.program, name.encode("ascii"))
        gl.glEnableVertexAttribArray(location)
        gl.glVertexAttribPointer(location, size, gl.GL_FLOAT, gl.GL_FALSE,
                                 stride, ct.c_void_p(offset))
        gl.glBindBuffer(gl.GL_ARRAY_BUFFER, 0)
        return vbo_id
Esempio n. 8
0
    def _init_shader(self):
        vertex_code = """
        #version 120
        attribute float particle_size;

        void main()
        {
            gl_PointSize = particle_size;
            gl_Position = ftransform();
            gl_FrontColor = gl_Color;
        }
        """
        frag_code = """
        #version 120
        uniform sampler2D sprite_texture;

        void main()
        {
            gl_FragColor = gl_Color * texture2D(sprite_texture, gl_PointCoord);
        }
        """
        self.sprite_shader = ShaderProgram.simple_program(
            'sprite', vertex_code, frag_code)
        self.particle_size_idx = gl.glGetAttribLocation(
            self.sprite_shader.program, b'particle_size')
Esempio n. 9
0
    def set_vertex_attrib(self, name, data):
        """This is an ugly way to set vertex attribute data in a shader, it lacks
        the flexibility of setting several attributes in one vertex buffer.

        name: the attribute name in the shader.
        data: a list of vertex attributes (positions, colors, texcoords, normals,...)
        example: name = 'positions', data = [(1, 1, 0), (2, 2, 1), ...]
        the items in data must all be 1D lists(or tuples) of the same length.
        """
        data_flatten = [x for vertex in data for x in vertex]
        size = len(data[0])
        data_ctype = (gl.GLfloat * len(data_flatten))(*data_flatten)

        vbo_id = gl.GLuint(0)
        gl.glGenBuffers(1, ct.byref(vbo_id))
        gl.glBindBuffer(gl.GL_ARRAY_BUFFER, vbo_id)
        gl.glBufferData(gl.GL_ARRAY_BUFFER, ct.sizeof(data_ctype), data_ctype,
                        gl.GL_STATIC_DRAW)

        location = gl.glGetAttribLocation(self.program, name.encode('ascii'))
        gl.glEnableVertexAttribArray(location)
        gl.glVertexAttribPointer(location, size, gl.GL_FLOAT, gl.GL_FALSE, 0,
                                 0)
        gl.glBindBuffer(gl.GL_ARRAY_BUFFER, 0)
        return vbo_id
Esempio n. 10
0
    def _enable_attrib(self, buf_desc: BufferDescription):
        buff = buf_desc.buffer
        stride = sum(attribsize for _, attribsize, _ in buf_desc.formats)

        if buf_desc.instanced:
            if self.num_vertices == -1:
                raise ShaderException(
                    "The first vertex attribute cannot be a per instance attribute."
                )
        else:
            self.num_vertices = max(self.num_vertices, buff.size // stride)
            # print(f"Number of vertices: {self.num_vertices}")

        gl.glBindBuffer(gl.GL_ARRAY_BUFFER, buff.buffer_id)
        offset = 0
        for (size, attribsize,
             gl_type_enum), attrib in zip(buf_desc.formats,
                                          buf_desc.attributes):
            loc = gl.glGetAttribLocation(self.program, attrib.encode('utf-8'))
            if loc == -1:
                raise ShaderException(
                    f"Attribute {attrib} not found in shader program")
            normalized = gl.GL_TRUE if attrib in buf_desc.normalized else gl.GL_FALSE
            gl.glVertexAttribPointer(loc, size, gl_type_enum, normalized,
                                     stride, c_void_p(offset))
            # print(f"{attrib} of size {size} with stride {stride} and offset {offset}")
            if buf_desc.instanced:
                gl.glVertexAttribDivisor(loc, 1)
            offset += attribsize
            gl.glEnableVertexAttribArray(loc)
Esempio n. 11
0
 def draw(self):
     """Draw the object to the display buffer"""
     from pyglet import gl
     gl.glUseProgram(self._program)
     for kind in ('fill', 'line'):
         if self._counts[kind] > 0:
             if kind == 'line':
                 if self._line_width <= 0.0:
                     continue
                 gl.glLineWidth(self._line_width)
                 if self._line_loop:
                     mode = gl.GL_LINE_LOOP
                 else:
                     mode = gl.GL_LINE_STRIP
                 cmd = partial(gl.glDrawArrays, mode, 0, self._counts[kind])
             else:
                 gl.glBindBuffer(gl.GL_ELEMENT_ARRAY_BUFFER,
                                 self._buffers[kind]['index'])
                 cmd = partial(gl.glDrawElements, gl.GL_TRIANGLES,
                               self._counts[kind], gl.GL_UNSIGNED_INT, 0)
             gl.glBindBuffer(gl.GL_ARRAY_BUFFER,
                             self._buffers[kind]['array'])
             loc_pos = gl.glGetAttribLocation(self._program, b'a_position')
             gl.glEnableVertexAttribArray(loc_pos)
             gl.glVertexAttribPointer(loc_pos, 2, gl.GL_FLOAT, gl.GL_FALSE,
                                      0, 0)
             loc_col = gl.glGetUniformLocation(self._program, b'u_color')
             gl.glUniform4f(loc_col, *self._colors[kind])
             cmd()
             # The following line is probably only necessary because
             # Pyglet makes some assumptions about the GL state that
             # it perhaps shouldn't. Without it, Text might not
             # render properly (see #252)
             gl.glDisableVertexAttribArray(loc_pos)
     gl.glUseProgram(0)
Esempio n. 12
0
    def set_vertex_attrib(self, name, data):
        '''
        this is an ugly way to set vertex attribute data in a shader.
        lacks the flexibility of setting several attributes in one vertex buffer.

        name: the attribute name in the shader.
        data: a list of vertex attributes (positions, colors, texcoords, normals,...)

        example:
        name = 'positions'
        data = [(1, 1, 0), (2, 2, 1), ...]

        the items in data must all be 1D lists(or tuples) of the same length.
        '''
        data_flatten = [x for vertex in data for x in vertex]
        size = len(data[0])
        data_ctype = (gl.GLfloat * len(data_flatten))(*data_flatten)

        vbo_id = gl.GLuint(0)
        gl.glGenBuffers(1, ct.byref(vbo_id))
        gl.glBindBuffer(gl.GL_ARRAY_BUFFER, vbo_id)
        gl.glBufferData(gl.GL_ARRAY_BUFFER, ct.sizeof(data_ctype), data_ctype, gl.GL_STATIC_DRAW)

        location = gl.glGetAttribLocation(self.program, name.encode('ascii'))
        gl.glEnableVertexAttribArray(location)
        gl.glVertexAttribPointer(location, size, gl.GL_FLOAT, gl.GL_FALSE, 0, 0)
        gl.glBindBuffer(gl.GL_ARRAY_BUFFER, 0)
        return vbo_id
Esempio n. 13
0
 def vertex_attrib_pointer(self, buffer, name, size, type=gl.GL_FLOAT, normalized=False, stride=0, offset=0):
     self.use()
     loc = gl.glGetAttribLocation(self.handle, ctypes.create_string_buffer(name))
     if loc < 0:
         logging.warning('Attribute {} is not in the shader.'.format(name))
         return
     gl.glEnableVertexAttribArray(loc)
     gl.glBindBuffer(gl.GL_ARRAY_BUFFER, buffer)
     gl.glVertexAttribPointer(loc, size, type, normalized, stride, ctypes.c_void_p(offset))
Esempio n. 14
0
  def __set_attributes(self):
    if self.__vao is None:
      self.__vao = util.vertex_array()
    gl.glBindVertexArray(self.__vao.value)

    # coord
    coord_loc = gl.glGetAttribLocation(self.__prog.value, "coord")
    gl.glBindBuffer(gl.GL_ARRAY_BUFFER, self.__geom_buffer.value)
    gl.glVertexAttribPointer(coord_loc, 3, gl.GL_FLOAT, gl.GL_FALSE, 0, 0)
    gl.glEnableVertexAttribArray(coord_loc)
Esempio n. 15
0
    def attribute(self, name, type, values_per_vertex=1):

        if name not in self.__attributes:

            location = gl.glGetAttribLocation(
                self.__program, name)

            self.__attributes[name] = Attribute(
                location, type, values_per_vertex)

        return self.__attributes[name]
Esempio n. 16
0
 def vertex_attrib_pointer(self,
                           buffer,
                           name,
                           size,
                           dtype=gl.GL_FLOAT,
                           normalized=False,
                           stride=0,
                           offset=0):
     self.use()
     loc = gl.glGetAttribLocation(self.handle,
                                  ctypes.create_string_buffer(name))
     if loc < 0:
         logging.warning('Attribute %s is not in the shader.', name)
         return
     gl.glEnableVertexAttribArray(loc)
     gl.glBindBuffer(gl.GL_ARRAY_BUFFER, buffer)
     gl.glVertexAttribPointer(loc, size, dtype, normalized, stride,
                              ctypes.c_void_p(offset))
Esempio n. 17
0
    def _introspect_attributes(self):
        """Introspect and store detailed info about an attribute"""
        # TODO: Ensure gl_* attributes are ignored
        num_attrs = gl.GLint()
        gl.glGetProgramiv(self._glo, gl.GL_ACTIVE_ATTRIBUTES, num_attrs)
        num_varyings = gl.GLint()
        gl.glGetProgramiv(self._glo, gl.GL_TRANSFORM_FEEDBACK_VARYINGS,
                          num_varyings)
        # print(f"attrs {num_attrs.value} varyings={num_varyings.value}")

        for i in range(num_attrs.value):
            c_name = create_string_buffer(256)
            c_size = gl.GLint()
            c_type = gl.GLenum()
            gl.glGetActiveAttrib(
                self._glo,  # program to query
                i,  # index (not the same as location)
                256,  # max attr name size
                None,  # c_length,  # length of name
                c_size,  # size of attribute (array or not)
                c_type,  # attribute type (enum)
                c_name,  # name buffer
            )

            # Get the actual location. Do not trust the original order
            location = gl.glGetAttribLocation(self._glo, c_name)

            # print(c_name.value, c_size, c_type)
            type_info = GLTypes.get(c_type.value)
            # print(type_info)
            self._attributes.append(
                AttribFormat(
                    c_name.value.decode(),
                    type_info.gl_type,
                    type_info.components,
                    type_info.gl_size,
                    location=location,
                ))

        # The attribute key is used to cache VertexArrays
        self.attribute_key = ":".join(
            f"{attr.name}[{attr.gl_type}/{attr.components}]"
            for attr in self._attributes)
Esempio n. 18
0
    def __init__(self, vertex_shader, fragment_shader, attributes):
        # compile and link
        self.program_name = gl.glCreateProgram()
        gl.glAttachShader(self.program_name,
                          compile_shader(gl.GL_VERTEX_SHADER, vertex_shader))
        gl.glAttachShader(
            self.program_name,
            compile_shader(gl.GL_FRAGMENT_SHADER, fragment_shader))
        link_program(self.program_name)

        # vertex type
        class VERTEX(ctypes.Structure):
            _fields_ = [(name, TYPE_NAME_TO_TYPE[tname] * size)
                        for (name, tname, size) in attributes]

        self.VERTEX = VERTEX

        # vertex array and buffer
        self.vertex_array_name = gl.GLuint(0)
        self.vertex_buffer_name = gl.GLuint(0)
        gl.glGenVertexArrays(1, ctypes.byref(self.vertex_array_name))
        gl.glGenBuffers(1, ctypes.byref(self.vertex_buffer_name))

        gl.glBindVertexArray(self.vertex_array_name)
        gl.glBindBuffer(gl.GL_ARRAY_BUFFER, self.vertex_buffer_name)
        for (name, tname, size) in attributes:
            location = gl.glGetAttribLocation(
                self.program_name,
                ctypes.create_string_buffer(name.encode('ascii')))
            if location < 0:
                warnings.warn('Attribute %r is not present.' % name,
                              stacklevel=2)
                continue
            gl.glEnableVertexAttribArray(location)
            gl.glVertexAttribPointer(
                location, size, tname, False, ctypes.sizeof(VERTEX),
                ctypes.c_void_p(getattr(VERTEX, name).offset))
        gl.glBindVertexArray(0)
        gl.glBindBuffer(gl.GL_ARRAY_BUFFER, 0)
Esempio n. 19
0
    def add_attribute(self,
                      name,
                      data_format,
                      normalize=False,
                      stride=0,
                      offset=0):
        """Add an attribute to the current shader.

        :param name: name of the attribute being added.
        :type name: str

        :param data_format: a string describing the data format of the
            attribute. The general syntax is `<size><data_type>` where
            size is the number of the data points that describe the
            attribute and data_type represents the data type of the
            data points. For example '3f' describes an attribute with
            3 floating point data points.
        :type data_format: str

        :param normalize: When set to True, OpenGL will normalize the
            data to the range [0.0, 1.0] (defaults to False)
        :type normalize: bool

        :param stride: Specifies the offset between consecutive
            attributes (defaults to 0).
        :type stride: int

        :param offset: Location of the first component of the
            attribute in the data array (defaults to 0).
        :type offset: int

        """

        size = int(data_format[0])
        dtype = attribute_dtype_map[data_format[1:]]
        norm = gl.GL_TRUE if normalize else gl.GL_FALSE
        loc = gl.glGetAttribLocation(self._pid, name.encode('utf-8'))
        self._attributes[name] = Attribute(name, loc, size, dtype, norm,
                                           stride, offset)
Esempio n. 20
0
    def _init_shader(self):
        vertex_code = """
        #version 120
        attribute float particle_size;

        void main()
        {
            gl_PointSize = particle_size;
            gl_Position = ftransform();
            gl_FrontColor = gl_Color;
        }
        """
        frag_code = """
        #version 120
        uniform sampler2D sprite_texture;

        void main()
        {
            gl_FragColor = gl_Color * texture2D(sprite_texture, gl_PointCoord);
        }
        """
        self.sprite_shader = ShaderProgram.simple_program('sprite', vertex_code, frag_code)
        self.particle_size_idx = gl.glGetAttribLocation(self.sprite_shader.program, b'particle_size')
Esempio n. 21
0
program = gl.glCreateProgram()
gl.glAttachShader(program, compile_shader(gl.GL_VERTEX_SHADER,
                                          vert_shader_src))
gl.glAttachShader(program,
                  compile_shader(gl.GL_FRAGMENT_SHADER, frag_shader_src))
gl.glLinkProgram(program)

# uniforms
u_origin = gl.glGetUniformLocation(program, b'uOrigin')
u_zoom = gl.glGetUniformLocation(program, b'uZoom')

origin = [0, 0]
zoom = [1, 1]

# attributes
a_position = gl.glGetAttribLocation(program, b'aPosition')
a_color = gl.glGetAttribLocation(program, b'aColor')
gl.glEnableVertexAttribArray(a_position)
gl.glEnableVertexAttribArray(a_color)


@window.event
def on_draw():
    gl.glClear(gl.GL_COLOR_BUFFER_BIT)
    gl.glUseProgram(program)
    gl.glUniform2f(u_origin, *origin)
    gl.glUniform2f(u_zoom, *zoom)
    gl.glDrawArrays(gl.GL_LINES, 0, len(verts))


@window.event
Esempio n. 22
0
        def __init__(self):
            #consider bumping opengl version if apple supports it
            #amdgpu-mesa currently supports up to 4.5
            super(ControledRender,
                  self).__init__(512,
                                 512,
                                 fullscreen=False,
                                 config=gl.Config(major_version=4,
                                                  minor_version=1),
                                 visible=False)
            print(self.context.get_info().get_version())

            self.vertex_buffer = gl.GLuint(0)
            self.vao = gl.GLuint(0)
            #self.prev_program = (gl.GLint * 1)()

            self.setupFBOandTextures()

            self.setupShaders()

            data = [
                -1.0, -1.0, 1.0, -1.0, 1.0, 1.0, -1.0, -1.0, 1.0, 1.0, -1.0,
                1.0
            ]

            dataGl = (gl.GLfloat * len(data))(*data)

            gl.glGenBuffers(1, ctypes.byref(self.vertex_buffer))
            gl.glBindBuffer(gl.GL_ARRAY_BUFFER, self.vertex_buffer)
            gl.glBufferData(gl.GL_ARRAY_BUFFER,
                            len(dataGl) * 4, dataGl, gl.GL_STATIC_DRAW)

            gl.glGenVertexArrays(1, ctypes.byref(self.vao))
            gl.glBindVertexArray(self.vao)
            gl.glUseProgram(self.programA)
            self.pos_posA = gl.glGetAttribLocation(
                self.programA, ctypes.create_string_buffer(b"a_position"))
            assert (self.pos_posA >= 0)
            gl.glEnableVertexAttribArray(self.pos_posA)
            gl.glBindBuffer(gl.GL_ARRAY_BUFFER, self.vertex_buffer)
            gl.glVertexAttribPointer(self.pos_posA, 2, gl.GL_FLOAT, False, 0,
                                     0)

            if args["shape"] == "sphere":
                self.radius_pos = gl.glGetUniformLocation(
                    self.programA, b"radius")
                self.center_pos = gl.glGetUniformLocation(
                    self.programA, b"center")
                self.checkUniformLocation(self.radius_pos)
                self.checkUniformLocation(self.center_pos)
                gl.glUniform1f(self.radius_pos, args["radius"])
                gl.glUniform3f(self.center_pos, args["center"][0],
                               args["center"][1], args["center"][2])
            elif args["shape"] == "cylinder":
                self.radius_pos = gl.glGetUniformLocation(
                    self.programA, b"radius")
                self.height_pos = gl.glGetUniformLocation(
                    self.programA, b"height")
                self.checkUniformLocation(self.radius_pos)
                self.checkUniformLocation(self.height_pos)
                gl.glUniform1f(self.radius_pos, args["radius"])
                gl.glUniform1f(self.height_pos, args["height"])

            self.slice_pos = gl.glGetUniformLocation(self.programA, b"slice")
            self.step_pos = gl.glGetUniformLocation(self.programA, b"step")

            self.checkUniformLocation(self.slice_pos)

            gl.glUniform1f(self.step_pos, 1 / args["resolution"])
            #may need changed for nonsquare textures

            gl.glViewport(0, 0, args["resolution"], args["resolution"])
Esempio n. 23
0
        def __init__(self, frames):
            #consider bumping opengl version if apple supports it
            #amdgpu-mesa currently supports up to 4.5
            super(ControledRender,
                  self).__init__(512,
                                 512,
                                 fullscreen=False,
                                 config=gl.Config(major_version=4,
                                                  minor_version=1),
                                 visible=False)
            print(self.context.get_info().get_version())

            self.frames = frames
            self.vertex_buffer = gl.GLuint(0)
            self.vao = gl.GLuint(0)
            #self.prev_program = (gl.GLint * 1)()

            self.dimx = args["A"].shape[0]
            self.dimy = args["A"].shape[1]

            A = args["A"].astype(np.float32)
            #print("A shape " + str(A.shape))
            #print(str(A.dtype))
            #print(A)

            B = args["B"].astype(np.float32)

            #self.dp = self.tdata.ctypes.data_as(ctypes.POINTER(ctypes.c_void_p))
            self.Ap = A.ctypes.data_as(ctypes.POINTER(ctypes.c_void_p))
            self.Bp = B.ctypes.data_as(ctypes.POINTER(ctypes.c_void_p))

            self.setupFBOandTextures()

            self.setupShaders()

            data = [
                -1.0, -1.0, 1.0, -1.0, 1.0, 1.0, -1.0, -1.0, 1.0, 1.0, -1.0,
                1.0
            ]

            dataGl = (gl.GLfloat * len(data))(*data)

            gl.glGenBuffers(1, ctypes.byref(self.vertex_buffer))
            gl.glBindBuffer(gl.GL_ARRAY_BUFFER, self.vertex_buffer)
            gl.glBufferData(gl.GL_ARRAY_BUFFER,
                            len(dataGl) * 4, dataGl, gl.GL_STATIC_DRAW)

            gl.glGenVertexArrays(1, ctypes.byref(self.vao))
            gl.glBindVertexArray(self.vao)
            gl.glUseProgram(self.programA)
            self.pos_posA = gl.glGetAttribLocation(
                self.programA, ctypes.create_string_buffer(b"a_position"))
            assert (self.pos_posA >= 0)
            gl.glEnableVertexAttribArray(self.pos_posA)
            gl.glBindBuffer(gl.GL_ARRAY_BUFFER, self.vertex_buffer)
            gl.glVertexAttribPointer(self.pos_posA, 2, gl.GL_FLOAT, False, 0,
                                     0)

            self.tex_pos_A_A = gl.glGetUniformLocation(self.programA, b"A")
            self.tex_pos_A_B = gl.glGetUniformLocation(self.programA, b"B")
            self.feed_pos_A = gl.glGetUniformLocation(self.programA, b"f")
            self.kill_pos_A = gl.glGetUniformLocation(self.programA, b"k")
            self.dA_pos_A = gl.glGetUniformLocation(self.programA, b"dA")
            self.dB_pos_A = gl.glGetUniformLocation(self.programA, b"dB")
            self.dt_pos_A = gl.glGetUniformLocation(self.programA, b"timestep")
            self.step_pos_A = gl.glGetUniformLocation(self.programA, b"step")
            gl.glUniform1f(self.feed_pos_A, args["feed"])
            gl.glUniform1f(self.kill_pos_A, args["kill"])
            gl.glUniform1f(self.dA_pos_A, args["dA"])
            gl.glUniform1f(self.dB_pos_A, args["dB"])
            gl.glUniform1f(self.dt_pos_A, args["dt"])
            #may need changed for nonsquare textures
            gl.glUniform1f(self.step_pos_A, 1 / self.dimx)

            gl.glUseProgram(self.programB)
            self.pos_posB = gl.glGetAttribLocation(
                self.programB, ctypes.create_string_buffer(b"a_position"))
            assert (self.pos_posB >= 0)
            gl.glEnableVertexAttribArray(self.pos_posB)
            gl.glBindBuffer(gl.GL_ARRAY_BUFFER, self.vertex_buffer)
            gl.glVertexAttribPointer(self.pos_posB, 2, gl.GL_FLOAT, False, 0,
                                     0)

            self.tex_pos_B_A = gl.glGetUniformLocation(self.programB, b"A")
            self.tex_pos_B_B = gl.glGetUniformLocation(self.programB, b"B")
            self.feed_pos_B = gl.glGetUniformLocation(self.programB, b"f")
            self.kill_pos_B = gl.glGetUniformLocation(self.programB, b"k")
            self.dA_pos_B = gl.glGetUniformLocation(self.programB, b"dA")
            self.dB_pos_B = gl.glGetUniformLocation(self.programB, b"dB")
            self.dt_pos_B = gl.glGetUniformLocation(self.programB, b"timestep")
            self.step_pos_B = gl.glGetUniformLocation(self.programB, b"step")
            gl.glUniform1f(self.feed_pos_B, args["feed"])
            gl.glUniform1f(self.kill_pos_B, args["kill"])
            gl.glUniform1f(self.dA_pos_B, args["dA"])
            gl.glUniform1f(self.dB_pos_B, args["dB"])
            gl.glUniform1f(self.dt_pos_B, args["dt"])
            #may need changed for nonsquare textures
            gl.glUniform1f(self.step_pos_B, 1 / self.dimx)

            gl.glViewport(0, 0, self.dimx, self.dimy)
Esempio n. 24
0
        def __init__(self):
            #consider bumping opengl version if apple supports it
            #amdgpu-mesa currently supports up to 4.5
            super(ControledRender,
                  self).__init__(512,
                                 512,
                                 fullscreen=False,
                                 config=gl.Config(major_version=4,
                                                  minor_version=1),
                                 visible=False)
            print(self.context.get_info().get_version())

            self.vertex_buffer = gl.GLuint(0)
            self.vao = gl.GLuint(0)
            #self.prev_program = (gl.GLint * 1)()

            self.dimx = args["A"].shape[0]
            self.dimy = args["A"].shape[1]
            self.dimz = args["A"].shape[2]

            A = args["A"].astype(np.float32)
            #print("A shape " + str(A.shape))
            #print(str(A.dtype))
            #print(A)

            #self.dp = self.tdata.ctypes.data_as(ctypes.POINTER(ctypes.c_void_p))
            self.Ap = A.ctypes.data_as(ctypes.POINTER(ctypes.c_void_p))

            T = args["transform"].astype(np.float32)

            self.Tp = T.ctypes.data_as(ctypes.POINTER(ctypes.c_float))

            self.setupFBOandTextures()

            self.setupShaders()

            data = [
                -1.0, -1.0, 1.0, -1.0, 1.0, 1.0, -1.0, -1.0, 1.0, 1.0, -1.0,
                1.0
            ]

            dataGl = (gl.GLfloat * len(data))(*data)

            gl.glGenBuffers(1, ctypes.byref(self.vertex_buffer))
            gl.glBindBuffer(gl.GL_ARRAY_BUFFER, self.vertex_buffer)
            gl.glBufferData(gl.GL_ARRAY_BUFFER,
                            len(dataGl) * 4, dataGl, gl.GL_STATIC_DRAW)

            gl.glGenVertexArrays(1, ctypes.byref(self.vao))
            gl.glBindVertexArray(self.vao)
            gl.glUseProgram(self.programA)
            self.pos_posA = gl.glGetAttribLocation(
                self.programA, ctypes.create_string_buffer(b"a_position"))
            assert (self.pos_posA >= 0)
            gl.glEnableVertexAttribArray(self.pos_posA)
            gl.glBindBuffer(gl.GL_ARRAY_BUFFER, self.vertex_buffer)
            gl.glVertexAttribPointer(self.pos_posA, 2, gl.GL_FLOAT, False, 0,
                                     0)

            self.tex_pos_A = gl.glGetUniformLocation(self.programA, b"A")
            self.transform_pos = gl.glGetUniformLocation(
                self.programA, b"transform")
            self.step_pos_A = gl.glGetUniformLocation(self.programA, b"step")
            self.slice_pos_A = gl.glGetUniformLocation(self.programA, b"slice")
            self.checkUniformLocation(self.tex_pos_A)
            self.checkUniformLocation(self.transform_pos)
            self.checkUniformLocation(self.step_pos_A)
            self.checkUniformLocation(self.slice_pos_A)

            gl.glUniformMatrix4fv(self.transform_pos, 1, True, self.Tp)
            #gl.glUniformMatrix4fv(self.transform_pos, 1, False, self.Tp)
            #may need changed for nonsquare textures
            gl.glUniform1f(self.step_pos_A, 1 / self.dimx)

            gl.glViewport(0, 0, self.dimx, self.dimy)