Exemplo n.º 1
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)
Exemplo n.º 2
0
    def __init__(self, **args):
        super(Window, self).__init__(**args)

        self.vao = gl.GLuint(0)
        gl.glGenVertexArrays(1, ctypes.byref(self.vao))
        gl.glBindVertexArray(self.vao)

        self.vbo = gl.GLuint(0)
        gl.glGenBuffers(1, ctypes.byref(self.vbo))
        gl.glBindBuffer(gl.GL_ARRAY_BUFFER, self.vbo)

        gl.glBufferData(gl.GL_ARRAY_BUFFER,
                        ctypes.sizeof(gl.GLfloat * len(vertex_positions)),
                        (gl.GLfloat *
                         len(vertex_positions))(*vertex_positions),
                        gl.GL_STATIC_DRAW)

        gl.glVertexAttribPointer(0, 3, gl.GL_FLOAT, gl.GL_FALSE, 0, 0)
        gl.glEnableVertexAttribArray(0)

        self.ibo = gl.GLuint(0)
        gl.glGenBuffers(1, self.ibo)
        gl.glBindBuffer(gl.GL_ELEMENT_ARRAY_BUFFER, self.ibo)

        gl.glBufferData(gl.GL_ELEMENT_ARRAY_BUFFER,
                        ctypes.sizeof(gl.GLuint * len(indices)),
                        (gl.GLuint * len(indices))(*indices),
                        gl.GL_STATIC_DRAW)
Exemplo n.º 3
0
def setup_render_vertexbuffer():
    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_texcoord = gl.glGetAttribLocation(
        render_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(render_vao)

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

    gl.glBindBuffer(gl.GL_ARRAY_BUFFER, render_vertexbuffer)

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

    gl.glBindVertexArray(0)
Exemplo 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)
Exemplo 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)
Exemplo n.º 6
0
    def __init__(self, world, chunk_position):
        self.chunk_position = chunk_position

        self.position = (  # get a world-space position for the chunk
            self.chunk_position[0] * CHUNK_WIDTH,
            self.chunk_position[1] * CHUNK_HEIGHT,
            self.chunk_position[2] * CHUNK_LENGTH)

        self.world = world

        self.blocks = [
            [
                [
                    0  # create an array of blocks filled with "air" (block number 0)
                    for z in range(CHUNK_LENGTH)
                ] for y in range(CHUNK_HEIGHT)
            ] for x in range(CHUNK_WIDTH)
        ]

        # mesh variables

        self.has_mesh = False

        self.mesh_vertex_positions = []
        self.mesh_tex_coords = []
        self.mesh_shading_values = []

        self.mesh_index_counter = 0
        self.mesh_indices = []

        # create vertex array object

        self.vao = gl.GLuint(0)
        gl.glGenVertexArrays(1, self.vao)
        gl.glBindVertexArray(self.vao)

        # create vertex position vbo

        self.vertex_position_vbo = gl.GLuint(0)
        gl.glGenBuffers(1, self.vertex_position_vbo)

        # create tex coord vbo

        self.tex_coord_vbo = gl.GLuint(0)
        gl.glGenBuffers(1, self.tex_coord_vbo)

        # create shading values vbo

        self.shading_values_vbo = gl.GLuint(0)
        gl.glGenBuffers(1, self.shading_values_vbo)

        # create index buffer object

        self.ibo = gl.GLuint(0)
        gl.glGenBuffers(1, self.ibo)
Exemplo n.º 7
0
    def __init__(self,
                 vertices: np.ndarray,
                 indices: np.ndarray,
                 mode=None,
                 texture=None):
        if mode is None:
            mode = gl.GL_TRIANGLES
        self.vertices = vertices
        self.indices = indices
        self.indices_size = indices.size
        self.mode = mode
        self.texture = texture

        self.vao = gl.GLuint(0)
        gl.glGenVertexArrays(1, ctypes.byref(self.vao))
        gl.glBindVertexArray(self.vao)

        self.vbo = gl.GLuint(0)
        gl.glGenBuffers(1, ctypes.byref(self.vbo))
        gl.glBindBuffer(gl.GL_ARRAY_BUFFER, self.vbo)
        gl.glBufferData(
            gl.GL_ARRAY_BUFFER,  # target
            vertices.nbytes,  # size
            (gl.GLbyte * vertices.nbytes)(*vertices.tobytes()),  # data
            gl.GL_STATIC_DRAW,
        )  # usage

        self.ebo = gl.GLuint(0)
        gl.glGenBuffers(1, ctypes.byref(self.ebo))
        gl.glBindBuffer(gl.GL_ELEMENT_ARRAY_BUFFER, self.ebo)
        gl.glBufferData(
            gl.GL_ELEMENT_ARRAY_BUFFER,
            indices.nbytes,
            (gl.GLbyte * indices.nbytes)(*indices.tobytes()),
            gl.GL_STATIC_DRAW,
        )

        for ind, fld in enumerate(
                sorted([f for f in vertices.dtype.fields.items()],
                       key=lambda i: i[1][1])):
            gl.glVertexAttribPointer(
                ind,  # index
                vertices[0][fld[0]].size,  # size
                gl.GL_FLOAT,  # type
                gl.GL_FALSE,  # normalized
                vertices.itemsize,  # stride
                ctypes.c_void_p(fld[1][1]),
            )  # pointer
            gl.glEnableVertexAttribArray(ind)

        if texture is not None:
            texture_image = pyglet.image.load(texture)
            self.texture = texture_image.get_texture()

        gl.glBindVertexArray(0)
