def _draw(self, transformation_matrix: numpy.ndarray): glUseProgram(self._shader) glUniformMatrix4fv( self._transform_location, 1, GL_FALSE, transformation_matrix.T.astype(numpy.float32), ) glUniform1i(self._texture_location, 0) try: glBindVertexArray(self._vao) except GLError: # There seems to be errors randomly when binding the VBO log.debug( f"Failed binding the OpenGL state for {self}. Trying to reload it." ) self.unload() self._setup() glBindVertexArray(self._vao) glActiveTexture(GL_TEXTURE0) glBindTexture(GL_TEXTURE_2D, self._texture) glDrawArrays(self.draw_mode, self.draw_start, self.draw_count) glBindVertexArray(0) glUseProgram(0)
def render(self, model, view_matrix, projection_matrix): glUseProgram(self.program) glEnableVertexAttribArray(self.texcoords) glEnableVertexAttribArray(self.vertices) glUniformMatrix4fv( self.model_view_matrix, 1, GL_TRUE, np.dot(view_matrix, model.matrix) ) glUniformMatrix4fv( self.projection_matrix, 1, GL_TRUE, projection_matrix ) for group in model.groups: glBindTexture(GL_TEXTURE_2D, group.material.texture) glUniform1i(self.texture, 0) glVertexAttribPointer( self.vertices, 3, GL_FLOAT, GL_FALSE, 0, group.vertex_buffer ) glVertexAttribPointer( self.texcoords, 2, GL_FLOAT, GL_FALSE, 0, group.texcoord_buffer ) glDrawArrays(GL_TRIANGLES, 0, len(group.vertex_buffer)) glDisableVertexAttribArray(self.vertices) glDisableVertexAttribArray(self.texcoords)
def _set_texture(self, name, value): from OpenGL.GL import glActiveTexture, glBindTexture, glUniform1i, \ GL_TEXTURE0, GL_TEXTURE_2D gl_texture_unit = self._assign_texture(name) glActiveTexture(GL_TEXTURE0 + gl_texture_unit) glBindTexture(GL_TEXTURE_2D, value._gl_handle) glUniform1i(self._uniform_handles.get(name), gl_texture_unit) # it seems that this unit should be activated before using # the framebuffer glActiveTexture(GL_TEXTURE0)
def enableGammaCorrection(window): """Enables M16 or C48 shader gamma correction""" from OpenGL.GL import glUseProgram, glUniform3f, glGetUniformLocation, glUniform1i if not hasattr(window, '_DPShaderProg'): raise Warning( "Shader not set up! make sure you call setUpShaderAndWindow before setting up gamma correction." ) return glUseProgram(window._DPShaderProg) glUniform1i( glGetUniformLocation(window._DPShaderProg, "gamma_correction_flag"), 1)
def set_int(self, variable: str, value: int) -> bool: """Set Integer value Args: variable: Variable name to set value: Integer value to set """ location = self.get_location(variable) if location < 0: logging.error(f"Variable not found in program [{variable}]") return False glUniform1i(location, ctypes.c_int(value)) return True
def setUpC48gammaCorrection(window, monitor, gamma_grid=None): """Sets up the gamma correction for C48 Args: window (PsychoPy.Window object): A PsychoPy Window object monitor (PsychoPy.Monitor object): The current monitor being used gamma_grid (list, optional): The gamma information if it is not contained in the monitor. (gamma_rgb; b_rgb, k_rgb) """ if not hasattr(window, '_DPShaderProg'): raise Warning( "Shader not set up! make sure you call setUpShaderAndWindow before setting up gamma correction." ) return from OpenGL.GL import glUseProgram, glUniform3f, glGetUniformLocation, glUniform1i glUseProgram(window._DPShaderProg) loc = glGetUniformLocation(window._DPShaderProg, "gamma_rgb") if loc == -1: raise Warning( "The current shader is not the right shader, are you sure you are in M16 mode?" ) return if gamma_grid is None: gamma_grid = monitor.getGammaGrid() if gamma_grid is None: raise Warning( "You did not provide gamma information and your monitor does not have any." ) return gamma_rgb = [gamma_grid[1][2], gamma_grid[2][2], gamma_grid[3][2]] # gamma b_rgb = [gamma_grid[1][4], gamma_grid[2][4], gamma_grid[3][4]] # b k_rgb = [gamma_grid[1][5], gamma_grid[2][5], gamma_grid[3][5]] # k else: gamma_rgb = [gamma_grid[0][0], gamma_grid[0][1], gamma_grid[0][2]] # gamma b_rgb = [gamma_grid[1][0], gamma_grid[1][1], gamma_grid[1][2]] # b k_rgb = [gamma_grid[2][0], gamma_grid[2][1], gamma_grid[2][2]] # k glUniform3f(glGetUniformLocation(window._DPShaderProg, "b_rgb"), b_rgb[0], b_rgb[1], b_rgb[2]) glUniform3f(glGetUniformLocation(window._DPShaderProg, "k_rgb"), k_rgb[0], k_rgb[1], k_rgb[2]) glUniform3f(glGetUniformLocation(window._DPShaderProg, "gamma_rgb"), gamma_rgb[0], gamma_rgb[1], gamma_rgb[2]) glUniform1i( glGetUniformLocation(window._DPShaderProg, "gamma_correction_flag"), 1)
def uniform(self, name, value): with self: if type(value) == int or type(value) == long: glUniform1i(self.uniformLocation(name), value) elif type(value) == float or type(value) == numpy.float32: glUniform1f(self.uniformLocation(name), value) elif len(value) == 4: value = numpy.array(value, dtype=numpy.float32) glUniform4f(self.uniformLocation(name), *value) elif len(value) == 16: glUniformMatrix4fv(self.uniformLocation(name), 1, GL_FALSE, value) elif len(value) == 9: glUniformMatrix3fv(self.uniformLocation(name), 1, GL_FALSE, value) elif len(value) == 2: value = numpy.array(value, dtype=numpy.float32) glUniform2f(self.uniformLocation(name), *value) else: print(len(value)) raise Exception('not implemented')
def render(self) -> None: """Render proxy objects to canvas with a diffuse shader.""" if not self.init(): return proj = self.parent.projection_matrix view = self.parent.modelview_matrix glUseProgram(self.parent.shaders['diffuse']) glUniformMatrix4fv(0, 1, GL_FALSE, glm.value_ptr(proj)) glUniformMatrix4fv(1, 1, GL_FALSE, glm.value_ptr(view)) for mesh in self._meshes: glBindVertexArray(mesh.vao) glUniform4fv(2, 1, glm.value_ptr(mesh.color)) glUniform1i(3, int(mesh.selected)) glDrawElements(GL_TRIANGLES, mesh.count, GL_UNSIGNED_INT, ctypes.c_void_p(0)) glBindVertexArray(0) glUseProgram(0)
def render_for_picking(self) -> None: """Render proxy objects for picking pass.""" if not self.init(): return proj = self.parent.projection_matrix view = self.parent.modelview_matrix glUseProgram(self.parent.shaders['solid']) glUniformMatrix4fv(0, 1, GL_FALSE, glm.value_ptr(proj)) glUniformMatrix4fv(1, 1, GL_FALSE, glm.value_ptr(view)) for mesh in self._meshes: glBindVertexArray(mesh.vao) glUniform1i(2, MAX_ID - mesh.object_id) glDrawElements(GL_TRIANGLES, mesh.count, GL_UNSIGNED_INT, ctypes.c_void_p(0)) glBindVertexArray(0) glUseProgram(0) glBindVertexArray(0) glUseProgram(0)
def setup(self, actor): ''' Setup the shader uniforms / attributes. Assumes actor.vbo is already bound ''' # Bind the shader shaders.glUseProgram(self.program) # Enable vertex attribute array glEnableVertexAttribArray(self.attrib_position) # Set the Attribute pointer glVertexAttribPointer(self.attrib_position, 4, GL_FLOAT, False, 0, actor.vbo) # Apply Uniforms glUniformMatrix4fv(self.uniform_modelCamera, 1, GL_TRUE, actor.modelCamera_matrix) glUniformMatrix4fv(self.uniform_projection, 1, GL_TRUE, actor.projection_matrix) glUniform4fv(self.uniform_color, 1, actor.color.data) glUniform1f(self.uniform_alpha, actor.alpha) glUniform1i(self.uniform_tex, 0) # Bind to the correct texture glBindTexture(GL_TEXTURE_2D, actor.atlas.texid)
def link_texture(self, name, number): """Link the texture to shaders.""" location = glGetUniformLocation(self.__program, name) assert location >= 0 glUniform1i(location, number)
def setInt(self, name, value): location = glGetUniformLocation(self.program, name) glUniform1i(location, value)
def set_uniform_i(self, name, value): location = glGetUniformLocation(self.program, name) glUniform1i(location, value)
def parametrizar_textura(self, ubicacion, textura): """Parametriza el shader con una textura (o un int). ubicacion = ubicación de la variable a parametrizar textura = posición de la textura a través de glActiveTexture()""" glUniform1i(ubicacion, textura)
def main(): global width global height global camera width = 1024 height = 1024 delta_time = 0.0 last_frame = 0.0 if not glfw.init(): return 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) glfw.window_hint(glfw.RESIZABLE, GL_FALSE) window = glfw.create_window(width, height, "opengl_lab1", None, None) glfw.set_key_callback(window, key_callback) glfw.set_cursor_pos_callback(window, mousemove_callback) glfw.set_mouse_button_callback(window, mouseclick_callback) if not window: glfw.terminate() return glfw.make_context_current(window) fun1 = lambda x, z: math.sin(x+z) fun2 = lambda x, z: math.exp(-x*x - z*z) fun3 = lambda x, z: (x**2 + z**2) / (x*z) contour_plot = lambda x, z: 0.0 heightmap_dummy_fun = lambda x, z: 0.0 surface_size = 50 (fun_vao1, ind_fun1) = create_surface(100, 100, surface_size, fun1, False) (fun_vao2, ind_fun2) = create_surface(100, 100, surface_size, fun2, False) (fun_vao3, ind_fun3) = create_surface(100, 100, surface_size, fun3, False) (grad_vao, grad_point_count) = create_grad(100, 100, surface_size) (contour_plot_vao, ind_con, vec_lines, vector_line_indexes) = create_surface(100, 100, surface_size, 0, False, True) (heightmap_vao, ind_hm) = create_surface(100,100, surface_size, heightmap_dummy_fun, True) (sphere_vao, sphere_ind, normals_for_glyph) = uv_sphere(22, 11) (torus_vao, torus_ind) = uv_torus(5, 10, 100, 100) (cm_vao, ind_cm) = create_surface(100, 100, surface_size, heightmap_dummy_fun, True) (cloud_vao, points_count) = read_ply() (perlin_vao, ind_perlin) = create_surface(100, 100, surface_size, heightmap_dummy_fun, False) (div_vao, ind_div) = create_surface(100, 100, surface_size, heightmap_dummy_fun, False) (traj_vao, ind_traj) = simple_cube() fun_shader_sources = [(GL_VERTEX_SHADER, "shaders/functions.vert"), (GL_FRAGMENT_SHADER, "shaders/functions.frag")] fun_program = ShaderProgram(fun_shader_sources) hm_shader_sources = [(GL_VERTEX_SHADER, "shaders/heightmap.vert"), (GL_FRAGMENT_SHADER, "shaders/heightmap.frag")] hm_program = ShaderProgram(hm_shader_sources) hm_texture = read_texture("1.jpg") contour_plot_shader_sources = [(GL_VERTEX_SHADER, "shaders/contourplot.vert"), (GL_FRAGMENT_SHADER, "shaders/contourplot.frag")] contour_plot_program = ShaderProgram(contour_plot_shader_sources) sphere_shader_sources = [(GL_VERTEX_SHADER, "shaders/sphere.vert"), (GL_FRAGMENT_SHADER, "shaders/sphere.frag")] sphere_program = ShaderProgram(sphere_shader_sources) glyph_shader_sources = [(GL_VERTEX_SHADER, "shaders/glyph.vert"), (GL_GEOMETRY_SHADER, "shaders/glyph.geom"), (GL_FRAGMENT_SHADER, "shaders/glyph.frag")] glyph_program = ShaderProgram(glyph_shader_sources) grad_shader_sources = [(GL_VERTEX_SHADER, "shaders/grad.vert"), (GL_GEOMETRY_SHADER, "shaders/grad.geom"), (GL_FRAGMENT_SHADER, "shaders/grad.frag")] grad_program = ShaderProgram(grad_shader_sources) cm_shader_sources = [(GL_VERTEX_SHADER, "shaders/colormap.vert"), (GL_FRAGMENT_SHADER, "shaders/colormap.frag")] cm_program = ShaderProgram( cm_shader_sources ) perlin_shader_sources = [(GL_VERTEX_SHADER, "shaders/perlin.vert"), (GL_FRAGMENT_SHADER, "shaders/perlin.frag")] perlin_program = ShaderProgram(perlin_shader_sources) cloud_shader_sources = [(GL_VERTEX_SHADER, "shaders/ply.vert"), (GL_FRAGMENT_SHADER, "shaders/ply.frag")] cloud_program = ShaderProgram(cloud_shader_sources) vf_shader_sources = [(GL_VERTEX_SHADER, "shaders/vector_field.vert"), (GL_FRAGMENT_SHADER, "shaders/vector_field.frag")] vf_program = ShaderProgram(vf_shader_sources) traj_shader_sources = [(GL_VERTEX_SHADER, "shaders/trajectory.vert"), (GL_FRAGMENT_SHADER, "shaders/trajectory.frag")] traj_program = ShaderProgram(traj_shader_sources) check_gl_errors() projection = projectionMatrixTransposed(60.0, float(width) / float(height), 1, 1000.0) HDR_TEXTURES_AMOUNT = 33 cm_textures = read_cm_textures(HDR_TEXTURES_AMOUNT) cm_texture_num = 0 cm_change_counter = 0 hdr_textures_speed = 6 perlin_time = 0.0 perlin_time_step = 0.03 cube_multiplier = 1.0 cube_center = [0.0, 0.0, 0.0] traj_points_list = [ cube_center ] cube_edge_length = 2.0 * cube_multiplier offset = cube_edge_length / 10 left_cube_pos = -25 * cube_edge_length cube_steps = -left_cube_pos / offset - 10 traj_points_count = int(cube_steps) for i in range(traj_points_count): traj_points_list.append( [0.5*cube_edge_length * i, 0.0, 0.0] ) traj_part_index = 0 while not glfw.window_should_close(window): current_frame = glfw.get_time() delta_time = current_frame - last_frame last_frame = current_frame glfw.poll_events() doCameraMovement(camera, delta_time) model = translateM4x4(np.array([0.0, 0.0, 0.0])) view = camera.get_view_matrix() glClearColor(0.5, 0.5, 0.5, 1.0) glViewport(0, 0, width, height) glEnable(GL_DEPTH_TEST) glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT) fun_program.bindProgram() glUniform3fv(fun_program.uniformLocation("col"), 1 , [1.0, 0, 0] ) glUniformMatrix4fv(fun_program.uniformLocation("model"), 1, GL_FALSE, np.transpose(model).flatten()) glUniformMatrix4fv(fun_program.uniformLocation("view"), 1, GL_FALSE, np.transpose(view).flatten()) glUniformMatrix4fv(fun_program.uniformLocation("projection"), 1, GL_FALSE, projection.flatten()) glBindVertexArray(fun_vao1) glDrawElements(GL_TRIANGLE_STRIP, ind_fun1, GL_UNSIGNED_INT, None) model = translateM4x4(np.array([-1.5*surface_size,0.0 ,0.0 ])) glUniform3fv(fun_program.uniformLocation("col"), 1, [0.0, 1.0, 0]) glUniformMatrix4fv(fun_program.uniformLocation("model"), 1, GL_FALSE, np.transpose(model).flatten()) glBindVertexArray(fun_vao2) glDrawElements(GL_TRIANGLE_STRIP, ind_fun2, GL_UNSIGNED_INT, None) model = translateM4x4(np.array([1.5 * surface_size, 0.0, 0.0])) glUniform3fv(fun_program.uniformLocation("col"), 1, [0.0, 0.0, 1.0]) glUniformMatrix4fv(fun_program.uniformLocation("model"), 1, GL_FALSE, np.transpose(model).flatten()) glBindVertexArray(fun_vao3) glDrawElements(GL_TRIANGLE_STRIP, ind_fun3, GL_UNSIGNED_INT, None) cloud_program.bindProgram() translate_cloud = translateM4x4(np.array([-2.5*surface_size,0.0 ,0.0 ])) # rotate_cloud = rotateYM4x4(math.radians(180)) model = translate_cloud # glUniform3fv(fun_program.uniformLocation("col"), 1, [0.0, 1.0, 0]) glUniformMatrix4fv(cloud_program.uniformLocation("model"), 1, GL_FALSE, np.transpose(model).flatten()) glUniformMatrix4fv(cloud_program.uniformLocation("view"), 1, GL_FALSE, np.transpose(view).flatten()) glUniformMatrix4fv(cloud_program.uniformLocation("projection"), 1, GL_FALSE, projection.flatten()) glBindVertexArray(cloud_vao) glDrawArrays(GL_POINTS, 0, points_count) sphere_program.bindProgram() sph_scale = scaleM4x4(np.array([sphere_radius, sphere_radius, sphere_radius])) sph_translate = translateM4x4(np.array([0.0, 0.0, 2.0 * surface_size])) glUniformMatrix4fv(sphere_program.uniformLocation("model"), 1, GL_FALSE, np.transpose(sph_translate + sph_scale).flatten()) glUniformMatrix4fv(sphere_program.uniformLocation("view"), 1, GL_FALSE, np.transpose(view).flatten()) glUniformMatrix4fv(sphere_program.uniformLocation("projection"), 1, GL_FALSE, projection.flatten()) glBindVertexArray(sphere_vao) glDrawElements(GL_TRIANGLES, sphere_ind, GL_UNSIGNED_INT, None) torus_translate = translateM4x4(np.array([0.0, 0.0, 3.0 * surface_size])) glUniformMatrix4fv(sphere_program.uniformLocation("model"), 1, GL_FALSE, np.transpose(torus_translate + sph_scale).flatten()) glBindVertexArray(torus_vao) glDrawElements(GL_TRIANGLES, torus_ind, GL_UNSIGNED_INT, None) glyph_program.bindProgram() sph_scale = scaleM4x4(np.array([sphere_radius, sphere_radius, sphere_radius])) sph_translate = translateM4x4(np.array([0.0, 0.0, 2.0 * surface_size])) glUniformMatrix4fv(glyph_program.uniformLocation("model"), 1, GL_FALSE, np.transpose(sph_translate + sph_scale).flatten()) glUniformMatrix4fv(glyph_program.uniformLocation("view"), 1, GL_FALSE, np.transpose(view).flatten()) glUniformMatrix4fv(glyph_program.uniformLocation("projection"), 1, GL_FALSE, projection.flatten()) vao = glGenVertexArrays(1) glBindVertexArray(vao) vbo = glGenBuffers(1) glBindBuffer(GL_ARRAY_BUFFER, vbo) glBufferData(GL_ARRAY_BUFFER, ArrayDatatype.arrayByteCount(normals_for_glyph), normals_for_glyph.flatten(), GL_STATIC_DRAW) glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 0, None) glEnableVertexAttribArray(0) glDrawArrays(GL_POINTS, 0, 10000) glBindVertexArray(0) contour_plot_program.bindProgram() model = translateM4x4(np.array([-1.5 * surface_size, 0.0, -1.5 * surface_size])) glUniformMatrix4fv(contour_plot_program.uniformLocation("model"), 1, GL_FALSE, np.transpose(model).flatten()) glUniformMatrix4fv(contour_plot_program.uniformLocation("view"), 1, GL_FALSE, np.transpose(view).flatten()) glUniformMatrix4fv(contour_plot_program.uniformLocation("projection"), 1, GL_FALSE, projection.flatten()) glBindVertexArray(contour_plot_vao) glDrawElements(GL_TRIANGLE_STRIP, ind_con, GL_UNSIGNED_INT, None) fun_program.bindProgram() lines_vao = glGenVertexArrays(1) glBindVertexArray(lines_vao) vbo_lines = glGenBuffers(1) vbo_indices = glGenBuffers(1) glBindBuffer(GL_ARRAY_BUFFER, vbo_lines) glBufferData(GL_ARRAY_BUFFER, ArrayDatatype.arrayByteCount(vec_lines), vec_lines.flatten(), GL_STATIC_DRAW) # glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 0, None) glEnableVertexAttribArray(0) glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, vbo_indices) glBufferData(GL_ELEMENT_ARRAY_BUFFER, ArrayDatatype.arrayByteCount(vector_line_indexes), vector_line_indexes.flatten(), GL_STATIC_DRAW) glUniformMatrix4fv(fun_program.uniformLocation("model"), 1, GL_FALSE, np.transpose(model).flatten()) glUniformMatrix4fv(fun_program.uniformLocation("view"), 1, GL_FALSE, np.transpose(view).flatten()) glUniformMatrix4fv(fun_program.uniformLocation("projection"), 1, GL_FALSE, projection.flatten()) glBindVertexArray(lines_vao) glDrawElements(GL_LINES, vector_line_indexes.size, GL_UNSIGNED_INT, None) hm_program.bindProgram() model = translateM4x4(np.array([0.0, 0.0, -1.5 * surface_size])) bindTexture(0, hm_texture) glUniform1i(hm_program.uniformLocation("tex"), 0) glUniformMatrix4fv(hm_program.uniformLocation("model"), 1, GL_FALSE, np.transpose(model).flatten()) glUniformMatrix4fv(hm_program.uniformLocation("view"), 1, GL_FALSE, np.transpose(view).flatten()) glUniformMatrix4fv(hm_program.uniformLocation("projection"), 1, GL_FALSE, projection.flatten()) glBindVertexArray(heightmap_vao) glDrawElements(GL_TRIANGLE_STRIP, ind_hm, GL_UNSIGNED_INT, None) cm_program.bindProgram() model = translateM4x4(np.array([1.5 * surface_size, 0.0, -1.5 * surface_size])) cur_cm_texture = cm_textures[cm_texture_num % HDR_TEXTURES_AMOUNT] bindTexture(1, cur_cm_texture) if cm_change_counter % hdr_textures_speed == 0: cm_texture_num += 1 cm_change_counter += 1 glUniform1i(cm_program.uniformLocation("cm_switch"), False) glUniform1i(cm_program.uniformLocation("tex"), 1) glUniformMatrix4fv(cm_program.uniformLocation("model"), 1, GL_FALSE, np.transpose(model).flatten()) glUniformMatrix4fv(cm_program.uniformLocation("view"), 1, GL_FALSE, np.transpose(view).flatten()) glUniformMatrix4fv(cm_program.uniformLocation("projection"), 1, GL_FALSE, projection.flatten()) glBindVertexArray(cm_vao) glDrawElements(GL_TRIANGLE_STRIP, ind_cm, GL_UNSIGNED_INT, None) # draw second animated hdr on the same shader model = translateM4x4(np.array([2.5 * surface_size, 0.0, -2.5 * surface_size])) glUniformMatrix4fv(cm_program.uniformLocation("model"), 1, GL_FALSE, np.transpose(model).flatten()) glUniform1i(cm_program.uniformLocation("cm_switch"), True) glDrawElements(GL_TRIANGLE_STRIP, ind_cm, GL_UNSIGNED_INT, None) perlin_program.bindProgram() model = translateM4x4(np.array([0.0, 0.0, -3.5 * surface_size])) glUniformMatrix4fv(perlin_program.uniformLocation("model"), 1, GL_FALSE, np.transpose(model).flatten()) glUniformMatrix4fv(perlin_program.uniformLocation("view"), 1, GL_FALSE, np.transpose(view).flatten()) glUniformMatrix4fv(perlin_program.uniformLocation("projection"), 1, GL_FALSE, projection.flatten()) glUniform1f(perlin_program.uniformLocation("time"), perlin_time) perlin_time += perlin_time_step glBindVertexArray(perlin_vao) glDrawElements(GL_TRIANGLE_STRIP, ind_perlin, GL_UNSIGNED_INT, None) grad_program.bindProgram() model = translateM4x4(np.array([-25.0, 0.0, -7.0 * surface_size])) glUniformMatrix4fv(grad_program.uniformLocation("model"), 1, GL_FALSE, np.transpose(model).flatten()) glUniformMatrix4fv(grad_program.uniformLocation("view"), 1, GL_FALSE, np.transpose(view).flatten()) glUniformMatrix4fv(grad_program.uniformLocation("projection"), 1, GL_FALSE, projection.flatten()) glBindVertexArray(grad_vao) glDrawArrays(GL_LINES, 0, grad_point_count) vf_program.bindProgram() model = translateM4x4(np.array([0.0, 0.0, -5.5 * surface_size])) glUniformMatrix4fv(vf_program.uniformLocation("model"), 1, GL_FALSE, np.transpose(model).flatten()) glUniformMatrix4fv(vf_program.uniformLocation("view"), 1, GL_FALSE, np.transpose(view).flatten()) glUniformMatrix4fv(vf_program.uniformLocation("projection"), 1, GL_FALSE, projection.flatten()) glUniform1i(vf_program.uniformLocation("cm_switch"), True) glBindVertexArray(div_vao) glDrawElements(GL_TRIANGLE_STRIP, ind_div, GL_UNSIGNED_INT, None) glUniform1i(vf_program.uniformLocation("cm_switch"), False) model = translateM4x4(np.array([1.0 * surface_size, 0.0, -6.5 * surface_size])) glUniformMatrix4fv(vf_program.uniformLocation("model"), 1, GL_FALSE, np.transpose(model).flatten()) glDrawElements(GL_TRIANGLE_STRIP, ind_div, GL_UNSIGNED_INT, None) traj_program.bindProgram() l_traj_part =[] r_traj_part =[] if offset > 0: traj_part_index = int(traj_points_count - cm_change_counter % cube_steps) r_traj_part = traj_points_list[0:traj_part_index] for traj_coords in r_traj_part: l_traj_part.append( [-x for x in traj_coords] ) else: traj_part_index = int(traj_points_count - cm_change_counter % cube_steps) # traj_part_index = int(cm_change_counter % cube_steps) l_traj_part = traj_points_list[0:traj_part_index] for traj_coords in l_traj_part: r_traj_part.append([-x for x in traj_coords]) l_traj_vec = np.array(l_traj_part, dtype=np.float32) r_traj_vec = np.array(r_traj_part, dtype=np.float32) indices_list = [i for i in range(len(r_traj_part))] indices_vec = np.array(indices_list, dtype=np.uint32) left_traj_vao = glGenVertexArrays(1) right_traj_vao = glGenVertexArrays(1) left_traj_vertices = glGenBuffers(1) left_traj_indices = glGenBuffers(1) right_traj_vertices = glGenBuffers(1) right_traj_indices = glGenBuffers(1) glBindVertexArray(left_traj_vao) glPointSize( 3.0 ) glBindBuffer(GL_ARRAY_BUFFER, left_traj_vertices) glBufferData(GL_ARRAY_BUFFER, ArrayDatatype.arrayByteCount(l_traj_vec), l_traj_vec.flatten(), GL_STATIC_DRAW) glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 0, None) glEnableVertexAttribArray(0) glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, left_traj_indices) glBufferData(GL_ELEMENT_ARRAY_BUFFER, ArrayDatatype.arrayByteCount(indices_vec), indices_vec.flatten(), GL_STATIC_DRAW) glBindVertexArray(right_traj_vao) glBindBuffer(GL_ARRAY_BUFFER, right_traj_vertices) glBufferData(GL_ARRAY_BUFFER, ArrayDatatype.arrayByteCount(r_traj_vec), r_traj_vec.flatten(), GL_STATIC_DRAW) glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 0, None) glEnableVertexAttribArray(0) glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, right_traj_indices) glBufferData(GL_ELEMENT_ARRAY_BUFFER, ArrayDatatype.arrayByteCount(indices_vec), indices_vec.flatten(), GL_STATIC_DRAW) glBindVertexArray(0) cube_scale_ = scaleM4x4(np.array([1.0, 1.0, 1.0])) left_cube_pos += offset left_translation = translateM4x4(np.array([left_cube_pos, 0.0, -7.5 * surface_size])) glUniformMatrix4fv(traj_program.uniformLocation("model"), 1, GL_FALSE, np.transpose(left_translation).flatten()) glUniformMatrix4fv(traj_program.uniformLocation("view"), 1, GL_FALSE, np.transpose(view).flatten()) glUniformMatrix4fv(traj_program.uniformLocation("projection"), 1, GL_FALSE, projection.flatten()) glBindVertexArray(left_traj_vao) glDrawElements(GL_LINE_STRIP, indices_vec.size, GL_UNSIGNED_INT, None) glBindVertexArray(traj_vao) glDrawElements(GL_TRIANGLE_STRIP, ind_traj, GL_UNSIGNED_INT, None) right_translation = translateM4x4(np.array([-left_cube_pos, 0.0, -8.5 * surface_size])) glUniformMatrix4fv(traj_program.uniformLocation("model"), 1, GL_FALSE, np.transpose(right_translation).flatten()) glDrawElements(GL_TRIANGLE_STRIP, ind_traj, GL_UNSIGNED_INT, None) glBindVertexArray(right_traj_vao) glDrawElements(GL_LINE_STRIP, indices_vec.size, GL_UNSIGNED_INT, None) if not cm_change_counter % cube_steps: # left_cube_pos = left_cube_pos + offset * (cube_steps-1) offset *= -1 # r_traj_part, l_traj_part = l_traj_part, r_traj_part traj_program.unbindProgram() glfw.swap_buffers(window) glfw.terminate()
def SetUniform1i(self, name, value): glUniform1i(self.GetUniformLocation(name), value)
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT) glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT) glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR) glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR) glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, img.size[0], img.size[1], 0, GL_RGBA, GL_UNSIGNED_BYTE, img_data) while running: glClear(GL_COLOR_BUFFER_BIT) # Specify shader to be used glUseProgram(program.program_id) glActiveTexture(GL_TEXTURE0) glBindTexture(GL_TEXTURE_2D, texture_id) sampler_loc = program.attribute_location('texture_sampler') glUniform1i(sampler_loc, 0) # Bind VAO - this will automatically # bind all the vbo's saving us a bunch # of calls glBindVertexArray(vao_id) # Modern GL makes the draw call really simple # All the complexity has been pushed elsewhere glDrawArrays(GL_TRIANGLES, 0, 6) # Lets unbind the shader and vertex array state glUseProgram(0) glBindVertexArray(0) # Now lets show our master piece on the screen
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT) glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR) glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR) glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, img.size[0], img.size[1], 0, GL_RGBA, GL_UNSIGNED_BYTE, img_data) while running: glClear(GL_COLOR_BUFFER_BIT) # Specify shader to be used glUseProgram(program.program_id) glActiveTexture(GL_TEXTURE0) glBindTexture(GL_TEXTURE_2D, texture_id) sampler_loc = program.attribute_location('texture_sampler') glUniform1i(sampler_loc, 0) # Bind VAO - this will automatically # bind all the vbo's saving us a bunch # of calls glBindVertexArray(vao_id) # Modern GL makes the draw call really simple # All the complexity has been pushed elsewhere glDrawArrays(GL_TRIANGLES, 0, 6) # Lets unbind the shader and vertex array state glUseProgram(0) glBindVertexArray(0) # Now lets show our master piece on the screen
def setInt(self, name, value): glUniform1i(self.getUniformLocation(name), value)
def update(self): for camera in self.__active_camera: self.__vertices = camera.vertices self.__indices = camera.indices self.__data_for_render = camera.get_data_for_render() glBindBuffer(GL_ARRAY_BUFFER, self.__VBO) glBufferData(GL_ARRAY_BUFFER, self.__vertices.nbytes, self.__vertices, GL_STATIC_DRAW) camera.bind_frame_buffer() glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT) for material, data in self.__data_for_render.items(): material.use_program() num_of_items = sum( TYPE_TO_LENGTH[type_] for attrib, type_ in material.attributes_types.items() if attrib not in material.instanced_attribs) pointer = 0 glBindBuffer(GL_ARRAY_BUFFER, self.__VBO) for attrib, index in sorted(material.attributes.items(), key=lambda x: x[1]): if attrib not in material.instanced_attribs: length = TYPE_TO_LENGTH[ material.attributes_types[attrib]] glEnableVertexAttribArray(index) glVertexAttribPointer( index, length, GL_FLOAT, GL_FALSE, self.__vertices.itemsize * num_of_items, ctypes.c_void_p(pointer * 4)) pointer += length if material.view_matrix_name in material.uniforms: glUniformMatrix4fv( material.uniforms[material.view_matrix_name], 1, GL_FALSE, camera.obj.inverse_matrix) if material.projection_matrix_name in material.uniforms: glUniformMatrix4fv( material.uniforms[material.projection_matrix_name], 1, GL_FALSE, camera.projection) for dat in data: sampler_id = 0 for uniform, index in material.uniforms.items(): if material.uniforms_types[uniform] == GL_SAMPLER_2D: if uniform in dat['object'].components[ 'Mesh'].uniform_data: unif_dat = dat['object'].components[ 'Mesh'].uniform_data[uniform] if callable(unif_dat): unif_dat = unif_dat() glUniform1i(index, sampler_id) glActiveTexture(GL_TEXTURE0 + sampler_id) unif_dat.bind_texture() unif_dat.load_settings() if unif_dat.default_texture == unif_dat.texture: unif_dat.send_texture() # if type(unif_dat) == int: # glUniform1i(index, sampler_id) # glActiveTexture(GL_TEXTURE0 + sampler_id) # glBindTexture(GL_TEXTURE_2D, unif_dat) else: glUniform1i(index, sampler_id) glActiveTexture(GL_TEXTURE0 + sampler_id) unif_dat.bind_texture() unif_dat.load_settings() if unif_dat.default_texture == unif_dat.texture: unif_dat.send_texture() # glUniform1i(index, sampler_id) # glActiveTexture(GL_TEXTURE0 + sampler_id) # glBindTexture(GL_TEXTURE_2D, unif_dat) elif 'Texture' in dat['object'].components: # location = material.uniforms[uniform] texture = dat['object'].components['Texture'] glUniform1i(index, sampler_id) glActiveTexture(GL_TEXTURE0 + sampler_id) texture.bind_texture() texture.load_settings() if texture.default_texture == texture.texture: texture.send_texture() # texture.bind_default_texture() sampler_id += 1 elif material.model_matrix_name == uniform: glUniformMatrix4fv( index, 1, GL_FALSE, dat['object'].transformation_matrix) elif material.view_matrix_name == uniform: pass elif material.projection_matrix_name == uniform: pass elif uniform in dat['object'].components[ 'Mesh'].uniform_data: uniform_data = dat['object'].components[ 'Mesh'].uniform_data[uniform] if callable(uniform_data): uniform_data = uniform_data() if type(uniform_data) == int or float: glUniform1f(index, float(uniform_data)) elif type(uniform_data) == int or float: glUniform1f(index, float(uniform_data)) # glDrawElements(GL_TRIANGLES, dat['length'], GL_UNSIGNED_INT, ctypes.c_void_p(dat['pointer'] * 0)) flatten_indices = dat['indices'] glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, self.__EBO) glBufferData(GL_ELEMENT_ARRAY_BUFFER, flatten_indices.nbytes, flatten_indices, GL_STATIC_DRAW) # glDrawElements(GL_TRIANGLES, len(flatten_indices), GL_UNSIGNED_INT, None) mesh = dat['object'].components['Mesh'] if len(mesh.instanced_point_data): instance_data = mesh.get_instanced_data_positioned_to_material( material, flattened=False) instance_cnt = len(instance_data) instance_data = instance_data.flatten() glBindBuffer(GL_ARRAY_BUFFER, self.__instanceVBO) glBufferData(GL_ARRAY_BUFFER, instance_data.nbytes, instance_data, GL_STATIC_DRAW) num_of_items = sum( TYPE_TO_LENGTH[material.attributes_types[attrib]] for attrib in material.instanced_attribs) ptr = 0 for attrib, index in sorted( material.attributes.items(), key=lambda x: x[1]): if attrib in material.instanced_attribs: length = TYPE_TO_LENGTH[ material.attributes_types[attrib]] glEnableVertexAttribArray(index) glVertexAttribPointer( index, length, GL_FLOAT, GL_FALSE, instance_data.itemsize * num_of_items, ctypes.c_void_p(ptr * 4)) glVertexAttribDivisor(index, 1) ptr += length glDrawElementsInstanced(GL_TRIANGLES, len(flatten_indices), GL_UNSIGNED_INT, None, instance_cnt) else: glDrawRangeElements(GL_TRIANGLES, dat['pointer'], dat['pointer'] + dat['length'], len(flatten_indices), GL_UNSIGNED_INT, None)