def __setitem__(self, key, value): with self.bound: sz = len(self) if isinstance(key, slice): start = int(key.start) if key.start is not None else 0 stop = int(key.stop) if key.stop is not None else start + value.size else: start = int(key) stop = start + 1 if start < 0 or stop < 0 or start >= stop: raise IndexError if stop > sz: newsz = max(sz * 2, stop) a = numpy.empty((newsz,), dtype=self.dtype) GL.glGetBufferSubData(GL.GL_ARRAY_BUFFER, 0, sz * self.dtype.itemsize, a.ctypes.data) b = numpy.asarray(value).reshape(-1) a[start:stop] = b GL.glBufferData(GL.GL_ARRAY_BUFFER, newsz * self.dtype.itemsize, a.ctypes.data, self.usage) else: a = numpy.ascontiguousarray(value, self.dtype).reshape(-1) sz = min((stop - start), len(a)) GL.glBufferSubData(GL.GL_ARRAY_BUFFER, start * self.dtype.itemsize, sz * self.dtype.itemsize, a)
def _resize(self): """ """ log("GPU: Resizing buffer(%d bytes)" % self._nbytes) gl.glBufferData(self._target, self._nbytes, None, self._usage) self._need_resize = False
def setup_buffers_v2(gltf, uri_path): buffers = gltf.get('buffers', []) data_buffers = [] for i, buffer in enumerate(buffers): uri = buffer['uri'] if uri.startswith('data:application/octet-stream;base64,'): data_buffers.append(base64.b64decode(uri.split(',')[1])) else: filename = os.path.join(uri_path, buffer['uri']) data_buffers.append(open(filename, 'rb').read()) _logger.debug('loaded buffer %s from "%s"', i if 'name' not in buffer else '%d ("%s")' % (i, buffer['name']), filename) for i, bufferView in enumerate(gltf.get('bufferViews', [])): buffer_id = gl.glGenBuffers(1) byteOffset = bufferView.get('byteOffset', 0) target = bufferView.get('target', gl.GL_ARRAY_BUFFER) gl.glBindBuffer(target, buffer_id) gl.glBufferData(target, bufferView['byteLength'], data_buffers[bufferView['buffer']][byteOffset:], gl.GL_STATIC_DRAW) if gl.glGetError() != gl.GL_NO_ERROR: raise Exception('failed to create bufferView %s' % i) bufferView['id'] = buffer_id gl.glBindBuffer(target, 0) _logger.debug('created bufferView %s', i if 'name' not in bufferView else '%d ("%s")' % (i, bufferView['name']))
def init_vertex_buf(self): self.vbo = GL.glGenBuffers(1) GL.glBindBuffer(GL.GL_ARRAY_BUFFER,self.vbo) ArrayType = (GL.GLfloat*len(self.vertices)) GL.glBufferData(GL.GL_ARRAY_BUFFER,len(self.vertices)*self.size_float, ArrayType(*self.vertices),GL.GL_STATIC_DRAW) GL.glBindBuffer(GL.GL_ARRAY_BUFFER,0)
def get_ub(listy, record_byte_size): ubo, binding_point_index = gen_ub() gl.glBindBufferBase(gl.GL_UNIFORM_BUFFER, binding_point_index, ubo) gl.glBufferData(gl.GL_UNIFORM_BUFFER, record_byte_size*len(listy), listy, gl.GL_DYNAMIC_DRAW) gl.glBindBuffer(gl.GL_UNIFORM_BUFFER, 0) return ubo, binding_point_index
def init(self): super(BasicWindow, self).init() vert_shader = compileShader(vert_shader_source, GL.GL_VERTEX_SHADER) frag_shader = compileShader(frag_shader_source, GL.GL_FRAGMENT_SHADER) self.shader = game_core.ShaderProgram(vert_shader, frag_shader) self.ndc_vao = GL.glGenVertexArrays(1) GL.glBindVertexArray(self.ndc_vao) vertex_buffer = GL.glGenBuffers(1) GL.glBindBuffer(GL.GL_ARRAY_BUFFER, vertex_buffer) data = [ -1.0, -1.0, 0.0, 0.0, 1.0, 0.0, 1.0, -1.0, 0.0, ] array_type = (GL.GLfloat*len(data)) GL.glBufferData( GL.GL_ARRAY_BUFFER, len(data)*game_core.FLOAT_SIZE, array_type(*data), GL.GL_STATIC_DRAW ) GL.glEnableVertexAttribArray(0) GL.glVertexAttribPointer(0, 3, GL.GL_FLOAT, GL.GL_FALSE, 0, None) GL.glBindVertexArray(0)
def init_vertex_buf(self): self.vbo = GL.glGenBuffers(1) GL.glBindBuffer(GL.GL_ARRAY_BUFFER,self.vbo) array_type = (GL.GLfloat*len(VERTICES)) GL.glBufferData(GL.GL_ARRAY_BUFFER,len(VERTICES)*SIZE_FLOAT, array_type(*VERTICES),GL.GL_STATIC_DRAW) GL.glBindBuffer(GL.GL_ARRAY_BUFFER,0)
def sync(self): # Sync the buffer with the graphics hardware if the buffer is dirty if self.status == 'synced': return size = self.stride * self.count gl.glBindBuffer(self.target, self.id) gl.glBufferData(self.target, size, self.element, self.usage) self.status = 'synced'
def __init__(self, vertices, normals, indices, draw_method): self.draw_method = draw_method self.indices = indices self.vao = GL.glGenVertexArrays(1) GL.glBindVertexArray(self.vao) vertexBufferObject = GL.glGenBuffers(1) GL.glBindBuffer(GL.GL_ARRAY_BUFFER, vertexBufferObject) data = vertices + normals array_type = (GL.GLfloat*len(data)) GL.glBufferData( GL.GL_ARRAY_BUFFER, len(data)*FLOAT_SIZE, array_type(*data), GL.GL_STATIC_DRAW) GL.glEnableVertexAttribArray(0) GL.glEnableVertexAttribArray(1) GL.glVertexAttribPointer(0, 3, GL.GL_FLOAT, GL.GL_FALSE, 0, None) GL.glVertexAttribPointer(1, 3, GL.GL_FLOAT, GL.GL_FALSE, 0, GL.GLvoidp(len(vertices)*FLOAT_SIZE)) indexBufferObject = GL.glGenBuffers(1) GL.glBindBuffer(GL.GL_ELEMENT_ARRAY_BUFFER, indexBufferObject) array_type = (GL.GLuint*len(self.indices)) GL.glBufferData( GL.GL_ELEMENT_ARRAY_BUFFER, len(self.indices)*FLOAT_SIZE, array_type(*self.indices), GL.GL_STATIC_DRAW) GL.glBindVertexArray(0)
def __init__(self, name, vertices, indices): self.name = name assert len(indices) % 3 == 0 self.numTriangles = len(indices) / 3 vertex_data = vertices if isinstance(vertices, numpy.ndarray) else numpy.concatenate(vertices) index_data = numpy.array(indices, dtype=numpy.uint32) self.vao = GL.glGenVertexArrays(1) GL.glBindVertexArray(self.vao) self.vbo, self.ibo = GL.glGenBuffers(2) GL.glBindBuffer(GL.GL_ARRAY_BUFFER, self.vbo) GL.glBindBuffer(GL.GL_ELEMENT_ARRAY_BUFFER, self.ibo) self.program = BlinnWithoutNormalsProgram.get() GL.glEnableVertexAttribArray(self.program.attrib_position) GL.glVertexAttribPointer(self.program.attrib_position, 3, GL.GL_FLOAT, False, 3*SIZE_OF_FLOAT32, ctypes.c_void_p(0)) # Send the data over to the buffer GL.glBufferData(GL.GL_ARRAY_BUFFER, len(vertex_data) * SIZE_OF_FLOAT32, vertex_data.astype(numpy.float32, copy=False), GL.GL_STATIC_DRAW) GL.glBufferData(GL.GL_ELEMENT_ARRAY_BUFFER, len(index_data) * SIZE_OF_UNSIGNED32, index_data, GL.GL_STATIC_DRAW) # Unbind the VAO first (Important) GL.glBindVertexArray(0) # Unbind other stuff GL.glDisableVertexAttribArray(self.program.attrib_position) GL.glBindBuffer(GL.GL_ELEMENT_ARRAY_BUFFER, 0) GL.glBindBuffer(GL.GL_ARRAY_BUFFER, 0)
def __init__(self, elements, indices): temp_list = [0] # noinspection PyCallingNonCallable self.vbo = (ctypes.c_uint32 * 1)(*temp_list) # noinspection PyCallingNonCallable self.ibo = (ctypes.c_uint32 * 1)(*temp_list) GL.glGenBuffers(1, self.vbo) GL.glBindBuffer(GL.GL_ARRAY_BUFFER, self.vbo) # noinspection PyCallingNonCallable GL.glBufferData( GL.GL_ARRAY_BUFFER, len(elements) * 4, (ctypes.c_float * len(elements))(*elements), GL.GL_STATIC_DRAW ) GL.glGenBuffers(1, self.ibo) GL.glBindBuffer(GL.GL_ELEMENT_ARRAY_BUFFER, self.ibo) # noinspection PyCallingNonCallable GL.glBufferData( GL.GL_ELEMENT_ARRAY_BUFFER, len(indices) * 4, (ctypes.c_uint32 * len(indices))(*indices), GL.GL_STATIC_DRAW ) self.indices_number = ctypes.c_uint32(len(indices))
def initializeGL(self): gl.glClearColor(1.0,1.0,1.0,0.0) # gl.glColor3f(0.0,0.0, 0.0) # gl.glPointSize(4.0) # gl.glMatrixMode(gl.GL_PROJECTION) # gl.glLoadIdentity() # glu.gluOrtho2D(0.0,640.0,0.0,480.0) gl.glViewport (0, 0, 800, 600) gl.glClearColor (0.0, 0.5, 0.5, 1.0) gl.glEnableClientState (gl.GL_VERTEX_ARRAY) self._vertices, self._normals = util.load_obj("monkey.obj") self._vbo = gl.glGenBuffers(1) gl.glBindBuffer (gl.GL_ARRAY_BUFFER, self._vbo) gl.glBufferData (gl.GL_ARRAY_BUFFER, self._vertices.size*4, self._vertices, gl.GL_STATIC_DRAW) self._normal_vbo = gl.glGenBuffers(1) gl.glBindBuffer (gl.GL_ARRAY_BUFFER, self._normal_vbo) gl.glBufferData (gl.GL_ARRAY_BUFFER, self._normals.size*4, self._normals, gl.GL_STATIC_DRAW) self._shader_program = shader.LoadShaders("shader8.vs", "shader8.ps") gl.glEnable(gl.GL_DEPTH_TEST) gl.glDepthFunc(gl.GL_LESS)
def setBackground(self, aStreamer=None): """ Sets an streamer object as the one who provides the background image """ self.str = aStreamer if self.str: GL.glBindBuffer(GL.GL_PIXEL_UNPACK_BUFFER, self.pbo) GL.glBufferData(GL.GL_PIXEL_UNPACK_BUFFER, self.str.current(), GL.GL_DYNAMIC_DRAW) GL.glBindBuffer(GL.GL_PIXEL_UNPACK_BUFFER, 0)
def bind_attrib(self, attrib_id, size, data, storagetype=gl.GL_STATIC_DRAW, instance_divisor=0, datatype=gl.GL_FLOAT, stride=0, offset=None, normalize=False): if RenderObject.bound_vao is not self.vao_id: gl.glBindVertexArray(self.vao_id) RenderObject.bound_vao = self.vao_id # Keep track of max instance divisor self.max_instance_divisor = max(instance_divisor, self.max_instance_divisor) # If the input is an array create a new GL buffer, otherwise assume the buffer already exists and a buffer ID is passed if type(data) is np.ndarray: # Get an index to one new buffer in GPU mem, bind it, and copy the array data to it buf_id = gl.glGenBuffers(1) gl.glBindBuffer(gl.GL_ARRAY_BUFFER, buf_id) gl.glBufferData(gl.GL_ARRAY_BUFFER, data.nbytes, data, storagetype) else: # Assume that a GLuint is passed which means that the buffer is already in GPU memory buf_id = data gl.glBindBuffer(gl.GL_ARRAY_BUFFER, buf_id) # Assign this buffer to one of the attributes in the shader gl.glEnableVertexAttribArray(attrib_id) gl.glVertexAttribPointer(attrib_id, size, datatype, normalize, stride, offset) # For instanced data, indicate per how many instances we move a step in the buffer (1=per instance) if instance_divisor > 0: gl.glVertexAttribDivisor(attrib_id, instance_divisor) # Clean up gl.glDisableVertexAttribArray(attrib_id) self.enabled_attributes[attrib_id] = [size, buf_id, instance_divisor, datatype] return buf_id
def setAttributes(self, data): self.data = data self.dataLen = data.shape[0] # Make this buffer the default one gl.glBindVertexArray(self.VAO) gl.glBindBuffer(gl.GL_ARRAY_BUFFER, self.buffer) # Upload data gl.glBufferData(gl.GL_ARRAY_BUFFER, data.nbytes, data, gl.GL_DYNAMIC_DRAW) offset = 0 for i, name in enumerate(data.dtype.names): # import ipdb; ipdb.set_trace() stride = data[name].strides[0] if data[name].ndim == 1: size = 1 else: size = data[name].shape[1] loc = gl.glGetAttribLocation(self.program, name) # remember these properties for later updating of buffer self.attribute_layout[name] = {'offset':offset} gl.glVertexAttribPointer(loc, size, gl.GL_FLOAT, False, stride, ctypes.c_void_p(offset)) gl.glEnableVertexAttribArray(loc) offset += data.dtype[name].itemsize gl.glBindBuffer(gl.GL_ARRAY_BUFFER, 0) gl.glBindVertexArray(0) # ensure correct mask is rendered: self.setMask()
def __setitem__(self, idxs, data): """Set the contents of the buffer. Currently, only :py:obj:`Ellipsis` is valid as an index. :param idxs: The indices to set. A new buffer will be created if :py:obj:`Ellipsis` is passed. :param data: The new contents of the buffer. If a :py:class:`numpy.ndarray` is passed, it will be used to initialize the buffer. If a :py:class:`numpy.dtype` is passed, the buffer will not be initialized. :type data: :py:class:`numpy.dtype` or :py:class:`numpy.ndarray` .. warning:: |buffer-bind| """ if idxs is Ellipsis: if isinstance(data, dtype): dt = data data = None else: dt = ( data.dtype if product(data.shape) == 1 else dtype((data.dtype, data.shape)) ) try: binding = next(iter(self.active_bindings)) except StopIteration: raise RuntimeError("Buffer data can only be set if it is bound.") GL.glBufferData(binding, dt.itemsize, data, self.usage) self.dtype = dt else: raise NotImplementedError("TODO: Allow changing replacing buffer dtypes.")
def mySetup(self): self.shader = self.loadShader("vertexshader.glsl", "fragmentshader.glsl") #Define geometry: self.vertex_data = np.array([ [-1.0,-1.0, 0.0, -1.0, 0.0, 0.0], [ 1.0,-1.0, 0.0, 0.0,-1.0, 0.0], [ 1.0, 1.0, 0.0, 1.0, 0.0, 0.0], [-1.0, 1.0, 0.0, 0.0, 1.0, 0.0], ], dtype=np.float32) self.index_data = np.array([ [0, 1, 3], [1, 2, 3] ], dtype=np.uint32) GL.glEnable(GL.GL_CULL_FACE) # This isn't enabled by default GL.glFrontFace(GL.GL_CCW) # Standard, right hand rule GL.glCullFace(GL.GL_BACK) self.vbo = GL.glGenBuffers(1) self.ibo = GL.glGenBuffers(1) GL.glBindBuffer(GL.GL_ARRAY_BUFFER, self.vbo) # Select self.vbo GL.glBufferData(GL.GL_ARRAY_BUFFER, self.vertex_data, GL.GL_STATIC_DRAW) # Assign data to selected buffer GL.glBindBuffer(GL.GL_ELEMENT_ARRAY_BUFFER, self.ibo) # Select self.ibo GL.glBufferData(GL.GL_ELEMENT_ARRAY_BUFFER, self.index_data, GL.GL_STATIC_DRAW) # Assign data to selected buffer GL.glBindBuffer(GL.GL_ARRAY_BUFFER, 0) # Deselect buffers
def build_buffer(program, data, data_usage=gl.GL_STATIC_DRAW, buffer_target=gl.GL_ARRAY_BUFFER): # with use_program(program): buffer = gl.glGenBuffers(1) gl.glBindBuffer(buffer_target, buffer) gl.glBufferData(buffer_target, data.nbytes, data, data_usage) gl.glBindBuffer(buffer_target, 0) return buffer
def __init__(self, vertices, indices, draw_method): from . import SHORT_SIZE, FLOAT_SIZE self.draw_method = draw_method self.indices = indices self.vao = GL.glGenVertexArrays(1) GL.glBindVertexArray(self.vao) vertexBufferObject = GL.glGenBuffers(1) GL.glBindBuffer(GL.GL_ARRAY_BUFFER, vertexBufferObject) array_type = (GL.GLfloat*len(vertices)) GL.glBufferData( GL.GL_ARRAY_BUFFER, len(vertices)*FLOAT_SIZE, array_type(*vertices), GL.GL_STATIC_DRAW) GL.glEnableVertexAttribArray(0) GL.glVertexAttribPointer(0, 3, GL.GL_FLOAT, GL.GL_FALSE, 0, None) indexBufferObject = GL.glGenBuffers(1) GL.glBindBuffer(GL.GL_ELEMENT_ARRAY_BUFFER, indexBufferObject) array_type = (GL.GLushort*len(self.indices)) GL.glBufferData( GL.GL_ELEMENT_ARRAY_BUFFER, len(self.indices)*SHORT_SIZE, array_type(*self.indices), GL.GL_STATIC_DRAW) GL.glBindVertexArray(0)
def allocate(self, data, count): GL.glBufferData( self._btype, count, data, self._usage, )
def change_vbo_colors (col_vbo = None, colors = [], program = None): """ Function doc """ GL.glBindBuffer(GL.GL_ARRAY_BUFFER, col_vbo) GL.glBufferData(GL.GL_ARRAY_BUFFER, colors.itemsize*int(len(colors)), colors, GL.GL_STATIC_DRAW) att_colors = GL.glGetAttribLocation(program, 'vert_color') GL.glEnableVertexAttribArray(att_colors) GL.glVertexAttribPointer(att_colors, 3, GL.GL_FLOAT, GL.GL_FALSE, 3*colors.itemsize, ctypes.c_void_p(0))
def initializeGL(self): """ Set OpenGL variables """ self.qglClearColor(QtGui.QColor(250,250,250,255)) #GL.glShadeModel(GL.GL_FLAT) GL.glShadeModel(GL.GL_SMOOTH) GL.glEnable(GL.GL_DEPTH_TEST) GL.glEnable(GL.GL_POINT_SMOOTH ) #GL.glEnable(GL.GL_CULL_FACE) # Creates the pixel buffer object for the background and loads image data into it self.pbo = long(GL.glGenBuffers(1)) GL.glBindBuffer(GL.GL_PIXEL_UNPACK_BUFFER, self.pbo) if self.str: GL.glBufferData(GL.GL_PIXEL_UNPACK_BUFFER, self.str.current(), GL.GL_DYNAMIC_DRAW) # Creates the texture object for the background self.texid = long(GL.glGenTextures(1)) GL.glBindTexture(GL.GL_TEXTURE_2D, self.texid) GL.glTexParameterf(GL.GL_TEXTURE_2D, GL.GL_TEXTURE_MAG_FILTER, GL.GL_NEAREST) GL.glTexParameterf(GL.GL_TEXTURE_2D, GL.GL_TEXTURE_MIN_FILTER, GL.GL_NEAREST) GL.glPixelStorei(GL.GL_UNPACK_ALIGNMENT,1) # Loads image data from the PBO to the texture object if self.str: GL.glTexImage2D(GL.GL_TEXTURE_2D, 0, 3, self.str.width, self.str.height, 0, GL.GL_RGB, GL.GL_UNSIGNED_BYTE, GL.GLvoid) # Unbinds everything GL.glBindTexture(GL.GL_TEXTURE_2D, 0) GL.glBindBuffer(GL.GL_PIXEL_UNPACK_BUFFER, 0)
def initializeGL(self): """ Create the graphic buffers and compile the shaders. """ # Create and bind a new VAO (Vertex Array Object). self.vertex_array_object = gl.glGenVertexArrays(1) gl.glBindVertexArray(self.vertex_array_object) # Upload color values (one for each triangle vertex) in RGB format. colBuf = gl.glGenBuffers(1) gl.glBindBuffer(gl.GL_ARRAY_BUFFER, colBuf) col = np.array([1,0,0,0,1,0,0,0,1], dtype=np.float32) gl.glBufferData(gl.GL_ARRAY_BUFFER, col, gl.GL_STATIC_DRAW) gl.glVertexAttribPointer(0, 3, gl.GL_FLOAT, gl.GL_FALSE, 0, None) gl.glEnableVertexAttribArray(0) # Create and bind GPU buffer for vertex data. self.vertexBuffer = gl.glGenBuffers(1) gl.glBindBuffer(gl.GL_ARRAY_BUFFER, self.vertexBuffer) # Associate the vertex buffer with the "Layout 0" shader variable (look # for "v_N" variable in vertex shader program). gl.glVertexAttribPointer(1, 4, gl.GL_FLOAT, gl.GL_FALSE, 0, None) gl.glEnableVertexAttribArray(1) # Enable depth-sorting. gl.glEnable(gl.GL_DEPTH_TEST) gl.glDepthFunc(gl.GL_LESS) # Background color. gl.glClearColor(0, 0, 0, 0) # Compile- and install shader programs. self.shaders = self.linkShaders('blog4.vs', 'blog4.fs') gl.glUseProgram(self.shaders)
def initialize(self): vertex_shader = shaders.compileShader("""#version 330 in vec3 vPosition; uniform mat4 MVP; void main() { gl_Position = MVP * vec4(vPosition, 1.0); }""", gl.GL_VERTEX_SHADER) fragment_shader = shaders.compileShader("""#version 330 void main() { gl_FragColor = vec4( 0, 1, 1, 1 ); }""", gl.GL_FRAGMENT_SHADER) self._shader = shaders.compileProgram(vertex_shader, fragment_shader) self._position_handle = 0 gl.glBindAttribLocation(self._shader, self._position_handle, b"vPosition") self._mvp_handle = gl.glGetUniformLocation(self._shader, b"MVP") self._vertex_vbo = gl.glGenBuffers(1) gl.glBindBuffer(gl.GL_ARRAY_BUFFER, self._vertex_vbo) gl.glBufferData(gl.GL_ARRAY_BUFFER, len(self._model._vertex_buffer), self._model._vertex_buffer, gl.GL_STATIC_DRAW) gl.glBindBuffer(gl.GL_ARRAY_BUFFER, 0) self._index_vbo = gl.glGenBuffers(1) gl.glBindBuffer(gl.GL_ELEMENT_ARRAY_BUFFER, self._index_vbo) gl.glBufferData(gl.GL_ELEMENT_ARRAY_BUFFER, len(self._model._index_buffer), self._model._index_buffer, gl.GL_STATIC_DRAW) gl.glBindBuffer(gl.GL_ELEMENT_ARRAY_BUFFER, 0)
def setup_buffers(gltf, uri_path): buffers = gltf['buffers'] data_buffers = {} for buffer_name, buffer in buffers.items(): uri = buffer['uri'] if uri.startswith('data:application/octet-stream;base64,'): data_buffers[buffer_name] = base64.b64decode(uri.split(',')[1]) else: filename = os.path.join(uri_path, buffer['uri']) if buffer['type'] == 'arraybuffer': data_buffers[buffer_name] = open(filename, 'rb').read() elif buffer['type'] == 'text': raise Exception('TODO') #data_buffers[buffer_name] = open(filename, 'r').read() _logger.debug('* loaded buffer "%s" (from %s)', buffer_name, filename) for bufferView_name, bufferView in gltf['bufferViews'].items(): buffer_id = gl.glGenBuffers(1) #byteLength = bufferView['byteLength'] byteOffset = bufferView['byteOffset'] gl.glBindBuffer(bufferView['target'], buffer_id) gl.glBufferData(bufferView['target'], bufferView['byteLength'], data_buffers[bufferView['buffer']][byteOffset:], gl.GL_STATIC_DRAW) if gl.glGetError() != gl.GL_NO_ERROR: raise Exception('failed to create buffer "%s"' % bufferView_name) bufferView['id'] = buffer_id gl.glBindBuffer(bufferView['target'], 0) _logger.debug('* created buffer "%s"' % bufferView_name)
def init_gl(self, force=False): if not force and self.buffers is not None: return self.buffers = {} for name, values in self.attributes.items(): values = values.tobytes() vbo = gl.glGenBuffers(1) gl.glBindBuffer(gl.GL_ARRAY_BUFFER, vbo) if name in self.attribute_usage: usage = self.attribute_usage[name] else: usage = gl.GL_STATIC_DRAW gl.glBufferData(gl.GL_ARRAY_BUFFER, len(values), values, usage) if gl.glGetError() != gl.GL_NO_ERROR: raise Exception('failed to init gl buffer') self.buffers[name] = vbo gl.glBindBuffer(gl.GL_ARRAY_BUFFER, 0) if force or (self.index_buffer is None and self.indices is not None): indices = self.indices.tobytes() vao = gl.glGenBuffers(1) gl.glBindBuffer(gl.GL_ELEMENT_ARRAY_BUFFER, vao) gl.glBufferData(gl.GL_ELEMENT_ARRAY_BUFFER, len(indices), indices, gl.GL_STATIC_DRAW) if gl.glGetError() != gl.GL_NO_ERROR: raise Exception('failed to init gl buffer') self.index_buffer = vao gl.glBindBuffer(gl.GL_ELEMENT_ARRAY_BUFFER, 0) _logger.info('%s.init_gl: OK', self.__class__.__name__)
def create_object(shader): # Create a new VAO (Vertex Array Object) and bind it vertex_array_object = GL.glGenVertexArrays(1) GL.glBindVertexArray( vertex_array_object ) # Generate buffers to hold our vertices vertex_buffer = GL.glGenBuffers(1) GL.glBindBuffer(GL.GL_ARRAY_BUFFER, vertex_buffer) # Get the position of the 'position' in parameter of our shader and bind it. position = GL.glGetAttribLocation(shader, 'position') GL.glEnableVertexAttribArray(position) coord = GL.glGetAttribLocation(shader, 'coord') GL.glEnableVertexAttribArray(coord) # Describe the 'position' data layout in the buffer GL.glVertexAttribPointer(position, 2, GL.GL_FLOAT, False, 16, GL.GLvoidp(0)) GL.glVertexAttribPointer(coord, 2, GL.GL_FLOAT, False, 16, GL.GLvoidp(8)) # Send the data over to the buffer GL.glBufferData(GL.GL_ARRAY_BUFFER, 96, vertices, GL.GL_STATIC_DRAW) # Unbind the VAO first (Important) GL.glBindVertexArray(0) # Unbind other stuff GL.glDisableVertexAttribArray(position) GL.glDisableVertexAttribArray(coord) GL.glBindBuffer(GL.GL_ARRAY_BUFFER, 0) return vertex_array_object
def _make_sel_gl_dots(program, vismol_object = None, bckgrnd_color= [1.0,1.0,1.0,1.0]): """ Function doc """ colors = vismol_object.color_indexes dot_sizes = vismol_object.vdw_dot_sizes coords = vismol_object.frames[0] dot_qtty = int(len(coords)/3) bckgrnd_color = [bckgrnd_color[0],bckgrnd_color[1], bckgrnd_color[2],bckgrnd_color[3]]*dot_qtty bckgrnd_color = np.array(bckgrnd_color, dtype=np.float32) indexes = np.array(vismol_object.dot_indexes,dtype=np.uint32) vao = GL.glGenVertexArrays(1) GL.glBindVertexArray(vao) ind_vbo = GL.glGenBuffers(1) GL.glBindBuffer(GL.GL_ELEMENT_ARRAY_BUFFER, ind_vbo) GL.glBufferData(GL.GL_ELEMENT_ARRAY_BUFFER, indexes.itemsize*int(len(indexes)), indexes, GL.GL_DYNAMIC_DRAW) coord_vbo = GL.glGenBuffers(1) GL.glBindBuffer(GL.GL_ARRAY_BUFFER, coord_vbo) GL.glBufferData(GL.GL_ARRAY_BUFFER, coords.itemsize*int(len(coords)), coords, GL.GL_STATIC_DRAW) att_position = GL.glGetAttribLocation(program, 'vert_coord') GL.glEnableVertexAttribArray(att_position) GL.glVertexAttribPointer(att_position, 3, GL.GL_FLOAT, GL.GL_FALSE, 3*coords.itemsize, ctypes.c_void_p(0)) col_vbo = GL.glGenBuffers(1) GL.glBindBuffer(GL.GL_ARRAY_BUFFER, col_vbo) GL.glBufferData(GL.GL_ARRAY_BUFFER, colors.itemsize*int(len(colors)), colors, GL.GL_STATIC_DRAW) att_colors = GL.glGetAttribLocation(program, 'vert_color') GL.glEnableVertexAttribArray(att_colors) GL.glVertexAttribPointer(att_colors, 3, GL.GL_FLOAT, GL.GL_FALSE, 3*colors.itemsize, ctypes.c_void_p(0)) dot_vbo = GL.glGenBuffers(1) GL.glBindBuffer(GL.GL_ARRAY_BUFFER, dot_vbo) GL.glBufferData(GL.GL_ARRAY_BUFFER, dot_sizes.itemsize*len(dot_sizes), dot_sizes, GL.GL_STATIC_DRAW) att_size = GL.glGetAttribLocation(program, 'vert_dot_size') GL.glEnableVertexAttribArray(att_size) GL.glVertexAttribPointer(att_size, 1, GL.GL_FLOAT, GL.GL_FALSE, dot_sizes.itemsize, ctypes.c_void_p(0)) bckgrnd_vbo = GL.glGenBuffers(1) GL.glBindBuffer(GL.GL_ARRAY_BUFFER, bckgrnd_vbo) GL.glBufferData(GL.GL_ARRAY_BUFFER, bckgrnd_color.itemsize*len(bckgrnd_color), bckgrnd_color, GL.GL_STATIC_DRAW) att_bck_color = GL.glGetAttribLocation(program, 'bckgrnd_color') GL.glEnableVertexAttribArray(att_bck_color) GL.glVertexAttribPointer(att_bck_color, 4, GL.GL_FLOAT, GL.GL_FALSE, 4*bckgrnd_color.itemsize, ctypes.c_void_p(0)) GL.glBindVertexArray(0) GL.glDisableVertexAttribArray(att_position) GL.glDisableVertexAttribArray(att_colors) GL.glDisableVertexAttribArray(att_size) GL.glDisableVertexAttribArray(att_bck_color) GL.glBindBuffer(GL.GL_ARRAY_BUFFER, 0) GL.glBindBuffer(GL.GL_ELEMENT_ARRAY_BUFFER, 0) vismol_object.sel_dots_vao = vao vismol_object.sel_dot_buffers = (ind_vbo, coord_vbo, col_vbo) return True
def __init__(self, vertices): #pyglet.graphics.vertex_list((ntiles+1) * 4, ('v3f/static', v)) self.num_vertices = len(vertices) / 3 self.vbo = GL.glGenBuffers(1) GL.glBindBuffer(GL.GL_ARRAY_BUFFER, self.vbo) GL.glBufferData(GL.GL_ARRAY_BUFFER, len(vertices)*4, (c_float*len(vertices))(*vertices), GL.GL_STATIC_DRAW) GL.glBindBuffer(GL.GL_ARRAY_BUFFER, 0)
def paintGL(self): if GL.glCheckFramebufferStatus(GL.GL_FRAMEBUFFER) == 33305: return GL.glClear(GL.GL_COLOR_BUFFER_BIT) if not self.texture: return if not self.shader: self.compileShaders() if not self.vbo: self.vbo = GL.glGenBuffers(1) shaders.glUseProgram(self.shader) GL.glBindBuffer(GL.GL_ARRAY_BUFFER, self.vbo) vertices = numpy.array( [-self.scale + self.cx, -self.scale + self.cy , self.scale + self.cx, -self.scale + self.cy, self.scale + self.cx, self.scale + self.cy, -self.scale + self.cx, self.scale + self.cy, 0,0,1,0,1,1,0,1], dtype = numpy.float32) GL.glBufferData(GL.GL_ARRAY_BUFFER, 64, vertices, GL.GL_STATIC_DRAW) loc = GL.glGetAttribLocation(self.shader, "positionIn") GL.glEnableVertexAttribArray(loc) GL.glVertexAttribPointer(loc, 2, GL.GL_FLOAT, 0, 8, c_void_p(0)) loc = GL.glGetAttribLocation(self.shader, "texIn") GL.glEnableVertexAttribArray(loc) GL.glVertexAttribPointer(loc, 2, GL.GL_FLOAT, 0, 8, c_void_p(32)) def _uniformLoc(name): return GL.glGetUniformLocation(self.shader,name) GL.glUniform1f(_uniformLoc("g"), self.gamma); GL.glUniform1f(_uniformLoc("m"), math.pow(2, self.exposure + 2.47393)) GL.glUniform1f(_uniformLoc("s"), math.pow(2, -3.5 * self.gamma)) GL.glUniform1i(_uniformLoc("hdr_mode"), self.hdr_mode); GL.glUniform1i(_uniformLoc("texture"), 0); GL.glActiveTexture(GL.GL_TEXTURE0); GL.glBindTexture(GL.GL_TEXTURE_2D, self.texture) GL.glDrawArrays(GL.GL_QUADS, 0, 4); GL.glBindTexture(GL.GL_TEXTURE_2D, 0) loc = GL.glGetAttribLocation(self.shader, "positionIn") GL.glDisableVertexAttribArray(loc) loc = GL.glGetAttribLocation(self.shader, "texIn") GL.glDisableVertexAttribArray(loc) GL.glBindBuffer(GL.GL_ARRAY_BUFFER, 0) shaders.glUseProgram(0) if self.rightBtnDown: self.renderPixelInfo()
def main(): global delta_time, last_frame glfw.init() glfw.window_hint(glfw.CONTEXT_VERSION_MAJOR, 3) glfw.window_hint(glfw.CONTEXT_VERSION_MINOR, 3) glfw.window_hint(glfw.OPENGL_PROFILE, glfw.OPENGL_CORE_PROFILE) window = glfw.create_window(width, height, "LearnOpenGL", None, None) if not window: print("Window Creation failed!") glfw.terminate() glfw.make_context_current(window) glfw.set_window_size_callback(window, on_resize) gl.glEnable(gl.GL_DEPTH_TEST) shader = Shader(CURDIR / 'shaders/6.1.coordinate_systems.vs', CURDIR / 'shaders/6.1.coordinate_systems.fs') vertices = [ # positions tex_coords -0.5, -0.5, -0.5, 0.0, 0.0, 0.5, -0.5, -0.5, 1.0, 0.0, 0.5, 0.5, -0.5, 1.0, 1.0, 0.5, 0.5, -0.5, 1.0, 1.0, -0.5, 0.5, -0.5, 0.0, 1.0, -0.5, -0.5, -0.5, 0.0, 0.0, -0.5, -0.5, 0.5, 0.0, 0.0, 0.5, -0.5, 0.5, 1.0, 0.0, 0.5, 0.5, 0.5, 1.0, 1.0, 0.5, 0.5, 0.5, 1.0, 1.0, -0.5, 0.5, 0.5, 0.0, 1.0, -0.5, -0.5, 0.5, 0.0, 0.0, -0.5, 0.5, 0.5, 1.0, 0.0, -0.5, 0.5, -0.5, 1.0, 1.0, -0.5, -0.5, -0.5, 0.0, 1.0, -0.5, -0.5, -0.5, 0.0, 1.0, -0.5, -0.5, 0.5, 0.0, 0.0, -0.5, 0.5, 0.5, 1.0, 0.0, 0.5, 0.5, 0.5, 1.0, 0.0, 0.5, 0.5, -0.5, 1.0, 1.0, 0.5, -0.5, -0.5, 0.0, 1.0, 0.5, -0.5, -0.5, 0.0, 1.0, 0.5, -0.5, 0.5, 0.0, 0.0, 0.5, 0.5, 0.5, 1.0, 0.0, -0.5, -0.5, -0.5, 0.0, 1.0, 0.5, -0.5, -0.5, 1.0, 1.0, 0.5, -0.5, 0.5, 1.0, 0.0, 0.5, -0.5, 0.5, 1.0, 0.0, -0.5, -0.5, 0.5, 0.0, 0.0, -0.5, -0.5, -0.5, 0.0, 1.0, -0.5, 0.5, -0.5, 0.0, 1.0, 0.5, 0.5, -0.5, 1.0, 1.0, 0.5, 0.5, 0.5, 1.0, 0.0, 0.5, 0.5, 0.5, 1.0, 0.0, -0.5, 0.5, 0.5, 0.0, 0.0, -0.5, 0.5, -0.5, 0.0, 1.0 ] vertices = (c_float * len(vertices))(*vertices) cube_positions = [(0.0, 0.0, 0.0), (2.0, 5.0, -15.0), (-1.5, -2.2, -2.5), (-3.8, -2.0, -12.3), (2.4, -0.4, -3.5), (-1.7, 3.0, -7.5), (1.3, -2.0, -2.5), (1.5, 2.0, -2.5), (1.5, 0.2, -1.5), (-1.3, 1.0, -1.5)] vao = gl.glGenVertexArrays(1) gl.glBindVertexArray(vao) vbo = gl.glGenBuffers(1) gl.glBindBuffer(gl.GL_ARRAY_BUFFER, vbo) gl.glBufferData(gl.GL_ARRAY_BUFFER, sizeof(vertices), vertices, gl.GL_STATIC_DRAW) gl.glVertexAttribPointer(0, 3, gl.GL_FLOAT, gl.GL_FALSE, 5 * sizeof(c_float), c_void_p(0)) gl.glEnableVertexAttribArray(0) gl.glVertexAttribPointer(1, 2, gl.GL_FLOAT, gl.GL_FALSE, 5 * sizeof(c_float), c_void_p(3 * sizeof(c_float))) gl.glEnableVertexAttribArray(1) # -- load texture 1 texture1 = gl.glGenTextures(1) gl.glBindTexture(gl.GL_TEXTURE_2D, texture1) # -- texture wrapping gl.glTexParameter(gl.GL_TEXTURE_2D, gl.GL_TEXTURE_WRAP_S, gl.GL_REPEAT) gl.glTexParameter(gl.GL_TEXTURE_2D, gl.GL_TEXTURE_WRAP_T, gl.GL_REPEAT) # -- texture filterting gl.glTexParameter(gl.GL_TEXTURE_2D, gl.GL_TEXTURE_MIN_FILTER, gl.GL_LINEAR) gl.glTexParameter(gl.GL_TEXTURE_2D, gl.GL_TEXTURE_MAG_FILTER, gl.GL_LINEAR) img = Image.open(Tex('container.jpg')).transpose(Image.FLIP_TOP_BOTTOM) gl.glTexImage2D(gl.GL_TEXTURE_2D, 0, gl.GL_RGB, img.width, img.height, 0, gl.GL_RGB, gl.GL_UNSIGNED_BYTE, img.tobytes()) gl.glGenerateMipmap(gl.GL_TEXTURE_2D) # -- load texture 2 texture2 = gl.glGenTextures(1) gl.glBindTexture(gl.GL_TEXTURE_2D, texture2) # -- texture wrapping gl.glTexParameter(gl.GL_TEXTURE_2D, gl.GL_TEXTURE_WRAP_S, gl.GL_REPEAT) gl.glTexParameter(gl.GL_TEXTURE_2D, gl.GL_TEXTURE_WRAP_T, gl.GL_REPEAT) # -- texture filterting gl.glTexParameter(gl.GL_TEXTURE_2D, gl.GL_TEXTURE_MIN_FILTER, gl.GL_LINEAR) gl.glTexParameter(gl.GL_TEXTURE_2D, gl.GL_TEXTURE_MAG_FILTER, gl.GL_LINEAR) img = Image.open(Tex('awesomeface.png')) gl.glTexImage2D(gl.GL_TEXTURE_2D, 0, gl.GL_RGB, img.width, img.height, 0, gl.GL_RGBA, gl.GL_UNSIGNED_BYTE, img.tobytes()) gl.glGenerateMipmap(gl.GL_TEXTURE_2D) shader.use() shader.set_int("texture1", 0) shader.set_int("texture2", 1) projection = Matrix44.perspective_projection(45, width / height, 0.1, 100.0) shader.set_mat4('projection', projection) while not glfw.window_should_close(window): current_frame = glfw.get_time() delta_time = current_frame - last_frame last_frame = current_frame process_input(window) gl.glClearColor(.2, .3, .3, 1.0) gl.glClear(gl.GL_COLOR_BUFFER_BIT | gl.GL_DEPTH_BUFFER_BIT) gl.glActiveTexture(gl.GL_TEXTURE0) gl.glBindTexture(gl.GL_TEXTURE_2D, texture1) gl.glActiveTexture(gl.GL_TEXTURE1) gl.glBindTexture(gl.GL_TEXTURE_2D, texture2) shader.use() view = Matrix44.look_at(camera_pos, camera_pos + camera_front, camera_up) shader.set_mat4('view', view) gl.glBindVertexArray(vao) for idx, position in enumerate(cube_positions): angle = 20.0 * idx rotation = matrix44.create_from_axis_rotation([1.0, 0.3, 0.5], math.radians(angle)) translation = Matrix44.from_translation(position) model = translation * rotation shader.set_mat4('model', model) gl.glDrawArrays(gl.GL_TRIANGLES, 0, 36) glfw.poll_events() glfw.swap_buffers(window) gl.glDeleteVertexArrays(1, id(vao)) gl.glDeleteBuffers(1, id(vbo)) glfw.terminate()
def init(): global program global program2 global VAO_mesh global VBO_mesh global VAO_planes global VBO_planes global VAO_segments global VBO_segments global num_vertices_mesh global num_vertices_planes global num_vertices_segments # Build programs (shaders). program = ut.createShaderProgram(mesh_vs, mesh_fs) program2 = ut.createShaderProgram(segment_vs, segment_fs) # Load mesh. mesh = stlmesh.stlmesh(stl_file) mesh_min = mesh.min_coordinates()[2] mesh_max = mesh.max_coordinates()[2] # Compute slices. P = None srt = False mesh_slicer = slicer.slicer(mesh.triangles,P,delta,srt) mesh_slicer.incremental_slicing() # Create mesh data for GPU. data,num_vertices_mesh = mesh.OpenGLData(view_min, view_max) # Copy mesh data to GPU VAO_mesh = gl.glGenVertexArrays(1) VBO_mesh = gl.glGenBuffers(1) gl.glBindVertexArray(VAO_mesh) gl.glBindBuffer(gl.GL_ARRAY_BUFFER, VBO_mesh) gl.glBufferData(gl.GL_ARRAY_BUFFER, data.nbytes, data, gl.GL_STATIC_DRAW) gl.glVertexAttribPointer(0, 3, gl.GL_FLOAT, gl.GL_FALSE, 6*data.itemsize, None) gl.glEnableVertexAttribArray(0) gl.glVertexAttribPointer(1, 3, gl.GL_FLOAT, gl.GL_FALSE, 6*data.itemsize, c_void_p(3*data.itemsize)) gl.glEnableVertexAttribArray(1) # Unbind gl.glBindBuffer(gl.GL_ARRAY_BUFFER, 0) gl.glBindVertexArray(0) # Create data for planes. data,num_vertices_planes = mesh_slicer.OpenGLPlanesData(mesh_min,mesh_max,view_min,view_max) # Copy planes data to GPU VAO_planes = gl.glGenVertexArrays(1) VBO_planes = gl.glGenBuffers(1) gl.glBindVertexArray(VAO_planes) gl.glBindBuffer(gl.GL_ARRAY_BUFFER, VBO_planes) gl.glBufferData(gl.GL_ARRAY_BUFFER, data.nbytes, data, gl.GL_STATIC_DRAW) gl.glVertexAttribPointer(0, 3, gl.GL_FLOAT, gl.GL_FALSE, 6*data.itemsize, None) gl.glEnableVertexAttribArray(0) gl.glVertexAttribPointer(1, 3, gl.GL_FLOAT, gl.GL_FALSE, 6*data.itemsize, c_void_p(3*data.itemsize)) gl.glEnableVertexAttribArray(1) # Unbind gl.glBindBuffer(gl.GL_ARRAY_BUFFER, 0) gl.glBindVertexArray(0) # Create slices data for GPU. mesh_max = mesh.max_coordinates() mesh_min = mesh.min_coordinates() data,num_vertices_segments = mesh_slicer.OpenGLPolygonsData(mesh_min,mesh_max,view_min,view_max) # Copy segments data to GPU VAO_segments = gl.glGenVertexArrays(1) VBO_segments = gl.glGenBuffers(1) gl.glBindVertexArray(VAO_segments) gl.glBindBuffer(gl.GL_ARRAY_BUFFER, VBO_segments) gl.glBufferData(gl.GL_ARRAY_BUFFER, data.nbytes, data, gl.GL_STATIC_DRAW) gl.glVertexAttribPointer(0, 3, gl.GL_FLOAT, gl.GL_FALSE, 6*data.itemsize, None) gl.glEnableVertexAttribArray(0) gl.glVertexAttribPointer(1, 3, gl.GL_FLOAT, gl.GL_FALSE, 6*data.itemsize, c_void_p(3*data.itemsize)) gl.glEnableVertexAttribArray(1) # Unbind gl.glBindBuffer(gl.GL_ARRAY_BUFFER, 0) gl.glBindVertexArray(0) # Set depth gl.glEnable(gl.GL_DEPTH_TEST) gl.glEnable(gl.GL_BLEND) gl.glBlendFunc(gl.GL_SRC_ALPHA, gl.GL_ONE_MINUS_SRC_ALPHA)
def init_target() -> RenderTarget: # pragma: no cover # Setting up VAO vao = gl.glGenVertexArrays(1) gl.glBindVertexArray(vao) # Quad vertex buffer vbo = gl.glGenBuffers(1) gl.glBindBuffer(gl.GL_ARRAY_BUFFER, vbo) gl.glBufferData(gl.GL_ARRAY_BUFFER, QUAD_VERTS.nbytes, QUAD_VERTS, gl.GL_DYNAMIC_DRAW) gl.glEnableVertexAttribArray(0) gl.glVertexAttribPointer(0, 2, gl.GL_FLOAT, gl.GL_FALSE, 0, None) # Finish setting up VAO gl.glBindVertexArray(0) # Quad index buffer ebo = gl.glGenBuffers(1) gl.glBindBuffer(gl.GL_ELEMENT_ARRAY_BUFFER, ebo) gl.glBufferData(gl.GL_ELEMENT_ARRAY_BUFFER, QUAD_IDX.nbytes, QUAD_IDX, gl.GL_STATIC_DRAW) # Regions data world_ssbo = gl.glGenBuffers(1) # Create shaders vs_src, fs_src = __load_shaders() vs = shaders.compileShader(vs_src, gl.GL_VERTEX_SHADER) fs = shaders.compileShader(fs_src, gl.GL_FRAGMENT_SHADER) program = shaders.compileProgram(vs, fs) # Create target texture render_texture = gl.glGenTextures(1) gl.glBindTexture(gl.GL_TEXTURE_2D, render_texture) gl.glTexImage2D( gl.GL_TEXTURE_2D, 0, # level gl.GL_RGBA, # internalFormat 1, # width 1, # height 0, # border gl.GL_RGBA, # format gl.GL_FLOAT, # type None # data ) gl.glTexParameteri(gl.GL_TEXTURE_2D, gl.GL_TEXTURE_MIN_FILTER, gl.GL_NEAREST) gl.glTexParameteri(gl.GL_TEXTURE_2D, gl.GL_TEXTURE_MAG_FILTER, gl.GL_NEAREST) # Create target framebuffer # Create target framebuffer render_fbo = gl.glGenFramebuffers(1) gl.glBindFramebuffer(gl.GL_FRAMEBUFFER, render_fbo) gl.glFramebufferTexture2D(gl.GL_FRAMEBUFFER, gl.GL_COLOR_ATTACHMENT0, gl.GL_TEXTURE_2D, render_texture, 0) _validate_fbo_complete() gl.glBindFramebuffer(gl.GL_FRAMEBUFFER, 0) return RenderTarget( vao=vao, vbo=vbo, ebo=ebo, world_ssbo=world_ssbo, vertex_shader=vs, fragment_shader=fs, program=program, indices=np.copy(QUAD_IDX), render_fbo=render_fbo, render_texture=render_texture, )
def __init__(self, cubemap_img, alpha=1.0): # set up the shader self.i_tex = gl.glGenTextures(1) self.cubemap_img = cubemap_img i_vert = gl.glCreateShader(gl.GL_VERTEX_SHADER) gl.glShaderSource(i_vert, vert_shader) i_frag = gl.glCreateShader(gl.GL_FRAGMENT_SHADER) gl.glShaderSource(i_frag, frag_shader) self.program = gl.glCreateProgram() gl.glAttachShader(self.program, i_vert) gl.glAttachShader(self.program, i_frag) gl.glCompileShader(i_vert) gl.glCompileShader(i_frag) gl.glLinkProgram(self.program) gl.glValidateProgram(self.program) gl.glUseProgram(self.program) loc = gl.glGetUniformLocation(self.program, "cubemap") gl.glUniform1i(loc, 0) self.i_alpha = gl.glGetUniformLocation(self.program, "alpha") gl.glUniform1i(loc, 0) # set up the geometry i_pos = gl.glGetAttribLocation(self.program, "pos") self.i_vao = gl.glGenVertexArrays(1) i_vbo = gl.glGenBuffers(1) gl.glBindVertexArray(self.i_vao) gl.glBindBuffer(gl.GL_ARRAY_BUFFER, i_vbo) gl.glBufferData( gl.GL_ARRAY_BUFFER, # target vertices.nbytes, # size vertices, # data gl.GL_STATIC_DRAW, # usage ) gl.glEnableVertexAttribArray(i_pos) gl.glVertexAttribPointer( i_pos, # index 3, # size gl.GL_FLOAT, # type gl.GL_FALSE, # normalisation 0, # stride ctypes.c_void_p(0), # pointer ) self.i_proj = gl.glGetUniformLocation(self.program, "projection") self.i_view = gl.glGetUniformLocation(self.program, "view") self.i_rotate = gl.glGetUniformLocation(self.program, "rotate") # set the rotation matrix to null self.set_rotate(rotate=np.eye(4).T) gl.glUseProgram(0) gl.glEnable(gl.GL_TEXTURE_CUBE_MAP_SEAMLESS) for param in ("MIN", "MAG"): gl.glTexParameteri( gl.GL_TEXTURE_CUBE_MAP, getattr(gl, "GL_TEXTURE_" + param + "_FILTER"), gl.GL_LINEAR, ) for param in "STR": gl.glTexParameteri( gl.GL_TEXTURE_CUBE_MAP, getattr(gl, "GL_TEXTURE_WRAP_" + param), gl.GL_CLAMP_TO_EDGE, ) gl.glDepthFunc(gl.GL_LEQUAL) self.alpha = alpha # for some reason, the output is L-R flipped # apply this adjustment to the view matrix to fix it self.flip_mat = np.eye(4) self.flip_mat[0, 0] = -1 self.flip_mat = self.flip_mat.T
def initialize(): global shaderProgram global VAO global VBO vertexShader = shaders.compileShader( """ #version 330 layout (location=0) in vec4 position; layout (location=1) in vec4 colour; smooth out vec4 theColour; void main() { gl_Position = position; theColour = colour; } """, GL.GL_VERTEX_SHADER) fragmentShader = shaders.compileShader( """ #version 330 smooth in vec4 theColour; out vec4 outputColour; void main() { outputColour = theColour; } """, GL.GL_FRAGMENT_SHADER) shaderProgram = shaders.compileProgram(vertexShader, fragmentShader) vertexData = numpy.array( [ # Vertex Positions 0.0, 0.5, 0.0, 1.0, 0.5, -0.366, 0.0, 1.0, -0.5, -0.366, 0.0, 1.0, # Vertex Colours 1.0, 0.0, 0.0, 1.0, 0.0, 1.0, 0.0, 1.0, 0.0, 0.0, 1.0, 1.0, ], dtype=numpy.float32) # Core OpenGL requires that at least one OpenGL vertex array be bound VAO = GL.glGenVertexArrays(1) GL.glBindVertexArray(VAO) # Need VBO for triangle vertices and colours VBO = GL.glGenBuffers(1) GL.glBindBuffer(GL.GL_ARRAY_BUFFER, VBO) GL.glBufferData(GL.GL_ARRAY_BUFFER, vertexData.nbytes, vertexData, GL.GL_STATIC_DRAW) # enable array and set up data GL.glEnableVertexAttribArray(0) GL.glEnableVertexAttribArray(1) GL.glVertexAttribPointer(0, 4, GL.GL_FLOAT, GL.GL_FALSE, 0, None) # the last parameter is a pointer GL.glVertexAttribPointer(1, 4, GL.GL_FLOAT, GL.GL_FALSE, 0, ctypes.c_void_p(48)) GL.glBindBuffer(GL.GL_ARRAY_BUFFER, 0) GL.glBindVertexArray(0)
def initialize(self): vertices = np.array( [ 0.5, 0.5, 0.0, 1.0, 0.0, 0.0, 0.55, 0.55, # top right 0.5, -0.5, 0.0, 0.0, 1.0, 0.0, 0.55, 0.45, # bottom right -0.5, -0.5, 0.0, 0.0, 0.0, 1.0, 0.45, 0.45, # bottom left -0.5, 0.5, 0.0, 1.0, 1.0, 0.0, 0.45, 0.55 # top left ], dtype=np.float32) indices = np.array([0, 1, 3, 1, 2, 3], dtype=np.uint32) self._vao = GL.glGenVertexArrays(1) GL.glBindVertexArray(self._vao) vbo = GL.glGenBuffers(1) GL.glBindBuffer(GL.GL_ARRAY_BUFFER, vbo) GL.glBufferData(GL.GL_ARRAY_BUFFER, vertices, GL.GL_STATIC_DRAW) float_size = ctypes.sizeof(ctypes.c_float) GL.glVertexAttribPointer(0, 3, GL.GL_FLOAT, GL.GL_FALSE, 8 * float_size, ctypes.c_void_p(0)) GL.glEnableVertexAttribArray(0) GL.glVertexAttribPointer(1, 3, GL.GL_FLOAT, GL.GL_FALSE, 8 * float_size, ctypes.c_void_p(3 * float_size)) GL.glEnableVertexAttribArray(1) GL.glVertexAttribPointer(2, 2, GL.GL_FLOAT, GL.GL_FALSE, 8 * float_size, ctypes.c_void_p(6 * float_size)) GL.glEnableVertexAttribArray(2) ebo = GL.glGenBuffers(1) GL.glBindBuffer(GL.GL_ELEMENT_ARRAY_BUFFER, ebo) GL.glBufferData(GL.GL_ELEMENT_ARRAY_BUFFER, indices, GL.GL_STATIC_DRAW) GL.glBindVertexArray(0) self._texture = Texture2D("awesomeface.png", flip_y=True, wrap_s=GL.GL_REPEAT, wrap_t=GL.GL_REPEAT, min_filter=GL.GL_NEAREST, mag_filter=GL.GL_NEAREST) vertex_shader = Shader(GL.GL_VERTEX_SHADER, "shaders_src/textures_vertex.glsl") fragment_shader = Shader(GL.GL_FRAGMENT_SHADER, "shaders_src/textures_frag.glsl") self._shader_program = ShaderProgram(vertex_shader, fragment_shader) vertex_shader.delete() fragment_shader.delete()
def data(self, data_size, data): self.bind() GL.glBufferData(self.target, data_size, data, self.usage)
def tiny_glut(args): global vertex_code, fragment_code scale = 0.01 def display(): CAMERA.render() gl.glClear(gl.GL_COLOR_BUFFER_BIT) nonlocal scale scale_location = gl.glGetUniformLocation(program, "gScale") assert scale_location != 0xffffffff world_location = gl.glGetUniformLocation(program, "gWorld") assert world_location != 0xffffffff scale += 0.01 pipeline = Pipeline( rotation=[0.0, 30 * scale, 0.0], # scaling=[math.sin(scale)] * 3, translation=[0, 0, 6], projection=ProjParams(WINDOW_WIDTH, WINDOW_HEIGHT, 1.0, 100.0, 60.0)) pipeline.set_camera(CAMERA) gl.glUniformMatrix4fv(world_location, 1, gl.GL_TRUE, pipeline.get_wvp()) gl.glDrawElements(gl.GL_TRIANGLES, 18, gl.GL_UNSIGNED_INT, ctypes.c_void_p(0)) glut.glutSwapBuffers() # glut.glutPostRedisplay() def mouse(x, y): CAMERA.mouse(x, y) def keyboard(key, x, y): if key == glut.GLUT_KEY_F1: sys.exit(0) elif key == glut.GLUT_KEY_HOME: CAMERA.setup() else: CAMERA.keyboard(key) glut.glutInit(args) glut.glutInitDisplayMode(glut.GLUT_DOUBLE | glut.GLUT_RGBA | glut.GLUT_3_2_CORE_PROFILE) glut.glutInitWindowSize(WINDOW_WIDTH, WINDOW_HEIGHT) glut.glutInitWindowPosition(400, 100) # glut.glutCreateWindow("Camera Tutorial") glut.glutGameModeString("1920x1200@32") glut.glutEnterGameMode() # callbacks initialization glut.glutDisplayFunc(display) glut.glutIdleFunc(display) # glut.glutKeyboardFunc(keyboard) glut.glutPassiveMotionFunc(mouse) glut.glutSpecialFunc(keyboard) gl.glEnable(gl.GL_DEPTH_TEST) gl.glDepthFunc(gl.GL_LESS) gl.glClearColor(0, 0, 0, 0) vertices = np.array([-1, -1, 0, 0, -1, -1, 1, -1, 0, 0, -1, 1, 0, 1, 0], dtype=np.float32) indexes = np.array([0, 1, 2, 1, 2, 3, 0, 1, 4, 1, 2, 4, 2, 3, 4, 3, 0, 4], dtype=np.uint32) vertex_shader = gl.glCreateShader(gl.GL_VERTEX_SHADER) gl.glShaderSource(vertex_shader, vertex_code) gl.glCompileShader(vertex_shader) if not gl.glGetShaderiv(vertex_shader, gl.GL_COMPILE_STATUS): info = gl.glGetShaderInfoLog(vertex_shader) print("vertex shader error occurred") print(bytes.decode(info)) return fragment_shader = gl.glCreateShader(gl.GL_FRAGMENT_SHADER) gl.glShaderSource(fragment_shader, fragment_code) gl.glCompileShader(fragment_shader) if not gl.glGetShaderiv(fragment_shader, gl.GL_COMPILE_STATUS): info = gl.glGetShaderInfoLog(fragment_shader) print("fragment shader error occurred") print(bytes.decode(info)) return program = gl.glCreateProgram() gl.glAttachShader(program, vertex_shader) gl.glAttachShader(program, fragment_shader) gl.glLinkProgram(program) gl.glUseProgram(program) vao = gl.glGenVertexArrays(1) gl.glBindVertexArray(vao) vbo = gl.glGenBuffers(1) gl.glBindBuffer(gl.GL_ARRAY_BUFFER, vbo) gl.glBufferData(gl.GL_ARRAY_BUFFER, vertices.nbytes, vertices, gl.GL_STATIC_DRAW) gl.glEnableVertexAttribArray(0) gl.glVertexAttribPointer(0, 3, gl.GL_FLOAT, gl.GL_FALSE, 0, ctypes.c_void_p(0)) ibo = gl.glGenBuffers(1) gl.glBindBuffer(gl.GL_ELEMENT_ARRAY_BUFFER, ibo) gl.glBufferData(gl.GL_ELEMENT_ARRAY_BUFFER, indexes.nbytes, indexes, gl.GL_STATIC_DRAW) glut.glutMainLoop()
def main(): # glfw: initialize and configure glfw.init() glfw.window_hint(glfw.CONTEXT_VERSION_MAJOR, 3) glfw.window_hint(glfw.CONTEXT_VERSION_MINOR, 3) glfw.window_hint(glfw.OPENGL_PROFILE, glfw.OPENGL_CORE_PROFILE) # for Apple devices uncomment the following line # glfw.window_hint(glfw.OPENGL_FORWARD_COMPAT, gl.GL_TRUE) # glfw: window creation window = glfw.create_window(SCR_WIDTH, SCR_HEIGHT, "Learn OpenGL", None, None) if window is None: glfw.terminate() raise Exception("Failed to create GLFW window") glfw.make_context_current(window) glfw.set_framebuffer_size_callback(window, framebuffer_size_callback) # build and compile our shader program # vertex shader vertexShader = gl.glCreateShader(gl.GL_VERTEX_SHADER) gl.glShaderSource( vertexShader, vertexShaderSource) # INFO: Changed method head in PyOpenGL gl.glCompileShader(vertexShader) # check for shader compile errors success = gl.glGetShaderiv(vertexShader, gl.GL_COMPILE_STATUS) if not success: info_log = gl.glGetShaderInfoLog(vertexShader, 512, None) raise Exception("ERROR::SHADER::VERTEX::COMPILATION_FAILED\n%s" % info_log) # fragment shader fragmentShader = gl.glCreateShader(gl.GL_FRAGMENT_SHADER) gl.glShaderSource(fragmentShader, fragmentShaderSource) # Changed! gl.glCompileShader(fragmentShader) # check for shader compile errors success = gl.glGetShaderiv(fragmentShader, gl.GL_COMPILE_STATUS) if not success: info_log = gl.glGetShaderInfoLog(fragmentShader, 512, None) raise Exception("ERROR::SHADER::FRAGMENT::COMPILATION_FAILED\n%s" % info_log) # link shaders shaderProgram = gl.glCreateProgram() gl.glAttachShader(shaderProgram, vertexShader) gl.glAttachShader(shaderProgram, fragmentShader) gl.glLinkProgram(shaderProgram) # check for linking errors success = gl.glGetProgramiv(shaderProgram, gl.GL_LINK_STATUS) if not success: info_log = gl.glGetProgramInfoLog(shaderProgram, 512, None) raise Exception("ERROR::SHADER::PROGRAM::LINKING_FAILED\n%s" % info_log) gl.glDeleteShader(vertexShader) gl.glDeleteShader(fragmentShader) # set up vertex data (and buffer(s)) and configure vertex attributes vertices = np.array( [ 0.5, 0.5, 0.0, # left 0.5, -0.5, 0.0, # right -0.5, -0.5, 0.0, # top -0.5, 0.5, 0.0 ], dtype=np.float32) indices = np.array( [ # note that we start from 0! 0, 1, 3, # first triangle 1, 2, 3 # second triangle ], dtype=np.int32 ) # INFO: Stored as np.array with float32 for compatibility VAO = gl.glGenVertexArrays(1) VBO = gl.glGenBuffers(1) EBO = gl.glGenBuffers(1) # bind the Vertex Array Object first, then bind and set vertex buffer(s), and then configure vertex attributes(s). gl.glBindVertexArray(VAO) # store vertices in buffer gl.glBindBuffer(gl.GL_ARRAY_BUFFER, VBO) gl.glBufferData(gl.GL_ARRAY_BUFFER, vertices.nbytes, vertices, gl.GL_STATIC_DRAW) # INFO: use np.array with nsize # store indices in buffer gl.glBindBuffer(gl.GL_ELEMENT_ARRAY_BUFFER, EBO) gl.glBufferData(gl.GL_ELEMENT_ARRAY_BUFFER, indices.nbytes, indices, gl.GL_STATIC_DRAW) # ToDo fix size of float gl.glVertexAttribPointer( 0, 3, gl.GL_FLOAT, 3 * 4, 0, c_void_p(0)) # INFO: replaced (gl.void*)0 with c_void_p gl.glEnableVertexAttribArray(0) # note that this is allowed, the call to glVertexAttribPointer registered VBO as the vertex attribute's bound vertex buffer object so afterwards we can safely unbind gl.glBindBuffer(gl.GL_ARRAY_BUFFER, 0) # You can unbind the VAO afterwards so other VAO calls won't accidentally modify this VAO, but this rarely happens. Modifying other # VAOs requires a call to glBindVertexArray anyways so we generally don't unbind VAOs (nor VBOs) when it's not directly necessary. gl.glBindVertexArray(0) gl.glPolygonMode(gl.GL_FRONT_AND_BACK, gl.GL_LINE) # for activating wireframe mode # main event loop while not glfw.window_should_close(window): # input process_input(window) # render gl.glClearColor(0.2, 0.3, 0.3, 1.0) gl.glClear(gl.GL_COLOR_BUFFER_BIT) # draw our first triangle gl.glUseProgram(shaderProgram) gl.glBindVertexArray(VAO) gl.glDrawElements(gl.GL_TRIANGLES, 6, gl.GL_UNSIGNED_INT, None) # gl.glBindVertexArray(0) # no need to unbind it every time # glfw: swap buffers and poll IO events (keys pressed/released, mouse moved etc.) glfw.swap_buffers(window) glfw.poll_events() # optional: de-allocate all resources once they've outlived their purpose: gl.glDeleteVertexArrays(1, VAO) gl.glDeleteBuffers(1, VBO) gl.glDeleteBuffers(1, EBO) gl.glDeleteProgram(shaderProgram) # glfw: terminate, clearing all previously allocated GLFW resources. glfw.terminate() return 0
def __init__(self, data): self._vbo = gl.GLuint() gl.glGenBuffers(1, self._vbo) self.bind() gl.glBufferData(self._buffer_type, data, gl.GL_STATIC_DRAW)
def init_gl_modern(display_size): """ Initialise open GL in the 'modern' open GL style for open GL versions greater than 3.1. :param display_size: Size of the window/viewport. """ # Create shaders # -------------------------------------- vertex_code = """ uniform mat4 model; uniform mat4 view; uniform mat4 projection; uniform vec4 colour_mul; uniform vec4 colour_add; attribute vec4 vertex_colour; // vertex colour in attribute vec3 vertex_position; varying vec4 vertex_shader_out; // vertex colour out void main() { vertex_shader_out = (colour_mul * vertex_colour) + colour_add; gl_Position = projection * view * model * vec4(vertex_position, 1.0); } """ fragment_code = """ varying vec4 vertex_shader_out; // vertex colour from vertex shader void main() { gl_FragColor = vertex_shader_out; } """ program = GL.glCreateProgram() vertex = GL.glCreateShader(GL.GL_VERTEX_SHADER) fragment = GL.glCreateShader(GL.GL_FRAGMENT_SHADER) GL.glShaderSource(vertex, vertex_code) GL.glCompileShader(vertex) GL.glAttachShader(program, vertex) GL.glShaderSource(fragment, fragment_code) GL.glCompileShader(fragment) GL.glAttachShader(program, fragment) GL.glLinkProgram(program) GL.glDetachShader(program, vertex) GL.glDetachShader(program, fragment) GL.glUseProgram(program) # Create vertex buffers and shader constants # ------------------------------------------ # Cube Data vertices = zeros(8, [("vertex_position", float32, 3), ("vertex_colour", float32, 4)]) vertices["vertex_position"] = [ [1, 1, 1], [-1, 1, 1], [-1, -1, 1], [1, -1, 1], [1, -1, -1], [1, 1, -1], [-1, 1, -1], [-1, -1, -1], ] vertices["vertex_colour"] = [ [0, 1, 1, 1], [0, 0, 1, 1], [0, 0, 0, 1], [0, 1, 0, 1], [1, 1, 0, 1], [1, 1, 1, 1], [1, 0, 1, 1], [1, 0, 0, 1], ] filled_cube_indices = array( [ 0, 1, 2, 0, 2, 3, 0, 3, 4, 0, 4, 5, 0, 5, 6, 0, 6, 1, 1, 6, 7, 1, 7, 2, 7, 4, 3, 7, 3, 2, 4, 7, 6, 4, 6, 5, ], dtype=uint32, ) outline_cube_indices = array( [ 0, 1, 1, 2, 2, 3, 3, 0, 4, 7, 7, 6, 6, 5, 5, 4, 0, 5, 1, 6, 2, 7, 3, 4 ], dtype=uint32, ) shader_data = {"buffer": {}, "constants": {}} GL.glBindVertexArray(GL.glGenVertexArrays(1)) # Have to do this first shader_data["buffer"]["vertices"] = GL.glGenBuffers(1) GL.glBindBuffer(GL.GL_ARRAY_BUFFER, shader_data["buffer"]["vertices"]) GL.glBufferData(GL.GL_ARRAY_BUFFER, vertices.nbytes, vertices, GL.GL_DYNAMIC_DRAW) stride = vertices.strides[0] offset = ctypes.c_void_p(0) loc = GL.glGetAttribLocation(program, "vertex_position") GL.glEnableVertexAttribArray(loc) GL.glVertexAttribPointer(loc, 3, GL.GL_FLOAT, False, stride, offset) offset = ctypes.c_void_p(vertices.dtype["vertex_position"].itemsize) loc = GL.glGetAttribLocation(program, "vertex_colour") GL.glEnableVertexAttribArray(loc) GL.glVertexAttribPointer(loc, 4, GL.GL_FLOAT, False, stride, offset) shader_data["buffer"]["filled"] = GL.glGenBuffers(1) GL.glBindBuffer(GL.GL_ELEMENT_ARRAY_BUFFER, shader_data["buffer"]["filled"]) GL.glBufferData( GL.GL_ELEMENT_ARRAY_BUFFER, filled_cube_indices.nbytes, filled_cube_indices, GL.GL_STATIC_DRAW, ) shader_data["buffer"]["outline"] = GL.glGenBuffers(1) GL.glBindBuffer(GL.GL_ELEMENT_ARRAY_BUFFER, shader_data["buffer"]["outline"]) GL.glBufferData( GL.GL_ELEMENT_ARRAY_BUFFER, outline_cube_indices.nbytes, outline_cube_indices, GL.GL_STATIC_DRAW, ) shader_data["constants"]["model"] = GL.glGetUniformLocation( program, "model") GL.glUniformMatrix4fv(shader_data["constants"]["model"], 1, False, eye(4)) shader_data["constants"]["view"] = GL.glGetUniformLocation(program, "view") view = translate(eye(4), z=-6) GL.glUniformMatrix4fv(shader_data["constants"]["view"], 1, False, view) shader_data["constants"]["projection"] = GL.glGetUniformLocation( program, "projection") GL.glUniformMatrix4fv(shader_data["constants"]["projection"], 1, False, eye(4)) # This colour is multiplied with the base vertex colour in producing # the final output shader_data["constants"]["colour_mul"] = GL.glGetUniformLocation( program, "colour_mul") GL.glUniform4f(shader_data["constants"]["colour_mul"], 1, 1, 1, 1) # This colour is added on to the base vertex colour in producing # the final output shader_data["constants"]["colour_add"] = GL.glGetUniformLocation( program, "colour_add") GL.glUniform4f(shader_data["constants"]["colour_add"], 0, 0, 0, 0) # Set GL drawing data # ------------------- GL.glClearColor(0, 0, 0, 0) GL.glPolygonOffset(1, 1) GL.glEnable(GL.GL_LINE_SMOOTH) GL.glBlendFunc(GL.GL_SRC_ALPHA, GL.GL_ONE_MINUS_SRC_ALPHA) GL.glDepthFunc(GL.GL_LESS) GL.glHint(GL.GL_LINE_SMOOTH_HINT, GL.GL_NICEST) GL.glLineWidth(1.0) projection = perspective(45.0, display_size[0] / float(display_size[1]), 2.0, 100.0) GL.glUniformMatrix4fv(shader_data["constants"]["projection"], 1, False, projection) return shader_data, filled_cube_indices, outline_cube_indices
def main(): glfw.init() glfw.window_hint(glfw.CONTEXT_VERSION_MAJOR, 3) glfw.window_hint(glfw.CONTEXT_VERSION_MINOR, 3) glfw.window_hint(glfw.OPENGL_PROFILE, glfw.OPENGL_CORE_PROFILE) window = glfw.create_window(SCR_WIDTH, SCR_HEIGHT, "LearnOpenGL", None, None) if window == 0: print("Failed to create GLFW window") glfw.terminate() return -1 glfw.make_context_current(window) glfw.set_framebuffer_size_callback(window, frame_size_callback) vertexShader = gl.glCreateShader(gl.GL_VERTEX_SHADER) gl.glShaderSource(vertexShader, vertexShaderSource) gl.glCompileShader(vertexShader) success = gl.glGetShaderiv(vertexShader, gl.GL_COMPILE_STATUS) if not success: infoLog = gl.glGetShaderInfoLog(vertexShader) print("ERROR::SHADER::VERTEX::COMPILATION_FAILED\n", infoLog) fragmentShader = gl.glCreateShader(gl.GL_FRAGMENT_SHADER) gl.glShaderSource(fragmentShader, fragmentShaderSource) gl.glCompileShader(fragmentShader) success = gl.glGetShaderiv(fragmentShader, gl.GL_COMPILE_STATUS) if not success: infoLog = gl.glGetShaderInfoLog(fragmentShader) print("ERROR::SHADER::FRAGMENT::COMPILATION_FAILED\n", infoLog) shaderProgram = gl.glCreateProgram() gl.glAttachShader(shaderProgram, vertexShader) gl.glAttachShader(shaderProgram, fragmentShader) gl.glLinkProgram(shaderProgram) success = gl.glGetProgramiv(shaderProgram, gl.GL_LINK_STATUS) if not success: infoLog = gl.glGetProgramInfoLog(shaderProgram) print("ERROR::SHADER::PROGRAM::LINKING_FAILED\n", infoLog) gl.glDeleteShader(vertexShader) gl.glDeleteShader(fragmentShader) vertices = np.array( [ -0.5, -0.5, 0, # left 0.5, -0.5, 0, # right 0, 0.5, 0 # top ], dtype=np.float32) VAO = gl.glGenVertexArrays(1) VBO = gl.glGenBuffers(1) gl.glBindVertexArray(VAO) gl.glBindBuffer(gl.GL_ARRAY_BUFFER, VBO) gl.glBufferData(gl.GL_ARRAY_BUFFER, sys.getsizeof(vertices), vertices, gl.GL_STATIC_DRAW) gl.glVertexAttribPointer(0, 3, gl.GL_FLOAT, gl.GL_FALSE, 12, None) gl.glEnableVertexAttribArray(0) gl.glBindBuffer(gl.GL_ARRAY_BUFFER, 0) gl.glBindVertexArray(0) while not glfw.window_should_close(window): processInput(window) gl.glClearColor(0.2, 0.3, 0.3, 1.0) gl.glClear(gl.GL_COLOR_BUFFER_BIT) gl.glUseProgram(shaderProgram) gl.glBindVertexArray(VAO) gl.glDrawArrays(gl.GL_TRIANGLES, 0, 3) glfw.swap_buffers(window) glfw.poll_events() # gl.glDeleteVertexArrays(1, VAO) 这里有点问题。暂时不知道怎么解决 # gl.glDeleteBuffers(1, VBO) glfw.terminate() return 0
def main(): glfw.init() glfw.window_hint(glfw.CONTEXT_VERSION_MAJOR, 3) glfw.window_hint(glfw.CONTEXT_VERSION_MINOR, 3) glfw.window_hint(glfw.OPENGL_PROFILE, glfw.OPENGL_CORE_PROFILE) window = glfw.create_window(800, 600, "LearnOpenGL", None, None) if not window: print("Window Creation failed!") glfw.terminate() glfw.make_context_current(window) glfw.set_window_size_callback(window, on_resize) shader = Shader(CURDIR / 'shaders/5.1.transform.vs', CURDIR / 'shaders/5.1.transform.fs') vertices = [ # positions tex_coords 0.5, 0.5, 0.0, 1.0, 1.0, # top right 0.5, -0.5, 0.0, 1.0, 0.0, # bottom right -0.5, -0.5, 0.0, 0.0, 0.0, # bottom left -0.5, 0.5, 0.0, 0.0, 1.0, # top left ] vertices = (c_float * len(vertices))(*vertices) indices = [ 0, 1, 3, 1, 2, 3 ] indices = (c_uint * len(indices))(*indices) vao = gl.glGenVertexArrays(1) gl.glBindVertexArray(vao) vbo = gl.glGenBuffers(1) gl.glBindBuffer(gl.GL_ARRAY_BUFFER, vbo) gl.glBufferData(gl.GL_ARRAY_BUFFER, sizeof(vertices), vertices, gl.GL_STATIC_DRAW) ebo = gl.glGenBuffers(1) gl.glBindBuffer(gl.GL_ELEMENT_ARRAY_BUFFER, ebo) gl.glBufferData(gl.GL_ELEMENT_ARRAY_BUFFER, sizeof(indices), indices, gl.GL_STATIC_DRAW) gl.glVertexAttribPointer(0, 3, gl.GL_FLOAT, gl.GL_FALSE, 5 * sizeof(c_float), c_void_p(0)) gl.glEnableVertexAttribArray(0) gl.glVertexAttribPointer(1, 2, gl.GL_FLOAT, gl.GL_FALSE, 5 * sizeof(c_float), c_void_p(3 * sizeof(c_float))) gl.glEnableVertexAttribArray(1) # -- load texture 1 texture1 = gl.glGenTextures(1) gl.glBindTexture(gl.GL_TEXTURE_2D, texture1) # -- texture wrapping gl.glTexParameter(gl.GL_TEXTURE_2D, gl.GL_TEXTURE_WRAP_S, gl.GL_REPEAT) gl.glTexParameter(gl.GL_TEXTURE_2D, gl.GL_TEXTURE_WRAP_T, gl.GL_REPEAT) # -- texture filterting gl.glTexParameter(gl.GL_TEXTURE_2D, gl.GL_TEXTURE_MIN_FILTER, gl.GL_LINEAR) gl.glTexParameter(gl.GL_TEXTURE_2D, gl.GL_TEXTURE_MAG_FILTER, gl.GL_LINEAR) img = Image.open(Tex('container.jpg')).transpose(Image.FLIP_TOP_BOTTOM) gl.glTexImage2D(gl.GL_TEXTURE_2D, 0, gl.GL_RGB, img.width, img.height, 0, gl.GL_RGB, gl.GL_UNSIGNED_BYTE, img.tobytes()) gl.glGenerateMipmap(gl.GL_TEXTURE_2D) # -- load texture 2 texture2 = gl.glGenTextures(1) gl.glBindTexture(gl.GL_TEXTURE_2D, texture2) # -- texture wrapping gl.glTexParameter(gl.GL_TEXTURE_2D, gl.GL_TEXTURE_WRAP_S, gl.GL_REPEAT) gl.glTexParameter(gl.GL_TEXTURE_2D, gl.GL_TEXTURE_WRAP_T, gl.GL_REPEAT) # -- texture filterting gl.glTexParameter(gl.GL_TEXTURE_2D, gl.GL_TEXTURE_MIN_FILTER, gl.GL_LINEAR) gl.glTexParameter(gl.GL_TEXTURE_2D, gl.GL_TEXTURE_MAG_FILTER, gl.GL_LINEAR) img = Image.open(Tex('awesomeface.png')).transpose(Image.FLIP_TOP_BOTTOM) gl.glTexImage2D(gl.GL_TEXTURE_2D, 0, gl.GL_RGB, img.width, img.height, 0, gl.GL_RGBA, gl.GL_UNSIGNED_BYTE, img.tobytes()) gl.glGenerateMipmap(gl.GL_TEXTURE_2D) shader.use() shader.set_int("texture1", 0) shader.set_int("texture2", 1) while not glfw.window_should_close(window): process_input(window) gl.glClearColor(.2, .3, .3, 1.0) gl.glClear(gl.GL_COLOR_BUFFER_BIT) gl.glActiveTexture(gl.GL_TEXTURE0) gl.glBindTexture(gl.GL_TEXTURE_2D, texture1) gl.glActiveTexture(gl.GL_TEXTURE1) gl.glBindTexture(gl.GL_TEXTURE_2D, texture2) translation = Matrix44.from_translation([0.5, -0.5, 0.0]) rotation = Matrix44.from_z_rotation(glfw.get_time()) transform = translation * rotation shader.use() shader.set_mat4('transform', transform) gl.glBindVertexArray(vao) gl.glDrawElements(gl.GL_TRIANGLES, 6, gl.GL_UNSIGNED_INT, c_void_p(0)) # -- second container translation = Matrix44.from_translation([-0.5, 0.5, 0.0]) scale = Matrix44.from_scale([math.sin(glfw.get_time())]*3) transform = translation * scale shader.set_mat4('transform', transform) gl.glDrawElements(gl.GL_TRIANGLES, 6, gl.GL_UNSIGNED_INT, c_void_p(0)) glfw.poll_events() glfw.swap_buffers(window) gl.glDeleteVertexArrays(1, id(vao)) gl.glDeleteBuffers(1, id(vbo)) gl.glDeleteBuffers(1, id(ebo)) glfw.terminate()
def initializeGL(self): log.info("OpenGL Vendor: {}".format(GL.glGetString(GL.GL_VENDOR))) log.info("OpenGL Renderer: {}".format(GL.glGetString(GL.GL_RENDERER))) log.info("OpenGL Version: {}".format(GL.glGetString(GL.GL_VERSION))) for drawable in self.drawables: drawable.initialise_gl() return self.texture = GL.glGenTextures(1) self.shader_program.addShaderFromSourceCode(QOpenGLShader.Vertex, VERTEX) self.shader_program.addShaderFromSourceCode(QOpenGLShader.Fragment, FRAGMENT) if not self.shader_program.link(): raise Exception("Could not link shaders - {}".format( self.shader_program.log())) LOC = 1.0 vertexData = np.array( [ # X, Y, Z U, V -LOC, LOC, 0.0, 0.0, 1.0, LOC, LOC, 0.0, 1.0, 1.0, LOC, -LOC, 0.0, 1.0, 0.0, LOC, -LOC, 0.0, 1.0, 0.0, -LOC, -LOC, 0.0, 0.0, 0.0, -LOC, LOC, 0.0, 0.0, 1.0, ], dtype=np.float32) self.VAO = GL.glGenVertexArrays(1) GL.glBindVertexArray(self.VAO) VBO = GL.glGenBuffers(1) GL.glBindBuffer(GL.GL_ARRAY_BUFFER, VBO) GL.glBufferData(GL.GL_ARRAY_BUFFER, vertexData.nbytes, vertexData, GL.GL_STATIC_DRAW) vertex_position = self.shader_program.attributeLocation( "vertexPosition") self.homography_matrix_uniform = self.shader_program.uniformLocation( "homography_matrix") self.intensity_mask_uniform = self.shader_program.uniformLocation( "intensity_mask") self.inverted_uniform = self.shader_program.uniformLocation("inverted") self.projection_matrix_uniform = self.shader_program.uniformLocation( "projection_matrix") self.view_matrix_uniform = self.shader_program.uniformLocation( "view_matrix") self.centre_x_uniform = self.shader_program.uniformLocation("centre_x") self.centre_y_uniform = self.shader_program.uniformLocation("centre_y") self.height_uniform = self.shader_program.uniformLocation("height") self.shape_uniform = self.shader_program.uniformLocation("shape") self.width_x_uniform = self.shader_program.uniformLocation("width_x") self.width_y_uniform = self.shader_program.uniformLocation("width_y") self.rotation_uniform = self.shader_program.uniformLocation("rotation") GL.glEnableVertexAttribArray(0) GL.glEnableVertexAttribArray(1) GL.glVertexAttribPointer(vertex_position, 3, GL.GL_FLOAT, GL.GL_FALSE, 20, None) GL.glVertexAttribPointer(texture_coords, 2, GL.GL_FLOAT, GL.GL_TRUE, 20, ctypes.c_void_p(12)) self.texture_sampler = self.shader_program.uniformLocation( "textureSampler") GL.glBindBuffer(GL.GL_ARRAY_BUFFER, 0) GL.glBindVertexArray(0) self.crosshair.initialise_gl() self.gl_initialised = True
gl.glDetachShader(program, fragment) # Make program the default program gl.glUseProgram(program) # Build buffer # -------------------------------------- # Request a buffer slot from GPU buffer = gl.glGenBuffers(1) # Make this buffer the default one gl.glBindBuffer(gl.GL_ARRAY_BUFFER, buffer) # Upload data gl.glBufferData(gl.GL_ARRAY_BUFFER, data.nbytes, data, gl.GL_DYNAMIC_DRAW) # Bind the position attribute # -------------------------------------- stride = data.strides[0] offset = ctypes.c_void_p(0) loc = gl.glGetAttribLocation(program, "position") gl.glEnableVertexAttribArray(loc) gl.glBindBuffer(gl.GL_ARRAY_BUFFER, buffer) gl.glVertexAttribPointer(loc, 2, gl.GL_FLOAT, False, stride, offset) # Upload the uniform color # -------------------------------------- loc = gl.glGetUniformLocation(program, "color") gl.glUniform4f(loc, 0.0, 0.0, 1.0, 1.0)
def main(): # declare draw method so it can be reused during resizing def draw(): gl.glClearColor(0.2, 0.3, 0.3, 1.0) gl.glClear(gl.GL_COLOR_BUFFER_BIT) gl.glUseProgram(shaderProgram) gl.glBindVertexArray(VAO) gl.glDrawElements(gl.GL_TRIANGLES, 3 * indices.shape[0], gl.GL_UNSIGNED_INT, None) gl.glBindVertexArray(VAO2) gl.glDrawElements(gl.GL_TRIANGLES, 3 * indices2.shape[0], gl.GL_UNSIGNED_INT, None) gl.glBindVertexArray(0) glfw.swap_buffers(window) # declaring resize callback in main to allow access to variables def window_size_callback(window, width, height): gl.glViewport(0, 0, width, height) # calling draw to allow drawing while resizing draw() # glfw: initialize and configure glfw.init() glfw.window_hint(glfw.CONTEXT_VERSION_MAJOR, 3) glfw.window_hint(glfw.CONTEXT_VERSION_MINOR, 3) glfw.window_hint(glfw.OPENGL_PROFILE, glfw.OPENGL_CORE_PROFILE) # No deprecated functions glfw.window_hint(glfw.RESIZABLE, gl.GL_TRUE) # checking if run on Mac OS X if sys.platform == 'darwin': glfw.window_hint(glfw.OPENGL_FORWARD_COMPAT, gl.GL_TRUE) # glfw window creation window = glfw.create_window(WIDTH, HEIGHT, 'LearnOpenGL', None, None) # tutorial: (800, 600... if window is None: glfw.terminate() raise Exception("ERROR: Failed to create GLFW window") glfw.make_context_current(window) glfw.set_key_callback(window, key_callback) width, height = glfw.get_framebuffer_size(window) glfw.set_window_size_callback(window, window_size_callback) # build and compile shader program # vertex shader vertexShader = gl.glCreateShader(gl.GL_VERTEX_SHADER) gl.glShaderSource(vertexShader, vertexShaderSource) gl.glCompileShader(vertexShader) if not gl.glGetShaderiv(vertexShader, gl.GL_COMPILE_STATUS): infoLog = gl.glGetShaderInfoLog(vertexShader).decode() raise Exception("ERROR::SHADER::VERTEX::COMPILATION_FAILED\n" + infoLog) # fragment shader fragmentShader = gl.glCreateShader(gl.GL_FRAGMENT_SHADER) gl.glShaderSource(fragmentShader, fragmentShaderSource) gl.glCompileShader(fragmentShader) if not gl.glGetShaderiv(fragmentShader, gl.GL_COMPILE_STATUS): infoLog = gl.glGetShaderInfoLog(fragmentShader).decode() raise Exception("ERROR::SHADER::FRAGMENT::COMPILATION_FAILED\n" + infoLog) # link shaders shaderProgram = gl.glCreateProgram() gl.glAttachShader(shaderProgram, vertexShader) gl.glAttachShader(shaderProgram, fragmentShader) gl.glLinkProgram(shaderProgram) if not gl.glGetProgramiv(shaderProgram, gl.GL_LINK_STATUS): infoLog = gl.glGetProgramInfoLog(shaderProgram).decode() raise Exception("ERROR::SHADER::PROGRAM::LINKING_FAILED\n" + infoLog) gl.glDeleteShader(vertexShader) gl.glDeleteShader(fragmentShader) # set up vertex data (and buffer(s)) and configure vertex attributes vertices = np.array( [ [0.5, 0.5, 0.0], # Left [0.5, -0.5, 0.0], # Right [-0.5, -0.5, 0.0], [-0.5, 0.5, 0.0], [1.0, -0.5, 0.0] ], # Top dtype=np.float32) indices = np.array( [[3, 2, 1]], # first triangle dtype=np.int32) indices2 = np.array( [[0, 1, 4]], # second triangle dtype=np.int32) VBO, VBO2, VAO, VAO2, EBO, EBO2 = gl.GLuint(), gl.GLuint(), gl.GLuint( ), gl.GLuint(), gl.GLuint(), gl.GLuint() gl.glGenVertexArrays(1, VAO) # 1 -> 1 buffer to be generated gl.glGenVertexArrays(1, VAO2) gl.glGenBuffers(1, VBO) gl.glGenBuffers(1, VBO2) gl.glGenBuffers(1, EBO) gl.glGenBuffers(1, EBO2) # bind the Vertex Array Object first, then bind and set vertex buffer(s), and then configure vertex attributes(s) # first set with VAO and VBO gl.glBindVertexArray(VAO) gl.glBindBuffer(gl.GL_ARRAY_BUFFER, VBO) # bind = make active/current for subsequent ops gl.glBufferData(gl.GL_ARRAY_BUFFER, vertices, gl.GL_STATIC_DRAW) gl.glBindBuffer(gl.GL_ELEMENT_ARRAY_BUFFER, EBO) gl.glBufferData(gl.GL_ELEMENT_ARRAY_BUFFER, indices, gl.GL_STATIC_DRAW) stride = vertices.itemsize * vertices.shape[1] offset = gl.ctypes.c_void_p(vertices.itemsize * 0) gl.glVertexAttribPointer(0, 3, gl.GL_FLOAT, gl.GL_FALSE, stride, offset) gl.glEnableVertexAttribArray(0) # location = 0 # second set with VAO2 and VBO2 gl.glBindVertexArray(VAO2) gl.glBindBuffer(gl.GL_ARRAY_BUFFER, VBO2) # bind = make active/current for subsequent ops gl.glBufferData(gl.GL_ARRAY_BUFFER, vertices, gl.GL_STATIC_DRAW) gl.glBindBuffer(gl.GL_ELEMENT_ARRAY_BUFFER, EBO2) gl.glBufferData(gl.GL_ELEMENT_ARRAY_BUFFER, indices2, gl.GL_STATIC_DRAW) stride = vertices.itemsize * vertices.shape[1] offset = gl.ctypes.c_void_p(vertices.itemsize * 0) gl.glVertexAttribPointer(0, 3, gl.GL_FLOAT, gl.GL_FALSE, stride, offset) gl.glEnableVertexAttribArray(0) # location = 0 gl.glBindBuffer(gl.GL_ARRAY_BUFFER, 0) gl.glBindVertexArray(0) # to put in wireframe mode # gl.glPolygonMode(gl.GL_FRONT_AND_BACK, gl.GL_LINE) # render loop while not glfw.window_should_close(window): glfw.poll_events() draw() glfw.terminate() return 0
def main(): global delta_time, last_frame if not glfw.init(): raise ValueError("Failed to initialize glfw") glfw.window_hint(glfw.CONTEXT_VERSION_MAJOR, 3) glfw.window_hint(glfw.CONTEXT_VERSION_MINOR, 3) glfw.window_hint(glfw.OPENGL_PROFILE, glfw.OPENGL_CORE_PROFILE) window = glfw.create_window(SRC_WIDTH, SRC_HEIGHT, "learnOpenGL", None, None) if not window: glfw.terminate() raise ValueError("Failed to create window") glfw.make_context_current(window) glfw.set_framebuffer_size_callback(window, framebuffer_size_callback) glfw.set_cursor_pos_callback(window, mouse_callback) glfw.set_scroll_callback(window, scroll_callback) glfw.set_input_mode(window, glfw.CURSOR, glfw.CURSOR_DISABLED) gl.glEnable(gl.GL_DEPTH_TEST) lamp_shader = Shader(CURDIR / "shaders/1.lamp.vs", CURDIR / "shaders/1.lamp.fs") lighting_shader = Shader(CURDIR / "shaders/2.2.basic_lighting.vs", CURDIR / "shaders/2.2.basic_lighting.fs") vertices = [ -0.5, -0.5, -0.5, 0.0, 0.0, -1.0, 0.5, -0.5, -0.5, 0.0, 0.0, -1.0, 0.5, 0.5, -0.5, 0.0, 0.0, -1.0, 0.5, 0.5, -0.5, 0.0, 0.0, -1.0, -0.5, 0.5, -0.5, 0.0, 0.0, -1.0, -0.5, -0.5, -0.5, 0.0, 0.0, -1.0, -0.5, -0.5, 0.5, 0.0, 0.0, 1.0, 0.5, -0.5, 0.5, 0.0, 0.0, 1.0, 0.5, 0.5, 0.5, 0.0, 0.0, 1.0, 0.5, 0.5, 0.5, 0.0, 0.0, 1.0, -0.5, 0.5, 0.5, 0.0, 0.0, 1.0, -0.5, -0.5, 0.5, 0.0, 0.0, 1.0, -0.5, 0.5, 0.5, -1.0, 0.0, 0.0, -0.5, 0.5, -0.5, -1.0, 0.0, 0.0, -0.5, -0.5, -0.5, -1.0, 0.0, 0.0, -0.5, -0.5, -0.5, -1.0, 0.0, 0.0, -0.5, -0.5, 0.5, -1.0, 0.0, 0.0, -0.5, 0.5, 0.5, -1.0, 0.0, 0.0, 0.5, 0.5, 0.5, 1.0, 0.0, 0.0, 0.5, 0.5, -0.5, 1.0, 0.0, 0.0, 0.5, -0.5, -0.5, 1.0, 0.0, 0.0, 0.5, -0.5, -0.5, 1.0, 0.0, 0.0, 0.5, -0.5, 0.5, 1.0, 0.0, 0.0, 0.5, 0.5, 0.5, 1.0, 0.0, 0.0, -0.5, -0.5, -0.5, 0.0, -1.0, 0.0, 0.5, -0.5, -0.5, 0.0, -1.0, 0.0, 0.5, -0.5, 0.5, 0.0, -1.0, 0.0, 0.5, -0.5, 0.5, 0.0, -1.0, 0.0, -0.5, -0.5, 0.5, 0.0, -1.0, 0.0, -0.5, -0.5, -0.5, 0.0, -1.0, 0.0, -0.5, 0.5, -0.5, 0.0, 1.0, 0.0, 0.5, 0.5, -0.5, 0.0, 1.0, 0.0, 0.5, 0.5, 0.5, 0.0, 1.0, 0.0, 0.5, 0.5, 0.5, 0.0, 1.0, 0.0, -0.5, 0.5, 0.5, 0.0, 1.0, 0.0, -0.5, 0.5, -0.5, 0.0, 1.0, 0.0 ] vertices = (c_float * len(vertices))(*vertices) cube_vao = gl.glGenVertexArrays(1) vbo = gl.glGenBuffers(1) gl.glBindBuffer(gl.GL_ARRAY_BUFFER, vbo) gl.glBufferData(gl.GL_ARRAY_BUFFER, sizeof(vertices), vertices, gl.GL_STATIC_DRAW) gl.glBindVertexArray(cube_vao) # -- position attribute gl.glVertexAttribPointer(0, 3, gl.GL_FLOAT, gl.GL_FALSE, 6 * sizeof(c_float), c_void_p(0)) gl.glEnableVertexAttribArray(0) # -- normal attribute gl.glVertexAttribPointer(1, 3, gl.GL_FLOAT, gl.GL_FALSE, 6 * sizeof(c_float), c_void_p(3 * sizeof(c_float))) gl.glEnableVertexAttribArray(1) # -- second configure light vao (vbo is the same) light_vao = gl.glGenVertexArrays(1) gl.glBindVertexArray(light_vao) gl.glBindBuffer(gl.GL_ARRAY_BUFFER, vbo) gl.glVertexAttribPointer(0, 3, gl.GL_FLOAT, gl.GL_FALSE, 6 * sizeof(c_float), c_void_p(0)) gl.glEnableVertexAttribArray(0) while not glfw.window_should_close(window): # -- time logic current_frame = glfw.get_time() delta_time = current_frame - last_frame last_frame = current_frame # -- input process_input(window) # -- render gl.glClearColor(0.1, 0.1, 0.1, 1.0) gl.glClear(gl.GL_COLOR_BUFFER_BIT | gl.GL_DEPTH_BUFFER_BIT) lighting_shader.use() lighting_shader.set_vec3("objectColor", Vector3([1.0, 0.5, 0.31])) lighting_shader.set_vec3("lightColor", Vector3([1.0, 1.0, 1.0])) lighting_shader.set_vec3("lightPos", light_pos) lighting_shader.set_vec3("viewPos", camera.position) # -- view.projection transformations projection = Matrix44.perspective_projection(camera.zoom, SRC_WIDTH / SRC_HEIGHT, 0.1, 100.0) view = camera.get_view_matrix() lighting_shader.set_mat4("projection", projection) lighting_shader.set_mat4("view", view) # -- world transformation model = Matrix44.identity() lighting_shader.set_mat4("model", model) # -- render cube gl.glBindVertexArray(cube_vao) gl.glDrawArrays(gl.GL_TRIANGLES, 0, 36) # -- draw lamp object lamp_shader.use() lamp_shader.set_mat4("projection", projection) lamp_shader.set_mat4("view", view) model = Matrix44.identity() model *= Matrix44.from_translation(light_pos) model *= Matrix44.from_scale(Vector3([.2, .2, .2])) lamp_shader.set_mat4("model", model) gl.glBindVertexArray(light_vao) gl.glDrawArrays(gl.GL_TRIANGLES, 0, 36) glfw.swap_buffers(window) glfw.poll_events() gl.glDeleteVertexArrays(1, id(cube_vao)) gl.glDeleteVertexArrays(1, id(light_vao)) gl.glDeleteBuffers(1, id(vbo)) glfw.terminate()
def initialize(): global shaderProgram global VAO global idxCnt global texUnitUniform global sampleTexture vertexStaticShader = shaders.compileShader( """ #version 330 core layout (location=0) in vec3 position; layout (location=1) in vec3 aNormal; uniform mat4 rot; uniform mat4 translation; uniform mat4 projection; uniform mat4 view; out vec3 theCoords; out vec3 theNormal; void main() { vec4 world = translation*rot*vec4((1*position), 1); gl_Position = projection*view*world; theCoords = 0.5*(vec3(1,1,1)+1*position); theNormal = aNormal; } """, GL.GL_VERTEX_SHADER) fragmentShader = shaders.compileShader( """ #version 330 core uniform sampler3D texUnit; in vec3 theCoords; in vec3 theNormal; uniform vec3 lightPos; out vec4 outputColour; float ambientStrenght; float diff; vec3 lightColor; vec3 ambient; vec3 norm; vec3 lightDir; vec3 diffuse; void main() { // ambient lightColor = vec3(1, 1, 1); ambientStrenght = 1.0; ambient = ambientStrenght * lightColor; // diffusse norm = normalize(theNormal); lightDir = normalize(lightPos - theCoords); diff = max(dot(norm, lightDir), 0.0); diffuse = diff * lightColor; // out outputColour = vec4(diffuse+ambient, 1.0)*texture(texUnit, theCoords); } """, GL.GL_FRAGMENT_SHADER) vertexData = np.array([ 1.0, -1.0, -1.0, 0, -1, 0, 1.0, -1.0, 1.0, 0, -1, 0, -1.0, -1.0, 1.0, 0, -1, 0, -1.0, -1.0, -1.0, 0, -1, 0, 1.0, 1.0, -1.0, 0, 1, 0, 1.0, 1.0, 1.0, 0, 1, 0, -1.0, 1.0, 1.0, 0, 1, 0, -1.0, 1.0, -1.0, 0, 1, 0, 1.0, -1.0, -1.0, 1, 0, 0, 1.0, -1.0, 1.0, 1, 0, 0, 1.0, 1.0, -1.0, 1, 0, 0, 1.0, 1.0, 1.0, 1, 0, 0, 1.0, -1.0, -1.0, 0, 0, -1, -1.0, -1.0, -1.0, 0, 0, -1, 1.0, 1.0, -1.0, 0, 0, -1, -1.0, 1.0, -1.0, 0, 0, -1, -1.0, -1.0, 1.0, -1, 0, 0, -1.0, -1.0, -1.0, -1, 0, 0, -1.0, 1.0, 1.0, -1, 0, 0, -1.0, 1.0, -1.0, -1, 0, 0, 1.0, -1.0, 1.0, 0, 0, 1, -1.0, -1.0, 1.0, 0, 0, 1, 1.0, 1.0, 1.0, 0, 0, 1, -1.0, 1.0, 1.0, 0, 0, 1, ], dtype=np.float32) faceData = np.array([ 1, 3, 0, 7, 5, 4, 22, 21, 20, 10, 9, 8, 12, 15, 14, 16, 19, 17, 1, 2, 3, 7, 6, 5, 22, 23, 21, 10, 11, 9, 12, 13, 15, 16, 18, 19, ], dtype=np.uint32) idxCnt = faceData.shape[0] GL.glEnable(GL.GL_DEPTH_TEST) GL.glDepthFunc(GL.GL_LEQUAL) shaderProgram = shaders.compileProgram(vertexStaticShader, fragmentShader) GL.glDeleteShader(vertexStaticShader) GL.glDeleteShader(fragmentShader) VAO = GL.glGenVertexArrays(1) GL.glBindVertexArray(VAO) # Need VBO for triangle vertices coordinates VBO = GL.glGenBuffers(1) GL.glBindBuffer(GL.GL_ARRAY_BUFFER, VBO) GL.glBufferData(GL.GL_ARRAY_BUFFER, vertexData.nbytes, vertexData, GL.GL_STATIC_DRAW) GL.glEnableVertexAttribArray(0) GL.glVertexAttribPointer(0, 3, GL.GL_FLOAT, GL.GL_FALSE, stride, vertex_offset) GL.glVertexAttribPointer(1, 3, GL.GL_FLOAT, GL.GL_FALSE, stride, normal_offset) GL.glEnableVertexAttribArray(1) IBO = GL.glGenBuffers(1) GL.glBindBuffer(GL.GL_ELEMENT_ARRAY_BUFFER, IBO) GL.glBufferData(GL.GL_ELEMENT_ARRAY_BUFFER, faceData.nbytes, faceData, GL.GL_STATIC_DRAW) # Finished GL.glBindBuffer(GL.GL_ARRAY_BUFFER, 0) GL.glBindVertexArray(0) GL.glBindBuffer(GL.GL_ELEMENT_ARRAY_BUFFER, 0) GL.glBindBuffer(GL.GL_ARRAY_BUFFER, 0) GL.glBindVertexArray(0) GL.glBindBuffer(GL.GL_ELEMENT_ARRAY_BUFFER, 0) # load texture and assign texture unit for shaders sampleTexture = loadTexture(texture) texUnitUniform = GL.glGetUniformLocation(shaderProgram, 'texUnit')
def load_line_buffer(self): LOG.debug("load line buffer start") start = time.time() line_p = [] line_t = [] line_c = [] self.line_buffer_length = 0 self.add_lines_reference(line_p, line_c) line_t += [0, 0, 0] * self.line_buffer_length def segment_layer(time_, layer): """ Return the layer number plus the fraction of the layer completed. """ return layer.number + (time_ - layer.max_segment.start_time ) / layer.max_segment.duration profile_start = time.time() for layer in self.model: layer_chunk_start = self.line_buffer_length for segment in layer: line_p += [ segment.start[0], segment.start[1], segment.start[2] ] line_p += [segment.end[0], segment.end[1], segment.end[2]] line_t += [ segment.start_time, segment_layer(segment.start_time, layer), 0 ] line_t += [ segment.start_time + segment.duration, segment_layer(segment.start_time + segment.duration, layer), 0 ] self.line_buffer_length += 2 * len(layer) self.model_layer_chunks.append( [layer_chunk_start, self.line_buffer_length]) LOG.debug( f"analyse model layer sizes {time.time() - profile_start:0.2f}") model_lines_buffer_length = (self.model_layer_chunks[-1][1] - self.model_layer_chunks[0][0]) line_c += self.model_channel_buffer[self.channel] GL.glBindVertexArray(self.line_array) GL.glBindBuffer(GL.GL_ARRAY_BUFFER, self.line_buffer_position) GL.glBufferData(GL.GL_ARRAY_BUFFER, np.array(line_p, dtype='float32'), GL.GL_STATIC_DRAW) GL.glVertexAttribPointer(self.locations["vertex_position"], 3, GL.GL_FLOAT, GL.GL_FALSE, 0, None) GL.glBindBuffer(GL.GL_ARRAY_BUFFER, self.line_buffer_progress) GL.glBufferData(GL.GL_ARRAY_BUFFER, np.array(line_t, dtype='float32'), GL.GL_STATIC_DRAW) GL.glVertexAttribPointer(self.locations["vertex_progress"], 3, GL.GL_FLOAT, GL.GL_FALSE, 0, None) GL.glBindBuffer(GL.GL_ARRAY_BUFFER, self.line_buffer_color) GL.glBufferData(GL.GL_ARRAY_BUFFER, np.array(line_c, dtype='float32'), GL.GL_STATIC_DRAW) GL.glVertexAttribPointer(self.locations["vertex_color"], 3, GL.GL_FLOAT, GL.GL_FALSE, 0, None) duration = time.time() - start LOG.debug(f"load line buffer end {duration:0.2f}") GLUT.glutPostRedisplay()
def main(): glfw.init() glfw.window_hint(glfw.CONTEXT_VERSION_MAJOR, 3) glfw.window_hint(glfw.CONTEXT_VERSION_MINOR, 3) glfw.window_hint(glfw.OPENGL_PROFILE, glfw.OPENGL_CORE_PROFILE) window = glfw.create_window(800, 600, "LearnOpenGL", None, None) if not window: print("Window Creation failed!") glfw.terminate() glfw.make_context_current(window) glfw.set_window_size_callback(window, on_resize) shader = Shader(CURDIR / 'shaders/4.1.texture.vs', CURDIR / 'shaders/4.1.texture.fs') shader_mix = Shader(CURDIR / 'shaders/4.1.texture.vs', CURDIR / 'shaders/4.1.texture_mix.fs') vertices = [ # positions colors tex_coords 0.5, 0.5, 0.0, 1.0, 0.0, 0.0, 1.0, 1.0, # top right 0.5, -0.5, 0.0, 0.0, 1.0, 0.0, 1.0, 0.0, # bottom right -0.5, -0.5, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, # bottom left -0.5, 0.5, 0.0, 1.0, 1.0, 0.0, 0.0, 1.0, # top left ] vertices = (c_float * len(vertices))(*vertices) indices = [0, 1, 3, 1, 2, 3] indices = (c_uint * len(indices))(*indices) vao = gl.glGenVertexArrays(1) gl.glBindVertexArray(vao) vbo = gl.glGenBuffers(1) gl.glBindBuffer(gl.GL_ARRAY_BUFFER, vbo) gl.glBufferData(gl.GL_ARRAY_BUFFER, sizeof(vertices), vertices, gl.GL_STATIC_DRAW) ebo = gl.glGenBuffers(1) gl.glBindBuffer(gl.GL_ELEMENT_ARRAY_BUFFER, ebo) gl.glBufferData(gl.GL_ELEMENT_ARRAY_BUFFER, sizeof(indices), indices, gl.GL_STATIC_DRAW) gl.glVertexAttribPointer(0, 3, gl.GL_FLOAT, gl.GL_FALSE, 8 * sizeof(c_float), c_void_p(0)) gl.glEnableVertexAttribArray(0) gl.glVertexAttribPointer(1, 3, gl.GL_FLOAT, gl.GL_FALSE, 8 * sizeof(c_float), c_void_p(3 * sizeof(c_float))) gl.glEnableVertexAttribArray(1) gl.glVertexAttribPointer(2, 2, gl.GL_FLOAT, gl.GL_FALSE, 8 * sizeof(c_float), c_void_p(6 * sizeof(c_float))) gl.glEnableVertexAttribArray(2) # -- load texture texture = gl.glGenTextures(1) gl.glBindTexture(gl.GL_TEXTURE_2D, texture) # -- texture wrapping gl.glTexParameter(gl.GL_TEXTURE_2D, gl.GL_TEXTURE_WRAP_S, gl.GL_REPEAT) gl.glTexParameter(gl.GL_TEXTURE_2D, gl.GL_TEXTURE_WRAP_T, gl.GL_REPEAT) # -- texture filterting gl.glTexParameter(gl.GL_TEXTURE_2D, gl.GL_TEXTURE_MIN_FILTER, gl.GL_LINEAR_MIPMAP_LINEAR) gl.glTexParameter(gl.GL_TEXTURE_2D, gl.GL_TEXTURE_MAG_FILTER, gl.GL_LINEAR) img = Image.open(Tex('container.jpg')) gl.glTexImage2D(gl.GL_TEXTURE_2D, 0, gl.GL_RGB, img.width, img.height, 0, gl.GL_RGB, gl.GL_UNSIGNED_BYTE, img.tobytes()) gl.glGenerateMipmap(gl.GL_TEXTURE_2D) while not glfw.window_should_close(window): process_input(window) gl.glClearColor(.2, .3, .3, 1.0) gl.glClear(gl.GL_COLOR_BUFFER_BIT) gl.glBindTexture(gl.GL_TEXTURE_2D, texture) shader.use() # -- uncomment to see mixture of vertex color and texture color # shader_mix.use() gl.glBindVertexArray(vao) gl.glDrawElements(gl.GL_TRIANGLES, 6, gl.GL_UNSIGNED_INT, c_void_p(0)) glfw.poll_events() glfw.swap_buffers(window) gl.glDeleteVertexArrays(1, id(vao)) gl.glDeleteBuffers(1, id(vbo)) gl.glDeleteBuffers(1, id(ebo)) glfw.terminate()
def render(self, draw_data): # perf: local for faster access io = self.io display_width, display_height = self.io.display_size fb_width = int(display_width * io.display_fb_scale[0]) fb_height = int(display_height * io.display_fb_scale[1]) if fb_width == 0 or fb_height == 0: return draw_data.scale_clip_rects(*io.display_fb_scale) # backup GL state # todo: provide cleaner version of this backup-restore code last_program = gl.glGetIntegerv(gl.GL_CURRENT_PROGRAM) last_texture = gl.glGetIntegerv(gl.GL_TEXTURE_BINDING_2D) last_active_texture = gl.glGetIntegerv(gl.GL_ACTIVE_TEXTURE) last_array_buffer = gl.glGetIntegerv(gl.GL_ARRAY_BUFFER_BINDING) last_element_array_buffer = gl.glGetIntegerv( gl.GL_ELEMENT_ARRAY_BUFFER_BINDING) last_vertex_array = gl.glGetIntegerv(gl.GL_VERTEX_ARRAY_BINDING) last_blend_src = gl.glGetIntegerv(gl.GL_BLEND_SRC) last_blend_dst = gl.glGetIntegerv(gl.GL_BLEND_DST) last_blend_equation_rgb = gl.glGetIntegerv(gl.GL_BLEND_EQUATION_RGB) last_blend_equation_alpha = gl.glGetIntegerv( gl.GL_BLEND_EQUATION_ALPHA) last_viewport = gl.glGetIntegerv(gl.GL_VIEWPORT) last_scissor_box = gl.glGetIntegerv(gl.GL_SCISSOR_BOX) last_enable_blend = gl.glIsEnabled(gl.GL_BLEND) last_enable_cull_face = gl.glIsEnabled(gl.GL_CULL_FACE) last_enable_depth_test = gl.glIsEnabled(gl.GL_DEPTH_TEST) last_enable_scissor_test = gl.glIsEnabled(gl.GL_SCISSOR_TEST) gl.glEnable(gl.GL_BLEND) gl.glBlendEquation(gl.GL_FUNC_ADD) gl.glBlendFunc(gl.GL_SRC_ALPHA, gl.GL_ONE_MINUS_SRC_ALPHA) gl.glDisable(gl.GL_CULL_FACE) gl.glDisable(gl.GL_DEPTH_TEST) gl.glEnable(gl.GL_SCISSOR_TEST) gl.glActiveTexture(gl.GL_TEXTURE0) gl.glViewport(0, 0, int(fb_width), int(fb_height)) ortho_projection = [[2.0 / display_width, 0.0, 0.0, 0.0], [0.0, 2.0 / -display_height, 0.0, 0.0], [0.0, 0.0, -1.0, 0.0], [-1.0, 1.0, 0.0, 1.0]] gl.glUseProgram(self._shader_handle) gl.glUniform1i(self._attrib_location_tex, 0) gl.glUniformMatrix4fv(self._attrib_proj_mtx, 1, gl.GL_FALSE, ortho_projection) gl.glBindVertexArray(self._vao_handle) for commands in draw_data.commands_lists: idx_buffer_offset = 0 gl.glBindBuffer(gl.GL_ARRAY_BUFFER, self._vbo_handle) # todo: check this (sizes) gl.glBufferData(gl.GL_ARRAY_BUFFER, commands.vtx_buffer_size * imgui.VERTEX_SIZE, ctypes.c_void_p(commands.vtx_buffer_data), gl.GL_STREAM_DRAW) gl.glBindBuffer(gl.GL_ELEMENT_ARRAY_BUFFER, self._elements_handle) # todo: check this (sizes) gl.glBufferData(gl.GL_ELEMENT_ARRAY_BUFFER, commands.idx_buffer_size * imgui.INDEX_SIZE, ctypes.c_void_p(commands.idx_buffer_data), gl.GL_STREAM_DRAW) # todo: allow to iterate over _CmdList for command in commands.commands: gl.glBindTexture(gl.GL_TEXTURE_2D, command.texture_id) # todo: use named tuple x, y, w, z = command.clip_rect gl.glScissor(int(x), int(fb_height - w), int(z - x), int(w - y)) if imgui.INDEX_SIZE == 2: gltype = gl.GL_UNSIGNED_SHORT else: gltype = gl.GL_UNSIGNED_INT gl.glDrawElements(gl.GL_TRIANGLES, command.elem_count, gltype, ctypes.c_void_p(idx_buffer_offset)) idx_buffer_offset += command.elem_count * imgui.INDEX_SIZE # restore modified GL state gl.glUseProgram(last_program) gl.glActiveTexture(last_active_texture) gl.glBindTexture(gl.GL_TEXTURE_2D, last_texture) gl.glBindVertexArray(last_vertex_array) gl.glBindBuffer(gl.GL_ARRAY_BUFFER, last_array_buffer) gl.glBindBuffer(gl.GL_ELEMENT_ARRAY_BUFFER, last_element_array_buffer) gl.glBlendEquationSeparate(last_blend_equation_rgb, last_blend_equation_alpha) gl.glBlendFunc(last_blend_src, last_blend_dst) if last_enable_blend: gl.glEnable(gl.GL_BLEND) else: gl.glDisable(gl.GL_BLEND) if last_enable_cull_face: gl.glEnable(gl.GL_CULL_FACE) else: gl.glDisable(gl.GL_CULL_FACE) if last_enable_depth_test: gl.glEnable(gl.GL_DEPTH_TEST) else: gl.glDisable(gl.GL_DEPTH_TEST) if last_enable_scissor_test: gl.glEnable(gl.GL_SCISSOR_TEST) else: gl.glDisable(gl.GL_SCISSOR_TEST) gl.glViewport(last_viewport[0], last_viewport[1], last_viewport[2], last_viewport[3]) gl.glScissor(last_scissor_box[0], last_scissor_box[1], last_scissor_box[2], last_scissor_box[3])
def __init__(self, vec1:mmath.Vec3, vec2:mmath.Vec3, vec3:mmath.Vec3, vec4:mmath.Vec3, vec5:mmath.Vec3, vec6:mmath.Vec3, vec7:mmath.Vec3, vec8:mmath.Vec3, textureId:int, textureVerNum_f:float, textureHorNum_f:float, shininess:float, specularStrength:float, startPos_l:list): super().__init__() self.renderFlag = True self.vertices_l = [vec1, vec2, vec3, vec4, vec5, vec6, vec7, vec8] self.textureId = textureId self.textureVerNum_f = float(textureVerNum_f) self.textureHorNum_f = float(textureHorNum_f) self.shininess_f = float(shininess) self.specularStrength_f = float(specularStrength) self.pos_l = startPos_l self.selectedTexId = self.textureId self.textureId2 = None self.collideModels_l.append( co.AabbActor(vec3, vec5, self) ) #self.collideModels_l.append() #### #### self.vao = gl.glGenVertexArrays(1) gl.glBindVertexArray(self.vao) vertices = np.array([*vec1.getXYZ(), *vec2.getXYZ(), *vec3.getXYZ(), *vec1.getXYZ(), *vec3.getXYZ(), *vec4.getXYZ(), *vec2.getXYZ(), *vec6.getXYZ(), *vec7.getXYZ(), *vec2.getXYZ(), *vec7.getXYZ(), *vec3.getXYZ(), *vec3.getXYZ(), *vec7.getXYZ(), *vec8.getXYZ(), *vec3.getXYZ(), *vec8.getXYZ(), *vec4.getXYZ(), *vec4.getXYZ(), *vec8.getXYZ(), *vec5.getXYZ(), *vec4.getXYZ(), *vec5.getXYZ(), *vec1.getXYZ(), *vec1.getXYZ(), *vec5.getXYZ(), *vec6.getXYZ(), *vec1.getXYZ(), *vec6.getXYZ(), *vec2.getXYZ(), *vec8.getXYZ(), *vec7.getXYZ(), *vec6.getXYZ(), *vec8.getXYZ(), *vec6.getXYZ(), *vec5.getXYZ()], dtype=np.float32) size = vertices.size * vertices.itemsize self.vertexSize_i = vertices.size self.verticesBuffer = gl.glGenBuffers(1) # Create a buffer. gl.glBindBuffer(gl.GL_ARRAY_BUFFER, self.verticesBuffer) # Bind the buffer. gl.glBufferData(gl.GL_ARRAY_BUFFER, size, vertices, gl.GL_STATIC_DRAW) # Allocate memory. gl.glVertexAttribPointer(0, 3, gl.GL_FLOAT, gl.GL_FALSE, 0, None) # Defines vertex attributes. What are those? gl.glEnableVertexAttribArray(0) #### Texture Coord #### textureCoords = np.array([0, 1, 0, 0, 1, 0, 0, 1, 1, 0, 1, 1, 0, 1, 0, 0, 1, 0, 0, 1, 1, 0, 1, 1, 0, 1, 0, 0, 1, 0, 0, 1, 1, 0, 1, 1, 0, 1, 0, 0, 1, 0, 0, 1, 1, 0, 1, 1, 0, 1, 0, 0, 1, 0, 0, 1, 1, 0, 1, 1, 0, 1, 0, 0, 1, 0, 0, 1, 1, 0, 1, 1], dtype=np.float32) size = textureCoords.size * textureCoords.itemsize self.texCoordBuffer = gl.glGenBuffers(1) # Create a buffer. gl.glBindBuffer(gl.GL_ARRAY_BUFFER, self.texCoordBuffer) # Bind the buffer. gl.glBufferData(gl.GL_ARRAY_BUFFER, size, textureCoords, gl.GL_STATIC_DRAW) # Allocate memory. gl.glVertexAttribPointer(1, 2, gl.GL_FLOAT, gl.GL_FALSE, 0, None) # Defines vertex attributes. What are those? gl.glEnableVertexAttribArray(1)
gl.glCompileShader(vs) prgrm = gl.glCreateProgram() gl.glAttachShader(prgrm, vs) gl.glAttachShader(prgrm, fs) gl.glLinkProgram(prgrm) gl.glUseProgram(prgrm) # create buffers vbo = gl.glGenBuffers(1) test1_ibo = gl.glGenBuffers(1) test2_ibo = gl.glGenBuffers(1) test3_ibo = gl.glGenBuffers(1) # push consecutive data gl.glBindBuffer(gl.GL_ARRAY_BUFFER, vbo) gl.glBufferData(gl.GL_ARRAY_BUFFER, points.itemsize * points.size, points, gl.GL_DYNAMIC_DRAW) # set attribute pointer gl.glEnableVertexAttribArray(0) gl.glVertexAttribPointer(index=0, size=4, type=gl.GL_FLOAT, normalized=gl.GL_FALSE, stride=32, pointer=ctypes.c_void_p(0)) gl.glEnableVertexAttribArray(1) gl.glVertexAttribPointer(index=1, size=4, type=gl.GL_FLOAT, normalized=gl.GL_FALSE, stride=32, pointer=ctypes.c_void_p(16))
def initData(): # Uses vertex arrays. global VAO1 global VBO1 global VAO2 global VBO2 global texture global scene global vertices global vertices_num global cx global cy global cz if len(sys.argv) == 1: vertices = loader.ObjLoader.load_model('cube.obj').astype('float32') else: vertices = loader.ObjLoader.load_model(str(sys.argv[1])).astype('float32') texture = gl.glGenTextures(1) gl.glBindTexture(gl.GL_TEXTURE_CUBE_MAP, texture) loadCubemap(["right.jpg", "left.jpg", "top.jpg", "bottom.jpg", "front.jpg", "back.jpg"], "yokohama") gl.glTexParameteri(gl.GL_TEXTURE_CUBE_MAP, gl.GL_TEXTURE_MIN_FILTER, gl.GL_LINEAR); gl.glTexParameteri(gl.GL_TEXTURE_CUBE_MAP, gl.GL_TEXTURE_MAG_FILTER, gl.GL_LINEAR); gl.glTexParameteri(gl.GL_TEXTURE_CUBE_MAP, gl.GL_TEXTURE_WRAP_S, gl.GL_CLAMP_TO_EDGE); gl.glTexParameteri(gl.GL_TEXTURE_CUBE_MAP, gl.GL_TEXTURE_WRAP_T, gl.GL_CLAMP_TO_EDGE); gl.glTexParameteri(gl.GL_TEXTURE_CUBE_MAP, gl.GL_TEXTURE_WRAP_R, gl.GL_CLAMP_TO_EDGE); # Set cube vertices. skyboxVertices = np.array([ -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 ], dtype='float32') # Vertex array. VAO1 = gl.glGenVertexArrays(1) gl.glBindVertexArray(VAO1) # Vertex buffer VBO1 = gl.glGenBuffers(1) gl.glBindBuffer(gl.GL_ARRAY_BUFFER, VBO1) gl.glBufferData(gl.GL_ARRAY_BUFFER, skyboxVertices.nbytes, skyboxVertices, gl.GL_STATIC_DRAW) # Set attributes. gl.glVertexAttribPointer(0, 3, gl.GL_FLOAT, gl.GL_FALSE, 3 * skyboxVertices.itemsize, None) gl.glEnableVertexAttribArray(0) # Set pyramid vertices. pyramid = np.array([ # Front face # coordinates # normals 0.0, 1.0, 0.0, 0.0, 1.0, 0.0, -1.0, -1.0, 0.0, 1.0, 0.0, 1.0, 1.0, -1.0, 0.0, 0.0, 1.0, 0.0, # Right face 1.0, -1.0, 0.0, 0.0, 1.0, 0.0, 0.0, 1.0, 0.0, 1.0, 0.0, 1.0, 0.0, -1.0, -1.0, 0.0, 1.0, 0.0, # Left face -1.0, -1.0, 0.0, 0.0, 1.0, 0.0, 0.0, 1.0, 0.0, 1.0, 0.0, 1.0, 0.0, -1.0, -1.0, 0.0, 1.0, 0.0, # Bottom face 1 -1.0, -1.0, 0.0, 0.0, 1.0, 0.0, 1.0, -1.0, 0.0, 1.0, 0.0, 1.0, 0.0, -1.0, -1.0, 0.0, 1.0, 0.0, # back right face 1.0, -1.0, 0.0, 0.0, 1.0, 0.0, 0.0, 1.0, 0.0, 1.0, 0.0, 1.0, 0.0, -1.0, 1.0, 0.0, 1.0, 0.0, # back left face -1.0, -1.0, 0.0, 0.0, 1.0, 0.0, 0.0, 1.0, 0.0, 1.0, 0.0, 1.0, 0.0, -1.0, 1.0, 0.0, 1.0, 0.0, # Bottom face 2 -1.0, -1.0, 0.0, 0.0, 1.0, 0.0, 1.0, -1.0, 0.0, 1.0, 0.0, 1.0, 0.0, -1.0, 1.0, 0.0, 1.0, 0.0, ], dtype='float32') # Vertex array. VAO2 = gl.glGenVertexArrays(1) gl.glBindVertexArray(VAO2) # Vertex buffer VBO2 = gl.glGenBuffers(1) gl.glBindBuffer(gl.GL_ARRAY_BUFFER, VBO2) gl.glBufferData(gl.GL_ARRAY_BUFFER, pyramid.nbytes, pyramid, gl.GL_STATIC_DRAW) # Set attributes. gl.glVertexAttribPointer(0, 3, gl.GL_FLOAT, gl.GL_FALSE, 6 * pyramid.itemsize, None) gl.glEnableVertexAttribArray(0) gl.glVertexAttribPointer(1, 3, gl.GL_FLOAT, gl.GL_FALSE, 6 * pyramid.itemsize, c_void_p(3*pyramid.itemsize)) gl.glEnableVertexAttribArray(1) # Unbind Vertex Array Object. gl.glBindVertexArray(0) # Enable depth test. gl.glEnable(gl.GL_DEPTH_TEST);
def main(): global delta_time, last_frame glfw.init() glfw.window_hint(glfw.CONTEXT_VERSION_MAJOR, 3) glfw.window_hint(glfw.CONTEXT_VERSION_MINOR, 3) glfw.window_hint(glfw.OPENGL_PROFILE, glfw.OPENGL_CORE_PROFILE) window = glfw.create_window(SRC_WIDTH, SRC_HEIGHT, "learnOpenGL", None, None) if not window: glfw.terminate() raise ValueError("Failed to create window") glfw.make_context_current(window) glfw.set_framebuffer_size_callback(window, framebuffer_size_callback) glfw.set_cursor_pos_callback(window, mouse_callback) glfw.set_scroll_callback(window, scroll_callback) glfw.set_input_mode(window, glfw.CURSOR, glfw.CURSOR_DISABLED) gl.glEnable(gl.GL_DEPTH_TEST) lamp_shader = Shader(CURDIR / "shaders/1.lamp.vs", CURDIR / "shaders/1.lamp.fs") lighting_shader = Shader(CURDIR / "shaders/5.4.light_casters.vs", CURDIR / "shaders/5.4.light_casters.fs") vertices = [ # positions normals texture coords -0.5, -0.5, -0.5, 0.0, 0.0, -1.0, 0.0, 0.0, 0.5, -0.5, -0.5, 0.0, 0.0, -1.0, 1.0, 0.0, 0.5, 0.5, -0.5, 0.0, 0.0, -1.0, 1.0, 1.0, 0.5, 0.5, -0.5, 0.0, 0.0, -1.0, 1.0, 1.0, -0.5, 0.5, -0.5, 0.0, 0.0, -1.0, 0.0, 1.0, -0.5, -0.5, -0.5, 0.0, 0.0, -1.0, 0.0, 0.0, -0.5, -0.5, 0.5, 0.0, 0.0, 1.0, 0.0, 0.0, 0.5, -0.5, 0.5, 0.0, 0.0, 1.0, 1.0, 0.0, 0.5, 0.5, 0.5, 0.0, 0.0, 1.0, 1.0, 1.0, 0.5, 0.5, 0.5, 0.0, 0.0, 1.0, 1.0, 1.0, -0.5, 0.5, 0.5, 0.0, 0.0, 1.0, 0.0, 1.0, -0.5, -0.5, 0.5, 0.0, 0.0, 1.0, 0.0, 0.0, -0.5, 0.5, 0.5, -1.0, 0.0, 0.0, 1.0, 0.0, -0.5, 0.5, -0.5, -1.0, 0.0, 0.0, 1.0, 1.0, -0.5, -0.5, -0.5, -1.0, 0.0, 0.0, 0.0, 1.0, -0.5, -0.5, -0.5, -1.0, 0.0, 0.0, 0.0, 1.0, -0.5, -0.5, 0.5, -1.0, 0.0, 0.0, 0.0, 0.0, -0.5, 0.5, 0.5, -1.0, 0.0, 0.0, 1.0, 0.0, 0.5, 0.5, 0.5, 1.0, 0.0, 0.0, 1.0, 0.0, 0.5, 0.5, -0.5, 1.0, 0.0, 0.0, 1.0, 1.0, 0.5, -0.5, -0.5, 1.0, 0.0, 0.0, 0.0, 1.0, 0.5, -0.5, -0.5, 1.0, 0.0, 0.0, 0.0, 1.0, 0.5, -0.5, 0.5, 1.0, 0.0, 0.0, 0.0, 0.0, 0.5, 0.5, 0.5, 1.0, 0.0, 0.0, 1.0, 0.0, -0.5, -0.5, -0.5, 0.0, -1.0, 0.0, 0.0, 1.0, 0.5, -0.5, -0.5, 0.0, -1.0, 0.0, 1.0, 1.0, 0.5, -0.5, 0.5, 0.0, -1.0, 0.0, 1.0, 0.0, 0.5, -0.5, 0.5, 0.0, -1.0, 0.0, 1.0, 0.0, -0.5, -0.5, 0.5, 0.0, -1.0, 0.0, 0.0, 0.0, -0.5, -0.5, -0.5, 0.0, -1.0, 0.0, 0.0, 1.0, -0.5, 0.5, -0.5, 0.0, 1.0, 0.0, 0.0, 1.0, 0.5, 0.5, -0.5, 0.0, 1.0, 0.0, 1.0, 1.0, 0.5, 0.5, 0.5, 0.0, 1.0, 0.0, 1.0, 0.0, 0.5, 0.5, 0.5, 0.0, 1.0, 0.0, 1.0, 0.0, -0.5, 0.5, 0.5, 0.0, 1.0, 0.0, 0.0, 0.0, -0.5, 0.5, -0.5, 0.0, 1.0, 0.0, 0.0, 1.0 ] vertices = (c_float * len(vertices))(*vertices) cube_positions = [ ( 0.0, 0.0, 0.0), ( 2.0, 5.0, -15.0), (-1.5, -2.2, -2.5), (-3.8, -2.0, -12.3), ( 2.4, -0.4, -3.5), (-1.7, 3.0, -7.5), ( 1.3, -2.0, -2.5), ( 1.5, 2.0, -2.5), ( 1.5, 0.2, -1.5), (-1.3, 1.0, -1.5) ] cube_vao = gl.glGenVertexArrays(1) vbo = gl.glGenBuffers(1) gl.glBindBuffer(gl.GL_ARRAY_BUFFER, vbo) gl.glBufferData(gl.GL_ARRAY_BUFFER, sizeof(vertices), vertices, gl.GL_STATIC_DRAW) gl.glBindVertexArray(cube_vao) # -- position attribute gl.glVertexAttribPointer(0, 3, gl.GL_FLOAT, gl.GL_FALSE, 8 * sizeof(c_float), c_void_p(0)) gl.glEnableVertexAttribArray(0) # -- normal attribute gl.glVertexAttribPointer(1, 3, gl.GL_FLOAT, gl.GL_FALSE, 8 * sizeof(c_float), c_void_p(3 * sizeof(c_float))) gl.glEnableVertexAttribArray(1) # -- texture coordinate gl.glVertexAttribPointer(2, 2, gl.GL_FLOAT, gl.GL_FALSE, 8 * sizeof(c_float), c_void_p(6 * sizeof(c_float))) gl.glEnableVertexAttribArray(2) # -- second configure light vao (vbo is the same) light_vao = gl.glGenVertexArrays(1) gl.glBindVertexArray(light_vao) gl.glBindBuffer(gl.GL_ARRAY_BUFFER, vbo) gl.glVertexAttribPointer(0, 3, gl.GL_FLOAT, gl.GL_FALSE, 8 * sizeof(c_float), c_void_p(0)) gl.glEnableVertexAttribArray(0) # -- load texture diffuse_map = load_texture("container2.png") specular_map = load_texture("container2_specular.png") # -- shader configuration lighting_shader.use() lighting_shader.set_int("material.diffuse", 0) lighting_shader.set_int("material.specular", 1) while not glfw.window_should_close(window): # -- time logic current_frame = glfw.get_time() delta_time = current_frame - last_frame last_frame = current_frame # -- input process_input(window) # -- render gl.glClearColor(0.1, 0.1, 0.1, 1.0) gl.glClear(gl.GL_COLOR_BUFFER_BIT | gl.GL_DEPTH_BUFFER_BIT) lighting_shader.use() lighting_shader.set_vec3("light.position", camera.position) lighting_shader.set_vec3("light.direction", camera.front) lighting_shader.set_float("light.cutOff", math.cos(math.radians(12.5))) lighting_shader.set_float("light.outerCutOff", math.cos(math.radians(17.5))) lighting_shader.set_vec3("viewPos", camera.position) # -- light properties lighting_shader.set_vec3("light.ambient", Vector3([0.1, 0.1, 0.1])) # we configure the diffuse intensity slightly higher; the right lighting conditions differ with each lighting method and environment. # each environment and lighting type requires some tweaking to get the best out of your environment. lighting_shader.set_vec3("light.diffuse", Vector3([0.8, 0.8, 0.8])) lighting_shader.set_vec3("light.specular", Vector3([1.0, 1.0, 1.0])) lighting_shader.set_float("light.constant", 1.0) lighting_shader.set_float("light.linear", 0.09) lighting_shader.set_float("light.quadratic", 0.032) # -- material properties lighting_shader.set_float("material.shininess", 32.0) # -- view.projection transformations projection = Matrix44.perspective_projection(camera.zoom, SRC_WIDTH/SRC_HEIGHT, 0.1, 100.0) view = camera.get_view_matrix() lighting_shader.set_mat4("projection", projection) lighting_shader.set_mat4("view", view) # -- world transformation model = Matrix44.identity() lighting_shader.set_mat4("model", model) # -- bind diffuse map gl.glActiveTexture(gl.GL_TEXTURE0) gl.glBindTexture(gl.GL_TEXTURE_2D, diffuse_map) # -- bind specular map gl.glActiveTexture(gl.GL_TEXTURE1) gl.glBindTexture(gl.GL_TEXTURE_2D, specular_map) # -- render continers gl.glBindVertexArray(cube_vao) for idx, position in enumerate(cube_positions): angle = 20.0 * idx rotation = matrix44.create_from_axis_rotation([1.0, 0.3, 0.5], math.radians(angle)) translation = Matrix44.from_translation(position) model = translation * rotation lighting_shader.set_mat4('model', model) gl.glDrawArrays(gl.GL_TRIANGLES, 0, 36) # # -- draw lamp object # lamp_shader.use() # lamp_shader.set_mat4("projection", projection) # lamp_shader.set_mat4("view", view) # model = Matrix44.identity() # model *= Matrix44.from_translation(light_pos) # model *= Matrix44.from_scale(Vector3([.2, .2, .2])) # lamp_shader.set_mat4("model", model) # gl.glBindVertexArray(light_vao) # gl.glDrawArrays(gl.GL_TRIANGLES, 0, 36) glfw.swap_buffers(window) glfw.poll_events() gl.glDeleteVertexArrays(1, id(cube_vao)) gl.glDeleteVertexArrays(1, id(light_vao)) gl.glDeleteBuffers(1, id(vbo)) glfw.terminate()
def run(): if sdl2.SDL_Init(sdl2.SDL_INIT_VIDEO) != 0: print(sdl2.SDL_GetError()) return -1 window = sdl2.SDL_CreateWindow(b"OpenGL demo", sdl2.SDL_WINDOWPOS_UNDEFINED, sdl2.SDL_WINDOWPOS_UNDEFINED, 800, 600, sdl2.SDL_WINDOW_OPENGL) if not window: print(sdl2.SDL_GetError()) return -1 # Force OpenGL 3.3 'core' context. # Must set *before* creating GL context! video.SDL_GL_SetAttribute(video.SDL_GL_CONTEXT_MAJOR_VERSION, 3) video.SDL_GL_SetAttribute(video.SDL_GL_CONTEXT_MINOR_VERSION, 3) video.SDL_GL_SetAttribute(video.SDL_GL_CONTEXT_PROFILE_MASK, video.SDL_GL_CONTEXT_PROFILE_CORE) context = sdl2.SDL_GL_CreateContext(window) quad = [-0.5, -0.5, 0.0, 1.0, 0.0, 0.0, 0.5, -0.5, 0.0, 0.0, 1.0, 0.0, 0.5, 0.5, 0.0, 0.0, 0.0, 1.0, -0.5, 0.5, 0.0, 1.0, 1.0, 1.0] quad = numpy.array(quad, dtype=numpy.float32) indices = [0, 1, 2, 2, 3, 0] indices = numpy.array(indices, dtype=numpy.uint32) # Setup GL shaders, data, etc. vertex_shader = shaders.compileShader(""" #version 330 in vec3 position; in vec3 color; out vec3 newColor; void main() { gl_Position = vec4(position, 1.0f); newColor = color; } """ , GL.GL_VERTEX_SHADER) fragment_shader = shaders.compileShader(""" #version 330 in vec3 newColor; out vec4 outColor; void main() { outColor = vec4(newColor, 1.0f); } """ , GL.GL_FRAGMENT_SHADER) shaderProgram = shaders.compileProgram(vertex_shader, fragment_shader) GL.glUseProgram(shaderProgram) # Need VBO for triangle vertices and colours VBO = GL.glGenBuffers(1) GL.glBindBuffer(GL.GL_ARRAY_BUFFER, VBO) GL.glBufferData(GL.GL_ARRAY_BUFFER, 96, quad, GL.GL_STATIC_DRAW) EBO = GL.glGenBuffers(1) GL.glBindBuffer(GL.GL_ELEMENT_ARRAY_BUFFER, EBO) GL.glBufferData(GL.GL_ELEMENT_ARRAY_BUFFER, 24, indices, GL.GL_STATIC_DRAW) position = GL.glGetAttribLocation(shaderProgram, "position") GL.glVertexAttribPointer(position, 3, GL.GL_FLOAT, GL.GL_FALSE, 24, ctypes.c_void_p(0)) GL.glEnableVertexAttribArray(position) color = GL.glGetAttribLocation(shaderProgram, "color") GL.glVertexAttribPointer(color, 3, GL.GL_FLOAT, GL.GL_FALSE, 24, ctypes.c_void_p(12)) GL.glEnableVertexAttribArray(color) event = sdl2.SDL_Event() running = True GL.glClearColor(0, 0, 0, 1) while running: while sdl2.SDL_PollEvent(ctypes.byref(event)) != 0: if event.type == sdl2.SDL_QUIT: running = False try: GL.glClear(GL.GL_COLOR_BUFFER_BIT) GL.glDrawElements(GL.GL_TRIANGLES, 6, GL.GL_UNSIGNED_INT, None) finally: GL.glUseProgram(0) sdl2.SDL_GL_SwapWindow(window) sdl2.SDL_Delay(10) sdl2.SDL_GL_DeleteContext(context) sdl2.SDL_DestroyWindow(window) sdl2.SDL_Quit() return 0
def create_empty_buffer(size, target=gl.GL_ARRAY_BUFFER, usage=gl.GL_STATIC_DRAW): buf_id = gl.glGenBuffers(1) gl.glBindBuffer(target, buf_id) gl.glBufferData(target, size, None, usage) return buf_id
def __init__( self, img, global_alpha=1.0, apply_global_alpha=False, srgb=True, colour_mod=None, ): self.i_tex = gl.glGenTextures(1) self.set_img(img=img, srgb=srgb) # set up the shader i_vert = gl.glCreateShader(gl.GL_VERTEX_SHADER) gl.glShaderSource(i_vert, vert_shader) i_frag = gl.glCreateShader(gl.GL_FRAGMENT_SHADER) gl.glShaderSource(i_frag, frag_shader) self.program = gl.glCreateProgram() gl.glAttachShader(self.program, i_vert) gl.glAttachShader(self.program, i_frag) gl.glCompileShader(i_vert) gl.glCompileShader(i_frag) gl.glLinkProgram(self.program) gl.glValidateProgram(self.program) gl.glUseProgram(self.program) self.i_global_alpha = gl.glGetUniformLocation(self.program, "global_alpha") self.i_apply_global_alpha = gl.glGetUniformLocation( self.program, "apply_global_alpha" ) self.i_colour_mod = gl.glGetUniformLocation(self.program, "colour_mod") # set up the geometry i_pos = gl.glGetAttribLocation(self.program, "pos") self.i_vao = gl.glGenVertexArrays(1) i_vbo = gl.glGenBuffers(1) gl.glBindVertexArray(self.i_vao) gl.glBindBuffer(gl.GL_ARRAY_BUFFER, i_vbo) gl.glBufferData( gl.GL_ARRAY_BUFFER, # target points.nbytes, # size points, # data gl.GL_STATIC_DRAW, # usage ) gl.glEnableVertexAttribArray(i_pos) gl.glVertexAttribPointer( i_pos, # index 2, # size gl.GL_FLOAT, # type gl.GL_FALSE, # normalisation 0, # stride ctypes.c_void_p(0), # pointer ) for param in "ST": gl.glTexParameteri( gl.GL_TEXTURE_2D, getattr(gl, "GL_TEXTURE_WRAP_" + param), gl.GL_CLAMP_TO_EDGE, ) for param in ("MIN", "MAG"): gl.glTexParameteri( gl.GL_TEXTURE_2D, getattr(gl, "GL_TEXTURE_" + param + "_FILTER"), gl.GL_LINEAR, ) gl.glTexParameterfv(gl.GL_TEXTURE_2D, gl.GL_TEXTURE_BORDER_COLOR, np.zeros(4)) gl.glUseProgram(0) self.global_alpha = global_alpha self.apply_global_alpha = apply_global_alpha if colour_mod is None: self.colour_mod = (1.0,) * 3
def glize(node): model = node.transformation.astype(numpy.float32) gl.glUniformMatrix4fv( gl.glGetUniformLocation(shader, "model"), 1 , gl.GL_FALSE, model ) gl.glUniformMatrix4fv( gl.glGetUniformLocation(shader, "view"), 1 , gl.GL_FALSE, glm.value_ptr(view) ) gl.glUniformMatrix4fv( gl.glGetUniformLocation(shader, "projection"), 1 , gl.GL_FALSE, glm.value_ptr(projection) ) for mesh in node.meshes: #assert False , texture #prueba para ver el nombre de la textura texture_surface = pygame.image.load(getTexture(mesh)) texture_data = pygame.image.tostring(texture_surface, "RGB", 1) width = texture_surface.get_width() height = texture_surface.get_height() texture = gl.glGenTextures(1) gl.glBindTexture(gl.GL_TEXTURE_2D, texture) gl.glTexImage2D(gl.GL_TEXTURE_2D, 0, gl.GL_RGB, width, height, 0, gl.GL_RGB, gl.GL_UNSIGNED_BYTE, texture_data) gl.glGenerateMipmap(gl.GL_TEXTURE_2D) vertex_data = numpy.hstack(( numpy.array(mesh.vertices, dtype=numpy.float32), numpy.array(mesh.normals, dtype=numpy.float32), numpy.array(mesh.texturecoords[0], dtype=numpy.float32) )) index_data = numpy.hstack( numpy.array(mesh.faces, dtype=numpy.int32) ) vertex_buffer_object = gl.glGenVertexArrays(1) gl.glBindBuffer(gl.GL_ARRAY_BUFFER, vertex_buffer_object) gl.glBufferData(gl.GL_ARRAY_BUFFER, vertex_data.nbytes, vertex_data, gl.GL_STATIC_DRAW) gl.glVertexAttribPointer(0, 3, gl.GL_FLOAT, False, 9 * 4, None) gl.glEnableVertexAttribArray(0) gl.glVertexAttribPointer(1, 3, gl.GL_FLOAT, False, 9 * 4, ctypes.c_void_p(3 * 4)) gl.glEnableVertexAttribArray(1) gl.glVertexAttribPointer(2, 3, gl.GL_FLOAT, False, 9 * 4, ctypes.c_void_p(6 * 4)) gl.glEnableVertexAttribArray(2) element_buffer_object = gl.glGenBuffers(1) gl.glBindBuffer(gl.GL_ELEMENT_ARRAY_BUFFER, element_buffer_object) gl.glBufferData(gl.GL_ELEMENT_ARRAY_BUFFER, index_data.nbytes, index_data, gl.GL_STATIC_DRAW) diffuse = mesh.material.properties["diffuse"] gl.glUniform4f( gl.glGetUniformLocation(shader, "color"), *diffuse, 1 ) gl.glUniform4f( gl.glGetUniformLocation(shader, "light"), int(lighting.x), int(lighting.y), int(lighting.z), 1 ) gl.glDrawElements(gl.GL_TRIANGLES, len(index_data), gl.GL_UNSIGNED_INT, None) for child in node.children: glize(child)
def initializeGL(self): """Initialize OpenGL, VBOs, upload data on the GPU, etc.""" # background color gl.glClearColor(0.8, 0.8, 0.8, 0) # Make initial data array. # compile the vertex shader vs = compile_shader(VERTEX, gl.GL_VERTEX_SHADER) # compile the geometry shader gs = compile_shader(GEOMETRY, gl.GL_GEOMETRY_SHADER) # compile the fragment shader fs = compile_shader(FRAGMENT, gl.GL_FRAGMENT_SHADER) # Link the programs. self.render_program = link_shaders(vs, gs, fs) # Compile the compute shader cs = compile_shader(COMPUTE, gl.GL_COMPUTE_SHADER) # Create the compute shader buffers. self.makeBuffers() #self.vbo = glvbo.VBO(self.attributes) self.vbo = gl.glGenBuffers(1) gl.glBindBuffer(gl.GL_ARRAY_BUFFER, self.vbo) gl.glBufferData(gl.GL_ARRAY_BUFFER, self.attributes.nbytes, self.attributes, gl.GL_DYNAMIC_COPY) gl.glBindBuffer(gl.GL_ARRAY_BUFFER, 0) self.ssbo = gl.glGenBuffers(1) gl.glBindBufferBase(gl.GL_SHADER_STORAGE_BUFFER, 1, self.ssbo) gl.glBufferData(gl.GL_SHADER_STORAGE_BUFFER, self.velocities.nbytes, self.velocities, gl.GL_DYNAMIC_COPY) self.compute_program = link_shaders(cs)