Exemplo n.º 8
0
    def __init__(self, **args):
        super().__init__(**args)

        # create vertex array object

        self.vao = gl.GLuint(0)
        gl.glGenVertexArrays(1, ctypes.byref(self.vao))
        gl.glBindVertexArray(self.vao)

        # create vertex buffer object

        self.vbo = gl.GLuint(0)
        gl.glGenBuffers(1, ctypes.byref(self.vbo))
        gl.glBindBuffer(gl.GL_ARRAY_BUFFER, self.vbo)

        gl.glBufferData(gl.GL_ARRAY_BUFFER,
                        ctypes.sizeof(gl.GLfloat * len(vertex_positions)),
                        (gl.GLfloat *
                         len(vertex_positions))(*vertex_positions),
                        gl.GL_STATIC_DRAW)

        gl.glVertexAttribPointer(0, 3, gl.GL_FLOAT, gl.GL_FALSE, 0, 0)
        gl.glEnableVertexAttribArray(0)

        # create index buffer object

        self.ibo = gl.GLuint(0)
        gl.glGenBuffers(1, self.ibo)
        gl.glBindBuffer(gl.GL_ELEMENT_ARRAY_BUFFER, self.ibo)

        gl.glBufferData(gl.GL_ELEMENT_ARRAY_BUFFER,
                        ctypes.sizeof(gl.GLuint * len(indices)),
                        (gl.GLuint * len(indices))(*indices),
                        gl.GL_STATIC_DRAW)

        # create shader

        self.shader = shader.Shader("vert.glsl", "frag.glsl")
        self.shader_matrix_location = self.shader.find_uniform(
            b"matrix")  # get the shader matrix uniform location
        self.shader.use()

        # create matrices

        self.mv_matrix = matrix.Matrix()  # modelview
        self.p_matrix = matrix.Matrix()  # projection

        self.x = 0  # temporary variable
        pyglet.clock.schedule_interval(
            self.update,
            1.0 / 60)  # call update function every 60th of a second
Exemplo n.º 9
0
	def __init__(self, world, chunk_position):
		self.world = world
		
		self.modified = False
		self.chunk_position = chunk_position

		self.position = (
			self.chunk_position[0] * CHUNK_WIDTH,
			self.chunk_position[1] * CHUNK_HEIGHT,
			self.chunk_position[2] * CHUNK_LENGTH)
		
		self.blocks = [[[0
			for z in range(CHUNK_LENGTH)]
			for y in range(CHUNK_HEIGHT)]
			for x in range(CHUNK_WIDTH )]

		self.subchunks = {}
		
		for x in range(int(CHUNK_WIDTH / subchunk.SUBCHUNK_WIDTH)):
			for y in range(int(CHUNK_HEIGHT / subchunk.SUBCHUNK_HEIGHT)):
				for z in range(int(CHUNK_LENGTH / subchunk.SUBCHUNK_LENGTH)):
					self.subchunks[(x, y, z)] = subchunk.Subchunk(self, (x, y, z))

		# mesh variables

		self.mesh_vertex_positions = []
		self.mesh_tex_coords = []
		self.mesh_shading_values = []

		self.mesh_index_counter = 0
		self.mesh_indices = []

		# create VAO and VBO's

		self.vao = gl.GLuint(0)
		gl.glGenVertexArrays(1, self.vao)
		gl.glBindVertexArray(self.vao)

		self.vertex_position_vbo = gl.GLuint(0)
		gl.glGenBuffers(1, self.vertex_position_vbo)

		self.tex_coord_vbo = gl.GLuint(0)
		gl.glGenBuffers(1, self.tex_coord_vbo)

		self.shading_values_vbo = gl.GLuint(0)
		gl.glGenBuffers(1, self.shading_values_vbo)

		self.ibo = gl.GLuint(0)
		gl.glGenBuffers(1, self.ibo)
