def mainloop(): vp_valid, vp_size, view, projection = glut_navigation.update() angle1 = elapsed_ms() * math.pi * 2 / 5000.0 angle2 = elapsed_ms() * math.pi * 2 / 7333.0 model_matrices = [] for i in range(no_of_meshes): if i == 0: model = glm.mat4(1) model = glm.translate(model, glm.vec3(0, 0, -1)) else: angleY = angle1 + math.pi*2 * (i-1) / (no_of_meshes-1) model = glm.mat4(1) model = glm.rotate(model, angleY, glm.vec3(0, 0, 0.5)) model = glm.translate(model, glm.vec3(diameter/2, 0, 0.5)) model = glm.rotate(model, angle2, glm.vec3(0, 1, 0)) model_matrices.append(model) light_pos = glm.vec3(0, 0, 3) light_dir = glm.vec3(0, 0, -1) light_cone_angle_degree = 60 light_cone_cos = math.cos(math.radians(light_cone_angle_degree) / 2) shadow_proj = glm.perspective(glm.radians(light_cone_angle_degree + 1), 1, 0.1, 100.0) shadow_view = glm.lookAt(light_pos, light_pos+light_dir, glm.vec3(0,1,0)) glBindBuffer(GL_SHADER_STORAGE_BUFFER, model_ssbo) for i, model in enumerate(model_matrices): glBufferSubData(GL_SHADER_STORAGE_BUFFER, i*4*16, glm.sizeof(glm.mat4), glm.value_ptr(model)) glBindFramebuffer(GL_FRAMEBUFFER, shadow_fbo) glViewport(0, 0, *shadow_buffer_size) glClear(GL_DEPTH_BUFFER_BIT) glUseProgram(shadow_program) glUniformMatrix4fv(0, 1, GL_FALSE, glm.value_ptr(shadow_proj)) glUniformMatrix4fv(1, 1, GL_FALSE, glm.value_ptr(shadow_view)) glEnable(GL_POLYGON_OFFSET_FILL) glPolygonOffset(1.0, 1.0) model_multimesh.draw() glDisable(GL_POLYGON_OFFSET_FILL) glBindFramebuffer(GL_FRAMEBUFFER, 0) glViewport(0, 0, *vp_size) glClearColor(0.2, 0.3, 0.3, 1.0) glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT) glUseProgram(phong_program) glUniformMatrix4fv(0, 1, GL_FALSE, glm.value_ptr(projection)) glUniformMatrix4fv(1, 1, GL_FALSE, glm.value_ptr(view)) glUniformMatrix4fv(2, 1, GL_FALSE, glm.value_ptr(shadow_proj)) glUniformMatrix4fv(3, 1, GL_FALSE, glm.value_ptr(shadow_view)) glUniform4fv(4, 1, glm.value_ptr(glm.vec4(light_pos, 1))) glUniform4fv(5, 1, glm.value_ptr(glm.vec4(light_dir, light_cone_cos))) glBindTextureUnit(1, shadow_depth_to) model_multimesh.draw() glutSwapBuffers() glutPostRedisplay()
def updateUniformBuffers(self): self.uboVS['projection'] = glm.transpose( glm.perspectiveRH_ZO(glm.radians(60.0), self.width / self.height, 0.001, 256.0)) view = glm.transpose( glm.translate(glm.mat4(1.0), glm.vec3(0.0, 0.0, self.zoom))) self.uboVS['model'] = view * glm.translate(glm.mat4(1.0), self.cameraPos) self.uboVS['model'] = glm.rotate(self.uboVS['model'], glm.radians(self.rotation.x), glm.vec3(1.0, 0.0, 0.0)) self.uboVS['model'] = glm.rotate(self.uboVS['model'], glm.radians(self.rotation.y), glm.vec3(0.0, 1.0, 0.0)) self.uboVS['model'] = glm.rotate(self.uboVS['model'], glm.radians(self.rotation.z), glm.vec3(0.0, 0.0, 1.0)) self.uboVS['viewPos'] = glm.vec4(0.0, 0.0, -self.zoom, 0.0) uboVSSize = sum([glm.sizeof(ubo) for ubo in self.uboVS.values()]) uboVSBuffer = np.concatenate( (np.array(self.uboVS['projection']).flatten(order='C'), np.array(self.uboVS['model']).flatten(order='C'), np.array(self.uboVS['viewPos']).flatten(order='C'), np.array(self.uboVS['lodBias']).flatten(order='C'))) self.uniformBufferVS.map() self.uniformBufferVS.copyTo(uboVSBuffer, uboVSSize) self.uniformBufferVS.unmap()
def updateUniformBuffers(self): # see https://matthewwellings.com/blog/the-new-vulkan-coordinate-system/ #vulk=glm.mat4((1,0,0,0),(0,-1,0,0),(0,0,0.5,0),(0,0,0.5,1)) #self.uboVS['projectionMatrix'] = vulk*glm.perspective(glm.radians(60.0), self.width / self.height, 0.1, 256.0) #self.uboVS['projectionMatrix'] = glm.perspectiveRH_ZO(glm.radians(60.0), self.width / self.height, 0.1, 256.0) self.uboVS['projectionMatrix'] = glm.transpose( glm.perspectiveRH_ZO(glm.radians(60.0), self.width / self.height, 0.1, 256.0)) self.uboVS['viewMatrix'] = glm.transpose( glm.translate(glm.mat4(1.0), glm.vec3(0.0, 0.0, self.zoom))) self.uboVS['modelMatrix'] = glm.mat4(1.0) self.uboVS['modelMatrix'] = glm.rotate(self.uboVS['modelMatrix'], glm.radians(self.rotation.x), glm.vec3(1.0, 0.0, 0.0)) self.uboVS['modelMatrix'] = glm.rotate(self.uboVS['modelMatrix'], glm.radians(self.rotation.y), glm.vec3(0.0, 1.0, 0.0)) self.uboVS['modelMatrix'] = glm.rotate(self.uboVS['modelMatrix'], glm.radians(self.rotation.z), glm.vec3(0.0, 0.0, 1.0)) uboVSSize = sum([glm.sizeof(ubo) for ubo in self.uboVS.values()]) uboVSBuffer = np.concatenate( (np.array(self.uboVS['projectionMatrix']).flatten(order='C'), np.array(self.uboVS['modelMatrix']).flatten(order='C'), np.array(self.uboVS['viewMatrix']).flatten(order='C'))) data = vk.vkMapMemory(self.device, self.uniformBufferVS['memory'], 0, uboVSSize, 0) datawrapper = np.array(data, copy=False) np.copyto(datawrapper, uboVSBuffer.view(dtype=np.uint8), casting='no') vk.vkUnmapMemory(self.device, self.uniformBufferVS['memory'])
def prepareUniformBuffers(self): uboVSSize = sum([glm.sizeof(ubo) for ubo in self.uboVS.values()]) self.uniformBufferVS = self.vulkanDevice.createvksBuffer( vk.VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT, vk.VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | vk.VK_MEMORY_PROPERTY_HOST_COHERENT_BIT, uboVSSize) self.updateUniformBuffers()
def __mainloop(self): vp_valid, self.vp_size, view, projection = self.__glut_navigation.update() if not vp_valid: glViewport(0, 0, *self.vp_size) glUniformMatrix4fv(self.___uniform['u_proj'], 1, GL_FALSE, glm.value_ptr(projection)) glUniformMatrix4fv(self.___uniform['u_view'], 1, GL_FALSE, glm.value_ptr(view)) glClearColor(0.2, 0.3, 0.3, 1.0) glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT) if self.__auto_rotate: self.__angle1 = self.elapsed_ms() * math.pi * 2 / 5000.0 self.__angle2 = self.elapsed_ms() * math.pi * 2 / 7333.0 model_matrices = [] for i, mesh in enumerate(self.__meshes): angleY = self.__angle1 + math.pi*2 * i / len(self.__meshes) #angleY = math.pi*2 * i / len(self.__meshes) model = glm.mat4(1) model = glm.rotate(model, angleY, glm.vec3(0, 0, 1)) model = glm.translate(model, glm.vec3(self.__diameter/2, 0, 0)) model = glm.rotate(model, self.__angle2, glm.vec3(0, 1, 0)) model_matrices.append(model) multi_mesh = True if multi_mesh: glBindBuffer(GL_SHADER_STORAGE_BUFFER, self.__ssbo) for i, model in enumerate(model_matrices): glBufferSubData(GL_SHADER_STORAGE_BUFFER, i*4*16, glm.sizeof(glm.mat4), glm.value_ptr(model)) self.__multimesh.draw() else: for model, mesh in zip(model_matrices, self.__meshes): glBindBuffer(GL_SHADER_STORAGE_BUFFER, self.__ssbo) glBufferSubData(GL_SHADER_STORAGE_BUFFER, 0, glm.sizeof(glm.mat4), glm.value_ptr(model)) mesh.draw() glutSwapBuffers() glutPostRedisplay() if self.__sceen_shot: self.__sceen_shot = False image_data = glReadPixels(0, 0, *self.vp_size, GL_RGBA, GL_UNSIGNED_BYTE) image = Image.frombytes('RGBA', self.vp_size, image_data).transpose(method=Image.FLIP_TOP_BOTTOM) image.save(self.screenshot_prefix + time.strftime("_%Y%m%d_%H%M%S") + '.png', 'PNG')
def _Draw(self, time): if self.__voxel_map.invalid: glTextureSubImage3D(self.__voxel_tob, 0, 0, 0, 0, *self.__voxel_map.size, GL_RED_INTEGER, GL_UNSIGNED_BYTE, self.__voxel_map.data) self.__voxel_map.invalid = False glBindBuffer(GL_SHADER_STORAGE_BUFFER, self.__mvp_ssbo) glBufferSubData(GL_SHADER_STORAGE_BUFFER, 0, glm.sizeof(glm.mat4), glm.value_ptr(self.__model)) if self.__update_view: glBufferSubData(GL_SHADER_STORAGE_BUFFER, 1 * glm.sizeof(glm.mat4), glm.sizeof(glm.mat4), glm.value_ptr(self.__view)) if self.__update_proj: glBufferSubData(GL_SHADER_STORAGE_BUFFER, 2 * glm.sizeof(glm.mat4), glm.sizeof(glm.mat4), glm.value_ptr(self.__proj)) glBindBuffer(GL_SHADER_STORAGE_BUFFER, self.__cube_ssbo) glBufferSubData(GL_SHADER_STORAGE_BUFFER, 0, glm.sizeof(glm.mat4), glm.value_ptr(self.__voxel_map.cube_model)) glBufferSubData(GL_SHADER_STORAGE_BUFFER, glm.sizeof(glm.mat4), SIZEOF_FLAOT32, (ctypes.c_float * 1)(self.__color_mix)) glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT) glEnable(GL_DEPTH_TEST) glBindProgramPipeline(self.__draw_pipeline[0]) self.__cube.Bind() self.__cube.Draw()
def _Draw(self, time): self.__model = glm.mat4(1) angle1 = time * 2 * math.pi / 13 angle2 = time * 2 * math.pi / 17 #self.__model = glm.rotate(self.__model, angle1, glm.vec3(1, 0, 0) ) #self.__model = glm.rotate(self.__model, angle2, glm.vec3(0, 0, 1) ) glBindBuffer(GL_SHADER_STORAGE_BUFFER, self.__mvp_ssbo ) glBufferSubData(GL_SHADER_STORAGE_BUFFER, 0, glm.sizeof(glm.mat4), glm.value_ptr(self.__model)) if self.__update_view: glBufferSubData(GL_SHADER_STORAGE_BUFFER, 1*glm.sizeof(glm.mat4), glm.sizeof(glm.mat4), glm.value_ptr(self.__view)) glClearColor(0.3, 0.3, 0.3, 1.0) glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT) self.__cube.Draw()
def __init__(self, vkdevice, queue): self.vulkanDevice = vkdevice self.queue = queue self.descriptorPool = None # We will be using separate descriptor sets (and bindings) # for material and scene related uniforms self.descriptorSetLayouts = {'material': None, 'scene': None} # We will be using one single index and vertex buffer # containing vertices and indices for all meshes in the scene # This allows us to keep memory allocations down self.vertexShape = np.dtype([('pos', np.float32, (3, )), ('normal', np.float32, (3, )), ('uv', np.float32, (2, )), ('color', np.float32, (3, )) ]) #position, normal, uv, color self.vertexBuffer = None self.indexBuffer = None self.descriptorSetScene = None self.aScene = None self.assetPath = "" # Shader properites for a material # Will be passed to the shaders using push constant self.scenematerialShape = { 'ambient': glm.vec4(0.0), 'diffuse': glm.vec4(0.0), 'specular': glm.vec4(0.0), 'opacity': glm.vec1(0.0) } self.materials = [] self.meshes = [] # Shared ubo containing matrices used by all # materials and meshes self.uniformBuffer = None self.uniformData = { 'projection': glm.mat4(), 'view': glm.mat4(), 'model': glm.mat4(), 'lightPos': glm.vec4(1.25, 8.35, 0.0, 0.0) } # Scene uses multiple pipelines self.pipelines = {'solid': None, 'blending': None, 'wireframe': None} # Shared pipeline layout self.pipelineLayout = None # For displaying only a single part of the scene self.renderSingleScenePart = False self.scenePartIndex = 0 # TODO if that does not work, do not use createvksBuffer but do it by hand as in the demo uboSize = sum([glm.sizeof(ubo) for ubo in self.uniformData.values()]) self.uniformBuffer = self.vulkanDevice.createvksBuffer( vk.VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT, vk.VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | vk.VK_MEMORY_PROPERTY_HOST_COHERENT_BIT, uboSize) self.uniformBuffer.map()
def sub_data(self, offset: int, data): """ Set the data of a specific range in this buffer. Args: offset (int): the offset (in bytes) of where to start setting data size (int): the size (in bytes) of the data to set data ([type]): the data """ glBufferSubData(self.target, offset, glm.sizeof(type(data)), glm.value_ptr(data))
def render(self, cmdBuffer, wireframe): offsets = [0] # Bind scene vertex and index buffers vk.vkCmdBindVertexBuffers(cmdBuffer, 0, 1, [self.vertexBuffer.buffer], offsets) vk.vkCmdBindIndexBuffer(cmdBuffer, self.indexBuffer.buffer, 0, vk.VK_INDEX_TYPE_UINT32) for i in range(len(self.meshes)): if self.renderSingleScenePart and i != self.scenePartIndex: continue # TODO : per material pipelines # vkCmdBindPipeline(cmdBuffer, VK_PIPELINE_BIND_POINT_GRAPHICS, *mesh.material->pipeline); # We will be using multiple descriptor sets for rendering # In GLSL the selection is done via the set and binding keywords # VS: layout (set = 0, binding = 0) uniform UBO; # FS: layout (set = 1, binding = 0) uniform sampler2D samplerColorMap; descriptorSets = [] descriptorSets.append(self.descriptorSetScene) descriptorSets.append(self.meshes[i]['material']['descriptorSet']) vk.vkCmdBindPipeline( cmdBuffer, vk.VK_PIPELINE_BIND_POINT_GRAPHICS, self.pipelines['wireframe'] if wireframe else self.meshes[i]['material']['pipeline']) vk.vkCmdBindDescriptorSets(cmdBuffer, vk.VK_PIPELINE_BIND_POINT_GRAPHICS, self.pipelineLayout, 0, len(descriptorSets), descriptorSets, 0, None) # Pass material properies via push constants propertiesSize = sum([ glm.sizeof(pdata) for pdata in self.meshes[i]['material']['properties'].values() ]) propertiesData = np.concatenate( (np.array(self.meshes[i]['material']['properties'] ['ambient']).flatten(order='C'), np.array(self.meshes[i]['material']['properties'] ['diffuse']).flatten(order='C'), np.array(self.meshes[i]['material']['properties'] ['specular']).flatten(order='C'), np.array(self.meshes[i]['material']['properties'] ['opacity']).flatten(order='C'))) vk.vkCmdPushConstants( cmdBuffer, self.pipelineLayout, vk.VK_SHADER_STAGE_FRAGMENT_BIT, 0, propertiesSize, propertiesData.__array_interface__['data'][0]) # Render from the global scene vertex buffer using the mesh index offset vk.vkCmdDrawIndexed(cmdBuffer, self.meshes[i]['indexCount'], 1, 0, self.meshes[i]['indexBase'], 0)
def updateUniformBuffers(self): if self.attachLight: self.scene.uniformData['lightPos'] = glm.vec4( -self.camera.position, 1.0) self.scene.uniformData['projection'] = self.camera.matrices[ 'perspective'] self.scene.uniformData['view'] = self.camera.matrices['view'] self.scene.uniformData['model'] = glm.mat4(1.0) uDataSize = sum( [glm.sizeof(udata) for udata in self.scene.uniformData.values()]) uData = np.concatenate( (np.array(self.scene.uniformData['projection']).flatten(order='C'), np.array(self.scene.uniformData['view']).flatten(order='C'), np.array(self.scene.uniformData['model']).flatten(order='C'), np.array(self.scene.uniformData['lightPos']).flatten(order='C'))) self.scene.uniformBuffer.copyTo(uData, uDataSize)
def draw(self, opengl_frame): self.status_text.set( f"fps {opengl_frame.fps:.03f} frame: {opengl_frame.number_of_frames:05d}" ) vp_valid, vp_size, view, projection = self.__tkinter_navigation.update( ) if not vp_valid: glViewport(0, 0, *vp_size) if self.cull_mode == 0: glDisable(GL_CULL_FACE) else: glEnable(GL_CULL_FACE) glCullFace(GL_FRONT if self.cull_mode == 2 else GL_BACK) glPolygonMode( GL_FRONT_AND_BACK, GL_POINT if self.polygon_mode == 0 else GL_LINE if self.polygon_mode == 1 else GL_FILL) glUniformMatrix4fv(self.___uniform['u_proj'], 1, GL_FALSE, glm.value_ptr(projection)) glUniformMatrix4fv(self.___uniform['u_view'], 1, GL_FALSE, glm.value_ptr(view)) glClearColor(0.2, 0.3, 0.3, 1.0) glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT) angle1 = 0 # self.elapsed_ms() * math.pi * 2 / 5000.0 angle2 = 0 # self.elapsed_ms() * math.pi * 2 / 7333.0 model = glm.mat4(1) model = glm.rotate(model, angle1, glm.vec3(0, 0, 1)) model = glm.rotate(model, angle2, glm.vec3(0, 1, 0)) multi_mesh = True index = self.shape_index if index < len(self.__meshes): glBindBuffer(GL_SHADER_STORAGE_BUFFER, self.__ssbo) glBufferSubData(GL_SHADER_STORAGE_BUFFER, 0, glm.sizeof(glm.mat4), glm.value_ptr(model)) if multi_mesh: self.__multimesh.draw_range(index, index + 1) else: self.__meshes[index].draw()
def configura_VAO_e_VBO_triangulo(color_VBO, lista_cores, indiceVAO, data): gl.glBindVertexArray(VAO[indiceVAO]) gl.glBindBuffer(gl.GL_ARRAY_BUFFER, VBO[indiceVAO]) # Efetua o bind do VBO gl.glBufferData(target=gl.GL_ARRAY_BUFFER, size=glm.sizeof(data), data=glm.value_ptr(data), usage=gl.GL_STATIC_DRAW) local = gl.glGetAttribLocation(shaderProgram, 'vPos') vertexDim = 3 # quantidade de elementos do vetor declarado no shader stride = 0 # Espaço em bytes até o próximo valor. E.g. próximo x, quando for posição (X | Y | Z | X | Y | ...) offset = None # Onde os dados iniciam no Vertex Buffer # Descreve a forma de organização dos dados dentro do último buffer (VBO) vinculado (glBindBuffer) gl.glVertexAttribPointer(local, vertexDim, gl.GL_FLOAT, gl.GL_FALSE, stride, offset) gl.glEnableVertexAttribArray( local) # Associa e habilita os dados do Vertex Buffer (VBO) no Array colors_to_buffer = np.array(lista_cores, dtype=np.float32) gl.glBindBuffer(gl.GL_ARRAY_BUFFER, color_VBO[indiceVAO]) # Efetua o bind do VBO gl.glBufferData(gl.GL_ARRAY_BUFFER, (ctypes.c_float * len(colors_to_buffer))(*colors_to_buffer), gl.GL_DYNAMIC_DRAW) # usando ctypes local_vCor = gl.glGetAttribLocation(shaderProgram, 'vCor') tam_cores = 3 # Quantidade valores que definem a cor (tipo vec3) stride = 0 # Espaço entre os dados de cor offset = None # Onde os dados iniciam no Vertex Buffer # Descreve a forma de organização dos dados dentro do último buffer (VBO) vinculado (glBindBuffer) gl.glVertexAttribPointer(local_vCor, tam_cores, gl.GL_FLOAT, gl.GL_FALSE, stride, offset) gl.glEnableVertexAttribArray( local_vCor ) # Associa e habilita os dados do Vertex Buffer (VBO) no Array # Desvincula o VAO, VBO gl.glBindVertexArray(0) # Importante: Unbind do VAO primeiro gl.glDisableVertexAttribArray(local) gl.glDisableVertexAttribArray(local_vCor) gl.glBindBuffer(gl.GL_ARRAY_BUFFER, 0)
def prepareUniformBuffers(self): """ Prepare and initialize a uniform buffer block containing shader uniforms Single uniforms like in OpenGL are no longer present in Vulkan. All Shader uniforms are passed via uniform buffer blocks """ # Vertex shader uniform buffer block uboVSSize = sum([glm.sizeof(ubo) for ubo in self.uboVS.values()]) bufferInfo = vk.VkBufferCreateInfo( sType=vk.VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO, size=uboVSSize, # This buffer will be used as a uniform buffer usage=vk.VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT) # Create a new buffer self.uniformBufferVS['buffer'] = vk.vkCreateBuffer( self.device, bufferInfo, None) # Get memory requirements including size, alignment and memory type memReqs = vk.vkGetBufferMemoryRequirements( self.device, self.uniformBufferVS['buffer']) # Get the memory type index that supports host visibile memory access # Most implementations offer multiple memory types and selecting the correct one to allocate memory from is crucial # We also want the buffer to be host coherent so we don't have to flush (or sync after every update. #Note: This may affect performance so you might not want to do this in a real world application that updates buffers on a regular base allocInfo = vk.VkMemoryAllocateInfo( sType=vk.VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO, pNext=None, allocationSize=memReqs.size, memoryTypeIndex=self.vulkanDevice.getMemoryType( memReqs.memoryTypeBits, vk.VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | vk.VK_MEMORY_PROPERTY_HOST_COHERENT_BIT)) # Allocate memory for the uniform buffer self.uniformBufferVS['memory'] = vk.vkAllocateMemory( self.device, allocInfo, None) # Bind memory to buffer vk.vkBindBufferMemory(self.device, self.uniformBufferVS['buffer'], self.uniformBufferVS['memory'], 0) # Store information in the uniform's descriptor that is used by the descriptor set self.uniformBufferVS['descriptor'] = vk.VkDescriptorBufferInfo( buffer=self.uniformBufferVS['buffer'], offset=0, range=uboVSSize) self.updateUniformBuffers()
def display(self): global last_time global total_time currentTime = time.time() uint_zeros = [0, 0, 0, 0] float_zeros = [0.0, 0.0, 0.0, 0.0] float_ones = [1.0, 1.0, 1.0, 1.0] draw_buffers = [GL_COLOR_ATTACHMENT0, GL_COLOR_ATTACHMENT1] if (not paused): total_time += (currentTime - last_time) last_time = currentTime t = total_time glBindFramebuffer(GL_FRAMEBUFFER, gbuffer) glViewport(0, 0, self.width, self.height) glDrawBuffers(2, draw_buffers) glClearBufferuiv(GL_COLOR, 0, uint_zeros) glClearBufferuiv(GL_COLOR, 1, uint_zeros) glClearBufferfv(GL_DEPTH, 0, float_ones) glBindBufferBase(GL_UNIFORM_BUFFER, 0, render_transform_ubo) matrices = glMapBufferRange( GL_UNIFORM_BUFFER, 0, (2 + NUM_INSTANCES) * glm.sizeof(glm.mat4), GL_MAP_WRITE_BIT | GL_MAP_INVALIDATE_BUFFER_BIT) matricesp = (GLfloat * 16 * (2 + NUM_INSTANCES)).from_address(matrices) proj_matrix = (GLfloat * 16)(*identityMatrix) proj_matrix = m3dPerspective(m3dDegToRad(50.0), float(self.width) / float(self.height), 0.1, 1000.0) matricesp[0] = proj_matrix d = (sin(t * 0.131) + 2.0) * 0.15 eye_pos = (d * 120.0 * sin(t * 0.11), 5.5, d * 120.0 * cos(t * 0.01)) view_matrix = (GLfloat * 16)(*identityMatrix) view_matrix = m3dLookAt(eye_pos, (0.0, -20.0, 0.0), (0.0, 1.0, 0.0)) matricesp[1] = (GLfloat * 16)(*view_matrix) for j in range(0, 15): j_f = float(j) for i in range(0, 15): i_f = float(i) T = (GLfloat * 16)(*identityMatrix) m3dTranslateMatrix44(T, (i - 7.5) * 7.0, 0.0, (j - 7.5) * 11.0) matricesp[j * 15 + i + 2] = T glUnmapBuffer(GL_UNIFORM_BUFFER) glUseProgram(render_program_nm if use_nm else render_program) glActiveTexture(GL_TEXTURE0) glBindTexture(GL_TEXTURE_2D, tex_diffuse) glActiveTexture(GL_TEXTURE1) glBindTexture(GL_TEXTURE_2D, tex_nm) glEnable(GL_DEPTH_TEST) glDepthFunc(GL_LEQUAL) myobject.render(NUM_INSTANCES) glBindFramebuffer(GL_FRAMEBUFFER, 0) glViewport(0, 0, self.width, self.height) glDrawBuffer(GL_BACK) glActiveTexture(GL_TEXTURE0) glBindTexture(GL_TEXTURE_2D, gbuffer_tex[0]) glActiveTexture(GL_TEXTURE1) glBindTexture(GL_TEXTURE_2D, gbuffer_tex[1]) if (vis_mode == VIS_OFF): glUseProgram(light_program) else: glUseProgram(vis_program) glUniform1i(loc_vis_mode, vis_mode) glDisable(GL_DEPTH_TEST) glBindBufferBase(GL_UNIFORM_BUFFER, 0, light_ubo) size_light_t = ctypes.sizeof(ctypes.c_float) * 6 lights = glMapBufferRange( GL_UNIFORM_BUFFER, 0, NUM_LIGHTS * size_light_t, GL_MAP_WRITE_BIT | GL_MAP_INVALIDATE_BUFFER_BIT) lightsp = (GLfloat * 6 * NUM_LIGHTS).from_address(lights) for i in range(0, NUM_LIGHTS): i_f = (i - 7.5) * 0.1 + 0.3 lightsp[i][0:3] = glm.vec3( 100.0 * sin(t * 1.1 + (5.0 * i_f)) * cos(t * 2.3 + (9.0 * i_f)), 15.0, 100.0 * sin(t * 1.5 + (6.0 * i_f)) * cos(t * 1.9 + (11.0 * i_f))) lightsp[i][3:6] = glm.vec3( cos(i_f * 14.0) * 0.5 + 0.8, sin(i_f * 17.0) * 0.5 + 0.8, sin(i_f * 13.0) * cos(i_f * 19.0) * 0.5 + 0.8) glUnmapBuffer(GL_UNIFORM_BUFFER) glBindVertexArray(fs_quad_vao) glDrawArrays(GL_TRIANGLE_STRIP, 0, 4) glBindTexture(GL_TEXTURE_2D, 0) glActiveTexture(GL_TEXTURE0) glBindTexture(GL_TEXTURE_2D, 0) glutSwapBuffers()
def __init__(self, width, height): global gbuffer_tex global gbuffer global fs_quad_vao global light_ubo global render_transform_ubo global myobject global tex_nm global tex_diffuse glGenFramebuffers(1, gbuffer) glBindFramebuffer(GL_FRAMEBUFFER, gbuffer) gbuffer_tex = [glGenTextures(1) for _ in range(3)] glBindTexture(GL_TEXTURE_2D, gbuffer_tex[0]) glTexStorage2D(GL_TEXTURE_2D, 1, GL_RGBA32UI, MAX_DISPLAY_WIDTH, MAX_DISPLAY_HEIGHT) glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST) glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST) glBindTexture(GL_TEXTURE_2D, gbuffer_tex[1]) glTexStorage2D(GL_TEXTURE_2D, 1, GL_RGBA32F, MAX_DISPLAY_WIDTH, MAX_DISPLAY_HEIGHT) glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST) glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST) glBindTexture(GL_TEXTURE_2D, gbuffer_tex[2]) glTexStorage2D(GL_TEXTURE_2D, 1, GL_DEPTH_COMPONENT32F, MAX_DISPLAY_WIDTH, MAX_DISPLAY_HEIGHT) glFramebufferTexture(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, gbuffer_tex[0], 0) glFramebufferTexture(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT1, gbuffer_tex[1], 0) glFramebufferTexture(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, gbuffer_tex[2], 0) glBindFramebuffer(GL_FRAMEBUFFER, 0) glGenVertexArrays(1, fs_quad_vao) glBindVertexArray(fs_quad_vao) myobject.load("ladybug.sbm") tex_nm = ktxobject.ktx_load("ladybug_nm.ktx") tex_diffuse = ktxobject.ktx_load("ladybug_co.ktx") load_shaders() light_ubo = glGenBuffers(1) glBindBuffer(GL_UNIFORM_BUFFER, light_ubo) size_light_t = ctypes.sizeof(ctypes.c_float) * 6 glBufferData(GL_UNIFORM_BUFFER, NUM_LIGHTS * size_light_t, None, GL_DYNAMIC_DRAW) render_transform_ubo = glGenBuffers(1) glBindBuffer(GL_UNIFORM_BUFFER, render_transform_ubo) glBufferData(GL_UNIFORM_BUFFER, (2 + NUM_INSTANCES) * glm.sizeof(glm.mat4), None, GL_DYNAMIC_DRAW)
def _Init(self): # create cube mesh self.__cube = GL_MeshCube() # model view projection data shader storage block self.__model = glm.mat4(1) self.__view = glm.lookAt(glm.vec3(0,-3,0), glm.vec3(0,0,0), glm.vec3(0,0,1)) self.__proj = glm.perspective(glm.radians(90), self.__vp_size[0]/self.__vp_size[1], 0.1, 100) buffer_data = np.zeros(3*16, dtype=np.float32) for i in range(4): for j in range(4): buffer_data temp_ssbo = np.empty(1, dtype=np.uint32) glCreateBuffers(len(temp_ssbo), temp_ssbo) self.__mvp_ssbo = temp_ssbo[0] dynamic_mvp_data = True code = 0 if not dynamic_mvp_data else GL_DYNAMIC_STORAGE_BIT | GL_MAP_WRITE_BIT| GL_MAP_PERSISTENT_BIT glNamedBufferStorage(self.__mvp_ssbo, 3*16*SIZEOF_FLAOT32, None, code) glBindBufferBase(GL_SHADER_STORAGE_BUFFER, 1, self.__mvp_ssbo) ssbo_buffer = np.empty([16*3], dtype=np.float32) #modelbuffer = np.frombuffer(glm.value_ptr(self.__model), dtype=float) #viewbuffer = np.frombuffer(glm.value_ptr(self.__view), dtype=float) #projbuffer = np.frombuffer(glm.value_ptr(self.__proj), dtype=float) #glBufferSubData(GL_SHADER_STORAGE_BUFFER, 0, glm.sizeof(glm.mat4), modelbuffer) #glBufferSubData(GL_SHADER_STORAGE_BUFFER, 1*glm.sizeof(glm.mat4), glm.sizeof(glm.mat4), viewbuffer) #glBufferSubData(GL_SHADER_STORAGE_BUFFER, 2*glm.sizeof(glm.mat4), glm.sizeof(glm.mat4), projbuffer) #np.put(ssbo_buffer, [i for i in range(16)], glm.value_ptr(self.__model)) glBufferSubData(GL_SHADER_STORAGE_BUFFER, 0, glm.sizeof(glm.mat4), glm.value_ptr(self.__model)) glBufferSubData(GL_SHADER_STORAGE_BUFFER, 1*glm.sizeof(glm.mat4), glm.sizeof(glm.mat4), glm.value_ptr(self.__view)) glBufferSubData(GL_SHADER_STORAGE_BUFFER, 2*glm.sizeof(glm.mat4), glm.sizeof(glm.mat4), glm.value_ptr(self.__proj)) # light data shader storage block light_data = [-1.0, -0.5, -2.0, 0.0, 0.2, 0.8, 0.8, 10.0] light_data_buffer = np.array( light_data, dtype=np.float32 ) temp_ssbo = np.empty(1, dtype=np.uint32) glCreateBuffers(len(temp_ssbo), temp_ssbo) self.__light_ssbo = temp_ssbo[0] dynamic_light_data = True code = 0 if not dynamic_light_data else GL_DYNAMIC_STORAGE_BIT | GL_MAP_WRITE_BIT| GL_MAP_PERSISTENT_BIT glNamedBufferStorage(self.__light_ssbo, light_data_buffer.nbytes, light_data_buffer, code) glBindBufferBase(GL_SHADER_STORAGE_BUFFER, 2, self.__light_ssbo) # set states glEnable(GL_DEPTH_TEST) self.__cube.Bind() # initialize (compile and link) shader program # This should be done after all OpenGL states have been set, # because NVIDIA optimize the current program for the current states an would have to recompile it if the states would change. # https://www.opengl.org/discussion_boards/showthread.php/175944-NVidia-280-x-and-GeForce-4xx?p=1229120&viewfull=1#post1229120 if os.path.isfile(spv_vert_draw_file) and os.path.isfile(spv_frag_draw_file): self.__draw_prog = GL_Program_SpirV(spv_vert_draw_file, spv_frag_draw_file) else: self.__draw_prog = GL_Program_GLSL(glsl_vert_draw_file, glsl_frag_draw_file) # create pipeline for draw mesh self.__draw_pipeline = np.empty(1, dtype=np.uint32) glGenProgramPipelines(1, self.__draw_pipeline) glUseProgramStages(self.__draw_pipeline[0], GL_VERTEX_SHADER_BIT | GL_FRAGMENT_SHADER_BIT, self.__draw_prog.Object()) #al = ['inPos', 'inNV', 'inCol'] #self.___attrib = self.__draw_prog.AttributeLocations(al) #print(self.___attrib) #ul = ['u_model', 'u_view', 'u_proj'] #self.__uniform = self.__draw_prog.UniformLocations(ul) #print(self.__uniform) # activate program and set states glBindProgramPipeline(self.__draw_pipeline[0])
def __init__(self, width, height): global m_vao global m_vbo i = 0 j = 0 load_shaders() initial_positions = [glm.vec4() for _ in range(POINTS_TOTAL)] initial_velocities = [glm.vec3() for _ in range(POINTS_TOTAL)] connection_vectors = [glm.ivec3() for _ in range(POINTS_TOTAL)] n = 0 for j in range(0, POINTS_Y): fj = float(j) / float(POINTS_Y) for i in range(0, POINTS_X): fi = float(i) / float(POINTS_X) initial_positions[n] = glm.vec4((fi - 0.5) * float(POINTS_X), (fj - 0.5) * float(POINTS_Y), 0.6 * sin(fi) * cos(fj), 1.0) initial_velocities[n] = glm.vec3(0.0) connection_vectors[n] = glm.ivec4(-1) if (j != (POINTS_Y - 1)): if (i != 0): connection_vectors[n][0] = n - 1 if (j != 0): connection_vectors[n][1] = n - POINTS_X if (i != (POINTS_X - 1)): connection_vectors[n][2] = n + 1 if (j != (POINTS_Y - 1)): connection_vectors[n][3] = n + POINTS_X n += 1 for i in range(0, 2): glGenVertexArrays(1, m_vao[i]) for i in range(0, 5): glGenBuffers(i + 1, m_vbo[i]) for i in range(0, 2): glBindVertexArray(m_vao[i]) glBindBuffer(GL_ARRAY_BUFFER, m_vbo[POSITION_A + i]) # POSITION_A glBindBuffer(GL_ARRAY_BUFFER, m_vbo[POSITION_A + i]) ar_position = np.empty([POINTS_TOTAL, 4], dtype='float32') for j, e in enumerate(initial_positions): ar_position[j] = e glBufferData(GL_ARRAY_BUFFER, POINTS_TOTAL * glm.sizeof(glm.vec4()), ar_position, GL_DYNAMIC_COPY) glVertexAttribPointer(0, 4, GL_FLOAT, GL_FALSE, 0, None) glEnableVertexAttribArray(0) # VELOCITY_A glBindBuffer(GL_ARRAY_BUFFER, m_vbo[VELOCITY_A + i]) ar_velocities = np.empty([POINTS_TOTAL, 3], dtype='float32') for j, e in enumerate(initial_velocities): ar_velocities[j] = e glBufferData(GL_ARRAY_BUFFER, POINTS_TOTAL * glm.sizeof(glm.vec3()), ar_velocities, GL_DYNAMIC_COPY) glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, 0, None) glEnableVertexAttribArray(1) # CONNECTION glBindBuffer(GL_ARRAY_BUFFER, m_vbo[CONNECTION]) ar_connection = np.empty([POINTS_TOTAL, 4], dtype='uint32') for j, e in enumerate(connection_vectors): ar_connection[j] = e glBufferData(GL_ARRAY_BUFFER, POINTS_TOTAL * glm.sizeof(glm.ivec4()), ar_connection, GL_STATIC_DRAW) glVertexAttribIPointer(2, 4, GL_INT, 0, None) glEnableVertexAttribArray(2) glGenTextures(2, m_pos_tbo) glBindTexture(GL_TEXTURE_BUFFER, m_pos_tbo[0]) glTexBuffer(GL_TEXTURE_BUFFER, GL_RGBA32F, m_vbo[POSITION_A]) glBindTexture(GL_TEXTURE_BUFFER, m_pos_tbo[1]) glTexBuffer(GL_TEXTURE_BUFFER, GL_RGBA32F, m_vbo[POSITION_B]) lines = (POINTS_X - 1) * POINTS_Y + (POINTS_Y - 1) * POINTS_X glGenBuffers(1, m_index_buffer) glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, m_index_buffer) glBufferData(GL_ELEMENT_ARRAY_BUFFER, lines * 2 * ctypes.sizeof(ctypes.c_int), None, GL_STATIC_DRAW) e = glMapBufferRange(GL_ELEMENT_ARRAY_BUFFER, 0, lines * 2 * ctypes.sizeof(ctypes.c_int), GL_MAP_WRITE_BIT | GL_MAP_INVALIDATE_BUFFER_BIT) int_array = (ctypes.c_int * (4 * lines * 2)).from_address(e) n = 0 for j in range(0, POINTS_Y): for i in range(0, POINTS_X - 1): int_array[n] = i + j * POINTS_X n += 1 int_array[n] = 1 + i + j * POINTS_X n += 1 for i in range(0, POINTS_X): for j in range(0, POINTS_Y - 1): int_array[n] = i + j * POINTS_X n += 1 int_array[n] = POINTS_X + i + j * POINTS_X n += 1 glUnmapBuffer(GL_ELEMENT_ARRAY_BUFFER)
def __init__(self, width, height): global render_prog global star_vao global star_buffer global uniforms global star_texture self.width = width self.height = height vs = GLuint(0) fs = GLuint(0) fs_source = ''' #version 410 core layout (location = 0) out vec4 color; uniform sampler2D tex_star; flat in vec4 starColor; void main(void) { color = starColor * texture(tex_star, gl_PointCoord); //color.r = 1.0; } ''' vs_source = ''' #version 410 core layout (location = 0) in vec4 position; layout (location = 1) in vec4 color; uniform float time; uniform mat4 proj_matrix; flat out vec4 starColor; void main(void) { vec4 newVertex = position; newVertex.z += time; newVertex.z = fract(newVertex.z); float size = (20.0 * newVertex.z * newVertex.z); starColor = smoothstep(1.0, 7.0, size) * color; newVertex.z = (999.9 * newVertex.z) - 1000.0; gl_Position = proj_matrix * newVertex; gl_PointSize = size; } ''' vs = glCreateShader(GL_VERTEX_SHADER) glShaderSource(vs, vs_source) glCompileShader(vs) if not glGetShaderiv(vs, GL_COMPILE_STATUS): print( 'compile error:' ) print( glGetShaderInfoLog(vs) ) fs = glCreateShader(GL_FRAGMENT_SHADER) glShaderSource(fs, fs_source) glCompileShader(fs) if not glGetShaderiv(fs, GL_COMPILE_STATUS): print( 'compile error:' ) print( glGetShaderInfoLog(fs) ) render_prog = glCreateProgram() glAttachShader(render_prog, vs) glAttachShader(render_prog, fs) glLinkProgram(render_prog) if not glGetProgramiv(render_prog, GL_LINK_STATUS): print( 'link error:' ) print( glGetProgramInfoLog(render_prog) ) glDeleteShader(vs) glDeleteShader(fs) uniforms.time = glGetUniformLocation(render_prog, "time") uniforms.proj_matrix = glGetUniformLocation(render_prog, "proj_matrix") star_texture = ktxobject.ktx_load("star.ktx") glGenVertexArrays(1, star_vao) glBindVertexArray(star_vao) class star_t: position = glm.vec3 color = glm.vec3 size_star_t = ctypes.sizeof(ctypes.c_float) * 6; # same as glm.sizeof(glm.vec3) * 2 glGenBuffers(1, star_buffer) glBindBuffer(GL_ARRAY_BUFFER, star_buffer) glBufferData(GL_ARRAY_BUFFER, NUM_STARS * size_star_t, None, GL_STATIC_DRAW) star = glMapBufferRange(GL_ARRAY_BUFFER, 0, NUM_STARS * size_star_t, GL_MAP_WRITE_BIT | GL_MAP_INVALIDATE_BUFFER_BIT) m = (GLfloat * 6 * NUM_STARS).from_address(star) for i in range(0, 1000): m[i][0] = (random_float() * 2.0 - 1.0) * 100.0 m[i][1] = (random_float() * 2.0 - 1.0) * 100.0 m[i][2] = random_float() m[i][3] = 0.8 + random_float() * 0.2 m[i][4] = 0.8 + random_float() * 0.2 m[i][5] = 0.8 + random_float() * 0.2 glUnmapBuffer(GL_ARRAY_BUFFER) glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, size_star_t, None) glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, size_star_t, ctypes.c_void_p(glm.sizeof(glm.vec3) ) ) glEnableVertexAttribArray(0) glEnableVertexAttribArray(1)
def loadMaterials(self): for i in range(len(self.aScene.materials)): m = self.aScene.materials[i] scenematerial = { 'name': None, 'properties': { 'ambient': glm.vec4(0.0), 'diffuse': glm.vec4(0.0), 'specular': glm.vec4(0.0), 'opacity': glm.vec1(0.0) }, 'diffuse': vks.vulkantexture.Texture2D(), 'descriptorSet': None, 'pipeline': None } scenematerial['name'] = m.properties.get(AI_MATKEY_NAME) color = m.properties.get( AI_MATKEY_COLOR_AMBIENT ) # returned as a list r, g, b, a hopefully if color: scenematerial['properties']['ambient'] = glm.vec4( color) + glm.vec4(0.1) color = m.properties.get(AI_MATKEY_COLOR_DIFFUSE) if color: scenematerial['properties']['diffuse'] = glm.vec4(color) color = m.properties.get(AI_MATKEY_COLOR_SPECULAR) if color: scenematerial['properties']['specular'] = glm.vec4(color) if m.properties.get(AI_MATKEY_OPACITY): scenematerial['properties']['opacity'] = glm.vec1( m.properties.get(AI_MATKEY_OPACITY)) if scenematerial['properties']['opacity'] > glm.vec1(0.0): scenematerial['properties']['specular'] = glm.vec4(0.0) print("Material: \"" + scenematerial['name'] + "\"") # Textures texFormatSuffix = "" texFormat = None # Get supported compressed texture format if self.vulkanDevice.features.textureCompressionBC: texFormatSuffix = "_bc3_unorm" texFormat = vk.VK_FORMAT_BC3_UNORM_BLOCK elif self.vulkanDevice.features.textureCompressionASTC_LDR: texFormatSuffix = "_astc_8x8_unorm" texFormat = vk.VK_FORMAT_ASTC_8x8_UNORM_BLOCK elif self.vulkanDevice.features.textureCompressionETC2: texFormatSuffix = "_etc2_unorm" texFormat = vk.VK_FORMAT_ETC2_R8G8B8_UNORM_BLOCK else: raise NotImplementedError( "Device does not support any compressed texture format!") if m.properties.get( ('file', pyassimp.material.aiTextureType_DIFFUSE)): texturefile = m.properties.get( ('file', pyassimp.material.aiTextureType_DIFFUSE)) print(" Diffuse: \"" + texturefile + "\"") texturefile = texturefile.replace("\\", "/") suffixidx = texturefile.find(".ktx") filename = texturefile[: suffixidx] + texFormatSuffix + texturefile[ suffixidx:] scenematerial['diffuse'].loadFromFile( self.assetPath + filename, texFormat, self.vulkanDevice, self.queue) else: print(" Material has no diffuse, using dummy texture!") scenematerial['diffuse'].loadFromFile( self.assetPath + "dummy_rgba_unorm.ktx", vk.VK_FORMAT_R8G8B8A8_UNORM, self.vulkanDevice, self.queue) # For scenes with multiple textures per material we would need to check for additional texture types, e.g.: # aiTextureType_HEIGHT, aiTextureType_OPACITY, aiTextureType_SPECULAR, etc. # Assign pipeline: can not do it that in python as there are no refernces yet to the pipelines # scenematerial['pipeline'] = self.pipelines['solid'] if scenematerial['properties']['opacity'] == 0.0 else self.pipelines['blending'] self.materials.append(scenematerial) # Generate descriptor sets for the materials # Descriptor pool poolSizes = [] poolSize = vk.VkDescriptorPoolSize( type=vk.VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, descriptorCount=len(self.materials)) poolSizes.append(poolSize) poolSize = vk.VkDescriptorPoolSize( type=vk.VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, descriptorCount=len(self.materials)) poolSizes.append(poolSize) descriptorPoolInfo = vk.VkDescriptorPoolCreateInfo( sType=vk.VK_STRUCTURE_TYPE_DESCRIPTOR_POOL_CREATE_INFO, poolSizeCount=len(poolSizes), pPoolSizes=poolSizes, maxSets=len(self.materials) + 1) self.descriptorPool = vk.vkCreateDescriptorPool( self.vulkanDevice.logicalDevice, descriptorPoolInfo, None) # Descriptor set and pipeline layouts # Set 0: Scene matrices setLayoutBindings = [] layoutBinding = vk.VkDescriptorSetLayoutBinding( descriptorType=vk.VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, descriptorCount=1, stageFlags=vk.VK_SHADER_STAGE_VERTEX_BIT, binding=0) setLayoutBindings.append(layoutBinding) descriptorLayout = vk.VkDescriptorSetLayoutCreateInfo( sType=vk.VK_STRUCTURE_TYPE_DESCRIPTOR_SET_LAYOUT_CREATE_INFO, bindingCount=len(setLayoutBindings), pBindings=setLayoutBindings) self.descriptorSetLayouts['scene'] = vk.vkCreateDescriptorSetLayout( self.vulkanDevice.logicalDevice, descriptorLayout, None) # Set 1: Material data setLayoutBindings = [] layoutBinding = vk.VkDescriptorSetLayoutBinding( descriptorType=vk.VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, descriptorCount=1, stageFlags=vk.VK_SHADER_STAGE_FRAGMENT_BIT, binding=0) setLayoutBindings.append(layoutBinding) descriptorLayout = vk.VkDescriptorSetLayoutCreateInfo( sType=vk.VK_STRUCTURE_TYPE_DESCRIPTOR_SET_LAYOUT_CREATE_INFO, bindingCount=len(setLayoutBindings), pBindings=setLayoutBindings) self.descriptorSetLayouts['material'] = vk.vkCreateDescriptorSetLayout( self.vulkanDevice.logicalDevice, descriptorLayout, None) # Setup pipeline layout setLayouts = [ self.descriptorSetLayouts['scene'], self.descriptorSetLayouts['material'] ] scenematerialSize = sum([ glm.sizeof(scenematerialprop) for scenematerialprop in self.scenematerialShape.values() ]) pushConstantRange = vk.VkPushConstantRange( stageFlags=vk.VK_SHADER_STAGE_FRAGMENT_BIT, offset=0, size=scenematerialSize) pPipelineLayoutCreateInfo = vk.VkPipelineLayoutCreateInfo( sType=vk.VK_STRUCTURE_TYPE_PIPELINE_LAYOUT_CREATE_INFO, setLayoutCount=len(setLayouts), pSetLayouts=setLayouts, pushConstantRangeCount=1, pPushConstantRanges=[pushConstantRange]) self.pipelineLayout = vk.vkCreatePipelineLayout( self.vulkanDevice.logicalDevice, pPipelineLayoutCreateInfo, None) # Material descriptor sets for m in self.materials: allocInfo = vk.VkDescriptorSetAllocateInfo( sType=vk.VK_STRUCTURE_TYPE_DESCRIPTOR_SET_ALLOCATE_INFO, descriptorPool=self.descriptorPool, descriptorSetCount=1, pSetLayouts=[self.descriptorSetLayouts['material']]) descriptorSets = vk.vkAllocateDescriptorSets( self.vulkanDevice.logicalDevice, allocInfo) m['descriptorSet'] = descriptorSets[0] # Binding 0: Diffuse texture writeDescriptorSets = [] writeDescriptorSet = vk.VkWriteDescriptorSet( sType=vk.VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET, dstSet=m['descriptorSet'], descriptorType=vk.VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, dstBinding=0, pImageInfo=[m['diffuse'].descriptor], descriptorCount=1) writeDescriptorSets.append(writeDescriptorSet) vk.vkUpdateDescriptorSets(self.vulkanDevice.logicalDevice, len(writeDescriptorSets), writeDescriptorSets, 0, None) # Scene descriptor set allocInfo = vk.VkDescriptorSetAllocateInfo( sType=vk.VK_STRUCTURE_TYPE_DESCRIPTOR_SET_ALLOCATE_INFO, descriptorPool=self.descriptorPool, descriptorSetCount=1, pSetLayouts=[self.descriptorSetLayouts['scene']]) descriptorSets = vk.vkAllocateDescriptorSets( self.vulkanDevice.logicalDevice, allocInfo) self.descriptorSetScene = descriptorSets[0] writeDescriptorSets = [] writeDescriptorSet = vk.VkWriteDescriptorSet( sType=vk.VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET, dstSet=self.descriptorSetScene, descriptorType=vk.VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, dstBinding=0, pBufferInfo=[self.uniformBuffer.descriptor], descriptorCount=1) writeDescriptorSets.append(writeDescriptorSet) vk.vkUpdateDescriptorSets(self.vulkanDevice.logicalDevice, len(writeDescriptorSets), writeDescriptorSets, 0, None)
import OpenGL from OpenGL.GL import * from OpenGL.GLUT import * from OpenGL.GLU import * class Vertex: Position = glm.vec3(0) Color = glm.vec4(0) TexCoords = glm.vec2(0) TexIndex = ctypes.c_float.value = 0.0 indices = [Vertex()] * 2 teste = {"def": 123, "name": "Adriel"} teste["Nome"] = "Gabriel" def pega_nome(nome): try: return teste[nome] except: return teste["def"] nome = pega_nome("Nome") print(glm.sizeof(glm.vec3(0)))
def __init__(self, width, height): global program global vao global position_buffer global index_buffer global uniform_buffer vs_source = ''' #version 420 core in vec4 position; out VS_OUT { vec4 color; } vs_out; void main(void) { gl_Position = position; vs_out.color = position * 2.0 + vec4(0.5, 0.5, 0.5, 0.0); } ''' gs_source = ''' #version 420 core layout (triangles, invocations = 4) in; layout (triangle_strip, max_vertices = 3) out; layout (std140, binding = 0) uniform transform_block { mat4 mvp_matrix[4]; }; in VS_OUT { vec4 color; } gs_in[]; out GS_OUT { vec4 color; } gs_out; void main(void) { for (int i = 0; i < gl_in.length(); i++) { gs_out.color = gs_in[i].color; gl_Position = mvp_matrix[gl_InvocationID] * gl_in[i].gl_Position; gl_ViewportIndex = gl_InvocationID; EmitVertex(); } EndPrimitive(); } ''' fs_source = ''' #version 420 core out vec4 color; in GS_OUT { vec4 color; } fs_in; void main(void) { color = fs_in.color; } ''' program = glCreateProgram() vs = glCreateShader(GL_VERTEX_SHADER) glShaderSource(vs, vs_source) glCompileShader(vs) gs = glCreateShader(GL_GEOMETRY_SHADER) glShaderSource(gs, gs_source) glCompileShader(gs) fs = glCreateShader(GL_FRAGMENT_SHADER) glShaderSource(fs, fs_source) glCompileShader(fs) glAttachShader(program, vs) glAttachShader(program, gs) glAttachShader(program, fs) glLinkProgram(program) glGenVertexArrays(1, vao) glBindVertexArray(vao) vertex_indices = np.array([ 0, 1, 2, 2, 1, 3, 2, 3, 4, 4, 3, 5, 4, 5, 6, 6, 5, 7, 6, 7, 0, 0, 7, 1, 6, 0, 2, 2, 4, 6, 7, 5, 3, 7, 3, 1 ], dtype=np.uint16) # GLushort vertex_positions = np.array([ -0.25, -0.25, -0.25, -0.25, 0.25, -0.25, 0.25, -0.25, -0.25, 0.25, 0.25, -0.25, 0.25, -0.25, 0.25, 0.25, 0.25, 0.25, -0.25, -0.25, 0.25, -0.25, 0.25, 0.25, ], dtype=np.float32) # GLfloat size_vertex_indices = ctypes.sizeof(ctypes.c_ushort)*len(vertex_indices) size_vertex_positions = ctypes.sizeof(ctypes.c_float)*len(vertex_positions) glGenBuffers(1, position_buffer) glBindBuffer(GL_ARRAY_BUFFER, position_buffer) glBufferData(GL_ARRAY_BUFFER, size_vertex_positions, vertex_positions, GL_STATIC_DRAW) glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 0, None) glEnableVertexAttribArray(0) glGenBuffers(1, index_buffer) glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, index_buffer) glBufferData(GL_ELEMENT_ARRAY_BUFFER, size_vertex_indices, vertex_indices, GL_STATIC_DRAW) glGenBuffers(1, uniform_buffer) glBindBuffer(GL_UNIFORM_BUFFER, uniform_buffer) glBufferData(GL_UNIFORM_BUFFER, 4 * glm.sizeof(glm.mat4()), None, GL_DYNAMIC_DRAW) glEnable(GL_CULL_FACE) #// glFrontFace(GL_CW) glEnable(GL_DEPTH_TEST) glDepthFunc(GL_LEQUAL)
def display(self): currentTime = time.time() i=0 black = [ 0.0, 0.0, 0.0, 1.0 ] one = 1.0 glViewport(0, 0, self.width, self.height) glClearBufferfv(GL_COLOR, 0, black) glClearBufferfv(GL_DEPTH, 0, one) # // Each rectangle will be 7/16 of the screen viewport_width = (7 * self.width) / 16.0 viewport_height = (7 * self.height) / 16.0 # // Four rectangles - lower left first... glViewportIndexedf(0, 0, 0, viewport_width, viewport_height); # // Lower right... glViewportIndexedf(1, self.width - viewport_width, 0, viewport_width, viewport_height); # // Upper left... glViewportIndexedf(2, 0, self.height - viewport_height, viewport_width, viewport_height); # // Upper right... glViewportIndexedf(3, self.width - viewport_width, self.height - viewport_height, viewport_width, viewport_height); proj_matrix = (GLfloat * 16)(*identityMatrix) proj_matrix = m3dPerspective(m3dDegToRad(50.0), float(self.width) / float(self.height), .1, 1000.0) f = currentTime * 0.3; glBindBufferBase(GL_UNIFORM_BUFFER, 0, uniform_buffer) mv_matrix_array = glMapBufferRange(GL_UNIFORM_BUFFER, 0, 4 * glm.sizeof(glm.mat4()), GL_MAP_WRITE_BIT | GL_MAP_INVALIDATE_BUFFER_BIT) mv_matrix_array_p = (GLfloat * 16 * 4).from_address(mv_matrix_array) for i in range(0, 4): T = (GLfloat * 16)(*identityMatrix) m3dTranslateMatrix44(T, 0.0, 0.0, -2.0) RY = (GLfloat * 16)(*identityMatrix) m3dRotationMatrix44(RY, currentTime * m3dDegToRad(17.0)*(i+1), 0.0, 1.0, 0.0) RX = (GLfloat * 16)(*identityMatrix) m3dRotationMatrix44(RX, currentTime * m3dDegToRad(10.0)*(i+1), 1.0, 0.0, 0.0) mv_matrix = (GLfloat * 16)(*identityMatrix) mv_matrix = m3dMultiply(T, m3dMultiply(RY, RX)) mvp_matrix = m3dMultiply(proj_matrix , mv_matrix) mv_matrix_array_p[i][:] = mvp_matrix glUnmapBuffer(GL_UNIFORM_BUFFER) glUseProgram(program) glDrawElements(GL_TRIANGLES, 36, GL_UNSIGNED_SHORT, 0) glutSwapBuffers()
def __init__(self, width, height): global myobject global vao global render_fbo global tex_scene global tex_brightpass global tex_depth global filter_fbo global tex_filter global tex_lut global ubo_transform global ubo_material self.width = width self.height = height buffers = [GL_COLOR_ATTACHMENT0, GL_COLOR_ATTACHMENT1] glGenVertexArrays(1, vao) glBindVertexArray(vao) load_shaders() exposureLUT = [ 11.0, 6.0, 3.2, 2.8, 2.2, 1.90, 1.80, 1.80, 1.70, 1.70, 1.60, 1.60, 1.50, 1.50, 1.40, 1.40, 1.30, 1.20, 1.10, 1.00 ] glGenFramebuffers(1, render_fbo) glBindFramebuffer(GL_FRAMEBUFFER, render_fbo) tex_scene = glGenTextures(1) glBindTexture(GL_TEXTURE_2D, tex_scene) glTexStorage2D(GL_TEXTURE_2D, 1, GL_RGBA16F, MAX_SCENE_WIDTH, MAX_SCENE_HEIGHT) glFramebufferTexture(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, tex_scene, 0) tex_brightpass = glGenTextures(1) glBindTexture(GL_TEXTURE_2D, tex_brightpass) glTexStorage2D(GL_TEXTURE_2D, 1, GL_RGBA16F, MAX_SCENE_WIDTH, MAX_SCENE_HEIGHT) glFramebufferTexture(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT1, tex_brightpass, 0) tex_depth = glGenTextures(1) glBindTexture(GL_TEXTURE_2D, tex_depth) glTexStorage2D(GL_TEXTURE_2D, 1, GL_DEPTH_COMPONENT32F, MAX_SCENE_WIDTH, MAX_SCENE_HEIGHT) glFramebufferTexture(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, tex_depth, 0) glDrawBuffers(2, buffers) #glGenFramebuffers(2, filter_fbo[0]) filter_fbo = [glGenFramebuffers(1) for _ in range(2)] #glGenTextures(2, tex_filter[0]) tex_filter = [glGenTextures(1) for _ in range(2)] for i in range(0, 2): glBindFramebuffer(GL_FRAMEBUFFER, filter_fbo[i]) glBindTexture(GL_TEXTURE_2D, tex_filter[i]) glTexStorage2D(GL_TEXTURE_2D, 1, GL_RGBA16F, MAX_SCENE_WIDTH if i == 0 else MAX_SCENE_HEIGHT, MAX_SCENE_HEIGHT if i == 0 else MAX_SCENE_WIDTH) glFramebufferTexture(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, tex_filter[i], 0) glDrawBuffers(1, buffers) glBindFramebuffer(GL_FRAMEBUFFER, 0) tex_lut = glGenTextures(1) glBindTexture(GL_TEXTURE_1D, tex_lut) glTexStorage1D(GL_TEXTURE_1D, 1, GL_R32F, 20) glTexSubImage1D(GL_TEXTURE_1D, 0, 0, 20, GL_RED, GL_FLOAT, exposureLUT) glTexParameteri(GL_TEXTURE_1D, GL_TEXTURE_MIN_FILTER, GL_LINEAR) glTexParameteri(GL_TEXTURE_1D, GL_TEXTURE_MAG_FILTER, GL_LINEAR) glTexParameteri(GL_TEXTURE_1D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE) myobject.load("torus.sbm") glGenBuffers(1, ubo_transform) glBindBuffer(GL_UNIFORM_BUFFER, ubo_transform) glBufferData(GL_UNIFORM_BUFFER, (2 + SPHERE_COUNT) * glm.sizeof(glm.mat4), None, GL_DYNAMIC_DRAW) class material: diffuse_color = glm.vec3 specular_color = glm.vec3 specular_power = GLfloat(0) ambient_color = glm.vec3 glGenBuffers(1, ubo_material) glBindBuffer(GL_UNIFORM_BUFFER, ubo_material) size_material = ctypes.sizeof(ctypes.c_float) * 12 glBufferData(GL_UNIFORM_BUFFER, SPHERE_COUNT * size_material, None, GL_STATIC_DRAW) mat = glMapBufferRange(GL_UNIFORM_BUFFER, 0, SPHERE_COUNT * size_material, GL_MAP_WRITE_BIT | GL_MAP_INVALIDATE_BUFFER_BIT) m = (GLfloat * 12 * SPHERE_COUNT).from_address(mat) ambient = 0.002 for i in range(SPHERE_COUNT): fi = 3.14159267 * i / 8.0 m[i][0:3] = (ctypes.c_float * 3)(sin(fi) * 0.5 + 0.5, sin(fi + 1.345) * 0.5 + 0.5, sin(fi + 2.567) * 0.5 + 0.5) m[i][4:7] = (ctypes.c_float * 3)(2.8, 2.8, 2.9) m[i][7] = 30 m[i][8:11] = (ctypes.c_float * 3)(ambient * 0.025, ambient * 0.025, ambient * 0.025) ambient *= 1.5 glUnmapBuffer(GL_UNIFORM_BUFFER)
def display(self): global program_filter global program_resolve global program_render global tex_filter global exposure global vao global filter_fbo global ubo_transform global ubo_material global bloom_thresh_min global bloom_thresh_max global uniforms global tex_brightpass global myobject global render_fbo currentTime = time.time() black = [0.0, 0.0, 0.0, 1.0] one = 1.0 last_time = 0.0 total_time = 0.0 if (not paused): total_time += (currentTime - last_time) last_time = currentTime t = total_time glViewport(0, 0, self.width, self.height) glBindFramebuffer(GL_FRAMEBUFFER, render_fbo) glClearBufferfv(GL_COLOR, 0, black) glClearBufferfv(GL_COLOR, 1, black) glClearBufferfv(GL_DEPTH, 0, one) glEnable(GL_DEPTH_TEST) glDepthFunc(GL_LESS) glUseProgram(program_render) glBindBufferBase(GL_UNIFORM_BUFFER, 0, ubo_transform) class transforms_t: mat_proj = glm.mat4 mat_view = glm.mat4 mat_model = [glm.mat4 for _ in range(SPHERE_COUNT)] size_transforms_t = glm.sizeof(glm.mat4) * (SPHERE_COUNT + 2) mbuffer = glMapBufferRange( GL_UNIFORM_BUFFER, 0, size_transforms_t, GL_MAP_WRITE_BIT | GL_MAP_INVALIDATE_BUFFER_BIT) bufferp = (GLfloat * 16 * (SPHERE_COUNT + 2)).from_address(mbuffer) mat_proj = (GLfloat * 16)(*identityMatrix) mat_proj = m3dPerspective(m3dDegToRad(50.0), float(self.width) / float(self.height), 1.0, 1000.0) T = (GLfloat * 16)(*identityMatrix) m3dTranslateMatrix44(T, 0.0, 0.0, -20.0) bufferp[0] = mat_proj bufferp[1] = T for i in range(2, SPHERE_COUNT + 2): fi = 3.141592 * i / 16.0 # // float r = cosf(fi * 0.25f) * 0.4f + 1.0f r = 0.6 if (i & 2) else 1.5 T1 = (GLfloat * 16)(*identityMatrix) m3dTranslateMatrix44(T1, cos(t + fi) * 5.0 * r, sin(t + fi * 4.0) * 4.0, sin(t + fi) * 5.0 * r) RY = (GLfloat * 16)(*identityMatrix) m3dRotationMatrix44(RY, currentTime * m3dDegToRad(30.0) * fi, sin(t + fi * 2.13) * 75.0, cos(t + fi * 1.37) * 92.0, 0.0) m_model = (GLfloat * 16)(*identityMatrix) m_model = m3dMultiply(T1, RY) bufferp[i] = m_model glUnmapBuffer(GL_UNIFORM_BUFFER) glBindBufferBase(GL_UNIFORM_BUFFER, 1, ubo_material) glUniform1f(uniforms.scene.bloom_thresh_min, bloom_thresh_min) glUniform1f(uniforms.scene.bloom_thresh_max, bloom_thresh_max) myobject.render(SPHERE_COUNT) glDisable(GL_DEPTH_TEST) glUseProgram(program_filter) glBindVertexArray(vao) glBindFramebuffer(GL_FRAMEBUFFER, filter_fbo[0]) glBindTexture(GL_TEXTURE_2D, tex_brightpass) glViewport(0, 0, self.height, self.width) glDrawArrays(GL_TRIANGLE_STRIP, 0, 4) glBindFramebuffer(GL_FRAMEBUFFER, filter_fbo[1]) glBindTexture(GL_TEXTURE_2D, tex_filter[0]) glViewport(0, 0, self.width, self.height) glDrawArrays(GL_TRIANGLE_STRIP, 0, 4) glUseProgram(program_resolve) glUniform1f(uniforms.resolve.exposure, exposure) if (show_prefilter): glUniform1f(uniforms.resolve.bloom_factor, 0.0) glUniform1f(uniforms.resolve.scene_factor, 1.0) else: glUniform1f(uniforms.resolve.bloom_factor, bloom_factor if show_bloom else 0.0) glUniform1f(uniforms.resolve.scene_factor, 1.0 if show_scene else 0.0) glBindFramebuffer(GL_FRAMEBUFFER, 0) glActiveTexture(GL_TEXTURE1) glBindTexture(GL_TEXTURE_2D, tex_filter[1]) glActiveTexture(GL_TEXTURE0) glBindTexture(GL_TEXTURE_2D, tex_brightpass if show_prefilter else tex_scene) glDrawArrays(GL_TRIANGLE_STRIP, 0, 4) glutSwapBuffers()