def __init__(self): mesh = ObjLoader() mesh.load_model("../models/cube.obj") num_verts = len(mesh.model_vertices) // 3 group = pyglet.graphics.Group() group.set_state = self.state self.verts = main_batch.add(num_verts, GL_TRIANGLES, group, ('v3f', mesh.model_vertices), ('t2f', mesh.model_textures)) self.model = matrix44.create_from_translation(Vector3( [2.0, 0.0, -4.0])).flatten().astype("float32") self.c_model = numpy.ctypeslib.as_ctypes(self.model) # region texture settings self.texture = GLuint(0) glGenTextures(1, self.texture) glBindTexture(GL_TEXTURE_2D, self.texture) # set the texture wrapping glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT) glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT) # set the texture filtering glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR) glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR) image = pyglet.image.load('../models/cube.jpg') image_data = image.get_data('RGB', image.pitch) glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, image.width, image.height, 0, GL_RGB, GL_UNSIGNED_BYTE, image_data)
def create_object(shader): obj = ObjLoader() obj.load_model(Path('res', 'cube.obj')) texture_offset = len(obj.vertex_index) * len( obj.vert_coords[0]) * obj.model.itemsize # Create a new VAO (Vertex Array Object) and bind it vertex_array_object = glGenVertexArrays(1) glBindVertexArray(vertex_array_object) # Generate buffers to hold our vertices vertex_buffer = glGenBuffers(1) glBindBuffer(GL_ARRAY_BUFFER, vertex_buffer) # Generate buffers to hold our texture texture = glGenTextures(1) glBindTexture(GL_TEXTURE_2D, texture) # Set the position of the 'position' in parameter of our shader and bind it. position = 0 glBindAttribLocation(shader, position, 'position') glEnableVertexAttribArray(position) # Describe the position data layout in the buffer glVertexAttribPointer(position, 3, GL_FLOAT, False, obj.model.itemsize * 3, ctypes.c_void_p(0)) # Set the position of the 'inTexCoords' in parameter of our shader and bind it. texture_coords = 1 glBindAttribLocation(shader, texture_coords, 'inTexCoords') glEnableVertexAttribArray(texture_coords) # Describe the texture data layout in the buffer glVertexAttribPointer(texture_coords, 2, GL_FLOAT, False, obj.model.itemsize * 2, ctypes.c_void_p(texture_offset)) # Texture wrapping params glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT) glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT) # Texture filtering params glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR) glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR) # Load and convert Texture image = Image.open(Path('res', 'cube_texture.jpg')) flipped_image = image.transpose(Image.FLIP_TOP_BOTTOM) img_data = numpy.array(list(flipped_image.getdata()), numpy.uint8) # Send the data over to the buffers glBufferData(GL_ARRAY_BUFFER, obj.model.itemsize * len(obj.model), obj.model, GL_STATIC_DRAW) # Vertices array glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, image.width, image.height, 0, GL_RGB, GL_UNSIGNED_BYTE, img_data) # Unbind the VAO first (Important) glBindVertexArray(0) # Unbind other stuff glDisableVertexAttribArray(position) glBindBuffer(GL_ARRAY_BUFFER, 0) return vertex_array_object, obj
def __init__(self): mesh = ObjLoader() mesh.load_model("../models/monkey.obj") num_verts = len(mesh.model_vertices) // 3 self.batch = pyglet.graphics.Batch() self.verts = self.batch.add(num_verts, GL_TRIANGLES, None, ('v3f', mesh.model_vertices), ('t2f', mesh.model_textures)) shader = ShaderLoader.compile_shader("shaders/video_13_vert.glsl", "shaders/video_13_frag.glsl") glUseProgram(shader) # vertices glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 0, self.verts.vertices) glEnableVertexAttribArray(0) # textures glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, 0, self.verts.tex_coords) glEnableVertexAttribArray(1) projection = matrix44.create_perspective_projection_matrix( 45.0, 1280 / 720, 0.1, 100.0).flatten().astype("float32") view = matrix44.create_from_translation(Vector3( [0.0, 0.0, -2.0])).flatten().astype("float32") self.translation = matrix44.create_from_translation( Vector3([0.0, 0.0, -2.0])) c_projection = numpy.ctypeslib.as_ctypes(projection) c_view = numpy.ctypeslib.as_ctypes(view) view_loc = glGetUniformLocation(shader, b"view") proj_loc = glGetUniformLocation(shader, b"projection") self.model_loc = glGetUniformLocation(shader, b"model") glUniformMatrix4fv(view_loc, 1, GL_FALSE, c_view) glUniformMatrix4fv(proj_loc, 1, GL_FALSE, c_projection) # region texture settings and loading texture = GLuint(0) glGenTextures(1, texture) glBindTexture(GL_TEXTURE_2D, texture) # set the texture wrapping glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT) glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT) # set the texture filtering glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR) glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR) # endregion image = pyglet.image.load('../models/monkey.jpg') image_data = image.get_data('RGB', image.pitch) glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, image.width, image.height, 0, GL_RGB, GL_UNSIGNED_BYTE, image_data)
def initializeGL(self): """Initialize OpenGL, VBOs, upload data on the GPU, etc.""" print('Loaded OpenGL {} with GLSL {}'.format( str(gl.glGetString(gl.GL_VERSION), 'utf-8'), str(gl.glGetString(gl.GL_SHADING_LANGUAGE_VERSION), 'utf-8'))) gl.glClearColor(0.2, 0.2, 0.2, 0) # Background color gl.glEnable(gl.GL_DEPTH_TEST) # Enable depth buffer # gl.glEnable(gl.GL_BLEND) # Enable blending for alpha # gl.glBlendFunc(gl.GL_SRC_ALPHA, gl.GL_ONE_MINUS_SRC_ALPHA) # gl.glBlendEquationSeparate(gl.GL_FUNC_ADD, gl.GL_FUNC_ADD) # Compiling vertex & fragment shader vs = compileVertexShader(VS) fs = compileFragmentShader(FS) self.shaders_program = createProgram(vs, fs) gl.glUseProgram(self.shaders_program) # Set up uniforms for sending data from host to the shaders self.T_IM_I_device = gl.glGetUniformLocation(self.shaders_program, 'T_IM_I') self.T_SI_S_device = gl.glGetUniformLocation(self.shaders_program, 'T_SI_S') self.T_CS_C_device = gl.glGetUniformLocation(self.shaders_program, 'T_CS_C') self.T_NC_N_device = gl.glGetUniformLocation(self.shaders_program, 'T_NC_N') self.T_NR_N_device = gl.glGetUniformLocation(self.shaders_program, 'T_NR_N') self.is_radial = gl.glGetUniformLocation(self.shaders_program, 'is_radial') # Use the custom (very simple) object loader. # This only handles the most basic of models self.model = ObjLoader() self.model.loadModel('manta_test_object_with_plane.obj') self.image_frame_model = ObjLoader() self.image_frame_model.loadModel('image_test_object.obj') # Put the model vertices into vertex buffer objects (VBOs) self.vbo_model_vertices = glvbo.VBO(self.model.vertices) self.vbo_image_frame_vertices = glvbo.VBO( self.image_frame_model.vertices) # usage=gl.DYNAMIC_DRAW, # target=gl.GL_ARRAY_BUFFER self.vbo_model_normals = glvbo.VBO(self.model.normals) self.vbo_image_frame_normals = glvbo.VBO( self.image_frame_model.normals) # For the display, we are going to wiggle the model's roll and pitch. self.psi = 0 # Roll self.phi = 0 # Pitch self.theta = 0 # Yaw gl.glUseProgram(self.shaders_program)
def __init__(self): mesh = ObjLoader() mesh.load_model("../models/cube.obj") self.num_verts = len(mesh.vertex_index) cube_texture_offset = len(mesh.vertex_index) * 12 cube_data = numpy.array(mesh.model, dtype=GLfloat) self.vao_cube = GLuint() # generate a vertex array object for the cube - the vao glGenVertexArrays(1, self.vao_cube) # bind the cube's vao glBindVertexArray(self.vao_cube) # setup the cube's vertex buffer object - the vbo vbo_sphere = pyglet.graphics.vertexbuffer.create_buffer(cube_data.nbytes, GL_ARRAY_BUFFER, GL_STATIC_DRAW) vbo_sphere.bind() vbo_sphere.set_data(cube_data.ctypes.data) # vertex attribute pointer settings for the cube vbo glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 0, 0) glEnableVertexAttribArray(0) # textures glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, 0, cube_texture_offset) glEnableVertexAttribArray(1) glBindBuffer(GL_ARRAY_BUFFER, 0) # unbind the vbo glBindVertexArray(0) # unbind the vao # region texture settings self.texture = GLuint(0) glGenTextures(1, self.texture) glBindTexture(GL_TEXTURE_2D, self.texture) # set the texture wrapping glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT) glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT) # set the texture filtering glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR) glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR) image = pyglet.image.load('../models/cube.jpg') image_data = image.get_data('RGB', image.pitch) glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, image.width, image.height, 0, GL_RGB, GL_UNSIGNED_BYTE, image_data)
def main(): vertex_src = """ # version 330 layout(location = 0) in vec3 a_position; layout(location = 1) in vec2 a_texture; layout(location = 2) in vec3 a_normal; uniform mat4 model; uniform mat4 projection; uniform mat4 view; out vec2 v_texture; void main() { gl_Position = projection * view * model * vec4(a_position, 1.0); v_texture = a_texture; } """ fragment_src = """ # version 330 in vec2 v_texture; out vec4 out_color; uniform sampler2D s_texture; void main() { out_color = texture(s_texture, v_texture); } """ pygame.init() pygame.display.gl_set_attribute(pygame.GL_CONTEXT_MAJOR_VERSION, 4) pygame.display.gl_set_attribute(pygame.GL_CONTEXT_MINOR_VERSION, 1) pygame.display.gl_set_attribute(pygame.GL_CONTEXT_PROFILE_MASK, pygame.GL_CONTEXT_PROFILE_CORE) pygame.display.set_mode((WIDTH, HEIGHT), pygame.OPENGL | pygame.DOUBLEBUF | pygame.RESIZABLE) # |pygame.FULLSCREEN pygame.mouse.set_visible(False) pygame.event.set_grab(True) # load here the 3d meshes cube_indices, cube_buffer = ObjLoader.load_model("meshes/cube.obj", False) monkey_indices, monkey_buffer = ObjLoader.load_model("meshes/monkey.obj") floor_indices, floor_buffer = ObjLoader.load_model("meshes/floor.obj") # VAO and VBO VAO = glGenVertexArrays(3) VBO = glGenBuffers(3) EBO = glGenBuffers(1) # cube VAO glBindVertexArray(VAO[0]) shader = compileProgram(compileShader(vertex_src, GL_VERTEX_SHADER), compileShader(fragment_src, GL_FRAGMENT_SHADER)) # cube Vertex Buffer Object glBindBuffer(GL_ARRAY_BUFFER, VBO[0]) glBufferData(GL_ARRAY_BUFFER, cube_buffer.nbytes, cube_buffer, GL_STATIC_DRAW) glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, EBO) glBufferData(GL_ELEMENT_ARRAY_BUFFER, cube_indices.nbytes, cube_indices, GL_STATIC_DRAW) # cube vertices glEnableVertexAttribArray(0) glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, cube_buffer.itemsize * 8, ctypes.c_void_p(0)) # cube textures glEnableVertexAttribArray(1) glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, cube_buffer.itemsize * 8, ctypes.c_void_p(12)) # cube normals glVertexAttribPointer(2, 3, GL_FLOAT, GL_FALSE, cube_buffer.itemsize * 8, ctypes.c_void_p(20)) glEnableVertexAttribArray(2) glBindVertexArray(0) glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0) glBindBuffer(GL_ARRAY_BUFFER, 0) # monkey VAO glBindVertexArray(VAO[1]) # monkey Vertex Buffer Object glBindBuffer(GL_ARRAY_BUFFER, VBO[1]) glBufferData(GL_ARRAY_BUFFER, monkey_buffer.nbytes, monkey_buffer, GL_STATIC_DRAW) # monkey vertices glEnableVertexAttribArray(0) glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, monkey_buffer.itemsize * 8, ctypes.c_void_p(0)) # monkey textures glEnableVertexAttribArray(1) glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, monkey_buffer.itemsize * 8, ctypes.c_void_p(12)) # monkey normals glVertexAttribPointer(2, 3, GL_FLOAT, GL_FALSE, monkey_buffer.itemsize * 8, ctypes.c_void_p(20)) glEnableVertexAttribArray(2) glBindVertexArray(0) glBindBuffer(GL_ARRAY_BUFFER, 0) # floor VAO glBindVertexArray(VAO[2]) # floor Vertex Buffer Object glBindBuffer(GL_ARRAY_BUFFER, VBO[2]) glBufferData(GL_ARRAY_BUFFER, floor_buffer.nbytes, floor_buffer, GL_STATIC_DRAW) # floor vertices glEnableVertexAttribArray(0) glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, floor_buffer.itemsize * 8, ctypes.c_void_p(0)) # floor textures glEnableVertexAttribArray(1) glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, floor_buffer.itemsize * 8, ctypes.c_void_p(12)) # floor normals glVertexAttribPointer(2, 3, GL_FLOAT, GL_FALSE, floor_buffer.itemsize * 8, ctypes.c_void_p(20)) glEnableVertexAttribArray(2) glBindVertexArray(0) glBindBuffer(GL_ARRAY_BUFFER, 0) textures = glGenTextures(3) load_texture_pygame("meshes/cube.jpg", textures[0]) load_texture_pygame("meshes/monkey.jpg", textures[1]) load_texture_pygame("meshes/floor.jpg", textures[2]) glUseProgram(shader) glClearColor(0, 0.1, 0.1, 1) glEnable(GL_DEPTH_TEST) glEnable(GL_BLEND) glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA) projection = pyrr.matrix44.create_perspective_projection_matrix( 45, 1280 / 720, 0.1, 100) cube_pos = pyrr.matrix44.create_from_translation(pyrr.Vector3([6, 4, 0])) monkey_pos = pyrr.matrix44.create_from_translation( pyrr.Vector3([-4, 4, -4])) floor_pos = pyrr.matrix44.create_from_translation(pyrr.Vector3([0, 0, 0])) model_loc = glGetUniformLocation(shader, "model") proj_loc = glGetUniformLocation(shader, "projection") view_loc = glGetUniformLocation(shader, "view") glUniformMatrix4fv(proj_loc, 1, GL_FALSE, projection) glUseProgram(0) running = True while running: for event in pygame.event.get(): if event.type == pygame.QUIT: running = False elif event.type == pygame.KEYDOWN and event.key == pygame.K_ESCAPE: running = False if event.type == pygame.VIDEORESIZE: glViewport(0, 0, event.w, event.h) projection = pyrr.matrix44.create_perspective_projection_matrix( 45, event.w / event.h, 0.1, 100) glUniformMatrix4fv(proj_loc, 1, GL_FALSE, projection) keys_pressed = pygame.key.get_pressed() if keys_pressed[pygame.K_a]: cam.process_keyboard("LEFT", 0.08) if keys_pressed[pygame.K_d]: cam.process_keyboard("RIGHT", 0.08) if keys_pressed[pygame.K_w]: cam.process_keyboard("FORWARD", 0.08) if keys_pressed[pygame.K_s]: cam.process_keyboard("BACKWARD", 0.08) mouse_pos = pygame.mouse.get_pos() mouse_look(mouse_pos[0], mouse_pos[1]) # to been able to look around 360 degrees, still not perfect if mouse_pos[0] <= 0: pygame.mouse.set_pos((1279, mouse_pos[1])) elif mouse_pos[0] >= 1279: pygame.mouse.set_pos((0, mouse_pos[1])) ct = pygame.time.get_ticks() / 1000 glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT) view = cam.get_view_matrix() glUseProgram(shader) glUniformMatrix4fv(view_loc, 1, GL_FALSE, view) rot_y = pyrr.Matrix44.from_y_rotation(0.8 * ct) model = pyrr.matrix44.multiply(rot_y, cube_pos) # draw the cube glBindVertexArray(VAO[0]) glBindTexture(GL_TEXTURE_2D, textures[0]) glUniformMatrix4fv(model_loc, 1, GL_FALSE, model) glDrawElements(GL_TRIANGLES, len(cube_indices), GL_UNSIGNED_INT, None) # draw the monkey glBindVertexArray(VAO[1]) glBindTexture(GL_TEXTURE_2D, textures[1]) glUniformMatrix4fv(model_loc, 1, GL_FALSE, monkey_pos) glDrawArrays(GL_TRIANGLES, 0, len(monkey_indices)) # draw the floor glBindVertexArray(VAO[2]) glBindTexture(GL_TEXTURE_2D, textures[2]) glUniformMatrix4fv(model_loc, 1, GL_FALSE, floor_pos) glDrawArrays(GL_TRIANGLES, 0, len(floor_indices)) glUseProgram(0) pygame.display.flip() pygame.quit() sys.exit()
glfw.set_window_size_callback(window, window_resize) ##set the mouse position callback glfw.set_cursor_pos_callback(window, mouse_look_clb) ##set the keyboard input callback glfw.set_key_callback(window, key_input_clb) ##capture the mouse cursor glfw.set_input_mode(window, glfw.CURSOR, glfw.CURSOR_DISABLED) ##call back for mouse scroll glfw.set_scroll_callback(window, scroll_clb) ##make the context current glfw.make_context_current(window) ##load here the 3d meshes dh_indices, dh_buffer = ObjLoader.load_model("meshes/final.obj") ##dh_indices, dh_buffer=ObjLoader.load_model("meshes/cube.obj") shader = ShaderLoader.compile_shader("shaders/shader_vert.vs", "shaders/shader_frag.fs") shadowMapShader = Shader("shadowMap.vert", "shadowMap.frag") shadowMapShader.compile() displayShader = Shader("display.vert", "display.frag") displayShader.compile() ##VAO AND vbo VAO = glGenVertexArrays(1) vbo = glGenBuffers(1) ##VAO glBindVertexArray(VAO) ##Vertex Buffer Object
def __init__(self): mesh = ObjLoader() mesh.load_model("newCar.obj") num_verts = len(mesh.model_vertices) // 3 self.verts = pyglet.graphics.vertex_list(num_verts, ('v3f', mesh.model_vertices), ('t2f', mesh.model_textures), ('n3f', mesh.model_normals)) shader = ShaderLoader.compile_shader("shaders/vert.glsl", "shaders/frag.glsl") glUseProgram(shader) # vertices glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 0, self.verts.vertices) glEnableVertexAttribArray(0) # textures glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, 0, self.verts.tex_coords) glEnableVertexAttribArray(1) # normals glVertexAttribPointer(2, 3, GL_FLOAT, GL_FALSE, 0, self.verts.normals) glEnableVertexAttribArray(2) projection = matrix44.create_perspective_projection_matrix( 45.0, 1280 / 720, 0.1, 100.0).flatten().astype("float32") view = matrix44.create_from_translation(Vector3( [0.0, 0.0, -6.0])).flatten().astype("float32") model = matrix44.create_from_translation(Vector3( [0.0, 0.0, -1.0])).flatten().astype("float32") c_projection = numpy.ctypeslib.as_ctypes(projection) c_view = numpy.ctypeslib.as_ctypes(view) c_model = numpy.ctypeslib.as_ctypes(model) view_loc = glGetUniformLocation(shader, b"view") proj_loc = glGetUniformLocation(shader, b"projection") model_loc = glGetUniformLocation(shader, b"model") self.rotate_loc = glGetUniformLocation(shader, b'rotate') self.light_loc = glGetUniformLocation(shader, b"light") glUniformMatrix4fv(view_loc, 1, GL_FALSE, c_view) glUniformMatrix4fv(proj_loc, 1, GL_FALSE, c_projection) glUniformMatrix4fv(model_loc, 1, GL_FALSE, c_model) # texture settings and loading texture = GLuint(0) glGenTextures(1, texture) glBindTexture(GL_TEXTURE_2D, texture) # set the texture wrapping glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT) glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT) # set the texture filtering glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR) glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR) xmas = pyglet.image.load('car.png') image_data = xmas.get_data('RGB', xmas.pitch) glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, xmas.width, xmas.height, 0, GL_RGB, GL_UNSIGNED_BYTE, image_data)
def animation(): # Import position data for x y z coordinates global kinematic_data, model x = kinematic_data[7][0] y = kinematic_data[8][0] z = kinematic_data[9][0] # Load 3d Meshes cube_indices, cube_buffer = ObjLoader.load_model("meshes/Rubiks Cube.obj") grid_indices, grid_buffer = ObjLoader.load_model( "meshes/uv grid floor.obj") # Set up a pg display with Open GL buffer and double buff an d resizable tags pygame.display.set_mode( (WIDTH, HEIGHT), pygame.OPENGL | pygame.DOUBLEBUF | pygame.RESIZABLE) pygame.mouse.set_visible(False) pygame.event.set_grab(True) # Compile the shader program with the source vertex and fragment codes shader = compileProgram(compileShader(vertex_src, GL_VERTEX_SHADER), compileShader(fragment_src, GL_FRAGMENT_SHADER)) # Generate Vertex Array Objects, Vertex Buffer Objects and Element Buffer Objects for each geometry VAO = glGenVertexArrays(2) VBO = glGenBuffers(2) EBO = glGenBuffers(2) # Cube VAO glBindVertexArray(VAO[0]) glBindBuffer(GL_ARRAY_BUFFER, VBO[0]) glBufferData(GL_ARRAY_BUFFER, cube_buffer.nbytes, cube_buffer, GL_STATIC_DRAW) # Cube Element Buffer Object glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, EBO[0]) glBufferData(GL_ELEMENT_ARRAY_BUFFER, cube_indices.nbytes, cube_indices, GL_STATIC_DRAW) glEnableVertexAttribArray(0) glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, cube_buffer.itemsize * 8, ctypes.c_void_p(0)) glEnableVertexAttribArray(1) glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, cube_buffer.itemsize * 8, ctypes.c_void_p(12)) # Grid Floor VAO glBindVertexArray(VAO[1]) glBindBuffer(GL_ARRAY_BUFFER, VBO[1]) glBufferData(GL_ARRAY_BUFFER, grid_buffer.nbytes, grid_buffer, GL_STATIC_DRAW) # Quad Element Buffer Object glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, EBO[1]) glBufferData(GL_ELEMENT_ARRAY_BUFFER, grid_buffer.nbytes, grid_buffer, GL_STATIC_DRAW) glEnableVertexAttribArray(0) glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, grid_buffer.itemsize * 8, ctypes.c_void_p(0)) glEnableVertexAttribArray(1) glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, grid_buffer.itemsize * 8, ctypes.c_void_p(12)) # Generate and load all necessary textures texture = glGenTextures(2) load_texture_pygame("textures/Complete Rubiks Cube.png", texture[0]) load_texture_pygame("textures/uv grid floor.png", texture[1]) # Load Shader program and set up environment on window glUseProgram(shader) glClearColor(0, 0.1, 0.1, 1) glEnable(GL_DEPTH_TEST) glEnable(GL_BLEND) glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA) # Perspective, aspect ratio, near clipping plane, far clipping plane projection = pyrr.matrix44.create_perspective_projection_matrix( 45, WIDTH / HEIGHT, 0.1, 50) grid_pos = pyrr.matrix44.create_from_translation(pyrr.Vector3([0, -2, 0])) # Call matrices locations in the shader source code model_loc = glGetUniformLocation(shader, "model") proj_loc = glGetUniformLocation(shader, "projection") view_loc = glGetUniformLocation(shader, "view") # Upload static matrices to the shader program glUniformMatrix4fv(proj_loc, 1, GL_FALSE, projection) # Set up main application loop running = True do_move = False reset = False i = 0 while running: for event in pygame.event.get(): # Check if the window was closed if event.type == pygame.QUIT: running = False elif event.type == pygame.KEYDOWN and event.key == pygame.K_ESCAPE: running = False # Check if the window was resized if event.type == pygame.VIDEORESIZE: glViewport(0, 0, event.w, event.h) projection = pyrr.matrix44.create_perspective_projection_matrix( 45, event.w / event.h, 0.1, 100) glUniformMatrix4fv(proj_loc, 1, GL_FALSE, projection) velocity = 0.08 keys_pressed = pygame.key.get_pressed() if keys_pressed[pygame.K_RETURN]: do_move = True if keys_pressed[pygame.K_r]: reset = True if keys_pressed[pygame.K_1]: cam.camera_mode("TOPVIEW") if keys_pressed[pygame.K_2]: cam.camera_mode("FRONTVIEW") if keys_pressed[pygame.K_3]: cam.camera_mode("ISOMETRICVIEW") if keys_pressed[pygame.K_4]: cam.camera_mode("FREECAM") if keys_pressed[pygame.K_LSHIFT]: velocity = 0.5 if keys_pressed[pygame.K_a]: cam.process_keyboard("LEFT", velocity) if keys_pressed[pygame.K_d]: cam.process_keyboard("RIGHT", velocity) if keys_pressed[pygame.K_w]: cam.process_keyboard("FORWARD", velocity) if keys_pressed[pygame.K_s]: cam.process_keyboard("BACKWARD", velocity) if keys_pressed[pygame.K_SPACE]: cam.process_keyboard("UP", velocity) if keys_pressed[pygame.K_LCTRL]: cam.process_keyboard("DOWN", velocity) mouse_pos = pygame.mouse.get_pos() if mouse_pos[0] <= 0: pygame.mouse.set_pos((1279, mouse_pos[1])) elif mouse_pos[0] >= 1279: pygame.mouse.set_pos((0, mouse_pos[1])) mouse_look(mouse_pos[0], mouse_pos[1]) glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT) view = cam.get_view_matrix() glUniformMatrix4fv(view_loc, 1, GL_FALSE, view) if not do_move: model = pyrr.matrix44.create_from_translation( pyrr.Vector3([0, 0, 0])) elif do_move: model = pyrr.matrix44.create_from_translation( pyrr.Vector3([x[i], y[i], z[i]])) glBindVertexArray(VAO[0]) glBindTexture(GL_TEXTURE_2D, texture[0]) glUniformMatrix4fv(model_loc, 1, GL_FALSE, model) glDrawArrays(GL_TRIANGLES, 0, len(cube_indices)) glBindVertexArray(VAO[1]) glBindTexture(GL_TEXTURE_2D, texture[1]) glUniformMatrix4fv(model_loc, 1, GL_FALSE, grid_pos) glDrawArrays(GL_TRIANGLES, 0, len(grid_indices)) pygame.display.flip() pygame.time.wait(10) if reset: i = 0 reset = False do_move = False if do_move: if i < len(x) - 1: i += 1
# check if window was created if not window: glfw.terminate() raise Exception("glfw window can not be created!") # set window's position glfw.set_window_pos(window, 400, 200) # set the callback function for window resize glfw.set_window_size_callback(window, window_resize) # make the context current glfw.make_context_current(window) # load here the 3d meshes chibi_indices, chibi_buffer = ObjLoader.load_model("meshes/chair.obj") monkey_indices, monkey_buffer = ObjLoader.load_model("meshes/table.obj") shader = compileProgram(compileShader(vertex_src, GL_VERTEX_SHADER), compileShader(fragment_src, GL_FRAGMENT_SHADER)) # VAO and VBO VAO = glGenVertexArrays(2) VBO = glGenBuffers(2) # EBO = glGenBuffers(1) # Chibi VAO glBindVertexArray(VAO[0]) # Chibi Vertex Buffer Object glBindBuffer(GL_ARRAY_BUFFER, VBO[0]) glBufferData(GL_ARRAY_BUFFER, chibi_buffer.nbytes, chibi_buffer, GL_STATIC_DRAW)
class GLPlotWidget(QtWidgets.QOpenGLWidget): # default window size width, height = 1600, 800 def __init__(self): QtWidgets.QOpenGLWidget.__init__(self) self.i = 0 # # def initializeCL(self): # clinit() def initializeGL(self): """Initialize OpenGL, VBOs, upload data on the GPU, etc.""" print('Loaded OpenGL {} with GLSL {}'.format( str(gl.glGetString(gl.GL_VERSION), 'utf-8'), str(gl.glGetString(gl.GL_SHADING_LANGUAGE_VERSION), 'utf-8'))) gl.glClearColor(0.2, 0.2, 0.2, 0) # Background color gl.glEnable(gl.GL_DEPTH_TEST) # Enable depth buffer # gl.glEnable(gl.GL_BLEND) # Enable blending for alpha # gl.glBlendFunc(gl.GL_SRC_ALPHA, gl.GL_ONE_MINUS_SRC_ALPHA) # gl.glBlendEquationSeparate(gl.GL_FUNC_ADD, gl.GL_FUNC_ADD) # Compiling vertex & fragment shader vs = compileVertexShader(VS) fs = compileFragmentShader(FS) self.shaders_program = createProgram(vs, fs) gl.glUseProgram(self.shaders_program) # Set up uniforms for sending data from host to the shaders self.T_IM_I_device = gl.glGetUniformLocation(self.shaders_program, 'T_IM_I') self.T_SI_S_device = gl.glGetUniformLocation(self.shaders_program, 'T_SI_S') self.T_CS_C_device = gl.glGetUniformLocation(self.shaders_program, 'T_CS_C') self.T_NC_N_device = gl.glGetUniformLocation(self.shaders_program, 'T_NC_N') self.T_NR_N_device = gl.glGetUniformLocation(self.shaders_program, 'T_NR_N') self.is_radial = gl.glGetUniformLocation(self.shaders_program, 'is_radial') # Use the custom (very simple) object loader. # This only handles the most basic of models self.model = ObjLoader() self.model.loadModel('manta_test_object_with_plane.obj') self.image_frame_model = ObjLoader() self.image_frame_model.loadModel('image_test_object.obj') # Put the model vertices into vertex buffer objects (VBOs) self.vbo_model_vertices = glvbo.VBO(self.model.vertices) self.vbo_image_frame_vertices = glvbo.VBO( self.image_frame_model.vertices) # usage=gl.DYNAMIC_DRAW, # target=gl.GL_ARRAY_BUFFER self.vbo_model_normals = glvbo.VBO(self.model.normals) self.vbo_image_frame_normals = glvbo.VBO( self.image_frame_model.normals) # For the display, we are going to wiggle the model's roll and pitch. self.psi = 0 # Roll self.phi = 0 # Pitch self.theta = 0 # Yaw gl.glUseProgram(self.shaders_program) def drawModel(self, type, image_type, model, vbo_vertices, vbo_normals): # Bind (enable) the VBO for this model's vertices vbo_vertices.bind() # Connect VBO to 1st layout in shader, i.e. to vec3 p_MV_M gl.glEnableVertexAttribArray(0) # Describe vertex format: 3 single precision coordinates gl.glVertexAttribPointer(0, 3, gl.GL_FLOAT, gl.GL_FALSE, 0, None) # Repeat the same procedure for the normals too. # The normals are needed to compute lighting in the fragment shader vbo_normals.bind() gl.glEnableVertexAttribArray(1) gl.glVertexAttribPointer(1, 3, gl.GL_FLOAT, gl.GL_FALSE, 0, None) # Tell vertex shader whether we are rendering the sonar image or not, # so it can adjust its transforms accordingly if image_type == 'cartesian_view': gl.glUniform1i(self.is_radial, 0) elif image_type == 'radial_view': gl.glUniform1i(self.is_radial, 1) else: raise Exception("This should never happen") T_IM_I, T_SI_S, T_CS_C, T_NC_N, T_NR_N \ = computeGeometry(type, self.psi, self.theta, self.phi) # Upload all the newly computed transforms to the device gl.glUniformMatrix4fv(self.T_IM_I_device, 1, gl.GL_TRUE, T_IM_I) gl.glUniformMatrix4fv(self.T_SI_S_device, 1, gl.GL_TRUE, T_SI_S) gl.glUniformMatrix4fv(self.T_CS_C_device, 1, gl.GL_TRUE, T_CS_C) gl.glUniformMatrix4fv(self.T_NC_N_device, 1, gl.GL_TRUE, T_NC_N) gl.glUniformMatrix4fv(self.T_NR_N_device, 1, gl.GL_TRUE, T_NR_N) # The grand finale: Draw all the points gl.glDrawArrays(gl.GL_TRIANGLES, 0, len(model.vertices)) def paintGL(self): """This function gets called repeatedly. Each time we render two images: Left. A normal camera view, from the sonar looking at the image center Right. A bird view of the image (perfect fit) """ # Start fresh. Clear the screen buffer. gl.glClear(gl.GL_COLOR_BUFFER_BIT | gl.GL_DEPTH_BUFFER_BIT) for image_type, image_vals in { 'radial_view': { 'viewport': list(map(int, [0, 0, self.width / 2, self.height])) }, 'cartesian_view': { 'viewport': list(map(int, [self.width / 2, 0, self.width / 2, self.height])) } }.items(): # Specify which part of the screen to draw in (left or right) gl.glViewport(*image_vals['viewport']) for type, vals in { 'model': [self.model, self.vbo_model_vertices, self.vbo_model_normals], 'image_frame': [ self.image_frame_model, self.vbo_image_frame_vertices, self.vbo_image_frame_normals ] }.items(): # Let drawModel draw the current model self.drawModel(type, image_type, *vals) # For each iteration, we adjust the roll and pitch of the model a bit. # This makes the rendering more interesting to watch, but also helps # identify corner cases (it's easier to "think" 3D when there's movement) speed = 1 # Adjust at will self.psi = -pi * 22.5 / 180 * sin( self.i * pi * speed / 180) # Roll (around x-axis) self.theta = -pi * 12.5 / 180 * sin( self.i * pi * speed / 360) # Pitch (around y-axis) self.phi = -pi / 180 * speed * 0 # Yaw (around z-axis) self.update() self.i += 1 def resizeGL(self, width, height): """Called upon window resizing: Reinitialize the viewport.""" self.width, self.height = width, height
def __init__(self): self.tree = ObjLoader() self.tree.load_model("../models/xmas_tree.obj") self.vertex_shader_source = b""" #version 330 in layout(location = 0) vec3 positions; in layout(location = 1) vec2 textureCoords; in layout(location = 2) vec3 normals; uniform mat4 light; uniform mat4 projection; uniform mat4 view; uniform mat4 model; uniform mat4 rotate; out vec2 textures; out vec3 fragNormal; void main() { fragNormal = (light * vec4(normals, 0.0f)).xyz; gl_Position = projection * view * model * rotate * vec4(positions, 1.0f); textures = vec2(textureCoords.x, 1 - textureCoords.y); } """ self.fragment_shader_source = b""" #version 330 in vec2 textures; in vec3 fragNormal; uniform sampler2D sampTexture; out vec4 outColor; void main() { vec3 ambientLightIntensity = vec3(0.3f, 0.2f, 0.4f); vec3 sunLightIntensity = vec3(0.9f, 0.9f, 0.9f); vec3 sunLightDirection = normalize(vec3(1.0f, 1.0f, -0.5f)); vec4 texel = texture(sampTexture, textures); vec3 lightIntensity = ambientLightIntensity + sunLightIntensity * max(dot(fragNormal, sunLightDirection), 0.0f); outColor = vec4(texel.rgb * lightIntensity, texel.a); } """ vertex_buff = ctypes.create_string_buffer(self.vertex_shader_source) c_vertex = ctypes.cast(ctypes.pointer(ctypes.pointer(vertex_buff)), ctypes.POINTER(ctypes.POINTER(GLchar))) vertex_shader = glCreateShader(GL_VERTEX_SHADER) glShaderSource(vertex_shader, 1, c_vertex, None) glCompileShader(vertex_shader) fragment_buff = ctypes.create_string_buffer( self.fragment_shader_source) c_fragment = ctypes.cast(ctypes.pointer(ctypes.pointer(fragment_buff)), ctypes.POINTER(ctypes.POINTER(GLchar))) fragment_shader = glCreateShader(GL_FRAGMENT_SHADER) glShaderSource(fragment_shader, 1, c_fragment, None) glCompileShader(fragment_shader) shader = glCreateProgram() glAttachShader(shader, vertex_shader) glAttachShader(shader, fragment_shader) glLinkProgram(shader) glUseProgram(shader) vbo = GLuint(0) glGenBuffers(1, vbo) glBindBuffer(GL_ARRAY_BUFFER, vbo) glBufferData(GL_ARRAY_BUFFER, len(self.tree.model) * 4, self.tree.c_model, GL_STATIC_DRAW) texture_offset = len(self.tree.vertex_index) * 12 normal_offset = (texture_offset + len(self.tree.texture_index) * 8) #positions glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, self.tree.model.itemsize * 3, ctypes.c_void_p(0)) glEnableVertexAttribArray(0) #textures glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, self.tree.model.itemsize * 2, ctypes.c_void_p(texture_offset)) glEnableVertexAttribArray(1) #normals glVertexAttribPointer(2, 3, GL_FLOAT, GL_FALSE, self.tree.model.itemsize * 3, ctypes.c_void_p(normal_offset)) glEnableVertexAttribArray(2) texture = GLuint(0) glGenTextures(1, texture) glBindTexture(GL_TEXTURE_2D, texture) #set the texture wrapping glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT) glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT) #set the texture filtering glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR) glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR) glEnable(GL_BLEND) glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA) xmas = pyglet.image.load('../models/xmas_texture.jpg') image_data = xmas.get_data('RGB', xmas.pitch) glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, xmas.width, xmas.height, 0, GL_RGB, GL_UNSIGNED_BYTE, image_data) view = pyrr.matrix44.create_from_translation( pyrr.Vector3([0.0, 0.0, -3.0])).flatten() projection = pyrr.matrix44.create_perspective_projection_matrix( 62.0, 1280 / 720, 0.1, 100.0).flatten() model = pyrr.matrix44.create_from_translation( pyrr.Vector3([0.0, 0.5, -2.0])).flatten() c_view = (GLfloat * len(view))(*view) c_projection = (GLfloat * len(projection))(*projection) c_model = (GLfloat * len(model))(*model) self.rotate_loc = glGetUniformLocation(shader, b'rotate') self.view_loc = glGetUniformLocation(shader, b"view") self.proj_loc = glGetUniformLocation(shader, b"projection") self.model_loc = glGetUniformLocation(shader, b"model") self.light_loc = glGetUniformLocation(shader, b"light") glUniformMatrix4fv(self.view_loc, 1, GL_FALSE, c_view) glUniformMatrix4fv(self.proj_loc, 1, GL_FALSE, c_projection) glUniformMatrix4fv(self.model_loc, 1, GL_FALSE, c_model) self.rot_y = pyrr.Matrix44.identity()
# set window's position glfw.set_window_pos(window, 400, 200) # set the callback function for window resize glfw.set_window_size_callback(window, window_resize) # set the mouse position callback glfw.set_cursor_pos_callback(window, mouse_look_clb) # set the mouse enter callback glfw.set_cursor_enter_callback(window, mouse_enter_clb) # make the context current glfw.make_context_current(window) # load here the 3d meshes cube_indices, cube_buffer = ObjLoader.load_model("meshes/cube.obj") monkey_indices, monkey_buffer = ObjLoader.load_model("meshes/monkey.obj") floor_indices, floor_buffer = ObjLoader.load_model("meshes/floor.obj") shader = compileProgram(compileShader(vertex_src, GL_VERTEX_SHADER), compileShader(fragment_src, GL_FRAGMENT_SHADER)) # VAO and VBO VAO = glGenVertexArrays(3) VBO = glGenBuffers(3) # cube VAO glBindVertexArray(VAO[0]) # cube Vertex Buffer Object glBindBuffer(GL_ARRAY_BUFFER, VBO[0]) glBufferData(GL_ARRAY_BUFFER, cube_buffer.nbytes, cube_buffer, GL_STATIC_DRAW)
# set window's position glfw.set_window_pos(window, 400, 200) # set the callback function for window resize glfw.set_window_size_callback(window, window_resize) # set the mouse position callback glfw.set_cursor_pos_callback(window, mouse_look_clb) # set the keyboard input callback glfw.set_key_callback(window, key_input_clb) # capture the mouse cursor glfw.set_input_mode(window, glfw.CURSOR, glfw.CURSOR_DISABLED) # make the context current glfw.make_context_current(window) # load here the 3d meshes chibi_indices, chibi_buffer = ObjLoader.load_model("meshes/chibi.obj") plane_buffer = [ 0.0, 0.0, 0.0, 0.0, 0.0, 10.0, 0.0, 0.0, 1.0, 0.0, 10.0, 10.0, 0.0, 1.0, 1.0, 0.0, 10.0, 0.0, 0.0, 1.0 ] plane_buffer = np.array(plane_buffer, dtype=np.float32) plane_indices = [0, 1, 2, 2, 3, 0] plane_indices = np.array(plane_indices, dtype=np.uint32) shader = compileProgram(compileShader(vertex_src, GL_VERTEX_SHADER), compileShader(fragment_src, GL_FRAGMENT_SHADER)) # VAO and VBO
xoffset = xpos - lastX yoffset = lastY - ypos lastX = xpos lastY = ypos cam.process_mouse_movement(xoffset, yoffset) def main_menu(): pass # Load 3d Meshes cube_indices, cube_buffer = ObjLoader.load_model("meshes/Rubiks Cube.obj") grid_indices, grid_buffer = ObjLoader.load_model("meshes/uv grid floor.obj") # Initialize a pygame application pygame.init() # Set up a pygame display with Open GL buffer and double buff an d resizable tags pygame.display.set_mode((WIDTH, HEIGHT), pygame.OPENGL | pygame.DOUBLEBUF | pygame.RESIZABLE) # pygame.mouse.set_visible(False) pygame.event.set_grab(True) # Compile the shader program with the source vertex and fragment codes shader = compileProgram(compileShader(vertex_src, GL_VERTEX_SHADER), compileShader(fragment_src, GL_FRAGMENT_SHADER))
glfw.set_window_pos(window, 400, 200) # definindo a função de retorno de chamada para redimensionar a janela glfw.set_window_size_callback(window, window_resize_clb) # definindo o retorno de chamada da posição do mouse glfw.set_cursor_pos_callback(window, mouse_look_clb) # definindo o retorno de chamada da entrada do teclado glfw.set_key_callback(window, key_input_clb) # capturar o cursor do mouse glfw.set_input_mode(window, glfw.CURSOR, glfw.CURSOR_DISABLED) glfw.make_context_current(window) # Carregando objetos 3d walled_indices, walled_buffer = ObjLoader.load_model("meshes/wooden-wall3.obj") trees_indices, trees_buffer = ObjLoader.load_model("meshes/outono.obj") tower_indices, tower_buffer = ObjLoader.load_model("meshes/wallcastle2.obj") floor_indices, floor_buffer = ObjLoader.load_model("meshes/floor.obj") shader = compileProgram(compileShader(vertex_src, GL_VERTEX_SHADER), compileShader(fragment_src, GL_FRAGMENT_SHADER)) # VAO e VBO VAO = glGenVertexArrays(4) VBO = glGenBuffers(4) # walled VAO glBindVertexArray(VAO[0]) # walled Vertex Buffer Object glBindBuffer(GL_ARRAY_BUFFER, VBO[0])
from OpenGL.GL import * from OpenGL.GLU import * from OpenGL.GLUT import * from sys import argv from Loader import Loader from ObjLoader import ObjLoader from QEM import QEM script,filePath = argv loader = Loader(); files = loader.load(filePath); # for file in files: # print file objLoader = ObjLoader("./models/123.obj"); fileContent = objLoader.load(); qem = QEM() qem.toLowPloy(fileContent)
def main(): global shader vertex_src = """ # version 330 layout(location = 0) in vec3 a_position; layout(location = 1) in vec2 a_texture; layout(location = 2) in vec3 a_normal; uniform mat4 model; uniform mat4 projection; uniform mat4 view; out vec2 v_texture; void main() { gl_Position = projection * view * model * vec4(a_position, 1.0); v_texture = a_texture; } """ fragment_src = """ # version 330 in vec2 v_texture; out vec4 out_color; uniform sampler2D s_texture; void main() { out_color = texture(s_texture, v_texture); } """ # initializing glfw library if not glfw.init(): raise Exception("glfw can not be initialized!") if "Windows" in pltf.platform(): glfw.window_hint(glfw.CONTEXT_VERSION_MAJOR, 4) glfw.window_hint(glfw.CONTEXT_VERSION_MINOR, 6) glfw.window_hint(glfw.OPENGL_PROFILE, glfw.OPENGL_CORE_PROFILE) glfw.window_hint(glfw.OPENGL_FORWARD_COMPAT, True) else: glfw.window_hint(glfw.CONTEXT_VERSION_MAJOR, 4) glfw.window_hint(glfw.CONTEXT_VERSION_MINOR, 1) glfw.window_hint(glfw.OPENGL_PROFILE, glfw.OPENGL_CORE_PROFILE) glfw.window_hint(glfw.OPENGL_FORWARD_COMPAT, True) # creating the window window = glfw.create_window(1280, 720, "My OpenGL window", None, None) # check if window was created if not window: glfw.terminate() raise Exception("glfw window can not be created!") # set window's position glfw.set_window_pos(window, 100, 100) # set the callback function for window resize glfw.set_window_size_callback(window, window_resize_clb) # set the mouse position callback glfw.set_cursor_pos_callback(window, mouse_look_clb) # set the keyboard input callback glfw.set_key_callback(window, key_input_clb) # capture the mouse cursor glfw.set_input_mode(window, glfw.CURSOR, glfw.CURSOR_DISABLED) # make the context current glfw.make_context_current(window) # load here the 3d meshes chibi_indices, chibi_buffer = ObjLoader.load_model("meshes/chibi.obj") plane_buffer = [ 0.0, 0.0, 0.0, 0.0, 0.0, 10.0, 0.0, 0.0, 1.0, 0.0, 10.0, 10.0, 0.0, 1.0, 1.0, 0.0, 10.0, 0.0, 0.0, 1.0 ] plane_buffer = np.array(plane_buffer, dtype=np.float32) plane_indices = [0, 1, 2, 2, 3, 0] plane_indices = np.array(plane_indices, dtype=np.uint32) # VAO and VBO VAO = glGenVertexArrays(2) VBO = glGenBuffers(2) EBO = glGenBuffers(1) # Chibi VAO glBindVertexArray(VAO[0]) shader = compileProgram(compileShader(vertex_src, GL_VERTEX_SHADER), compileShader(fragment_src, GL_FRAGMENT_SHADER)) # Chibi Vertex Buffer Object glBindBuffer(GL_ARRAY_BUFFER, VBO[0]) glBufferData(GL_ARRAY_BUFFER, chibi_buffer.nbytes, chibi_buffer, GL_STATIC_DRAW) # chibi vertices glEnableVertexAttribArray(0) glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, chibi_buffer.itemsize * 8, ctypes.c_void_p(0)) # chibi textures glEnableVertexAttribArray(1) glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, chibi_buffer.itemsize * 8, ctypes.c_void_p(12)) # chibi normals glVertexAttribPointer(2, 3, GL_FLOAT, GL_FALSE, chibi_buffer.itemsize * 8, ctypes.c_void_p(20)) glEnableVertexAttribArray(2) # Plane VAO glBindVertexArray(VAO[1]) # Plane Vertex Buffer Object glBindBuffer(GL_ARRAY_BUFFER, VBO[1]) glBufferData(GL_ARRAY_BUFFER, plane_buffer.nbytes, plane_buffer, GL_STATIC_DRAW) glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, EBO) glBufferData(GL_ELEMENT_ARRAY_BUFFER, plane_indices.nbytes, plane_indices, GL_STATIC_DRAW) # plane vertices glEnableVertexAttribArray(0) glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, plane_buffer.itemsize * 5, ctypes.c_void_p(0)) # plane textures glEnableVertexAttribArray(1) glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, plane_buffer.itemsize * 5, ctypes.c_void_p(12)) textures = glGenTextures(2) load_texture("meshes/chibi.png", textures[0]) # create texture for the plane glBindTexture(GL_TEXTURE_2D, textures[1]) # texture wrapping params glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT) glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT) # texture filtering params glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR) glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR) glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, 1280, 720, 0, GL_RGBA, GL_UNSIGNED_BYTE, None) glBindTexture(GL_TEXTURE_2D, 0) depth_buff = glGenRenderbuffers(1) glBindRenderbuffer(GL_RENDERBUFFER, depth_buff) glRenderbufferStorage(GL_RENDERBUFFER, GL_DEPTH_COMPONENT, 1280, 720) FBO = glGenFramebuffers(1) glBindFramebuffer(GL_FRAMEBUFFER, FBO) glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, textures[1], 0) glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_RENDERBUFFER, depth_buff) glBindFramebuffer(GL_FRAMEBUFFER, 0) glUseProgram(shader) glClearColor(0, 0.1, 0.1, 1) glEnable(GL_DEPTH_TEST) glEnable(GL_BLEND) glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA) projection = pyrr.matrix44.create_perspective_projection_matrix( 45, 1280 / 720, 0.1, 100) chibi_pos_main = pyrr.matrix44.create_from_translation( pyrr.Vector3([0, 0, -5])) plane_pos = pyrr.matrix44.create_from_translation( pyrr.Vector3([-20, -3, -10])) model_loc = glGetUniformLocation(shader, "model") proj_loc = glGetUniformLocation(shader, "projection") view_loc = glGetUniformLocation(shader, "view") glUniformMatrix4fv(proj_loc, 1, GL_FALSE, projection) glUseProgram(0) # the main application loop while not glfw.window_should_close(window): glfw.poll_events() do_movement() glClearColor(0, 0.1, 0.1, 1) glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT) view = cam.get_view_matrix() glUseProgram(shader) glUniformMatrix4fv(view_loc, 1, GL_FALSE, view) rot_y = pyrr.Matrix44.from_y_rotation(0.8 * glfw.get_time()) model = pyrr.matrix44.multiply(rot_y, chibi_pos_main) # draw the chibi character glBindVertexArray(VAO[0]) glBindTexture(GL_TEXTURE_2D, textures[0]) glUniformMatrix4fv(model_loc, 1, GL_FALSE, model) glDrawArrays(GL_TRIANGLES, 0, len(chibi_indices)) # draw the chibi to the custom frame buffer glBindFramebuffer(GL_FRAMEBUFFER, FBO) glClearColor(0.0, 0.0, 0.0, 1.0) glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT) glDrawArrays(GL_TRIANGLES, 0, len(chibi_indices)) glBindVertexArray(0) glBindFramebuffer(GL_FRAMEBUFFER, 0) # draw the plane glBindVertexArray(VAO[1]) glBindTexture(GL_TEXTURE_2D, textures[1]) glUniformMatrix4fv(model_loc, 1, GL_FALSE, plane_pos) glDrawElements(GL_TRIANGLES, len(plane_indices), GL_UNSIGNED_INT, None) glUseProgram(0) glfw.swap_buffers(window) # terminate glfw, free up allocated resources glfw.terminate()
def main(): global shader vertex_src = """ # version 330 layout(location = 0) in vec3 a_position; layout(location = 1) in vec2 a_texture; layout(location = 2) in vec3 a_normal; uniform mat4 model; uniform mat4 projection; uniform mat4 view; out vec2 v_texture; void main() { gl_Position = projection * view * model * vec4(a_position, 1.0); v_texture = a_texture; } """ fragment_src = """ # version 330 in vec2 v_texture; out vec4 out_color; uniform sampler2D s_texture; void main() { out_color = texture(s_texture, v_texture); } """ # initializing glfw library if not glfw.init(): raise Exception("glfw can not be initialized!") if "Windows" in pltf.platform(): glfw.window_hint(glfw.CONTEXT_VERSION_MAJOR, 4) glfw.window_hint(glfw.CONTEXT_VERSION_MINOR, 6) glfw.window_hint(glfw.OPENGL_PROFILE, glfw.OPENGL_CORE_PROFILE) glfw.window_hint(glfw.OPENGL_FORWARD_COMPAT, True) else: glfw.window_hint(glfw.CONTEXT_VERSION_MAJOR, 4) glfw.window_hint(glfw.CONTEXT_VERSION_MINOR, 1) glfw.window_hint(glfw.OPENGL_PROFILE, glfw.OPENGL_CORE_PROFILE) glfw.window_hint(glfw.OPENGL_FORWARD_COMPAT, True) # creating the window window = glfw.create_window(WIDTH, HEIGHT, "My OpenGL window", None, None) # check if window was created if not window: glfw.terminate() raise Exception("glfw window can not be created!") # set window's position glfw.set_window_pos(window, 100, 100) # set the callback function for window resize glfw.set_window_size_callback(window, window_resize_clb) # set the mouse position callback glfw.set_cursor_pos_callback(window, mouse_look_clb) # set the keyboard input callback glfw.set_key_callback(window, key_input_clb) # capture the mouse cursor glfw.set_input_mode(window, glfw.CURSOR, glfw.CURSOR_DISABLED) # make the context current glfw.make_context_current(window) # load here the 3d meshes cube_indices, cube_buffer = ObjLoader.load_model("meshes/cube.obj") monkey_indices, monkey_buffer = ObjLoader.load_model("meshes/monkey.obj") floor_indices, floor_buffer = ObjLoader.load_model("meshes/floor.obj") # VAO and VBO VAO = glGenVertexArrays(3) VBO = glGenBuffers(3) # cube VAO glBindVertexArray(VAO[0]) shader = compileProgram(compileShader(vertex_src, GL_VERTEX_SHADER), compileShader(fragment_src, GL_FRAGMENT_SHADER)) # cube Vertex Buffer Object glBindBuffer(GL_ARRAY_BUFFER, VBO[0]) glBufferData(GL_ARRAY_BUFFER, cube_buffer.nbytes, cube_buffer, GL_STATIC_DRAW) # cube vertices glEnableVertexAttribArray(0) glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, cube_buffer.itemsize * 8, ctypes.c_void_p(0)) # cube textures glEnableVertexAttribArray(1) glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, cube_buffer.itemsize * 8, ctypes.c_void_p(12)) # cube normals glVertexAttribPointer(2, 3, GL_FLOAT, GL_FALSE, cube_buffer.itemsize * 8, ctypes.c_void_p(20)) glEnableVertexAttribArray(2) # monkey VAO glBindVertexArray(VAO[1]) # monkey Vertex Buffer Object glBindBuffer(GL_ARRAY_BUFFER, VBO[1]) glBufferData(GL_ARRAY_BUFFER, monkey_buffer.nbytes, monkey_buffer, GL_STATIC_DRAW) # monkey vertices glEnableVertexAttribArray(0) glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, monkey_buffer.itemsize * 8, ctypes.c_void_p(0)) # monkey textures glEnableVertexAttribArray(1) glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, monkey_buffer.itemsize * 8, ctypes.c_void_p(12)) # monkey normals glVertexAttribPointer(2, 3, GL_FLOAT, GL_FALSE, monkey_buffer.itemsize * 8, ctypes.c_void_p(20)) glEnableVertexAttribArray(2) # floor VAO glBindVertexArray(VAO[2]) # floor Vertex Buffer Object glBindBuffer(GL_ARRAY_BUFFER, VBO[2]) glBufferData(GL_ARRAY_BUFFER, floor_buffer.nbytes, floor_buffer, GL_STATIC_DRAW) # floor vertices glEnableVertexAttribArray(0) glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, floor_buffer.itemsize * 8, ctypes.c_void_p(0)) # floor textures glEnableVertexAttribArray(1) glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, floor_buffer.itemsize * 8, ctypes.c_void_p(12)) # floor normals glVertexAttribPointer(2, 3, GL_FLOAT, GL_FALSE, floor_buffer.itemsize * 8, ctypes.c_void_p(20)) glEnableVertexAttribArray(2) textures = glGenTextures(3) load_texture("meshes/cube.jpg", textures[0]) load_texture("meshes/monkey.jpg", textures[1]) load_texture("meshes/floor.jpg", textures[2]) glUseProgram(shader) glClearColor(0, 0.1, 0.1, 1) glEnable(GL_DEPTH_TEST) glEnable(GL_BLEND) glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA) projection = pyrr.matrix44.create_perspective_projection_matrix(45, WIDTH / HEIGHT, 0.1, 100) cube_pos = pyrr.matrix44.create_from_translation(pyrr.Vector3([6, 4, 0])) monkey_pos = pyrr.matrix44.create_from_translation(pyrr.Vector3([-4, 4, -4])) floor_pos = pyrr.matrix44.create_from_translation(pyrr.Vector3([0, 0, 0])) model_loc = glGetUniformLocation(shader, "model") proj_loc = glGetUniformLocation(shader, "projection") view_loc = glGetUniformLocation(shader, "view") glUniformMatrix4fv(proj_loc, 1, GL_FALSE, projection) glUseProgram(0) # the main application loop while not glfw.window_should_close(window): glfw.poll_events() glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT) view = cam.get_view_matrix() glUseProgram(shader) glUniformMatrix4fv(view_loc, 1, GL_FALSE, view) rot_y = pyrr.Matrix44.from_y_rotation(0.8 * glfw.get_time()) model = pyrr.matrix44.multiply(rot_y, cube_pos) # draw the cube glBindVertexArray(VAO[0]) glBindTexture(GL_TEXTURE_2D, textures[0]) glUniformMatrix4fv(model_loc, 1, GL_FALSE, model) glDrawArrays(GL_TRIANGLES, 0, len(monkey_indices)) # draw the monkey glBindVertexArray(VAO[1]) glBindTexture(GL_TEXTURE_2D, textures[1]) glUniformMatrix4fv(model_loc, 1, GL_FALSE, monkey_pos) glDrawArrays(GL_TRIANGLES, 0, len(monkey_indices)) # draw the floor glBindVertexArray(VAO[2]) glBindTexture(GL_TEXTURE_2D, textures[2]) glUniformMatrix4fv(model_loc, 1, GL_FALSE, floor_pos) glDrawArrays(GL_TRIANGLES, 0, len(floor_indices)) glUseProgram(0) glfw.swap_buffers(window) # terminate glfw, free up allocated resources glfw.terminate()
class Rock: ROCK_WIDTH = 3 instances = [] instance_locations = [] db = DBConnector() rock_path = db.execute("SELECT path FROM visualpropertypath WHERE name = 'rock'")[0][0] del db mesh = ObjLoader() mesh.load_model(rock_path) num_verts = len(mesh.vertex_index) texture_offset = len(mesh.vertex_index) * 12 data = numpy.array(mesh.model, dtype=GLfloat) del mesh def __init__(self, tekstur): Rock.instances.append(self) Rock.instance_locations.append([]) self.vao_rock = GLuint() # generate a vertex array object for the rock - the vao glGenVertexArrays(1, self.vao_rock) # bind the rock's vao glBindVertexArray(self.vao_rock) # setup the rock's vertex buffer object - the vbo vbo_sphere = pyglet.graphics.vertexbuffer.create_buffer(Rock.data.nbytes, GL_ARRAY_BUFFER, GL_STATIC_DRAW) vbo_sphere.bind() vbo_sphere.set_data(Rock.data.ctypes.data) # vertex attribute pointer settings for the rock vbo glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 0, 0) glEnableVertexAttribArray(0) # textures glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, 0, Rock.texture_offset) glEnableVertexAttribArray(1) glBindBuffer(GL_ARRAY_BUFFER, 0) # unbind the vbo glBindVertexArray(0) # unbind the vao # region texture settings self.texture = GLuint(0) glGenTextures(1, self.texture) glBindTexture(GL_TEXTURE_2D, self.texture) # set the texture wrapping glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT) glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT) # set the texture filtering glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR) glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR) image = pyglet.image.load(tekstur) image_data = image.get_data('RGB', image.pitch) glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, image.width, image.height, 0, GL_RGB, GL_UNSIGNED_BYTE, image_data) # endregion def render(self, translasi): # to draw the rock, we need to rebind the rock's vao model_loc = ObjectShader.model_loc rock_model = matrix44.create_from_translation(translasi).flatten().astype("float32") #this is the model transformation matrix c_rock_model = numpy.ctypeslib.as_ctypes(rock_model) glBindVertexArray(self.vao_rock) glBindTexture(GL_TEXTURE_2D, self.texture) glUniformMatrix4fv(model_loc, 1, GL_FALSE, c_rock_model) glDrawArrays(GL_POLYGON, 0, Rock.num_verts) glDrawArrays(GL_TRIANGLES, 0, Rock.num_verts) glBindVertexArray(0) def batch_render(self, list_translasi): # me-render banyak rock dengan tekstur sama glBindVertexArray(self.vao_rock) glBindTexture(GL_TEXTURE_2D, self.texture) model_loc = ObjectShader.model_loc for translasi in list_translasi: rock_model = matrix44.create_from_translation(Vector3(translasi)).flatten().astype("float32") #this is the model transformation matrix c_rock_model = numpy.ctypeslib.as_ctypes(rock_model) glUniformMatrix4fv(model_loc, 1, GL_FALSE, c_rock_model) glDrawArrays(GL_TRIANGLES, 0, Rock.num_verts) glBindVertexArray(0) @staticmethod def add_instance_location(rocktype, location): Rock.instance_locations[rocktype].append(location) @staticmethod def draw_all_rock(): for i in range(len(Rock.instances)): Rock.instances[i].batch_render(Rock.instance_locations[i])
glfw.set_window_pos(window, 400, 200) # set the callback function for window resize glfw.set_window_size_callback(window, window_resize_clb) # set the mouse position callback glfw.set_cursor_pos_callback(window, mouse_look_clb) # set the keyboard input callback glfw.set_key_callback(window, key_input_clb) # capture the mouse cursor glfw.set_input_mode(window, glfw.CURSOR, glfw.CURSOR_DISABLED) # make the context current glfw.make_context_current(window) # load here the 3d meshes cube_indices, cube_buffer = ObjLoader.load_model("meshes/20-table/table.obj") monkey_indices, monkey_buffer = ObjLoader.load_model("meshes/chibi.obj") floor_indices, floor_buffer = ObjLoader.load_model("meshes/floor.obj") shader = compileProgram(compileShader(vertex_src, GL_VERTEX_SHADER), compileShader(fragment_src, GL_FRAGMENT_SHADER)) # VAO and VBO VAO = glGenVertexArrays(3) VBO = glGenBuffers(3) # cube VAO glBindVertexArray(VAO[0]) # cube Vertex Buffer Object glBindBuffer(GL_ARRAY_BUFFER, VBO[0]) glBufferData(GL_ARRAY_BUFFER, cube_buffer.nbytes, cube_buffer, GL_STATIC_DRAW)
# check if window was created if not window: glfw.terminate() raise Exception("glfw window can not be created!") # set window's position glfw.set_window_pos(window, 400, 200) # set the callback function for window resize glfw.set_window_size_callback(window, window_resize) # make the context current glfw.make_context_current(window) # load here the 3d meshes chibi_indices, chibi_buffer = ObjLoader.load_model("meshes/steve.obj") monkey_indices, monkey_buffer = ObjLoader.load_model("meshes/monkey.obj") shader = compileProgram(compileShader(vertex_src, GL_VERTEX_SHADER), compileShader(fragment_src, GL_FRAGMENT_SHADER)) # VAO and VBO VAO = glGenVertexArrays(2) VBO = glGenBuffers(2) # EBO = glGenBuffers(1) # Chibi VAO glBindVertexArray(VAO[0]) # Chibi Vertex Buffer Object glBindBuffer(GL_ARRAY_BUFFER, VBO[0]) glBufferData(GL_ARRAY_BUFFER, chibi_buffer.nbytes, chibi_buffer, GL_STATIC_DRAW)
glfw.set_window_pos(window, 400, 200) # set the callback function for window resize glfw.set_window_size_callback(window, window_resize_clb) # set the mouse position callback glfw.set_cursor_pos_callback(window, mouse_look_clb) # set the keyboard input callback glfw.set_key_callback(window, key_input_clb) # capture the mouse cursor glfw.set_input_mode(window, glfw.CURSOR, glfw.CURSOR_DISABLED) # make the context current glfw.make_context_current(window) # load here the 3d meshes table_indices, table_buffer = ObjLoader.load_model("meshes/table.obj", False) sofa_indices, sofa_buffer = ObjLoader.load_model("meshes/sofa.obj", False) tv_indices, tv_buffer = ObjLoader.load_model("meshes/tivi.obj", False) floor_indices, floor_buffer = ObjLoader.load_model("meshes/floor.obj", False) shader = compileProgram(compileShader(vertex_src, GL_VERTEX_SHADER), compileShader(fragment_src, GL_FRAGMENT_SHADER)) # VAO (Vertex Array Object) and VBO (Vertex Buffer Object) VAO = glGenVertexArrays(3) VBO = glGenBuffers(3) EBO = glGenBuffers(3) # table VAO glBindVertexArray(VAO[0]) # table VBO glBindBuffer(GL_ARRAY_BUFFER, VBO[0])
class Mushroom: instances = {} instance_locations = {} instance_info = {} readable_instances = [] detected = [] db = DBConnector() shroom_paths = db.execute( "SELECT path FROM visualpropertypath WHERE path LIKE '%Mushroom.obj'") shroom_paths = sorted( [x[0] for x in shroom_paths], reverse=True) #now, list will be sorted small-medium-large del db texture_offsets = [] data_list = [] for i in range(3): mesh = ObjLoader() mesh.load_model(shroom_paths[i]) num_verts = len(mesh.vertex_index) texture_offset = len(mesh.vertex_index) * 12 data = numpy.array(mesh.model, dtype=GLfloat) texture_offsets.append(texture_offset) data_list.append(data) def __init__(self, tekstur, code, size=0): code += str(size) if code in Mushroom.instances: return None Mushroom.instances[code] = self Mushroom.instance_locations[code] = [] self.vao_mushroom = GLuint() # generate a vertex array object for the mushroom - the vao glGenVertexArrays(1, self.vao_mushroom) # bind the mushroom's vao glBindVertexArray(self.vao_mushroom) # setup the mushroom's vertex buffer object - the vbo vbo_sphere = pyglet.graphics.vertexbuffer.create_buffer( Mushroom.data_list[size].nbytes, GL_ARRAY_BUFFER, GL_STATIC_DRAW) vbo_sphere.bind() vbo_sphere.set_data(Mushroom.data_list[size].ctypes.data) # vertex attribute pointer settings for the mushroom vbo glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 0, 0) glEnableVertexAttribArray(0) # textures glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, 0, Mushroom.texture_offsets[size]) glEnableVertexAttribArray(1) glBindBuffer(GL_ARRAY_BUFFER, 0) # unbind the vbo glBindVertexArray(0) # unbind the vao # region texture settings self.texture = GLuint(0) glGenTextures(1, self.texture) glBindTexture(GL_TEXTURE_2D, self.texture) # set the texture wrapping glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT) glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT) # set the texture filtering glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR) glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR) # self.loadingthread = GeneralThread(load_texture_image, self, tekstur) # self.loadingthread.run() image = pyglet.image.load(tekstur) image_data = image.get_data('RGB', image.pitch) glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, image.width, image.height, 0, GL_RGB, GL_UNSIGNED_BYTE, image_data) # endregion def render(self, translasi): # if self.loadingthread.isAlive(): # return # to draw the mushroom, we need to rebind the mushroom's vao model_loc = ObjectShader.model_loc mushroom_model = matrix44.create_from_translation( translasi).flatten().astype( "float32") #this is the model transformation matrix c_mushroom_model = numpy.ctypeslib.as_ctypes(mushroom_model) glBindVertexArray(self.vao_mushroom) glBindTexture(GL_TEXTURE_2D, self.texture) glUniformMatrix4fv(model_loc, 1, GL_FALSE, c_mushroom_model) glDrawArrays(GL_TRIANGLES, 0, Mushroom.num_verts) glBindVertexArray(0) def batch_render(self, list_translasi, undraw_detected=False ): # me-render banyak mushroom dengan tekstur sama # if self.loadingthread.isAlive(): # return glBindVertexArray(self.vao_mushroom) glBindTexture(GL_TEXTURE_2D, self.texture) model_loc = ObjectShader.model_loc detected_translasi = [ Mushroom.instance_info[x][2] for x in Mushroom.detected ] for translasi in list_translasi: if translasi not in detected_translasi or not undraw_detected: mushroom_model = matrix44.create_from_translation( Vector3(translasi)).flatten().astype( "float32") #this is the model transformation matrix c_mushroom_model = numpy.ctypeslib.as_ctypes(mushroom_model) glUniformMatrix4fv(model_loc, 1, GL_FALSE, c_mushroom_model) glDrawArrays(GL_TRIANGLES, 0, Mushroom.num_verts) glBindVertexArray(0) @staticmethod def _draw_name_label(name, position): screenpos = convert_3dcoor_to_screen(position) # set_2d_mode() name_text = text.Label(name, font_size=18, color=[0, 0, 0, 255], x=screenpos[0], y=screenpos[1], anchor_x='center', anchor_y='bottom') name_length = (name_text.content_width + 5) / 2 graphics.vertex_list( 4, ('v2f', (screenpos[0] - name_length, screenpos[1], screenpos[0] - name_length, screenpos[1] + 25, screenpos[0] + name_length, screenpos[1] + 25, screenpos[0] + name_length, screenpos[1])), ('c3B', (200, 200, 200, 200, 200, 200, 200, 200, 200, 200, 200, 200))).draw(GL_QUADS) graphics.vertex_list( 4, ('v2f', (screenpos[0] - name_length, screenpos[1], screenpos[0] - name_length, screenpos[1] + 25, screenpos[0] + name_length, screenpos[1] + 25, screenpos[0] + name_length, screenpos[1])), ('c3B', (0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0))).draw(GL_LINE_LOOP) name_text.draw() # unset_2d_mode(ShapeShader.shader) @staticmethod def draw_warning_sign(position): screenpos = convert_3dcoor_to_screen(position) screenpos[0] -= 18 screenpos[1] += 36 # draw in 2d # set_2d_mode() graphics.vertex_list( 3, ('v2f', (screenpos[0], screenpos[1], screenpos[0] + 36, screenpos[1], screenpos[0] + 18, screenpos[1] + 36)), ('c3B', (255, 255, 0, 255, 255, 0, 255, 255, 0))).draw(GL_TRIANGLES) text.Label('!', font_size=18, color=[0, 0, 0, 255], x=screenpos[0] + 14, y=screenpos[1], anchor_x='left', anchor_y='bottom').draw() # unset_2d_mode(ShapeShader.shader) @staticmethod def get_all_shroom_position(): shroom_list = [] for key in Mushroom.instance_locations: shroom_list += Mushroom.instance_locations[key] return shroom_list @staticmethod def add_instance_location(shroomtype, location): Mushroom.instance_locations[shroomtype].append(location) @staticmethod def add_instance_detail(shroom_id, name, shroomtype, location, is_field): if is_field: used_id = 'f' + str(shroom_id) Mushroom.instance_info[used_id] = [name, shroomtype, location] else: used_id = 'm' + str(shroom_id) Mushroom.instance_info[used_id] = [name, shroomtype, location] Mushroom.add_instance_location(shroomtype, location) @staticmethod def move_shroom(shroom_id, is_field, shift_vector): used_id = ('f' if is_field else 'm') + str(shroom_id) Mushroom.instance_info[used_id][2] += shift_vector @staticmethod def set_readable(shroom_pos_list): Mushroom.readable_instances = shroom_pos_list @staticmethod def add_detected(shroom_ids): Mushroom.detected += [ shroom for shroom in shroom_ids if shroom not in Mushroom.detected ] @staticmethod def remove_detected(shroom_ids): Mushroom.detected = [ shroom for shroom in Mushroom.detected if shroom not in shroom_ids ] @staticmethod def set_detected(shroom_ids): Mushroom.detected = shroom_ids @staticmethod def draw_all_shroom(undraw_detected=False): for key in Mushroom.instances: Mushroom.instances[key].batch_render( Mushroom.instance_locations[key], undraw_detected=undraw_detected) set_2d_mode() for shroom_pos in Mushroom.readable_instances: all_info = Mushroom.instance_info.items() for info in all_info: if info[1][2] == shroom_pos: Mushroom._draw_name_label(info[1][0], info[1][2]) # for warned_id in Mushroom.detected: # Mushroom.draw_warning_sign(Mushroom.instance_info[warned_id][2]) unset_2d_mode(ObjectShader.shader)