Exemplo n.º 10
0
    def gen_vertices(self):
        # Just make a cube for now
        self.vertices = (GLfloat * 108)(*[
            -1.0, -1.0, -1.0,
            -1.0, -1.0, 1.0,
            -1.0, 1.0, 1.0,
            1.0, 1.0, -1.0,
            -1.0, -1.0, -1.0,
            -1.0, 1.0, -1.0,
            1.0, -1.0, 1.0,
            -1.0, -1.0, -1.0,
            1.0, -1.0, -1.0,
            1.0, 1.0, -1.0,
            1.0, -1.0, -1.0,
            -1.0, -1.0, -1.0,
            -1.0, -1.0, -1.0,
            -1.0, 1.0, 1.0,
            -1.0, 1.0, -1.0,
            1.0, -1.0, 1.0,
            -1.0, -1.0, 1.0,
            -1.0, -1.0, -1.0,
            -1.0, 1.0, 1.0,
            -1.0, -1.0, 1.0,
            1.0, -1.0, 1.0,
            1.0, 1.0, 1.0,
            1.0, -1.0, -1.0,
            1.0, 1.0, -1.0,
            1.0, -1.0, -1.0,
            1.0, 1.0, 1.0,
            1.0, -1.0, 1.0,
            1.0, 1.0, 1.0,
            1.0, 1.0, -1.0,
            -1.0, 1.0, -1.0,
            1.0, 1.0, 1.0,
            -1.0, 1.0, -1.0,
            -1.0, 1.0, 1.0,
            1.0, 1.0, 1.0,
            -1.0, 1.0, 1.0,
            1.0, -1.0, 1.0
        ])
        glGenVertexArrays(1, self.vao)
        glGenBuffers(1, self.vbo)

        glBindBuffer(GL_ARRAY_BUFFER, self.vbo)
        glBufferData(GL_ARRAY_BUFFER, sizeof(self.vertices), self.vertices, GL_STATIC_DRAW)

        glBindVertexArray(self.vao)
        glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 3 * sizeof(GLfloat), 0)
        glEnableVertexAttribArray(0)
Exemplo n.º 11
0
    def __init__(self,
                 prog: Program,
                 content: Iterable[BufferDescription],
                 index_buffer: Buffer = None):
        self.program = prog.prog_id
        self.vao = vao = gl.GLuint()
        self.num_vertices = -1
        self.ibo = index_buffer

        gl.glGenVertexArrays(1, byref(self.vao))
        gl.glBindVertexArray(self.vao)

        for buffer_desc in content:
            self._enable_attrib(buffer_desc)

        if self.ibo is not None:
            gl.glBindBuffer(gl.GL_ELEMENT_ARRAY_BUFFER, self.ibo.buffer_id)
        weakref.finalize(self, VertexArray.release, vao)
Exemplo n.º 12
0
    def __init__(self, **args):
        super().__init__(**args)

        # create vertex array object

        self.vao = gl.GLuint(0)
        gl.glGenVertexArrays(1, ctypes.byref(self.vao))
        gl.glBindVertexArray(self.vao)

        # create vertex buffer object

        self.vbo = gl.GLuint(0)
        gl.glGenBuffers(1, ctypes.byref(self.vbo))
        gl.glBindBuffer(gl.GL_ARRAY_BUFFER, self.vbo)

        gl.glBufferData(gl.GL_ARRAY_BUFFER,
                        ctypes.sizeof(gl.GLfloat * len(vertex_positions)),
                        (gl.GLfloat *
                         len(vertex_positions))(*vertex_positions),
                        gl.GL_STATIC_DRAW)

        gl.glVertexAttribPointer(0, 3, gl.GL_FLOAT, gl.GL_FALSE, 0, 0)
        gl.glEnableVertexAttribArray(0)

        # create index buffer object

        self.ibo = gl.GLuint(0)
        gl.glGenBuffers(1, self.ibo)
        gl.glBindBuffer(gl.GL_ELEMENT_ARRAY_BUFFER, self.ibo)

        gl.glBufferData(gl.GL_ELEMENT_ARRAY_BUFFER,
                        ctypes.sizeof(gl.GLuint * len(indices)),
                        (gl.GLuint * len(indices))(*indices),
                        gl.GL_STATIC_DRAW)

        # create shader

        self.shader = shader.Shader("vert.glsl", "frag.glsl")
        self.shader.use()
Exemplo n.º 13
0
def upload(asset: ModelAsset, gl_usage=GL_STATIC_DRAW):
    asset.vertex_array_id = GLuint()
    glGenVertexArrays(1, asset.vertex_array_id)

    asset.vertex_buffer_id = GLuint()
    glGenBuffers(1, asset.vertex_buffer_id)

    upload_vertices(asset, gl_usage)

    upload_indices(asset, gl_usage)

    if asset.texture is not None:
        glBindTexture(GL_TEXTURE_2D, asset.texture.id)
        glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR)
        glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR)

        # noinspection PyCallingNonCallable,PyTypeChecker
        texture_data = (GLubyte * len(asset.texture.buffer.flat))(
            *asset.texture.buffer.flatten())
        glTexImage2D(GL_TEXTURE_2D, 0, GL_ALPHA, asset.texture.width,
                     asset.texture.height, 0, asset.texture.format,
                     asset.texture.type, texture_data)
