def __receiveMode(self): if self.__displayMode == "Receive": glfw.set_window_title(self.__window, "Spout: " + self.__displayMode + " Texture") if self.__receiveWidth == 0 and self.__receiveHeight == 0: if not glfw.window_should_close(self.__window): glActiveTexture(GL_TEXTURE0) glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT) glLoadIdentity() glBegin(GL_QUADS) glTexCoord2f(0, 0) glVertex2f(0, 0) glTexCoord2f(1, 0) glVertex2f(1, 0) glTexCoord2f(1, 1) glVertex2f(1, 1) glTexCoord2f(0, 1) glVertex2f(0, 1) glEnd() glfw.swap_buffers(self.__window) glfw.poll_events() else: glfw.destroy_window(self.__window) glfw.terminate() else: if not glfw.window_should_close(self.__window): left = 0 top = 0 width = self.__windowWidth height = self.__windowHeight sx = self.__windowWidth / self.__receiveWidth sy = self.__windowHeight / self.__receiveHeight if sx > sy: width *= sy / sx left = (self.__windowWidth - width) / 2 else: height *= sx / sy top = (self.__windowHeight - height) / 2 glActiveTexture(GL_TEXTURE0) glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT) glLoadIdentity() glBegin(GL_QUADS) glTexCoord2f(0, 0) glVertex2f(left, top) glTexCoord2f(1, 0) glVertex2f(left + width, top) glTexCoord2f(1, 1) glVertex2f(left + width, top + height) glTexCoord2f(0, 1) glVertex2f(left, top + height) glEnd() glfw.swap_buffers(self.__window) glfw.poll_events() else: glfw.destroy_window(self.__window) glfw.terminate()
def render(self, clear=(0.0, 0.0, 0.0, 1.0)): self.key_pressed=None glfw.swap_interval(self.vsync) if self.alive == False: glfw.terminate() return if not glfw.window_should_close(self.win): self.ctx.clear(*clear) self.vao.render(gl.TRIANGLES) self.frame+=1 try: self.fps=self.frame/(time.time()-self.start) except: pass if time.time()-self.start >= 1: self.start=time.time() self.frame=0 if self.show_fps: glfw.set_window_title(self.win, self.name+' FPS:'+str(int(self.fps))) self.mat.write(numpy.array([self.camera.x*self.scale[0], 0.0, 0.0, 0.0, 0.0, self.camera.y*self.scale[1], 0.0, 0.0, 0.0, 0.0, self.camera.z*self.scale[2], 0.0, 0.0, 0.0, 0.0, 1.0], dtype='float32')) glfw.swap_buffers(self.win) glfw.poll_events() return self.alive=False glfw.terminate()
def __update_frame_counter(self): current_frame = glfw.get_time() self.delta_time = current_frame - self.last_frame self.last_frame = current_frame fps = 1.0 / self.delta_time glfw.set_window_title(self.window, 'Particle System (FPS: %.0f)' % fps)
def keyboard(window, key, scancode, action, mods): nonlocal mode_edit, iloop_selected, ivtx_selected, mode_exit if action != glfw.PRESS: return if key == glfw.KEY_1: # change edit mode to loop glfw.set_window_title(window, "new loop") mode_edit = EditMode.NEW_LOOP loops.append([]) iloop_selected = 0 elif key == glfw.KEY_2: glfw.set_window_title(window, "edit loop") mode_edit = EditMode.EDIT_LOOP iloop_selected = -1 ivtx_selected = -1 elif key == glfw.KEY_D: # delete selected loop if 0 <= iloop_selected < len(loops): loops.pop(iloop_selected) nloop = len(loops) if nloop == 0: iloop_selected = -1 else: iloop_selected = (iloop_selected + nloop - 1) % nloop elif key == glfw.KEY_S: mode_exit = ExitFlag.SAVE elif key == glfw.KEY_Q: mode_exit = ExitFlag.EXIT_WITHOUT_SAVE elif key == glfw.KEY_RIGHT: mode_exit = ExitFlag.NEXT1
def set_window_fps(self): current_time = glfw.get_time() DisplayManager.__nb_frames += 1 if current_time - DisplayManager.__last_time > 1.0: fps = str(DisplayManager.__nb_frames) + "fps" ms = str("%.2f" % (1000 / DisplayManager.__nb_frames)) + "ms" self.title = fps + " | " + ms + " - pyGL" DisplayManager.__nb_frames = 0 DisplayManager.__last_time += 1.0 glfw.set_window_title(self.window, self.title)
def b_init(self): glfw.init() glfw.window_hint(glfw.SAMPLES, 4) self.window = glfw.create_window(self.companion_width, self.companion_height, 'hello_vr', None, None) glfw.set_key_callback(self.window, self.key_callback) glfw.make_context_current(self.window) # self.hmd = openvr.init(openvr.VRApplication_Scene) # vr_sys = openvr.VRSystem() driver = vr_sys.getStringTrackedDeviceProperty( openvr.k_unTrackedDeviceIndex_Hmd, openvr.Prop_TrackingSystemName_String, ) display = vr_sys.getStringTrackedDeviceProperty( openvr.k_unTrackedDeviceIndex_Hmd, openvr.Prop_SerialNumber_String, ) glfw.set_window_title(self.window, f'hello_vr -- {driver} {display}') self.b_init_gl() assert openvr.VRCompositor() action_path = pkg_resources.resource_filename('samples', 'hellovr_actions.json') openvr.VRInput().setActionManifestPath(action_path) self.action_hide_cubes = openvr.VRInput().getActionHandle( '/actions/demo/in/HideCubes') self.action_hide_this_controller = openvr.VRInput().getActionHandle( '/actions/demo/in/HideThisController') self.action_trigger_haptic = openvr.VRInput().getActionHandle( '/actions/demo/in/TriggerHaptic') self.action_analog_input = openvr.VRInput().getActionHandle( '/actions/demo/in/AnalogInput') self.action_set_demo = openvr.VRInput().getActionSetHandle( '/actions/demo') self.hand[Left].action_haptic = openvr.VRInput().getActionHandle( '/actions/demo/out/Haptic_Left') self.hand[Left].source = openvr.VRInput().getInputSourceHandle( '/user/hand/left') self.hand[Left].action_pose = openvr.VRInput().getActionHandle( '/actions/demo/in/Hand_Left') self.hand[Right].action_haptic = openvr.VRInput().getActionHandle( '/actions/demo/out/Haptic_Right') self.hand[Right].source = openvr.VRInput().getInputSourceHandle( '/user/hand/right') self.hand[Right].action_pose = openvr.VRInput().getActionHandle( '/actions/demo/in/Hand_Right') return True
def open(self): self.view.set_hints() self.window = glfw.create_window(self.width, self.height, self.title, None, None) if not self.window: print("Failed to open GFLW window.") glfw.terminate() sys.exit(-1) glfw.make_context_current(self.window) glfw.set_window_pos(self.window, self.xpos, self.ypos) glfw.set_key_callback(self.window, lambda window, key, scancode, action, mods: self.key_callback(key, scancode, action, mods)) glfw.swap_interval(1) glfw.set_window_title(self.window, self.title)
def onKeyboard(self, win, key, scancode, action, mods): print("keyboard: ", win, key, scancode, action, mods) if action == glfw.PRESS: # ESC to quit if key == glfw.KEY_ESCAPE: self.exitNow = True ## orthogonal <-> perspective if key == glfw.KEY_O: self.scene.perspective = False glfw.set_window_title(win, '2D Scene - Orthographic') if key == glfw.KEY_P: self.scene.perspective = True glfw.set_window_title(win, '2D Scene - Perspective') ## COLORS if mods == glfw.MOD_SHIFT: # shift pressed (background color) if key == glfw.KEY_S: # black self.scene.actBgColor = self.scene.colors['BLACK'] if key == glfw.KEY_W: # white self.scene.actBgColor = self.scene.colors['WHITE'] if key == glfw.KEY_R: # red self.scene.actBgColor = self.scene.colors['RED'] if key == glfw.KEY_B: # blue self.scene.actBgColor = self.scene.colors['BLUE'] if key == glfw.KEY_G: # yellow self.scene.actBgColor = self.scene.colors['YELLOW'] else: # shift not pressed ( object color) if key == glfw.KEY_S: # black self.scene.actColor = self.scene.colors['BLACK'] if key == glfw.KEY_W: # white self.scene.actColor = self.scene.colors['WHITE'] if key == glfw.KEY_R: # red self.scene.actColor = self.scene.colors['RED'] if key == glfw.KEY_B: # blue self.scene.actColor = self.scene.colors['BLUE'] if key == glfw.KEY_G: # yellow self.scene.actColor = self.scene.colors['YELLOW'] if key == glfw.KEY_H: # shadows self.scene.hasShadow = not self.scene.hasShadow if key == glfw.KEY_N: # shadows self.scene.wireMode = not self.scene.wireMode
def update(dt: float): global position, rotation_ypr rvel = 90.0 if FLY_CONTROLS: vel = 10.0 if glfw.get_key(window, glfw.KEY_LEFT): position -= dt * vel * move_matrix[0] if glfw.get_key(window, glfw.KEY_RIGHT): position += dt * vel * move_matrix[0] if glfw.get_key(window, glfw.KEY_UP): position += dt * vel * move_matrix[1] if glfw.get_key(window, glfw.KEY_DOWN): position -= dt * vel * move_matrix[1] if glfw.get_key(window, glfw.KEY_SPACE): position += dt * vel * move_matrix[2] if glfw.get_key(window, glfw.KEY_LEFT_SHIFT): position -= dt * vel * move_matrix[2] if glfw.get_key(window, glfw.KEY_A): rotation_ypr.x += dt * rvel if glfw.get_key(window, glfw.KEY_D): rotation_ypr.x -= dt * rvel if glfw.get_key(window, glfw.KEY_W): rotation_ypr.y += dt * rvel if glfw.get_key(window, glfw.KEY_S): rotation_ypr.y -= dt * rvel if glfw.get_key(window, glfw.KEY_E): rotation_ypr.z += dt * rvel if glfw.get_key(window, glfw.KEY_Q): rotation_ypr.z -= dt * rvel else: vel = 5.0 if glfw.get_key(window, glfw.KEY_D): position += dt * vel * move_matrix[0] if glfw.get_key(window, glfw.KEY_A): position -= dt * vel * move_matrix[0] if glfw.get_key(window, glfw.KEY_W): position += dt * vel * move_matrix[1] if glfw.get_key(window, glfw.KEY_S): position -= dt * vel * move_matrix[1] if glfw.get_key(window, glfw.KEY_SPACE): position += dt * vel * move_matrix[2] if glfw.get_key(window, glfw.KEY_LEFT_SHIFT): position -= dt * vel * move_matrix[2] if glfw.get_key(window, glfw.KEY_LEFT): rotation_ypr.x += dt * rvel if glfw.get_key(window, glfw.KEY_RIGHT): rotation_ypr.x -= dt * rvel if glfw.get_key(window, glfw.KEY_UP): rotation_ypr.y += dt * rvel if glfw.get_key(window, glfw.KEY_DOWN): rotation_ypr.y -= dt * rvel if FLY_FORWARD: position += dt * 10.0 * move_matrix[1] update_rotation() fpsmeter.next_frame(dt) glfw.set_window_title(window, f'{fpsmeter.fps:.1f} FPS in Forest1')
def display_image(image, zoom=None, size=None, title=None): # HWC # Import OpenGL and glfw. import OpenGL.GL as gl import glfw # Zoom image if requested. image = np.asarray(image) if size is not None: assert zoom is None zoom = max(1, size // image.shape[0]) if zoom is not None: image = image.repeat(zoom, axis=0).repeat(zoom, axis=1) height, width, channels = image.shape # Initialize window. if title is None: title = 'Debug window' global _glfw_window if _glfw_window is None: glfw.init() _glfw_window = glfw.create_window(width, height, title, None, None) glfw.make_context_current(_glfw_window) glfw.show_window(_glfw_window) glfw.swap_interval(0) else: glfw.make_context_current(_glfw_window) glfw.set_window_title(_glfw_window, title) glfw.set_window_size(_glfw_window, width, height) # Update window. glfw.poll_events() gl.glClearColor(0, 0, 0, 1) gl.glClear(gl.GL_COLOR_BUFFER_BIT) gl.glWindowPos2f(0, 0) gl.glPixelStorei(gl.GL_UNPACK_ALIGNMENT, 1) gl_format = {3: gl.GL_RGB, 2: gl.GL_RG, 1: gl.GL_LUMINANCE}[channels] gl_dtype = { 'uint8': gl.GL_UNSIGNED_BYTE, 'float32': gl.GL_FLOAT }[image.dtype.name] gl.glDrawPixels(width, height, gl_format, gl_dtype, image[::-1]) glfw.swap_buffers(_glfw_window) if glfw.window_should_close(_glfw_window): return False return True
def _loop(self): frame_count = 0 fps_now = time.time() elapsed_now = time.time() while not glfw.window_should_close(self._window): self._key_poller.poll_keys(self._window) self._mouse_poller._poll_mouse(self._window) self._spaces.push() self._spaces.tint = WHITE glClearColor(*self._color) glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT) glEnable(GL_BLEND) glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA) now = time.time() self._elapsed_time = (now - elapsed_now) elapsed_now = now # draw call if self._handler is not None: self._handler(self) # render last batch of rects (if any) self._quad.draw_batch_if_started(self._spaces) # Swap front and back buffers glfw.swap_buffers(self._window) # Poll for and process events glfw.poll_events() frame_count += 1 fps_time_delta = (time.time() - fps_now) self.fps = frame_count / fps_time_delta if fps_time_delta >= 1: title = f'{self.title} @ {self.fps:.0f} FPS' glfw.set_window_title(self._window, title) fps_now = time.time() frame_count = 0 glfw.terminate()
def loop(): gl.glClearColor(0.05, 0.05, 0.05, 1.0) # Black color ticks = 0 frames = 0 frameTime = time.time_ns() secondTime = time.time_ns() lag = 0.0 # This clock system enticipate lags while not glfw.window_should_close(Window.window): lag += time.time_ns() - frameTime frameTime = time.time_ns() gl.glClear(gl.GL_COLOR_BUFFER_BIT | gl.GL_DEPTH_BUFFER_BIT) # Clear the window if time.time_ns() - secondTime >= Window.SECOND: if Config.values["general"]["debug"]: glfw.set_window_title( Window.window, "Moteur jeu en python | FPS:" + str(frames) + "; TPS:" + str(ticks)) ticks = 0 frames = 0 secondTime = time.time_ns() while lag >= Window.TICK_TIME: gm.GameManager.update() # Update() lag -= Window.TICK_TIME ticks += 1 gm.GameManager.display() # Display() frames += 1 glfw.swap_buffers(Window.window) glfw.poll_events() Window.frame += 1 Logger.setFrame(Window.frame)
def update(self): """Update and render the map.""" # Update states Peer.update(self) self.fpses.appendleft(self.fps) # Render to framebuffer self.fb.use() self.fb.clear() self.render() self.fb.color_attachments[0].use() self.ping.use() self.ping.clear() self.pfilter.render(moderngl.TRIANGLES) self.ping.color_attachments[0].use() # Gaussian blur self.pong.use() self.pong.clear() self.gausshva.render(moderngl.TRIANGLES) self.pong.color_attachments[0].use() self.ping.use() self.ping.clear() self.gaussvva.render(moderngl.TRIANGLES) self.ping.color_attachments[0].use() # Combine for glow effect, chromatic aberration and barrel distortion self.context.screen.use() self.context.clear() if self.camera.dead: abrtn = ABRTN_MAX else: abrtn = min(ABRTN_MAX, (self.fov * self.health)**-CONWAY) self.edge['abrtn'].value = abrtn self.edge['zoom'].value = (self.zmlvl + 1.0) / 100 self.combine.render(moderngl.TRIANGLES) glfw.swap_buffers(self.window) glfw.set_window_title( self.window, '{} - axuy@{}:{} ({})'.format(self.postr, *self.addr, self.fpstr))
def mouse_update_event(xpos, ypos, window): global mouse_x global mouse_y mouse_x = xpos mouse_y = ypos if r == 0 and g == 0 and b == 0: return if drawing: gridx = utility.convert_to_grid(main.grid_chunk_width, main.grid_chunk_height, xpos, ypos)[0] gridy = utility.convert_to_grid(main.grid_chunk_width, main.grid_chunk_height, xpos, ypos)[1] if not utility.point_exists(points[current_frame], gridx, gridy): points[current_frame].append((gridx, gridy, r, g, b)) glfw.set_window_title( window, "Drawing! - Left click to place, right click to break - " + str(len(points[current_frame]) - 1) + " Pixels Drawn - Red: " + str(r) + ", Green: " + str(g) + ", Blue: " + str(b)) if deleting: gridx = utility.convert_to_grid(main.grid_chunk_width, main.grid_chunk_height, xpos, ypos)[0] gridy = utility.convert_to_grid(main.grid_chunk_width, main.grid_chunk_height, xpos, ypos)[1] if utility.point_exists(points[current_frame], gridx, gridy): for a in points[current_frame]: if a[0] == gridx and a[1] == gridy: points[current_frame].remove(a) glfw.set_window_title( window, "Drawing! - Left click to place, right click to break - " + str(len(points[current_frame]) - 1) + " Pixels Drawn - Red: " + str(r) + ", Green: " + str(g) + ", Blue: " + str(b))
def title(self, value: str): glfw.set_window_title(self._window, value) self._title = value
def title(self, title): self._title = title if self.window != None: glfw.set_window_title(self.window, title)
def showfps(): title = ("FPS : {0:.0f}".format(1/(time.time()-t1))) glfw.set_window_title (window, title)
def bulletLogic(time): global logic global controller forDeletion = [] for bullet in logic.bullets: direction = bullet.direction yPos = bullet.yPos if round(time, 2) != bullet.time: bullet.time = round(time, 2) bullet.yPos += 0.01 * direction # Deleting bullets that won't be drawn if direction < 0 and yPos < -1.0: forDeletion.append(bullet) continue elif direction > 0 and yPos > 1.2: forDeletion.append(bullet) continue # Nothing happens in the middle of the screen if 0.5 > yPos > -0.45: continue # Using the bullet against the player if direction < 0: if abs(controller.xPos - bullet.xPos) <= 0.12: if abs(yPos + 0.8 - controller.yPos) <= 0.1: # The player has invulnerability frames if logic.impactTime + 1.0 < time: logic.hp -= 1 logic.impactTime = time print("Daño recibido!") forDeletion.append(bullet) continue # Using the bullet against one enemy for enemy in logic.enemies: if abs(enemy.xPos - bullet.xPos) <= 0.08: if abs(0.8 + enemy.yPos - yPos) <= 0.1: forDeletion.append(bullet) Explosion(enemy.xPos, 0.8 + enemy.yPos, time) logic.enemies.remove(enemy) # Updating the score logic.score += 1 if logic.score > 0: text = f"SPACE WAR (Score: {logic.score})" glfw.set_window_title(window, text) break for bullet in forDeletion: logic.bullets.remove(bullet)
def main(): # Initialize GLFW and open a window if not opengl_init(): return # Enable key events glfw.set_input_mode(window,glfw.STICKY_KEYS,GL_TRUE) glfw.set_cursor_pos(window, 1024/2, 768/2) # Set opengl clear color to something other than red (color used by the fragment shader) glClearColor(0.0,0.0,0.4,0.0) # Enable depth test glEnable(GL_DEPTH_TEST) # Accept fragment if it closer to the camera than the former one glDepthFunc(GL_LESS) # Cull triangles which normal is not towards the camera glEnable(GL_CULL_FACE) vertex_array_id = glGenVertexArrays(1) glBindVertexArray( vertex_array_id ) # Create and compile our GLSL program from the shaders program_id = common.LoadShaders( ".\\shaders\\Tutorial9\\StandardShading.vertexshader", ".\\shaders\\Tutorial9\\StandardShading.fragmentshader" ) # Get a handle for our "MVP" uniform matrix_id = glGetUniformLocation(program_id, "MVP") view_matrix_id = glGetUniformLocation(program_id, "V") model_matrix_id = glGetUniformLocation(program_id, "M") # Load the texture texture = textureutils.load_image(".\\content\\uvmap_suzanne.bmp") # Get a handle for our "myTextureSampler" uniform texture_id = glGetUniformLocation(program_id, "myTextureSampler") # Read our OBJ file vertices,faces,uvs,normals,colors = objloader.load(".\\content\\suzanne.obj") vertex_data,uv_data,normal_data = objloader.process_obj( vertices,faces,uvs,normals,colors) # Our OBJ loader uses Python lists, convert to ctype arrays before sending to OpenGL vertex_data = objloader.generate_2d_ctypes(vertex_data) uv_data = objloader.generate_2d_ctypes(uv_data) normal_data = objloader.generate_2d_ctypes(normal_data) indexed_vertices, indexed_uvs, indexed_normals, indices = vboindexer.indexVBO(vertex_data,uv_data,normal_data) indexed_vertices = c_type_fill(indexed_vertices,GLfloat) indexed_uvs = c_type_fill(indexed_uvs,GLfloat) indexed_normals = c_type_fill(indexed_normals,GLfloat) indices = c_type_fill_1D(indices,GLushort) # Load OBJ in to a VBO vertex_buffer = glGenBuffers(1); glBindBuffer(GL_ARRAY_BUFFER, vertex_buffer) glBufferData(GL_ARRAY_BUFFER, len(indexed_vertices) * 4 * 3, indexed_vertices, GL_STATIC_DRAW) uv_buffer = glGenBuffers(1) glBindBuffer(GL_ARRAY_BUFFER, uv_buffer) glBufferData(GL_ARRAY_BUFFER, len(indexed_uvs) * 4 * 2, indexed_uvs, GL_STATIC_DRAW) normal_buffer = glGenBuffers(1) glBindBuffer(GL_ARRAY_BUFFER, normal_buffer) glBufferData(GL_ARRAY_BUFFER, len(indexed_normals) * 4 * 3, indexed_normals, GL_STATIC_DRAW) # Generate a buffer for the indices as well elementbuffer = glGenBuffers(1) glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, elementbuffer) glBufferData(GL_ELEMENT_ARRAY_BUFFER, len(indices) * 2, indices , GL_STATIC_DRAW); # vsync and glfw do not play nice. when vsync is enabled mouse movement is jittery. common.disable_vsyc() # Get a handle for our "LightPosition" uniform glUseProgram(program_id); light_id = glGetUniformLocation(program_id, "LightPosition_worldspace"); last_time = glfw.get_time() frames = 0 while glfw.get_key(window,glfw.KEY_ESCAPE) != glfw.PRESS and not glfw.window_should_close(window): glClear(GL_COLOR_BUFFER_BIT| GL_DEPTH_BUFFER_BIT) current_time = glfw.get_time() if current_time - last_time >= 1.0: glfw.set_window_title(window,"Tutorial 9. FPS: %d"%(frames)) frames = 0 last_time = current_time glUseProgram(program_id) controls.computeMatricesFromInputs(window) ProjectionMatrix = controls.getProjectionMatrix(); ViewMatrix = controls.getViewMatrix(); ModelMatrix = mat4.identity(); mvp = ProjectionMatrix * ViewMatrix * ModelMatrix; # Send our transformation to the currently bound shader, # in the "MVP" uniform glUniformMatrix4fv(matrix_id, 1, GL_FALSE,mvp.data) glUniformMatrix4fv(model_matrix_id, 1, GL_FALSE, ModelMatrix.data); glUniformMatrix4fv(view_matrix_id, 1, GL_FALSE, ViewMatrix.data); lightPos = vec3(4,4,4) glUniform3f(light_id, lightPos.x, lightPos.y, lightPos.z) # Bind our texture in Texture Unit 0 glActiveTexture(GL_TEXTURE0); glBindTexture(GL_TEXTURE_2D, texture); # Set our "myTextureSampler" sampler to user Texture Unit 0 glUniform1i(texture_id, 0); #1rst attribute buffer : vertices glEnableVertexAttribArray(0) glBindBuffer(GL_ARRAY_BUFFER, vertex_buffer); glVertexAttribPointer( 0, # attribute 0. No particular reason for 0, but must match the layout in the shader. 3, # len(vertex_data) GL_FLOAT, # type GL_FALSE, # ormalized? 0, # stride null # array buffer offset (c_type == void*) ) # 2nd attribute buffer : colors glEnableVertexAttribArray(1) glBindBuffer(GL_ARRAY_BUFFER, uv_buffer); glVertexAttribPointer( 1, # attribute 1. No particular reason for 1, but must match the layout in the shader. 2, # len(vertex_data) GL_FLOAT, # type GL_FALSE, # ormalized? 0, # stride null # array buffer offset (c_type == void*) ) # 3rd attribute buffer : normals glEnableVertexAttribArray(2); glBindBuffer(GL_ARRAY_BUFFER, normal_buffer); glVertexAttribPointer( 2, # attribute 3, # size GL_FLOAT, # type GL_FALSE, # ormalized? 0, # stride null # array buffer offset (c_type == void*) ) # Draw the triangles, vertex data now contains individual vertices # so use array length # glDrawArrays(GL_TRIANGLES, 0, len(vertex_data)) # Index buffer glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, elementbuffer) # Draw the triangles ! glDrawElements( GL_TRIANGLES, # mode len(indices), # count GL_UNSIGNED_SHORT, # type null # element array buffer offset ) # Not strictly necessary because we only have glDisableVertexAttribArray(0) glDisableVertexAttribArray(1) glDisableVertexAttribArray(2) # Swap front and back buffers glfw.swap_buffers(window) # Poll for and process events glfw.poll_events() frames += 1 # !Note braces around vertex_buffer and uv_buffer. # glDeleteBuffers expects a list of buffers to delete glDeleteBuffers(1, [vertex_buffer]) glDeleteBuffers(1, [uv_buffer]) glDeleteBuffers(1, [normal_buffer]) glDeleteProgram(program_id) glDeleteTextures([texture_id]) glDeleteVertexArrays(1, [vertex_array_id]) glfw.terminate()
window_width = 800 window_height = 600 window = glfw.create_window(window_width, window_height, "Hello World", None, None) if not window: print("Failed to open GFLW window.") glfw.terminate() sys.exit(-1) glfw.make_context_current(window) # Setup the key callback. glfw.set_key_callback(window, key_callback) glfw.swap_interval(1) glfw.set_window_title(window, "Modern OpenGL") # Print out some environment information. print('Vendor: %s' % (glGetString(GL_VENDOR))) print('Opengl version: %s' % (glGetString(GL_VERSION))) print('GLSL Version: %s' % (glGetString(GL_SHADING_LANGUAGE_VERSION))) print('Renderer: %s' % (glGetString(GL_RENDERER))) # Compile shaders and link program. program = ShaderProgram(fragment=fragment, vertex=vertex) fragment_color_location = glGetFragDataLocation(program.program_id, "fragment_color") print("fragment_color_location = %d" % fragment_color_location) # Generate VAOs.
old_step_time = glfw.get_time() previous_time = glfw.get_time() frame_count = 0 while not glfw.window_should_close(window): current_time = glfw.get_time() frame_count += 1 if simulation_running: agents.step() if current_time - previous_time >= 1.0: title = "Crowd Simulation ( " + str(frame_count) + " FPS | Number Of Agents: " + str( len(agents.agent_list)) + " )" + " intensity: " + str(global_intensity) glfw.set_window_title(window, title) frame_count = 0 previous_time = current_time glfw.poll_events() glClearColor(0.0, 0.0, 0.0, 1.0) glClear(GL_COLOR_BUFFER_BIT) w, h = glfw.get_window_size(window) if w != w_prev or h != h_prev: w_prev = w h_prev = h tile_size[0] = (w - 2 * (offset + 1)) / len(maze[0]) tile_size[1] = (h - 2 * (offset + 1)) / len(maze)
glfw.init() pm = glfw.get_primary_monitor() vms = glfw.get_video_modes( pm ) print("Available video modes:\n%s\n" % "\n".join(map(str, vms))) vm = glfw.get_video_mode( pm ) print( "Desktop video mode:\n%s\n" % str(vm) ) print( "GLFW Version: %d.%d.%d" % glfw.get_version() ) w = glfw.create_window(800, 600, 'test', None, None) #print("OpenGL version: %d.%d.%d\n" % glfw.get_gl_version()) #glfw.ext.set_icons([(icon_data, icon_width, icon_height)]) glfw.set_window_title(w, "pyglfw test") #glfw.disable(w, glfw.AUTO_POLL_EVENTS) #glfw.enable(w, glfw.KEY_REPEAT) center_x = int(vm[0][0] / 2 - glfw.get_window_size(w)[0] / 2) center_y = int(vm[0][1] / 2 - glfw.get_window_size(w)[1] / 2) print( "new window position: {!s}, {!s}".format(center_x, center_y) ) glfw.set_window_pos(w, center_x, center_y) glfw.set_window_size_callback(w, on_resize) glfw.set_window_close_callback(w, on_close) glfw.set_window_refresh_callback(w, on_refresh) glfw.set_key_callback(w, on_key) glfw.set_char_callback(w, on_char) glfw.set_mouse_button_callback(w, on_button) glfw.set_cursor_pos_callback(w, on_pos)
def change_title(self, title): glfw.set_window_title(self.window, title)
def title(self, title): self._title = title glfw.set_window_title(self._window, self._title)
def set_title(self, title): if self.window is None: return False glfw.set_window_title(self.window, title) return True
def set_title(self, title): glfw.set_window_title(self.window, str(title))
glfw.init() pm = glfw.get_primary_monitor() vms = glfw.get_video_modes(pm) print("Available video modes:\n%s\n" % "\n".join(map(str, vms))) vm = glfw.get_video_mode(pm) print("Desktop video mode:\n%s\n" % str(vm)) print("GLFW Version: %d.%d.%d" % glfw.get_version()) w = glfw.create_window(800, 600, 'test', None, None) #print("OpenGL version: %d.%d.%d\n" % glfw.get_gl_version()) #glfw.ext.set_icons([(icon_data, icon_width, icon_height)]) glfw.set_window_title(w, "pyglfw test") #glfw.disable(w, glfw.AUTO_POLL_EVENTS) #glfw.enable(w, glfw.KEY_REPEAT) center_x = int(vm[0][0] / 2 - glfw.get_window_size(w)[0] / 2) center_y = int(vm[0][1] / 2 - glfw.get_window_size(w)[1] / 2) print("new window position: {!s}, {!s}".format(center_x, center_y)) glfw.set_window_pos(w, center_x, center_y) glfw.set_window_size_callback(w, on_resize) glfw.set_window_close_callback(w, on_close) glfw.set_window_refresh_callback(w, on_refresh) glfw.set_key_callback(w, on_key) glfw.set_char_callback(w, on_char) glfw.set_mouse_button_callback(w, on_button) glfw.set_cursor_pos_callback(w, on_pos)
def SetTitle(self, title): glfw.set_window_title(self.window, title)
def SetTitle(self, title: str) -> None: glfw.set_window_title(self.__handle, title)
def main(): # Initialize GLFW and open a window if not opengl_init(): return # Enable key events glfw.set_input_mode(window, glfw.STICKY_KEYS, GL_TRUE) glfw.set_cursor_pos(window, 1024 / 2, 768 / 2) # Set opengl clear color to something other than red (color used by the fragment shader) glClearColor(0.0, 0.0, 0.4, 0.0) # Enable depth test glEnable(GL_DEPTH_TEST) # Accept fragment if it closer to the camera than the former one glDepthFunc(GL_LESS) # Cull triangles which normal is not towards the camera glEnable(GL_CULL_FACE) vertex_array_id = glGenVertexArrays(1) glBindVertexArray(vertex_array_id) # Create and compile our GLSL program from the shaders program_id = common.LoadShaders( ".\\shaders\\Tutorial8\\StandardShading.vertexshader", ".\\shaders\\Tutorial8\\StandardShading.fragmentshader") # Get a handle for our "MVP" uniform matrix_id = glGetUniformLocation(program_id, "MVP") view_matrix_id = glGetUniformLocation(program_id, "V") model_matrix_id = glGetUniformLocation(program_id, "M") # Load the texture texture = load_image(".\\content\\oppo.bmp") #load image # Get a handle for our "myTextureSampler" uniform texture_id = glGetUniformLocation(program_id, "myTextureSampler") # Read our OBJ file # vertices,faces,uvs,normals,colors = objloader.load(".\\content\\suzanne.obj") # vertex_data,uv_data,normal_data = objloader.process_obj( vertices,faces,uvs,normals,colors) # Our OBJ loader uses Python lists, convert to ctype arrays before sending to OpenGL # vertex_data = objloader.generate_2d_ctypes(vertex_data) # uv_data = objloader.generate_2d_ctypes(uv_data) koordinat = 0.01 koordinat2 = 0.5 koordinat3 = 1.7 koordinat4 = 1.0 koordinat5 = 1.7 koordinat6 = 0.1 vertex_data = [ -koordinat2, -koordinat3, -koordinat, -koordinat2, -koordinat3, koordinat6, -koordinat2, koordinat5, koordinat6, koordinat4, koordinat5, -koordinat, -koordinat2, -koordinat3, -koordinat, -koordinat2, koordinat5, -koordinat, koordinat4, -koordinat3, koordinat6, -koordinat2, -koordinat3, -koordinat, koordinat4, -koordinat3, -koordinat, koordinat4, koordinat5, -koordinat, koordinat4, -koordinat3, -koordinat, -koordinat2, -koordinat3, -koordinat, -koordinat2, -koordinat3, -koordinat, -koordinat2, koordinat5, koordinat6, -koordinat2, koordinat5, -koordinat, koordinat4, -koordinat3, koordinat6, -koordinat2, -koordinat3, koordinat6, -koordinat2, -koordinat3, -koordinat, -koordinat2, koordinat5, koordinat6, -koordinat2, -koordinat3, koordinat6, koordinat4, -koordinat3, koordinat6, koordinat4, koordinat5, koordinat6, koordinat4, -koordinat3, -koordinat, koordinat4, koordinat5, -koordinat, koordinat4, -koordinat3, -koordinat, koordinat4, koordinat5, koordinat6, koordinat4, -koordinat3, koordinat6, koordinat4, koordinat5, koordinat6, koordinat4, koordinat5, -koordinat, -koordinat2, koordinat5, -koordinat, koordinat4, koordinat5, koordinat6, -koordinat2, koordinat5, -koordinat, -koordinat2, koordinat5, koordinat6, koordinat4, koordinat5, koordinat6, -koordinat2, koordinat5, koordinat6, koordinat4, -koordinat3, koordinat6 ] # Two UV coordinatesfor each vertex. They were created withe Blender. uv_data = [ 0.000059, 1.0 - 0.000004, 0.000103, 1.0 - 0.336048, 0.335973, 1.0 - 0.335903, 1.000023, 1.0 - 0.000013, 0.667979, 1.0 - 0.335851, 0.999958, 1.0 - 0.336064, 0.667979, 1.0 - 0.335851, 0.336024, 1.0 - 0.671877, 0.667969, 1.0 - 0.671889, 1.000023, 1.0 - 0.000013, 0.668104, 1.0 - 0.000013, 0.667979, 1.0 - 0.335851, 0.000059, 1.0 - 0.000004, 0.335973, 1.0 - 0.335903, 0.336098, 1.0 - 0.000071, 0.667979, 1.0 - 0.335851, 0.335973, 1.0 - 0.335903, 0.336024, 1.0 - 0.671877, 1.000004, 1.0 - 0.671847, 0.999958, 1.0 - 0.336064, 0.667979, 1.0 - 0.335851, 0.668104, 1.0 - 0.000013, 0.335973, 1.0 - 0.335903, 0.667979, 1.0 - 0.335851, 0.335973, 1.0 - 0.335903, 0.668104, 1.0 - 0.000013, 0.336098, 1.0 - 0.000071, 0.000103, 1.0 - 0.336048, 0.000004, 1.0 - 0.671870, 0.336024, 1.0 - 0.671877, 0.000103, 1.0 - 0.336048, 0.336024, 1.0 - 0.671877, 0.335973, 1.0 - 0.335903, 0.667969, 1.0 - 0.671889, 1.000004, 1.0 - 0.671847, 0.667979, 1.0 - 0.335851 ] normal_data = [ -0.5, 0, 0, -0.5, 0, 0, -0.5, 0, 0, 0, 0, -0.5, 0, 0, -0.5, 0, 0, -0.5, 0, -0.5, 0, 0, -0.5, 0, 0, -0.5, 0, 0, 0, -0.5, 0, 0, -0.5, 0, 0, -0.5, -0.5, 0, 0, -0.5, 0, 0, -0.5, 0, 0, 0, -0.5, 0, 0, -0.5, 0, 0, -0.5, 0, 0, 0, 1, 0, 0, 1, 0, 0, 1, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 0, 1, 0, 0, 1, 0, 0, 1 ] # Load OBJ in to a VBO vertex_buffer = glGenBuffers(1) array_type = GLfloat * len(vertex_data) glBindBuffer(GL_ARRAY_BUFFER, vertex_buffer) glBufferData(GL_ARRAY_BUFFER, len(vertex_data) * 4, array_type(*vertex_data), GL_STATIC_DRAW) uv_buffer = glGenBuffers(1) array_type = GLfloat * len(uv_data) glBindBuffer(GL_ARRAY_BUFFER, uv_buffer) glBufferData(GL_ARRAY_BUFFER, len(uv_data) * 4, array_type(*uv_data), GL_STATIC_DRAW) normal_buffer = glGenBuffers(1) array_type = GLfloat * len(normal_data) glBindBuffer(GL_ARRAY_BUFFER, normal_buffer) glBufferData(GL_ARRAY_BUFFER, len(normal_data) * 4, array_type(*normal_data), GL_STATIC_DRAW) # vsync and glfw do not play nice. when vsync is enabled mouse movement is jittery. common.disable_vsyc() # Get a handle for our "LightPosition" uniform glUseProgram(program_id) light_id = glGetUniformLocation(program_id, "LightPosition_worldspace") last_time = glfw.get_time() frames = 0 while glfw.get_key( window, glfw.KEY_ESCAPE ) != glfw.PRESS and not glfw.window_should_close(window): glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT) current_time = glfw.get_time() if current_time - last_time >= 1.0: glfw.set_window_title(window, "Tutorial 8. FPS: %d" % (frames)) frames = 0 last_time = current_time glUseProgram(program_id) controls.computeMatricesFromInputs(window) ProjectionMatrix = controls.getProjectionMatrix() ViewMatrix = controls.getViewMatrix() ModelMatrix = mat4.identity() mvp = ProjectionMatrix * ViewMatrix * ModelMatrix # Send our transformation to the currently bound shader, # in the "MVP" uniform glUniformMatrix4fv(matrix_id, 1, GL_FALSE, mvp.data) glUniformMatrix4fv(model_matrix_id, 1, GL_FALSE, ModelMatrix.data) glUniformMatrix4fv(view_matrix_id, 1, GL_FALSE, ViewMatrix.data) lightPos = vec3(4, 4, 4) glUniform3f(light_id, lightPos.x, lightPos.y, lightPos.z) # Bind our texture in Texture Unit 0 glActiveTexture(GL_TEXTURE0) glBindTexture(GL_TEXTURE_2D, texture) # Set our "myTextureSampler" sampler to user Texture Unit 0 glUniform1i(texture_id, 0) #1rst attribute buffer : vertices glEnableVertexAttribArray(0) glBindBuffer(GL_ARRAY_BUFFER, vertex_buffer) glVertexAttribPointer( 0, # attribute 0. No particular reason for 0, but must match the layout in the shader. 3, # len(vertex_data) GL_FLOAT, # type GL_FALSE, # ormalized? 0, # stride null # array buffer offset (c_type == void*) ) # 2nd attribute buffer : colors glEnableVertexAttribArray(1) glBindBuffer(GL_ARRAY_BUFFER, uv_buffer) glVertexAttribPointer( 1, # attribute 1. No particular reason for 1, but must match the layout in the shader. 2, # len(vertex_data) GL_FLOAT, # type GL_FALSE, # ormalized? 0, # stride null # array buffer offset (c_type == void*) ) # 3rd attribute buffer : normals glEnableVertexAttribArray(2) glBindBuffer(GL_ARRAY_BUFFER, normal_buffer) glVertexAttribPointer( 2, # attribute 3, # size GL_FLOAT, # type GL_FALSE, # ormalized? 0, # stride null # array buffer offset (c_type == void*) ) # Draw the triangles, vertex data now contains individual vertices # so use array length glDrawArrays(GL_TRIANGLES, 0, len(vertex_data)) # Not strictly necessary because we only have glDisableVertexAttribArray(0) glDisableVertexAttribArray(1) glDisableVertexAttribArray(2) # Swap front and back buffers glfw.swap_buffers(window) # Poll for and process events glfw.poll_events() frames += 1 # !Note braces around vertex_buffer and uv_buffer. # glDeleteBuffers expects a list of buffers to delete glDeleteBuffers(1, [vertex_buffer]) glDeleteBuffers(1, [uv_buffer]) glDeleteBuffers(1, [normal_buffer]) glDeleteProgram(program_id) glDeleteTextures([texture_id]) glDeleteVertexArrays(1, [vertex_array_id]) glfw.terminate()
circles += [circle] perfMonitor = pm.PerformanceMonitor(glfw.get_time(), 0.5) # glfw will swap buffers as soon as possible glfw.swap_interval(0) gravityAcceleration = np.array([0.0, -1.0], dtype=np.float32) noGravityAcceleration = np.array([0.0, 0.0], dtype=np.float32) # Application loop while not glfw.window_should_close(window): # Measuring performance perfMonitor.update(glfw.get_time()) glfw.set_window_title(window, title + str(perfMonitor)) # Using GLFW to check for input events glfw.poll_events() # Using the time as the theta parameter theta = glfw.get_time() deltaTime = perfMonitor.getDeltaTime() if controller.useGravity: acceleration = gravityAcceleration else: acceleration = noGravityAcceleration # Physics! for circle in circles:
def main(): # Initialize GLFW and open a window if not opengl_init(): return # Enable key events glfw.set_input_mode(window,glfw.STICKY_KEYS,GL_TRUE) glfw.set_cursor_pos(window, 1024/2, 768/2) # Set opengl clear color to something other than red (color used by the fragment shader) glClearColor(0.0,0.0,0.4,0.0) # Enable depth test glEnable(GL_DEPTH_TEST) # Accept fragment if it closer to the camera than the former one glDepthFunc(GL_LESS) # Cull triangles which normal is not towards the camera glEnable(GL_CULL_FACE) vertex_array_id = glGenVertexArrays(1) glBindVertexArray( vertex_array_id ) # Create and compile our GLSL program from the shaders program_id = common.LoadShaders( "Shaders/Tutorial8/StandardShading.vertexshader", "Shaders/Tutorial8/StandardShading.fragmentshader" ) # Get a handle for our "MVP" uniform matrix_id = glGetUniformLocation(program_id, "MVP") view_matrix_id = glGetUniformLocation(program_id, "V") model_matrix_id = glGetUniformLocation(program_id, "M") # Load the texture texture = load_image("Content/uvmap_suzanne.bmp") # Get a handle for our "myTextureSampler" uniform texture_id = glGetUniformLocation(program_id, "myTextureSampler") # Read our OBJ file vertices,faces,uvs,normals,colors = objloader.load("Content/suzanne.obj") vertex_data,uv_data,normal_data = objloader.process_obj( vertices,faces,uvs,normals,colors) # Our OBJ loader uses Python lists, convert to ctype arrays before sending to OpenGL vertex_data = objloader.generate_2d_ctypes(vertex_data) uv_data = objloader.generate_2d_ctypes(uv_data) normal_data = objloader.generate_2d_ctypes(normal_data) # Load OBJ in to a VBO vertex_buffer = glGenBuffers(1); glBindBuffer(GL_ARRAY_BUFFER, vertex_buffer) glBufferData(GL_ARRAY_BUFFER, len(vertex_data) * 4 * 3, vertex_data, GL_STATIC_DRAW) uv_buffer = glGenBuffers(1) glBindBuffer(GL_ARRAY_BUFFER, uv_buffer) glBufferData(GL_ARRAY_BUFFER, len(uv_data) * 4 * 2, uv_data, GL_STATIC_DRAW) normal_buffer = glGenBuffers(1) glBindBuffer(GL_ARRAY_BUFFER, normal_buffer) glBufferData(GL_ARRAY_BUFFER, len(normal_data) * 4 * 3, normal_data, GL_STATIC_DRAW) # vsync and glfw do not play nice. when vsync is enabled mouse movement is jittery. common.disable_vsyc() # Get a handle for our "LightPosition" uniform glUseProgram(program_id); light_id = glGetUniformLocation(program_id, "LightPosition_worldspace"); last_time = glfw.get_time() frames = 0 while glfw.get_key(window,glfw.KEY_ESCAPE) != glfw.PRESS and not glfw.window_should_close(window): glClear(GL_COLOR_BUFFER_BIT| GL_DEPTH_BUFFER_BIT) current_time = glfw.get_time() if current_time - last_time >= 1.0: glfw.set_window_title(window,"Tutorial 8. FPS: %d"%(frames)) frames = 0 last_time = current_time glUseProgram(program_id) controls.computeMatricesFromInputs(window) ProjectionMatrix = controls.getProjectionMatrix(); ViewMatrix = controls.getViewMatrix(); ModelMatrix = mat4.identity(); mvp = ProjectionMatrix * ViewMatrix * ModelMatrix; # Send our transformation to the currently bound shader, # in the "MVP" uniform glUniformMatrix4fv(matrix_id, 1, GL_FALSE,mvp.data) glUniformMatrix4fv(model_matrix_id, 1, GL_FALSE, ModelMatrix.data); glUniformMatrix4fv(view_matrix_id, 1, GL_FALSE, ViewMatrix.data); lightPos = vec3(4,4,4) glUniform3f(light_id, lightPos.x, lightPos.y, lightPos.z) # Bind our texture in Texture Unit 0 glActiveTexture(GL_TEXTURE0); glBindTexture(GL_TEXTURE_2D, texture); # Set our "myTextureSampler" sampler to user Texture Unit 0 glUniform1i(texture_id, 0); #1rst attribute buffer : vertices glEnableVertexAttribArray(0) glBindBuffer(GL_ARRAY_BUFFER, vertex_buffer); glVertexAttribPointer( 0, # attribute 0. No particular reason for 0, but must match the layout in the shader. 3, # len(vertex_data) GL_FLOAT, # type GL_FALSE, # ormalized? 0, # stride null # array buffer offset (c_type == void*) ) # 2nd attribute buffer : colors glEnableVertexAttribArray(1) glBindBuffer(GL_ARRAY_BUFFER, uv_buffer); glVertexAttribPointer( 1, # attribute 1. No particular reason for 1, but must match the layout in the shader. 2, # len(vertex_data) GL_FLOAT, # type GL_FALSE, # ormalized? 0, # stride null # array buffer offset (c_type == void*) ) # 3rd attribute buffer : normals glEnableVertexAttribArray(2); glBindBuffer(GL_ARRAY_BUFFER, normal_buffer); glVertexAttribPointer( 2, # attribute 3, # size GL_FLOAT, # type GL_FALSE, # ormalized? 0, # stride null # array buffer offset (c_type == void*) ) # Draw the triangles, vertex data now contains individual vertices # so use array length glDrawArrays(GL_TRIANGLES, 0, len(vertex_data)) # Not strictly necessary because we only have glDisableVertexAttribArray(0) glDisableVertexAttribArray(1) glDisableVertexAttribArray(2) # Swap front and back buffers glfw.swap_buffers(window) # Poll for and process events glfw.poll_events() frames += 1 # !Note braces around vertex_buffer and uv_buffer. # glDeleteBuffers expects a list of buffers to delete glDeleteBuffers(1, [vertex_buffer]) glDeleteBuffers(1, [uv_buffer]) glDeleteBuffers(1, [normal_buffer]) glDeleteProgram(program_id) glDeleteTextures([texture_id]) glDeleteVertexArrays(1, [vertex_array_id]) glfw.terminate()