Exemplo n.º 14
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)
Exemplo n.º 15
0
    def __init__(self):
        display = pyglet.canvas.get_display()
        config = display.get_default_screen().get_best_config(Config())
        config.major_version = 3
        config.minor_version = 3
        context = config.create_context(None)

        Window.__init__(self,
                        800,
                        600,
                        visible=False,
                        resizable=True,
                        caption='Tinyblend example',
                        context=context)

        self.vao = (GLuint * 1)()
        glGenVertexArrays(1, self.vao)
        glBindVertexArray(self.vao[0])

        # Load shaders
        shader = shaders.from_files_names('shaders/main.glsl.vert',
                                          'shaders/main.glsl.frag')
        shader.owned = False
        shader.use()
        shader.enable_all_attributes()
        self.shader = shader

        # Uniforms matrices setup
        self.rotation = [-90, 0, 0]
        self.position = [0, 0, -4.5]
        shaders.transpose_matrices(False)
        self.upload_uniforms()

        # Scene creation
        self.setup_scene()

        # Show the window
        self.set_visible()
Exemplo n.º 16
0
 def __init__(self):
     """Create an instance of a Vertex Array object."""
     self._context = pyglet.gl.current_context
     self._id = GLuint()
     glGenVertexArrays(1, self._id)
Exemplo n.º 17
0
	def __init__(self, world, chunk_position):
		self.world = world
		self.shader_chunk_offset_location = self.world.shader.find_uniform(b"u_ChunkPosition")
		
		self.modified = False
		self.chunk_position = chunk_position

		self.position = (
			self.chunk_position[0] * CHUNK_WIDTH,
			self.chunk_position[1] * CHUNK_HEIGHT,
			self.chunk_position[2] * CHUNK_LENGTH)
		
		self.blocks = [[[0 for z in range(CHUNK_LENGTH)]
							for y in range(CHUNK_HEIGHT)]
							for x in range(CHUNK_WIDTH)]
		# Numpy is really slow there
		self.lightmap = [[[0 for z in range(CHUNK_LENGTH)]
							for y in range(CHUNK_HEIGHT)]
							for x in range(CHUNK_WIDTH)]
		
		self.subchunks = {}
		self.chunk_update_queue = deque()
		
		for x in range(int(CHUNK_WIDTH / subchunk.SUBCHUNK_WIDTH)):
			for y in range(int(CHUNK_HEIGHT / subchunk.SUBCHUNK_HEIGHT)):
				for z in range(int(CHUNK_LENGTH / subchunk.SUBCHUNK_LENGTH)):
					self.subchunks[(x, y, z)] = subchunk.Subchunk(self, (x, y, z))

		# mesh variables

		self.mesh = []
		self.translucent_mesh = []

		self.mesh_quad_count = 0
		self.translucent_quad_count = 0

		# create VAO and VBO's

		self.vao = gl.GLuint(0)
		gl.glGenVertexArrays(1, self.vao)
		gl.glBindVertexArray(self.vao)
		
		self.vbo = gl.GLuint(0)
		gl.glGenBuffers(1, self.vbo)
		gl.glBindBuffer(gl.GL_ARRAY_BUFFER, self.vbo)
		gl.glBufferData(gl.GL_ARRAY_BUFFER, ctypes.sizeof(gl.GLfloat * CHUNK_WIDTH * CHUNK_HEIGHT * CHUNK_LENGTH * 7), None, gl.GL_DYNAMIC_DRAW)

		gl.glVertexAttribPointer(0, 3, gl.GL_FLOAT, 
				gl.GL_FALSE, 7 * ctypes.sizeof(gl.GLfloat), 0)
		gl.glEnableVertexAttribArray(0)
		gl.glVertexAttribPointer(1, 1, gl.GL_FLOAT, 
				gl.GL_FALSE, 7 * ctypes.sizeof(gl.GLfloat), 3 * ctypes.sizeof(gl.GLfloat))
		gl.glEnableVertexAttribArray(1)
		gl.glVertexAttribPointer(2, 1, gl.GL_FLOAT, 
				gl.GL_FALSE, 7 * ctypes.sizeof(gl.GLfloat), 4 * ctypes.sizeof(gl.GLfloat))
		gl.glEnableVertexAttribArray(2)
		gl.glVertexAttribPointer(3, 1, gl.GL_FLOAT, 
				gl.GL_FALSE, 7 * ctypes.sizeof(gl.GLfloat), 5 * ctypes.sizeof(gl.GLfloat))
		gl.glEnableVertexAttribArray(3)
		gl.glVertexAttribPointer(4, 1, gl.GL_FLOAT, 
				gl.GL_FALSE, 7 * ctypes.sizeof(gl.GLfloat), 6 * ctypes.sizeof(gl.GLfloat))
		gl.glEnableVertexAttribArray(4)
		


		gl.glBindBuffer(gl.GL_ELEMENT_ARRAY_BUFFER, world.ibo)
		
		if self.world.options.INDIRECT_RENDERING:
			self.indirect_command_buffer = gl.GLuint(0)
			gl.glGenBuffers(1, self.indirect_command_buffer)
			gl.glBindBuffer(gl.GL_DRAW_INDIRECT_BUFFER, self.indirect_command_buffer)
			gl.glBufferData(
				gl.GL_DRAW_INDIRECT_BUFFER, 
				ctypes.sizeof(gl.GLuint * 10),
				None,
				gl.GL_DYNAMIC_DRAW
			)	

		self.draw_commands = []

		self.occlusion_query = gl.GLuint(0)
		gl.glGenQueries(1, self.occlusion_query)
Exemplo n.º 18
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)
Exemplo n.º 19
0
def createVAO(vertexBuffer,
              textureCoordBuffer=None,
              normalBuffer=None,
              colorBuffer=None):
    """Create a Vertex Array Object (VAO) with specified Vertex Buffer Objects.
    VAOs store buffer binding states, reducing binding overhead when drawing
    objects with vertext data stored in VBOs.

    Parameters
    ----------
    vertexBuffer : :obj:`VertexBufferObject`
        Vertex buffer descriptor, must have 'bufferType' as GL_VERTEX_ARRAY.
    textureCoordBuffer : :obj:`VertexBufferObject` or None, optional
        Vertex buffer descriptor of texture coordinates, must have 'bufferType'
        as GL_TEXTURE_COORD_ARRAY.
    normalBuffer : :obj:`VertexBufferObject` or None, optional
        Vertex buffer descriptor of normals, must have 'bufferType' as
        GL_NORMAL_ARRAY.
    colorBuffer :obj:`VertexBufferObject` or None, optional
        Vertex buffer descriptor of colors, must have 'bufferType' as
        GL_COLOR_ARRAY.

    Returns
    -------
    VertexArrayObject
        A descriptor with vertex buffer information.

    Examples
    --------
    # create a VAO
    vaoDesc = createVAO(vboVerts, vboTexCoords, vboNormals)

    # draw the VAO, renders the mesh
    drawVAO(vaoDesc, GL.GL_TRIANGLES)

    """
    # create a vertex buffer ID
    vaoId = GL.GLuint()
    GL.glGenVertexArrays(1, ctypes.byref(vaoId))
    GL.glBindVertexArray(vaoId)

    # must have a vertex pointer
    assert vertexBuffer.bufferType == GL.GL_VERTEX_ARRAY

    # bind and set the vertex pointer, this is must be bound
    GL.glBindBuffer(GL.GL_ARRAY_BUFFER, vertexBuffer.id)
    GL.glVertexPointer(vertexBuffer.vertexSize, vertexBuffer.dtype, 0, None)
    GL.glEnableClientState(vertexBuffer.bufferType)

    # texture coordinates
    if textureCoordBuffer is not None:
        if vertexBuffer.indices != textureCoordBuffer.indices:
            raise RuntimeError(
                "Texture and vertex buffer indices do not match!")
        GL.glBindBuffer(GL.GL_ARRAY_BUFFER, textureCoordBuffer.id)
        GL.glTexCoordPointer(textureCoordBuffer.vertexSize,
                             textureCoordBuffer.dtype, 0, None)
        GL.glEnableClientState(GL.GL_TEXTURE_COORD_ARRAY)

    # normals
    if normalBuffer is not None:
        if vertexBuffer.indices != normalBuffer.indices:
            raise RuntimeError(
                "Normal and vertex buffer indices do not match!")
        GL.glBindBuffer(GL.GL_ARRAY_BUFFER, normalBuffer.id)
        GL.glNormalPointer(normalBuffer.dtype, 0, None)
        GL.glEnableClientState(GL.GL_NORMAL_ARRAY)

    # colors
    if colorBuffer is not None:
        if vertexBuffer.indices != colorBuffer.indices:
            raise RuntimeError("Color and vertex buffer indices do not match!")
        GL.glBindBuffer(GL.GL_ARRAY_BUFFER, colorBuffer.id)
        GL.glColorPointer(colorBuffer.vertexSize, colorBuffer.dtype, 0, None)
        GL.glEnableClientState(GL.GL_COLOR_ARRAY)

    GL.glBindVertexArray(0)

    return VertexArrayObject(vaoId, vertexBuffer.indices, dict())
Exemplo n.º 20
0
 def __init__(self):
     self.handle = GLuint()
     glGenVertexArrays(1, self.handle)
Exemplo n.º 21
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"])
Exemplo n.º 22
0
    def __init__(self, **args):
        super().__init__(**args)

        # create blocks

        self.texture_manager = texture_manager.Texture_manager(16, 16, 256)

        self.cobblestone = block_type.Block_type(self.texture_manager,
                                                 "cobblestone",
                                                 {"all": "cobblestone"})
        self.grass = block_type.Block_type(self.texture_manager, "grass", {
            "top": "grass",
            "bottom": "dirt",
            "sides": "grass_side"
        })
        self.dirt = block_type.Block_type(self.texture_manager, "dirt",
                                          {"all": "dirt"})
        self.stone = block_type.Block_type(self.texture_manager, "stone",
                                           {"all": "stone"})
        self.sand = block_type.Block_type(self.texture_manager, "sand",
                                          {"all": "sand"})
        self.planks = block_type.Block_type(self.texture_manager, "planks",
                                            {"all": "planks"})
        self.log = block_type.Block_type(self.texture_manager, "log", {
            "top": "log_top",
            "bottom": "log_top",
            "sides": "log_side"
        })

        self.texture_manager.generate_mipmaps()

        # create vertex array object

        self.vao = gl.GLuint(0)
        gl.glGenVertexArrays(1, ctypes.byref(self.vao))
        gl.glBindVertexArray(self.vao)

        # create vertex position vbo

        self.vertex_position_vbo = gl.GLuint(0)
        gl.glGenBuffers(1, ctypes.byref(self.vertex_position_vbo))
        gl.glBindBuffer(gl.GL_ARRAY_BUFFER, self.vertex_position_vbo)

        gl.glBufferData(
            gl.GL_ARRAY_BUFFER,
            ctypes.sizeof(gl.GLfloat * len(self.grass.vertex_positions)),
            (gl.GLfloat *
             len(self.grass.vertex_positions))(*self.grass.vertex_positions),
            gl.GL_STATIC_DRAW)

        gl.glVertexAttribPointer(0, 3, gl.GL_FLOAT, gl.GL_FALSE, 0, 0)
        gl.glEnableVertexAttribArray(0)

        # create tex coord vbo

        self.tex_coord_vbo = gl.GLuint(0)
        gl.glGenBuffers(1, ctypes.byref(self.tex_coord_vbo))
        gl.glBindBuffer(gl.GL_ARRAY_BUFFER, self.tex_coord_vbo)

        gl.glBufferData(gl.GL_ARRAY_BUFFER,
                        ctypes.sizeof(gl.GLfloat * len(self.grass.tex_coords)),
                        (gl.GLfloat *
                         len(self.grass.tex_coords))(*self.grass.tex_coords),
                        gl.GL_STATIC_DRAW)

        gl.glVertexAttribPointer(1, 3, gl.GL_FLOAT, gl.GL_FALSE, 0, 0)
        gl.glEnableVertexAttribArray(1)

        # create index buffer object

        self.ibo = gl.GLuint(0)
        gl.glGenBuffers(1, self.ibo)
        gl.glBindBuffer(gl.GL_ELEMENT_ARRAY_BUFFER, self.ibo)

        gl.glBufferData(gl.GL_ELEMENT_ARRAY_BUFFER,
                        ctypes.sizeof(gl.GLuint * len(self.grass.indices)),
                        (gl.GLuint *
                         len(self.grass.indices))(*self.grass.indices),
                        gl.GL_STATIC_DRAW)

        # create shader

        self.shader = shader.Shader("vert.glsl", "frag.glsl")
        self.shader_sampler_location = self.shader.find_uniform(
            b"texture_array_sampler")
        self.shader.use()

        # pyglet stuff

        pyglet.clock.schedule_interval(self.update, 1.0 / 60)
        self.mouse_captured = False

        # camera stuff

        self.camera = camera.Camera(self.shader, self.width, self.height)
Exemplo n.º 23
0
    def __init__(self, aspect: float):
        self.array = buffer_array = gl.GLuint(0)
        self.vertices = vertex_buffer = gl.GLuint(0)
        self.offsets = offset_buffer = gl.GLuint(0)
        self.indices = index_buffer = gl.GLuint(0)

        self.edge_chunks = 3
        self.instances = 0
        self.stored_chunks: list[int] = []

        gl.glGenVertexArrays(1, byref(buffer_array))
        gl.glGenBuffers(1, byref(vertex_buffer))
        gl.glGenBuffers(1, byref(offset_buffer))
        gl.glGenBuffers(1, byref(index_buffer))

        self.shader = from_files_names(
            "res/Shaders/chunk.vert",
            "res/Shaders/chunk.frag"
        )
        self.shader.use()

        width = aspect if aspect >= 1.0 else 1.0
        height = 1.0 / aspect if aspect < 1.0 else 1.0
        self.shader.uniforms["projection"].set((
            (1.0 / width, 0.0,          0.0, 0.0),
            (0.0,         1.0 / height, 0.0, 0.0),
            (0.0,         0.0,          1.0, 0.0),
            (0.0,         0.0,          0.0, 1.0)
        ))

        cell_size = 1.0 / Chunk.edge_cells

        # The math gets weird converting between quad and edge space.
        num_quads_x = num_quads_y = Chunk.edge_cells

        num_vertices_x = num_quads_x + 1
        num_vertices_y = num_quads_y + 1

        def construct_vertex_buffer():
            # Crazy thought, instead of creating quads here, we can render points
            #   and use a geometry shader to create the quads.
            # Saves (width + height) * 2 * sizeof(float) bytes on vertices and completely
            #   elminiates indices.

            # Create vertex buffer.
            x_slice = y_slice = cell_size
            chunk_vertices = (gl.GLfloat * (num_vertices_x * num_vertices_y * 2))()
            for row in range(num_vertices_y):
                for col in range(num_vertices_x):
                    index = (row * num_vertices_x + col) * 2  # Convert to array space.
                    chunk_vertices[index:index + 2] = (
                        # Define the chunk by its center.
                        x_slice * float(col) - 0.5,
                        y_slice * float(row) - 0.5
                    )

            gl.glBufferData(
                gl.GL_ARRAY_BUFFER,
                sizeof(chunk_vertices),
                chunk_vertices,
                gl.GL_STATIC_DRAW
            )

            gl.glEnableVertexAttribArray(0)
            gl.glVertexAttribPointer(0, 2, gl.GL_FLOAT, False, 2 * sizeof(gl.GLfloat), 0)

        def construct_offset_buffer():
            gl.glBufferData(gl.GL_ARRAY_BUFFER, 9 * 2 * sizeof(gl.GLfloat), None, gl.GL_DYNAMIC_DRAW)

            gl.glEnableVertexAttribArray(1)
            gl.glVertexAttribPointer(1, 2, gl.GL_FLOAT, False, 2 * sizeof(gl.GLfloat), 0)
            gl.glVertexAttribDivisor(1, 1)

        def construct_index_buffer():
            chunk_indices = (gl.GLuint * (num_quads_x * num_quads_y * 6))()
            for row in range(num_quads_y):
                for col in range(num_quads_x):
                    current_quad = row * num_quads_x + col  # Calculate the current block in the chunk.
                    left_corner = current_quad + row  # Add one extra column each time we need to go up a row.
                    index = current_quad * 6  # Convert to array space.
                    chunk_indices[index:index + 6] = (
                        # Quad lower right triangle.
                        left_corner,
                        left_corner + 1,
                        left_corner + num_vertices_x + 1,

                        # Quad upper right triangle.
                        left_corner + num_vertices_x + 1,
                        left_corner + num_vertices_x,
                        left_corner
                    )

            gl.glBufferData(gl.GL_ELEMENT_ARRAY_BUFFER, sizeof(chunk_indices), chunk_indices, gl.GL_STATIC_DRAW)

        gl.glBindVertexArray(buffer_array)
        gl.glBindBuffer(gl.GL_ARRAY_BUFFER, vertex_buffer)
        construct_vertex_buffer()

        gl.glBindBuffer(gl.GL_ARRAY_BUFFER, offset_buffer)
        construct_offset_buffer()

        gl.glBindBuffer(gl.GL_ELEMENT_ARRAY_BUFFER, index_buffer)
        construct_index_buffer()

        gl.glBindVertexArray(0)
        gl.glBindBuffer(gl.GL_ARRAY_BUFFER, 0)
        gl.glBindBuffer(gl.GL_ELEMENT_ARRAY_BUFFER, 0)
Exemplo n.º 24
0
 def __init__(self):
     """Create an instance of a Vertex Array object."""
     self._id = GLuint()
     glGenVertexArrays(1, self._id)
Exemplo n.º 25
0
    def _build(self, program: Program, content: Sequence[BufferDescription],
               index_buffer):
        """Build a vertex array compatible with the program passed in"""
        gl.glGenVertexArrays(1, byref(self.glo))
        gl.glBindVertexArray(self.glo)

        # Lookup dict for BufferDescription attrib names
        # print(content)
        descr_attribs = {
            attr.name: (descr, attr)
            for descr in content for attr in descr.formats
        }
        # print('->', descr_attribs)

        # Build the vao according to the shader's attribute specifications
        for i, prog_attr in enumerate(program.attributes):
            # print('prog_attr', prog_attr)
            # Do we actually have an attribute with this name in buffer descriptions?
            if prog_attr.name.startswith("gl_"):
                continue
            try:
                buff_descr, attr_descr = descr_attribs[prog_attr.name]
            except KeyError:
                raise ValueError((
                    f"Program needs attribute '{prog_attr.name}', but is not present in buffer description. "
                    f"Buffer descriptions: {content}"))

            # TODO: Sanity check this
            # if buff_descr.instanced and i == 0:
            #     raise ValueError("The first vertex attribute cannot be a per instance attribute.")

            # Make sure components described in BufferDescription and in the shader match
            if prog_attr.components != attr_descr.components:
                raise ValueError((
                    f"Program attribute '{prog_attr.name}' has {prog_attr.components} components "
                    f"while the buffer description has {attr_descr.components} components. "
                ))

            # TODO: Compare gltype between buffer descr and program attr

            gl.glEnableVertexAttribArray(prog_attr.location)
            gl.glBindBuffer(gl.GL_ARRAY_BUFFER, buff_descr.buffer.glo)

            # TODO: Detect normalization
            normalized = (gl.GL_TRUE if attr_descr.name
                          in buff_descr.normalized else gl.GL_FALSE)
            gl.glVertexAttribPointer(
                prog_attr.location,  # attrib location
                attr_descr.components,  # 1, 2, 3 or 4
                attr_descr.gl_type,  # GL_FLOAT etc
                normalized,  # normalize
                buff_descr.stride,
                c_void_p(attr_descr.offset),
            )
            # print((
            #     f"gl.glVertexAttribPointer(\n"
            #     f"    {prog_attr.location},  # attrib location\n"
            #     f"    {attr_descr.components},  # 1, 2, 3 or 4\n"
            #     f"    {attr_descr.gl_type},  # GL_FLOAT etc\n"
            #     f"    {normalized},  # normalize\n"
            #     f"    {buff_descr.stride},\n"
            #     f"    c_void_p({attr_descr.offset}),\n"
            # ))
            # TODO: Sanity check this
            if buff_descr.instanced:
                gl.glVertexAttribDivisor(prog_attr.location, 1)

        if index_buffer is not None:
            gl.glBindBuffer(gl.GL_ELEMENT_ARRAY_BUFFER, index_buffer.glo)
Exemplo n.º 26
0
    def __init__(self, **args):
        super().__init__(**args)

        # create blocks

        self.texture_manager = texture_manager.Texture_manager(
            16, 16, 256
        )  # create our texture manager (256 textures that are 16 x 16 pixels each)

        self.cobblestone = block_type.Block_type(
            self.texture_manager, "cobblestone", {"all": "cobblestone"}
        )  # create each one of our blocks with the texture manager and a list of textures per face
        self.grass = block_type.Block_type(self.texture_manager, "grass", {
            "top": "grass",
            "bottom": "dirt",
            "sides": "grass_side"
        })
        self.dirt = block_type.Block_type(self.texture_manager, "dirt",
                                          {"all": "dirt"})
        self.stone = block_type.Block_type(self.texture_manager, "stone",
                                           {"all": "stone"})
        self.sand = block_type.Block_type(self.texture_manager, "sand",
                                          {"all": "sand"})
        self.planks = block_type.Block_type(self.texture_manager, "planks",
                                            {"all": "planks"})
        self.log = block_type.Block_type(self.texture_manager, "log", {
            "top": "log_top",
            "bottom": "log_top",
            "sides": "log_side"
        })

        self.texture_manager.generate_mipmaps(
        )  # generate mipmaps for our texture manager's texture

        # create vertex array object

        self.vao = gl.GLuint(0)
        gl.glGenVertexArrays(1, ctypes.byref(self.vao))
        gl.glBindVertexArray(self.vao)

        # create vertex position vbo

        self.vertex_position_vbo = gl.GLuint(0)
        gl.glGenBuffers(1, ctypes.byref(self.vertex_position_vbo))
        gl.glBindBuffer(gl.GL_ARRAY_BUFFER, self.vertex_position_vbo)

        gl.glBufferData(
            gl.GL_ARRAY_BUFFER,
            ctypes.sizeof(gl.GLfloat * len(self.grass.vertex_positions)),
            (gl.GLfloat * len(self.grass.vertex_positions))(
                *self.grass.vertex_positions
            ),  # use grass block's vertex positions
            gl.GL_STATIC_DRAW)

        gl.glVertexAttribPointer(0, 3, gl.GL_FLOAT, gl.GL_FALSE, 0, 0)
        gl.glEnableVertexAttribArray(0)

        # create tex coord vbo

        self.tex_coord_vbo = gl.GLuint(0)
        gl.glGenBuffers(1, ctypes.byref(self.tex_coord_vbo))
        gl.glBindBuffer(gl.GL_ARRAY_BUFFER, self.tex_coord_vbo)

        gl.glBufferData(
            gl.GL_ARRAY_BUFFER,
            ctypes.sizeof(gl.GLfloat * len(self.grass.tex_coords)),
            (gl.GLfloat * len(self.grass.tex_coords))(
                *self.grass.tex_coords
            ),  # use grass block's texture coordinates positions
            gl.GL_STATIC_DRAW)

        gl.glVertexAttribPointer(1, 3, gl.GL_FLOAT, gl.GL_FALSE, 0, 0)
        gl.glEnableVertexAttribArray(1)

        # create index buffer object

        self.ibo = gl.GLuint(0)
        gl.glGenBuffers(1, self.ibo)
        gl.glBindBuffer(gl.GL_ELEMENT_ARRAY_BUFFER, self.ibo)

        gl.glBufferData(
            gl.GL_ELEMENT_ARRAY_BUFFER,
            ctypes.sizeof(gl.GLuint * len(self.grass.indices)),
            (gl.GLuint * len(self.grass.indices))(
                *self.grass.indices),  # use grass block's indices
            gl.GL_STATIC_DRAW)

        # create shader

        self.shader = shader.Shader("vert.glsl", "frag.glsl")
        self.shader_matrix_location = self.shader.find_uniform(b"matrix")
        self.shader_sampler_location = self.shader.find_uniform(
            b"texture_array_sampler"
        )  # find our texture array sampler's uniform
        self.shader.use()

        # create matrices

        self.mv_matrix = matrix.Matrix()
        self.p_matrix = matrix.Matrix()

        self.x = 0
        pyglet.clock.schedule_interval(self.update, 1.0 / 60)
Exemplo n.º 27
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)
Exemplo n.º 28
0
 def __init__(self):
     self.__value = None
     buf = ct.c_uint()
     gl.glGenVertexArrays(1, ct.byref(buf))
     self.__value = buf.value