def processInput(self): if glfw.get_key(self.window, glfw.KEY_ESCAPE) == glfw.PRESS: glfw.set_window_should_close(self.window, True) if glfw.get_key(self.window, glfw.KEY_SPACE) == glfw.PRESS: gl.glPolygonMode(gl.GL_FRONT_AND_BACK, gl.GL_LINE) else: gl.glPolygonMode(gl.GL_FRONT_AND_BACK, gl.GL_FILL) # Speed managment leftPressed = glfw.get_key(self.window, glfw.KEY_LEFT) if leftPressed == glfw.PRESS: if not self.pressed["left"]: if self.speed <= 1/16: self.speed = 0 else: self.speed /= 2 if self.speed > 1: self.speed = round(self.speed) self.speed = max(self.speed, 1/16) self.pressed["left"] = leftPressed rightPressed = glfw.get_key(self.window, glfw.KEY_RIGHT) if rightPressed == glfw.PRESS: if not self.pressed["right"]: if self.speed == 0: self.speed = 1/16 else: self.speed *= 2 if self.speed > 1: self.speed = round(self.speed) self.speed = min(self.speed, 2**10) self.pressed["right"] = rightPressed if self.camera is not None: self.camera.processInput(self.window, self._deltaTime)
def _cursor_pos_callback(self, window, xpos, ypos): if not (self._button_left_pressed or self._button_right_pressed): return # Determine whether to move, zoom or rotate view mod_shift = ( glfw.get_key(window, glfw.KEY_LEFT_SHIFT) == glfw.PRESS or glfw.get_key(window, glfw.KEY_RIGHT_SHIFT) == glfw.PRESS) if self._button_right_pressed: action = const.MOUSE_MOVE_H if mod_shift else const.MOUSE_MOVE_V elif self._button_left_pressed: action = const.MOUSE_ROTATE_H if mod_shift else const.MOUSE_ROTATE_V else: action = const.MOUSE_ZOOM # Determine dx = int(self._scale * xpos) - self._last_mouse_x dy = int(self._scale * ypos) - self._last_mouse_y width, height = glfw.get_framebuffer_size(window) with self._gui_lock: self.move_camera(action, dx / height, dy / height) self._last_mouse_x = int(self._scale * xpos) self._last_mouse_y = int(self._scale * ypos)
def actualizar(window): global xCarrito global yCarrito estadoIzquierda = glfw.get_key(window, glfw.KEY_LEFT) estadoDerecha = glfw.get_key(window, glfw.KEY_RIGHT) estadoAbajo = glfw.get_key(window, glfw.KEY_DOWN) estadoArriba = glfw.get_key(window, glfw.KEY_SPACE) if not chocando(xCarrito, yCarrito - 0.01, 0.05, 0.05, xObstaculo, yObstaculo, 1, 0.15): yCarrito = yCarrito - 0.01 if estadoIzquierda == glfw.PRESS and xCarrito - 0.05 > -1: xCarrito = xCarrito - 0.03 if estadoDerecha == glfw.PRESS and xCarrito + 0.05 < 1: xCarrito = xCarrito + 0.03 if estadoAbajo == glfw.PRESS and yCarrito - 0.05 > -1: if not chocando(xCarrito, yCarrito - 0.01, 0.05, 0.05, xObstaculo, yObstaculo, 1, 0.15): yCarrito = yCarrito - 0.03 if estadoArriba == glfw.PRESS and yCarrito + 0.05 + 0.01 < 1: if chocando(xCarrito, yCarrito - 0.01, 0.05, 0.05, xObstaculo, yObstaculo, 1, 0.15): yCarrito = (yCarrito + 0.4)
def _cursor_pos_callback(self, window, xpos, ypos): if not (self._button_left_pressed or self._button_right_pressed): return mod_shift = (glfw.get_key(window, glfw.KEY_LEFT_SHIFT) == glfw.PRESS or glfw.get_key(window, glfw.KEY_RIGHT_SHIFT) == glfw.PRESS) if self._button_right_pressed: action = (mujoco.mjtMouse.mjMOUSE_MOVE_H if mod_shift else mujoco.mjtMouse.mjMOUSE_MOVE_V) elif self._button_left_pressed: action = (mujoco.mjtMouse.mjMOUSE_ROTATE_H if mod_shift else mujoco.mjtMouse.mjMOUSE_ROTATE_V) else: action = mujoco.mjtMouse.mjMOUSE_ZOOM dx = int(self._scale * xpos) - self._last_mouse_x dy = int(self._scale * ypos) - self._last_mouse_y width, height = glfw.get_framebuffer_size(window) with self._gui_lock: mujoco.mjv_moveCamera(self.model, action, dx / height, dy / height, self.scn, self.cam) self._last_mouse_x = int(self._scale * xpos) self._last_mouse_y = int(self._scale * ypos)
def actualizar(self, window): estadoIzquierda = glfw.get_key(window, glfw.KEY_LEFT) estadoDerecha = glfw.get_key(window, glfw.KEY_RIGHT) estadoAbajo = glfw.get_key(window, glfw.KEY_DOWN) estadoArriba = glfw.get_key(window, glfw.KEY_UP) if estadoIzquierda == glfw.PRESS and self.colisionando == False: self.posicionX = self.posicionX - 0.2 self.direccion = 2 self.rotacion = 0 - self.desfase playsound.playsound('pacman-waka-waka.mp3', True) #playsound.playsound('pacman-waka-waka.mp3', False) #playsound.playsound('pacman-waka-waka.mp3', True) #playsound.playsound('pacman-waka-waka.mp3', True) if estadoDerecha == glfw.PRESS and self.colisionando == False: self.posicionX = self.posicionX + 0.2 self.direccion = 1 self.rotacion = 180 - self.desfase playsound.playsound('pacman-waka-waka.mp3', True) #playsound.playsound('pacman-waka-waka.mp3', True) #playsound.playsound('pacman-waka-waka.mp3', True) if estadoAbajo == glfw.PRESS and self.colisionando == False: self.posicionY = self.posicionY - 0.2 self.direccion = 3 self.rotacion = 90 - self.desfase playsound.playsound('pacman-waka-waka.mp3', True) #playsound.playsound('pacman-waka-waka.mp3', True) #playsound.playsound('pacman-waka-waka.mp3', True) if estadoArriba == glfw.PRESS and self.colisionando == False: self.posicionY = self.posicionY + 0.2 self.direccion = 0 self.rotacion = 270 - self.desfase playsound.playsound('pacman-waka-waka.mp3', True)
def draw(self, projection, view, model, win=None, **_kwargs): # some interactive elements if glfw.get_key(win, glfw.KEY_F6) == glfw.PRESS: self.f6 += 1 if (self.f6 % 100 == 0): self.f6 = 0 self.wrap_mode = next(self.wrap) self.texture = Texture(self.file, self.wrap_mode, *self.filter_mode) if glfw.get_key(win, glfw.KEY_F7) == glfw.PRESS: self.f7 += 1 if (self.f7 % 100 == 0): self.f7 = 0 self.filter_mode = next(self.filter) self.texture = Texture(self.file, self.wrap_mode, *self.filter_mode) GL.glUseProgram(self.shader.glid) # projection geometry loc = GL.glGetUniformLocation(self.shader.glid, 'modelviewprojection') GL.glUniformMatrix4fv(loc, 1, True, projection @ view @ model) # texture access setups loc = GL.glGetUniformLocation(self.shader.glid, 'diffuseMap') GL.glActiveTexture(GL.GL_TEXTURE0) GL.glBindTexture(GL.GL_TEXTURE_2D, self.texture.glid) GL.glUniform1i(loc, 0) self.vertex_array.draw(GL.GL_TRIANGLES) # leave clean state for easier debugging GL.glBindTexture(GL.GL_TEXTURE_2D, 0) GL.glUseProgram(0)
def actualizar(window): global tiempo_anterior global angulo global xCarrito global yCarrito tiempo_actual = glfw.get_time() tiempo_delta = tiempo_actual - tiempo_anterior estadoIzquierda = glfw.get_key(window, glfw.KEY_LEFT) estadoDerecha = glfw.get_key(window, glfw.KEY_RIGHT) estadoAbajo = glfw.get_key(window, glfw.KEY_DOWN) estadoArriba = glfw.get_key(window, glfw.KEY_UP) if estadoIzquierda == glfw.PRESS: angulo = angulo + (velocidad_angular * tiempo_delta) if angulo > 360: angulo = 0 if estadoDerecha == glfw.PRESS: angulo = angulo - (velocidad_angular * tiempo_delta) if angulo < 0: angulo = 360 if estadoArriba == glfw.PRESS: yCarrito = yCarrito + \ (sin((angulo + desfase) * 3.14159 / 180) * velocidad * tiempo_delta) xCarrito = xCarrito + \ (cos((angulo + desfase) * 3.14159 / 180) * velocidad * tiempo_delta) checar_colisiones() actualizar_bala(tiempo_delta) tiempo_anterior = tiempo_actual
def process_input(window): if glfw.get_key(window, glfw.KEY_ESCAPE) == glfw.PRESS: glfw.set_window_should_close(window, True) if glfw.get_key(window, glfw.KEY_LEFT) == glfw.PRESS: gl.glPolygonMode(gl.GL_FRONT_AND_BACK, gl.GL_FILL) if glfw.get_key(window, glfw.KEY_RIGHT) == glfw.PRESS: gl.glPolygonMode(gl.GL_FRONT_AND_BACK, gl.GL_LINE)
def actualizar(window): global velocidad global tiempo global tiempoAnterior global pos_x_triangulo global pos_y_triangulo tiempo = glfw.get_time() tiempoDiferencial = tiempo - tiempoAnterior estado_tecla_izquierda = glfw.get_key(window, glfw.KEY_LEFT) estado_tecla_derecha = glfw.get_key(window, glfw.KEY_RIGHT) estado_tecla_abajo = glfw.get_key(window, glfw.KEY_DOWN) estado_tecla_arriba = glfw.get_key(window, glfw.KEY_UP) cantidadMovimiento = velocidad * tiempoDiferencial if estado_tecla_izquierda == glfw.PRESS: pos_x_triangulo = pos_x_triangulo - cantidadMovimiento if estado_tecla_derecha == glfw.PRESS: pos_x_triangulo = pos_x_triangulo + cantidadMovimiento if estado_tecla_abajo == glfw.PRESS: pos_y_triangulo = pos_y_triangulo - cantidadMovimiento if estado_tecla_arriba == glfw.PRESS: pos_y_triangulo = pos_y_triangulo + cantidadMovimiento tiempoAnterior = tiempo
def actualizar(self, window, tiempo_delta): estadoIzquierda = glfw.get_key(window, glfw.KEY_LEFT) estadoDerecha = glfw.get_key(window, glfw.KEY_RIGHT) estadoAbajo = glfw.get_key(window, glfw.KEY_DOWN) estadoArriba = glfw.get_key(window, glfw.KEY_UP) if estadoIzquierda == glfw.PRESS: self.angulo = self.angulo + (self.velocidad_angular * tiempo_delta) if self.angulo > 360: self.angulo = 0 if estadoDerecha == glfw.PRESS: self.angulo = self.angulo - (self.velocidad_angular * tiempo_delta) if self.angulo < 0: self.angulo = 360 if estadoArriba == glfw.PRESS: self.posicionY = self.posicionY + \ (sin((self.angulo + self.desfase) * 3.14159 / 180) * self.velocidad * tiempo_delta) self.posicionX = self.posicionX + \ (cos((self.angulo + self.desfase) * 3.14159 / 180) * self.velocidad * tiempo_delta) if self.disparando: if bala.posicionX >= 1: self.disparando = False elif bala.posicionX <= -1: self.disparando = False elif bala.posicionY >= 1: self.disparando = False elif bala.posicionY <= -1: self.disparando = False if self.disparando: bala.actualizar(tiempo_delta)
def move(self, window, viewPos, forward, new_side, dt): if glfw.get_key(window, glfw.KEY_A) == glfw.PRESS: self.position[0] -= 2 * dt viewPos += new_side * dt * 10 elif glfw.get_key(window, glfw.KEY_D) == glfw.PRESS: self.position[0] += 2 * dt viewPos -= new_side * dt * 10 elif glfw.get_key(window, glfw.KEY_W) == glfw.PRESS: self.position[1] += 2 * dt viewPos += forward * dt * 10 elif glfw.get_key(window, glfw.KEY_S) == glfw.PRESS: self.position[1] -= 2 * dt viewPos -= forward * dt * 10 elif glfw.get_key(window, glfw.KEY_Q) == glfw.PRESS: self.position[2] += 2 * dt viewPos[2] += 2 * dt else: pass return self.position
def draw(self, projection, view, model, win=None, **param): assert win is not None self.angle += 2 * int(glfw.get_key(win, self.key_up) == glfw.PRESS) self.angle -= 2 * int(glfw.get_key(win, self.key_down) == glfw.PRESS) self.transform = rotate(self.axis, self.angle) super().draw(projection, view, model, win=win, **param)
def main(self): glfw.set_error_callback(error_callback) if not glfw.init(): raise RuntimeError('glfw.init()') glfw.window_hint(glfw.OPENGL_FORWARD_COMPAT, True) glfw.window_hint(glfw.OPENGL_PROFILE, glfw.OPENGL_CORE_PROFILE) glfw.window_hint(glfw.CONTEXT_VERSION_MAJOR, 3) glfw.window_hint(glfw.CONTEXT_VERSION_MINOR, 3) glfw.window_hint(glfw.SAMPLES, 4) glfw.window_hint(glfw.RESIZABLE, False) self.window = glfw.create_window(self.screen_x, self.screen_y, self.title, None, None) if not self.window: raise RuntimeError('glfw.CreateWindow())') glfw.make_context_current(self.window) glfw.set_input_mode(self.window, glfw.CURSOR, glfw.CURSOR_DISABLED) glfw.set_cursor_pos(self.window, 0, 0) glEnable(GL_BLEND) glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA) glEnable(GL_DEPTH_TEST) glDepthFunc(GL_LESS) glClearColor(0, 0, 0, 1) # print(b'OpenGL version: ' + glGetString(GL_VERSION)) # print(b'GLSL version: ' + glGetString(GL_SHADING_LANGUAGE_VERSION)) # print(b'Vendor: ' + glGetString(GL_VENDOR)) # print(b'Renderer: ' + glGetString(GL_RENDERER)) self.init() old_time = glfw.get_time() try: while not glfw.window_should_close(self.window): glfw.poll_events() if any(( ( glfw.get_key(self.window, glfw.KEY_LEFT_ALT) and \ glfw.get_key(self.window, glfw.KEY_F4) ), ( glfw.get_key(self.window, glfw.KEY_LEFT_CONTROL) and \ glfw.get_key(self.window, glfw.KEY_Q) ) )): glfw.set_window_should_close(self.window, True) now = glfw.get_time() self.update(float(now - old_time)) old_time = now self.render() glfw.swap_buffers(self.window) except KeyboardInterrupt: pass glfw.terminate()
def draw(self, shader, projection, view, model=None, is_fisheye=False, fish_fov=np.pi, win=None, **_kwargs): if model is None: model = self.model_matrix else: self.model_matrix = model # some interactive elements if glfw.get_key(win, glfw.KEY_F6) == glfw.PRESS: self.wrap_mode = next(self.wrap) self.texture = Texture(self.file, self.wrap_mode, *self.filter_mode) if glfw.get_key(win, glfw.KEY_F7) == glfw.PRESS: self.filter_mode = next(self.filter) self.texture = Texture(self.file, self.wrap_mode, *self.filter_mode) GL.glUseProgram(shader.glid) # projection geometry loc = GL.glGetUniformLocation(shader.glid, 'modelviewprojection') GL.glUniformMatrix4fv(loc, 1, True, np.dot(np.dot(projection, view), model)) if is_fisheye: loc = GL.glGetUniformLocation(shader.glid, 'modelview') GL.glUniformMatrix4fv(loc, 1, True, mat_from_gl(np.dot(view, model))) loc = GL.glGetUniformLocation(shader.glid, 'fov') GL.glUniform1f(loc, fish_fov) # texture access setups #GL.glTexEnvf(GL.GL_TEXTURE_ENV, GL.GL_TEXTURE_ENV_MODE, GL.GL_MODULATE) GL.glEnable(GL.GL_BLEND) GL.glBlendFunc(GL.GL_ONE, GL.GL_ONE_MINUS_SRC_ALPHA) # object transparancy loc = GL.glGetUniformLocation(shader.glid, 'alpha') GL.glUniform1f(loc, self.alpha) #GL.glColor4f(1.0, 1.0, 1.0, 0.5) loc = GL.glGetUniformLocation(shader.glid, 'diffuseMap') GL.glActiveTexture(GL.GL_TEXTURE0) GL.glBindTexture(GL.GL_TEXTURE_2D, self.texture.glid) GL.glUniform1i(loc, 0) self.vertex_array.execute(GL.GL_TRIANGLES) # leave clean state for easier debugging GL.glBindTexture(GL.GL_TEXTURE_2D, 0) GL.glUseProgram(0) GL.glDisable(GL.GL_BLEND)
def draw(self, projection, view, model, color_shader, win=None, **param): assert win is not None self.angle += 2 * int(glfw.get_key(win, self.key_up) == glfw.PRESS) self.angle -= 2 * int(glfw.get_key(win, self.key_down) == glfw.PRESS) self.transform = rotate(axis=self.axis, angle=self.angle) # call Node's draw method to pursue the hierarchical tree calling super().draw(projection, view, model, color_shader, win=win, **param)
def scroll_callback(window, x_offset, y_offset): mod_shift = glfw.get_key(window, glfw.KEY_LEFT_SHIFT) == glfw.PRESS or \ glfw.get_key(window, glfw.KEY_RIGHT_SHIFT) == glfw.PRESS if mod_shift: scroll_callback.pos -= 0.05 * y_offset callback(scroll_callback.pos) else: viewer._scroll_callback(window, x_offset, y_offset)
def handleInput(self, window): if glfw.get_key(window, glfw.KEY_J) == glfw.PRESS: self.dataToSend = 'a' if glfw.get_key(window, glfw.KEY_I) == glfw.PRESS: self.dataToSend = 'w' if glfw.get_key(window, glfw.KEY_L) == glfw.PRESS: self.dataToSend = 'd' if glfw.get_key(window, glfw.KEY_K) == glfw.PRESS: self.dataToSend = 's' if self.dataToSend == self.previousData: return if not self.pacman.isMoving and not self.alreadySend: if self.dataToSend != 'n': Network().sendData(self.dataToSend) self.previousData = self.dataToSend self.alreadySend = True elif not self.alreadySend: if self.pacman.currectDirection == Direction.LEFT: if 0.9 > (self.pacman.position[0] - math.floor(self.pacman.position[0])) > 0.8: print("Sending LEFT " + self.dataToSend) Network().sendData(self.dataToSend) self.previousData = self.dataToSend self.alreadySend = True elif self.pacman.currectDirection == Direction.RIGHT: if 0.1 < (self.pacman.position[0] - math.floor(self.pacman.position[0])) < 0.2: print("Sending RIGHT " + self.dataToSend) Network().sendData(self.dataToSend) self.previousData = self.dataToSend self.alreadySend = True elif self.pacman.currectDirection == Direction.UP: if 0.1 < (self.pacman.position[2] - math.floor(self.pacman.position[2])) < 0.2: print("Sending UP " + self.dataToSend) Network().sendData(self.dataToSend) self.previousData = self.dataToSend self.alreadySend = True elif self.pacman.currectDirection == Direction.DOWN: if 0.9 > (self.pacman.position[2] - math.floor(self.pacman.position[2])) > 0.8: print("Sending DOWN " + self.dataToSend) Network().sendData(self.dataToSend) self.previousData = self.dataToSend self.alreadySend = True else: self.alreadySend = False
def actualizar_movimiento(self, window, deltatime): movimiento = self.velocidad * deltatime estado_tecla_izquierda = glfw.get_key(window, glfw.KEY_LEFT) estado_tecla_derecha = glfw.get_key(window, glfw.KEY_RIGHT) estado_tecla_abajo = glfw.get_key(window, glfw.KEY_DOWN) estado_tecla_arriba = glfw.get_key(window, glfw.KEY_UP) if self.dano < 120: if estado_tecla_izquierda == glfw.PRESS: self.condicionXP = False self.condicionXN = True self.condicionYP = False self.condicionYN = False if self.psX - 0.05 < -0.8: self.condicionXP = True self.condicionXN = False self.condicionYP = False self.condicionYN = False if estado_tecla_derecha == glfw.PRESS: self.condicionXP = True self.condicionXN = False self.condicionYP = False self.condicionYN = False if self.psX + 0.05 > 0.8: self.condicionXP = False self.condicionXN = True self.condicionYP = False self.condicionYN = False if estado_tecla_abajo == glfw.PRESS: self.condicionXP = False self.condicionXN = False self.condicionYP = False self.condicionYN = True if self.psY - 0.1 < -1.0: self.condicionXP = False self.condicionXN = False self.condicionYP = True self.condicionYN = False if estado_tecla_arriba == glfw.PRESS: self.condicionXP = False self.condicionXN = False self.condicionYP = True self.condicionYN = False if self.psY + 0.1 > 1.0: self.condicionXP = False self.condicionXN = False self.condicionYP = False self.condicionYN = True if self.condicionXP == True: self.psX = self.psX + movimiento if self.condicionXN == True: self.psX = self.psX - movimiento if self.condicionYP == True: self.psY = self.psY + movimiento if self.condicionYN == True: self.psY = self.psY - movimiento
def key_event(window, key, scancode, action, mods): if glfw.get_key(window, glfw.KEY_C): scene.key_pressed('cube') elif glfw.get_key(window, glfw.KEY_Q): scene.key_pressed('quad') elif glfw.get_key(window, glfw.KEY_P): scene.key_pressed('polygon') elif glfw.get_key(window, glfw.KEY_O): scene.key_pressed('polygon off')
def __process_events(window): if glfw.get_key(window, glfw.KEY_ESCAPE) is glfw.PRESS: glfw.set_window_should_close(window, True) if glfw.get_key(window, glfw.KEY_W) == glfw.PRESS: glPolygonMode(GL_FRONT_AND_BACK, GL_LINE) if glfw.get_key(window, glfw.KEY_F) == glfw.PRESS: glPolygonMode(GL_FRONT_AND_BACK, GL_FILL) if glfw.get_key(window, glfw.KEY_P) == glfw.PRESS: glPolygonMode(GL_FRONT_AND_BACK, GL_POINT)
def moveInput(win, time): if glfw.get_key(win, glfw.KEY_W) == glfw.PRESS: camera.moveTop(time) if glfw.get_key(win, glfw.KEY_S) == glfw.PRESS: camera.moveBottom(time) if glfw.get_key(win, glfw.KEY_A) == glfw.PRESS: camera.moveLeft(time) if glfw.get_key(win, glfw.KEY_D) == glfw.PRESS: camera.moveRight(time)
def processInput(window): if glfw.get_key(window, glfw.KEY_ESCAPE) == glfw.PRESS: glfw.glfwSetWindowShouldClose() if glfw.get_key(window, glfw.KEY_LEFT) == glfw.PRESS: gl.glPolygonMode(gl.GL_FRONT_AND_BACK, gl.GL_FILL) if glfw.get_key(window, glfw.KEY_RIGHT) == glfw.PRESS: gl.glPolygonMode(gl.GL_FRONT_AND_BACK, gl.GL_LINE)
def draw(self, projection, view, model, win=None, **param): assert win is not None self.angle += 0.2 * int(glfw.get_key(win, self.key_up) == glfw.PRESS) self.angle -= 0.2 * int(glfw.get_key(win, self.key_down) == glfw.PRESS) #model = model @ param.get('transf', identity()) self.transform = rotate(self.axis, self.angle) # call Node's draw method to pursue the hierarchical tree calling super().draw(projection, view, model, win=win, **param)
def processInput(self, window, deltaTime): delta = self.speed * deltaTime if glfw.get_key(window, glfw.KEY_W) == glfw.PRESS: self.pos += delta * self.front if glfw.get_key(window, glfw.KEY_S) == glfw.PRESS: self.pos -= delta * self.front if glfw.get_key(window, glfw.KEY_A) == glfw.PRESS: self.pos -= glm.normalize(glm.cross(self.front, self.up)) * delta if glfw.get_key(window, glfw.KEY_D) == glfw.PRESS: self.pos += glm.normalize(glm.cross(self.front, self.up)) * delta
def trataTeclado(): global Cam_pos, Cam_yaw, Cam_yaw_speed, Tempo_entre_frames if (glfw.PRESS == glfw.get_key(Window, glfw.KEY_ESCAPE)): glfw.set_window_should_close(Window, True) if (glfw.PRESS == glfw.get_key(Window, glfw.KEY_A)): Cam_pos[0] -= Cam_speed * Tempo_entre_frames if (glfw.PRESS == glfw.get_key(Window, glfw.KEY_D)): Cam_pos[0] += Cam_speed * Tempo_entre_frames if (glfw.PRESS == glfw.get_key(Window, glfw.KEY_PAGE_UP)): Cam_pos[1] += Cam_speed * Tempo_entre_frames if (glfw.PRESS == glfw.get_key(Window, glfw.KEY_PAGE_DOWN)): Cam_pos[1] -= Cam_speed * Tempo_entre_frames if (glfw.PRESS == glfw.get_key(Window, glfw.KEY_W)): Cam_pos[2] -= Cam_speed * Tempo_entre_frames if (glfw.PRESS == glfw.get_key(Window, glfw.KEY_S)): Cam_pos[2] += Cam_speed * Tempo_entre_frames if (glfw.PRESS == glfw.get_key(Window, glfw.KEY_LEFT)): Cam_yaw += Cam_yaw_speed * Tempo_entre_frames if (glfw.PRESS == glfw.get_key(Window, glfw.KEY_RIGHT)): Cam_yaw -= Cam_yaw_speed * Tempo_entre_frames
def processInput(window): # global rotate, rpressed global cameraPos, cameraFront, ipressed if glfw.get_key(window, glfw.KEY_ESCAPE) == glfw.PRESS: glfw.set_window_should_close(window, True) if glfw.get_key(window, glfw.KEY_W) == glfw.PRESS: camera.processKeyboard(mycamera.FORWARD, deltaTime) if glfw.get_key(window, glfw.KEY_S) == glfw.PRESS: camera.processKeyboard(mycamera.BACKWARD, deltaTime) if glfw.get_key(window, glfw.KEY_A) == glfw.PRESS: camera.processKeyboard(mycamera.LEFT, deltaTime) if glfw.get_key(window, glfw.KEY_D) == glfw.PRESS: camera.processKeyboard(mycamera.RIGHT, deltaTime) if glfw.get_key(window, glfw.KEY_Q) == glfw.PRESS: camera.processKeyboard(mycamera.UP, deltaTime) if glfw.get_key(window, glfw.KEY_Z) == glfw.PRESS: camera.processKeyboard(mycamera.DOWN, deltaTime) if glfw.get_key(window, glfw.KEY_I) == glfw.PRESS: if not ipressed: print(f"lastX: {lastX:3.2f}, lastY: {lastY:3.2f}") print(f"fps: {1/deltaTime:3.1f}") print(camera) ipressed = True if glfw.get_key(window, glfw.KEY_I) == glfw.RELEASE: ipressed = False camera.step(deltaTime)
def handle_movement_of_paddles(): global paddle1, paddle2 if glfw.get_key(window, glfw.KEY_S) == glfw.PRESS: paddle1.input_offset_y -= 0.1 if glfw.get_key(window, glfw.KEY_W) == glfw.PRESS: paddle1.input_offset_y += 0.1 if glfw.get_key(window, glfw.KEY_K) == glfw.PRESS: paddle2.input_offset_y -= 0.1 if glfw.get_key(window, glfw.KEY_I) == glfw.PRESS: paddle2.input_offset_y += 0.1
def process_input(self, window, delta_time): if glfw.get_key(window, glfw.KEY_ESCAPE) == glfw.PRESS: glfw.set_window_should_close(window, True) if (glfw.get_key(window, glfw.KEY_W) == glfw.PRESS): self.camera.process_keyboard(CAMERA_MOVEMENT.FORWARD, delta_time) if (glfw.get_key(window, glfw.KEY_S) == glfw.PRESS): self.camera.process_keyboard(CAMERA_MOVEMENT.BACKWARD, delta_time) if (glfw.get_key(window, glfw.KEY_A) == glfw.PRESS): self.camera.process_keyboard(CAMERA_MOVEMENT.LEFT, delta_time) if (glfw.get_key(window, glfw.KEY_D) == glfw.PRESS): self.camera.process_keyboard(CAMERA_MOVEMENT.RIGHT, delta_time)
def input_events(self): if glfw.get_mouse_button(self._win, 0): glRotate(-2, 0, 1, 0) if glfw.get_mouse_button(self._win, 1): glRotate(2, 0, 1, 0) if glfw.get_key(self._win, 32): #TeclaS if not self.is_rotating: self.is_rotating = True if glfw.get_key(self._win, 68): #TeclaS for polygon in self._list_of_polygons: polygon.rotate_around_corner(-2)
def handle_movement_of_paddles() -> None: global paddle1, paddle2 if glfw.get_key(window, glfw.KEY_S) == glfw.PRESS: paddle1.position.y -= 0.1 if glfw.get_key(window, glfw.KEY_W) == glfw.PRESS: paddle1.position.y += 0.1 if glfw.get_key(window, glfw.KEY_K) == glfw.PRESS: paddle2.position.y -= 0.1 if glfw.get_key(window, glfw.KEY_I) == glfw.PRESS: paddle2.position.y += 0.1
def handle_mouse_move(self, window, xpos, ypos): # no buttons down: nothing to do if not self._button_left_pressed \ and not self._button_middle_pressed \ and not self._button_right_pressed: return # compute mouse displacement, save dx = int(self._scale * xpos) - self._last_mouse_x dy = int(self._scale * ypos) - self._last_mouse_y self._last_mouse_x = int(self._scale * xpos) self._last_mouse_y = int(self._scale * ypos) # require model if not self.model: return # get current window size width, height = glfw.get_framebuffer_size(self.window) # get shift key state mod_shift = glfw.get_key(window, glfw.KEY_LEFT_SHIFT) == glfw.PRESS \ or glfw.get_key(window, glfw.KEY_RIGHT_SHIFT) == glfw.PRESS # determine action based on mouse button action = None if self._button_right_pressed: action = MOUSE_MOVE_H if mod_shift else MOUSE_MOVE_V elif self._button_left_pressed: action = MOUSE_ROTATE_H if mod_shift else MOUSE_ROTATE_V else: action = MOUSE_ZOOM self.gui_lock.acquire() mjlib.mjv_moveCamera(action, dx, dy, byref(self.cam), width, height) self.gui_lock.release()
def main(): global current_vao global vaos if not opengl_init(): return glfw.set_input_mode(window,glfw.STICKY_KEYS,GL_TRUE) glfw.set_key_callback(window,key_event) # Set opengl clear color to something other than red (color used by the fragment shader) glClearColor(0,0,0.4,0) # Create vertex array object (VAO) 1: Full Triangle vao = glGenVertexArrays(1) glBindVertexArray(vao) init_object(vertex_data) glBindVertexArray(0) # Create vertex array object (VAO) 2: 1/2 Triangle vao2 = glGenVertexArrays(1) glBindVertexArray(vao2) init_object(vertex_data2) glBindVertexArray(0) program_id = common.LoadShaders( "SimpleVertexShader.vertexshader", "SimpleFragmentShader.fragmentshader" ) vertex_buffer = glGenBuffers(1) current_vao = 0 vaos = [vao,vao2] glewInit() while glfw.get_key(window,glfw.KEY_ESCAPE) != glfw.PRESS and not glfw.window_should_close(window): glClear(GL_COLOR_BUFFER_BIT) glUseProgram(program_id) glBindVertexArray(vaos[current_vao]) # Draw the triangle ! glDrawArrays (GL_TRIANGLES, 0, 3)#3 indices starting at 0 -> 1 triangle glBindVertexArray(0) # Swap front and back buffers glfw.swap_buffers(window) # Poll for and process events glfw.poll_events() glfw.terminate()
def main(): # Initialize the library if not glfw.init(): return # Open Window and create its OpenGL context window = glfw.create_window(1024, 768, "Tutorial 01", None, None) # glfw.window_hint(glfw.SAMPLES, 4) glfw.window_hint(glfw.CONTEXT_VERSION_MAJOR, 3) glfw.window_hint(glfw.CONTEXT_VERSION_MINOR, 3) glfw.window_hint(glfw.OPENGL_FORWARD_COMPAT, GL_TRUE) glfw.window_hint(glfw.OPENGL_PROFILE, glfw.OPENGL_CORE_PROFILE) if not window: print("Failed to open GLFW window. If you have an Intel GPU, they are not 3.3 compatible. Try the 2.1 version of the tutorials.\n",file=sys.stderr) glfw.terminate() return # Initialize GLEW glfw.make_context_current(window) glewExperimental = True # GLEW is a framework for testing extension availability. Please see tutorial notes for # more information including why can remove this code. if glewInit() != GLEW_OK: print("Failed to initialize GLEW\n",file=sys.stderr); return glfw.set_input_mode(window,glfw.STICKY_KEYS,True) # Loop until the user closes the window #while not glfw.window_should_close(window): while glfw.get_key(window,glfw.KEY_ESCAPE) != glfw.PRESS and not glfw.window_should_close(window): # Draw nothing sucker # Swap front and back buffers glfw.swap_buffers(window) # Poll for and process events glfw.poll_events() glfw.terminate()
def do_input(): global old_keys new_keys = [] # Map cursor position to key presses if blob_pos is not None: if blob_pos[0] > 2.0 / 3.0 * WINDOW_WIDTH: new_keys.append('d') elif blob_pos[0] < 1.0 / 3.0 * WINDOW_WIDTH: new_keys.append('a') if blob_pos[1] > 2.0 / 3.0 * WINDOW_HEIGHT: new_keys.append('w') elif blob_pos[1] < 1.0 / 3.0 * WINDOW_HEIGHT: new_keys.append('s') if glfw.get_key(window, glfw.KEY_ENTER) == glfw.PRESS: new_keys.append('Escape') # Send press and release events when key state changes for char in ['w', 'a', 's', 'd', 'Escape']: new = char in new_keys old = char in old_keys if new: if not old: display.send_event(dest_window, keyev(char, True), event_mask=1) elif old: if not new: display.send_event(dest_window, keyev(char, False), event_mask=1) # Events don't get processed unless they are manually flushed while display.pending_events() > 0: display.poll_events() old_keys = new_keys
def poll_event(self, window): flag = False cur_time = glfw.get_time() del_time = cur_time - self.last_time march = sidle = dive = 0. if glfw.get_key(window, glfw.KEY_W) == glfw.PRESS: march = self.speed * del_time elif glfw.get_key(window, glfw.KEY_S) == glfw.PRESS: march = - self.speed * del_time if glfw.get_key(window, glfw.KEY_D) == glfw.PRESS: sidle = self.speed * del_time elif glfw.get_key(window, glfw.KEY_A) == glfw.PRESS: sidle = - self.speed * del_time if glfw.get_key(window, glfw.KEY_SPACE) == glfw.PRESS: dive = self.speed * del_time elif glfw.get_key(window, glfw.KEY_V) == glfw.PRESS: dive = - self.speed * del_time if march or sidle or dive: self.translate(march, sidle, dive) flag = True cur_mx, cur_my = glfw.get_cursor_pos(window) if glfw.get_mouse_button(window, glfw.MOUSE_BUTTON_RIGHT) == glfw.PRESS: del_mx, del_my = cur_mx - self.last_mx, cur_my - self.last_my spin = tilt = 0. if del_mx: spin = self.rev * del_mx * del_time # self.spin += self.rev * del_mx if del_my: tilt = self.rev * del_my * del_time if spin or tilt: self.rotate(spin, tilt) flag = True self.last_mx, self.last_my = cur_mx, cur_my self.last_time = cur_time if flag: self._update_orientation() self._update_view_mat()
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\\Tutorial7\\TransformVertexShader.vertexshader", ".\\shaders\\Tutorial7\\TextureFragmentShader.fragmentshader" ) # Get a handle for our "MVP" uniform matrix_id = glGetUniformLocation(program_id, "MVP") # Load the texture texture = load_image(".\\content\\uvmap.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\\cube.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) # 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) array_type = GLfloat * len(uv_data) glBindBuffer(GL_ARRAY_BUFFER, uv_buffer) glBufferData(GL_ARRAY_BUFFER, len(uv_data) * 4 * 2, uv_data, GL_STATIC_DRAW) # vsync and glfw do not play nice. when vsync is enabled mouse movement is jittery. common.disable_vsyc() 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) 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) # 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*) ) # 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) # Swap front and back buffers glfw.swap_buffers(window) # Poll for and process events glfw.poll_events() # !Note braces around vertex_buffer and uv_buffer. # glDeleteBuffers expects a list of buffers to delete glDeleteBuffers(1, [vertex_buffer]) glDeleteBuffers(1, [uv_buffer]) glDeleteProgram(program_id) glDeleteTextures([texture_id]) glDeleteVertexArrays(1, [vertex_array_id]) glfw.terminate()
def _move_step(self, window, key_p, key_n, del_time): if glfw.get_key(window, key_p) == glfw.PRESS: return self.speed * del_time elif glfw.get_key(window, key_n) == glfw.PRESS: return - self.speed * del_time
#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) glfw.set_scroll_callback(w, on_scroll) while not glfw.window_should_close(w): glfw.poll_events() if glfw.get_key(w, glfw.KEY_E) == glfw.PRESS: break glClear(GL_COLOR_BUFFER_BIT) glfw.swap_buffers(w) glfw.close_window(w) glfw.terminate()
def main(): if not opengl_init(): return glfw.set_input_mode(window,glfw.STICKY_KEYS,GL_TRUE) # Set opengl clear color to something other than red (color used by the fragment shader) glClearColor(0,0,0.4,0) vertex_array_id = glGenVertexArrays(1) glBindVertexArray( vertex_array_id ) program_id = common.LoadShaders( ".\\shaders\\Tutorial3\\SimpleTransform.vertexshader", ".\\shaders\\Tutorial3\\SingleColor.fragmentshader" ) # Get a handle for our "MVP" uniform matrix_id= glGetUniformLocation(program_id, "MVP"); # Projection matrix : 45 Field of View, 4:3 ratio, display range : 0.1 unit <-> 100 units projection = mat4.perspective(45.0, 4.0 / 3.0, 0.1, 100.0) # Camera matrix view = mat4.lookat(vec3(4,3,3), # Camera is at (4,3,3), in World Space vec3(0,0,0), # and looks at the origin vec3(0,1,0)) # Model matrix : an identity matrix (model will be at the origin) model = mat4.identity() # Our ModelViewProjection : multiplication of our 3 matrices mvp = projection * view * model vertex_data = [-1.0, -1.0, 0.0, 1.0, -1.0, 0.0, 0.0, 1.0, 0.0] vertex_buffer = glGenBuffers(1); # GLFloat = c_types.c_float 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) while glfw.get_key(window,glfw.KEY_ESCAPE) != glfw.PRESS and not glfw.window_should_close(window): glClear(GL_COLOR_BUFFER_BIT) glUseProgram(program_id) # Send our transformation to the currently bound shader, # in the "MVP" uniform glUniformMatrix4fv(matrix_id, 1, GL_FALSE,mvp.data) # Bind vertex buffer data to the attribute 0 in our shader. # Note: This can also be done in the VAO itself (see vao_test.py) # Enable the vertex attribute at element[0], in this case that's the triangle's vertices # this could also be color, normals, etc. It isn't necessary to disable these # 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*) ) # Draw the triangle ! glDrawArrays(GL_TRIANGLES, 0, 3) #3 indices starting at 0 -> 1 triangle # Not strictly necessary because we only have glDisableVertexAttribArray(0) # Swap front and back buffers glfw.swap_buffers(window) # Poll for and process events glfw.poll_events() # note braces around vertex_buffer and vertex_array_id. # These 2 functions expect arrays of values glDeleteBuffers(1, [vertex_buffer]) glDeleteProgram(program_id) glDeleteVertexArrays(1, [vertex_array_id]) glfw.terminate()
def main(): if not opengl_init(): return # Enable key events glfw.set_input_mode(window,glfw.STICKY_KEYS,GL_TRUE) # Enable key event callback glfw.set_key_callback(window,key_event) # Set opengl clear color to something other than red (color used by the fragment shader) glClearColor(0,0,0.4,0) vertex_array_id = glGenVertexArrays(1) glBindVertexArray( vertex_array_id ) program_id = common.LoadShaders( "Shaders/Tutorial4/TransformVertexShader.vertexshader", "Shaders/Tutorial4/ColorFragmentShader.fragmentshader" ) # Get a handle for our "MVP" uniform matrix_id= glGetUniformLocation(program_id, "MVP"); # Projection matrix : 45 Field of View, 4:3 ratio, display range : 0.1 unit <-> 100 units projection = mat4.perspective(45.0, 4.0 / 3.0, 0.1, 100.0) # Camera matrix view = mat4.lookat(vec3(4,3,-3), # Camera is at (4,3,3), in World Space vec3(0,0,0), # and looks at the origin vec3(0,1,0)) # Model matrix : an identity matrix (model will be at the origin) model = mat4.identity() # Our ModelViewProjection : multiplication of our 3 matrices mvp = projection * view * model # Our vertices. Tree consecutive floats give a 3D vertex; Three consecutive vertices give a triangle. # A cube has 6 faces with 2 triangles each, so this makes 6*2=12 triangles, and 12*3 vertices vertex_data = [ -1.0,-1.0,-1.0, -1.0,-1.0, 1.0, -1.0, 1.0, 1.0, 1.0, 1.0,-1.0, -1.0,-1.0,-1.0, -1.0, 1.0,-1.0, 1.0,-1.0, 1.0, -1.0,-1.0,-1.0, 1.0,-1.0,-1.0, 1.0, 1.0,-1.0, 1.0,-1.0,-1.0, -1.0,-1.0,-1.0, -1.0,-1.0,-1.0, -1.0, 1.0, 1.0, -1.0, 1.0,-1.0, 1.0,-1.0, 1.0, -1.0,-1.0, 1.0, -1.0,-1.0,-1.0, -1.0, 1.0, 1.0, -1.0,-1.0, 1.0, 1.0,-1.0, 1.0, 1.0, 1.0, 1.0, 1.0,-1.0,-1.0, 1.0, 1.0,-1.0, 1.0,-1.0,-1.0, 1.0, 1.0, 1.0, 1.0,-1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0,-1.0, -1.0, 1.0,-1.0, 1.0, 1.0, 1.0, -1.0, 1.0,-1.0, -1.0, 1.0, 1.0, 1.0, 1.0, 1.0, -1.0, 1.0, 1.0, 1.0,-1.0, 1.0] # One color for each vertex. They were generated randomly. color_data = [ 0.583, 0.771, 0.014, 0.609, 0.115, 0.436, 0.327, 0.483, 0.844, 0.822, 0.569, 0.201, 0.435, 0.602, 0.223, 0.310, 0.747, 0.185, 0.597, 0.770, 0.761, 0.559, 0.436, 0.730, 0.359, 0.583, 0.152, 0.483, 0.596, 0.789, 0.559, 0.861, 0.639, 0.195, 0.548, 0.859, 0.014, 0.184, 0.576, 0.771, 0.328, 0.970, 0.406, 0.615, 0.116, 0.676, 0.977, 0.133, 0.971, 0.572, 0.833, 0.140, 0.616, 0.489, 0.997, 0.513, 0.064, 0.945, 0.719, 0.592, 0.543, 0.021, 0.978, 0.279, 0.317, 0.505, 0.167, 0.620, 0.077, 0.347, 0.857, 0.137, 0.055, 0.953, 0.042, 0.714, 0.505, 0.345, 0.783, 0.290, 0.734, 0.722, 0.645, 0.174, 0.302, 0.455, 0.848, 0.225, 0.587, 0.040, 0.517, 0.713, 0.338, 0.053, 0.959, 0.120, 0.393, 0.621, 0.362, 0.673, 0.211, 0.457, 0.820, 0.883, 0.371, 0.982, 0.099, 0.879] 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) color_buffer = glGenBuffers(1); array_type = GLfloat * len(color_data) glBindBuffer(GL_ARRAY_BUFFER, color_buffer) glBufferData(GL_ARRAY_BUFFER, len(color_data) * 4, array_type(*color_data), GL_STATIC_DRAW) while glfw.get_key(window,glfw.KEY_ESCAPE) != glfw.PRESS and not glfw.window_should_close(window): # Enable depth test glEnable(GL_DEPTH_TEST) # Accept fragment if it closer to the camera than the former one glDepthFunc(GL_LESS) glClear(GL_COLOR_BUFFER_BIT| GL_DEPTH_BUFFER_BIT) glUseProgram(program_id) # Send our transformation to the currently bound shader, # in the "MVP" uniform glUniformMatrix4fv(matrix_id, 1, GL_FALSE,mvp.data) # Bind vertex buffer data to the attribute 0 in our shader. # Note: This can also be done in the VAO itself (see vao_test.py) # Enable the vertex attribute at element[0], in this case that's the triangle's vertices # this could also be color, normals, etc. It isn't necessary to disable these # #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, color_buffer); glVertexAttribPointer( 1, # 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*) ) # Draw the triangle ! glDrawArrays(GL_TRIANGLES, 0, 12*3) #3 indices starting at 0 -> 1 triangle # Not strictly necessary because we only have glDisableVertexAttribArray(0) glDisableVertexAttribArray(1) # Swap front and back buffers glfw.swap_buffers(window) # Poll for and process events glfw.poll_events() # note braces around vertex_buffer and vertex_array_id. # These 2 functions expect arrays of values glDeleteBuffers(1, [vertex_buffer]) glDeleteBuffers(1, [color_buffer]) glDeleteProgram(program_id) glDeleteVertexArrays(1, [vertex_array_id]) glfw.terminate()
def get_key(self, key): return glfw.get_key(self.window, key) == glfw.PRESS
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.0,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\\common\\StandardShading.vertexshader", ".\\shaders\\common\\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") # Read our OBJ file vertices,faces,uvs,normals,colors = objloader.load(".\\content\\male_apose_closed2.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) 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) 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() 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(0,4,4) glUniform3f(light_id, lightPos.x, lightPos.y, lightPos.z) #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 : normals glEnableVertexAttribArray(1); glBindBuffer(GL_ARRAY_BUFFER, normal_buffer); glVertexAttribPointer( 1, # 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) # Swap front and back buffers glfw.swap_buffers(window) # Take screenshot of active buffer if glfw.get_key( window, glfw.KEY_P ) == glfw.PRESS: print("Saving screenshot as 'test.bmp'") screenshot('test.bmp',1024,768) # Dump MVP matrix to the command line if glfw.get_key( window, glfw.KEY_M ) == glfw.PRESS: print(mvp) # 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, [normal_buffer]) glDeleteProgram(program_id) glDeleteVertexArrays(1, [vertex_array_id]) glfw.terminate()
def main(): if not opengl_init(): return glfw.set_input_mode(window,glfw.STICKY_KEYS,GL_TRUE) # Set opengl clear color to something other than red (color used by the fragment shader) glClearColor(0,0,0.4,0) vertex_array_id = glGenVertexArrays(1) glBindVertexArray( vertex_array_id ) program_id = common.LoadShaders( "Shaders/Tutorial2/SimpleVertexShader.vertexshader", "Shaders/Tutorial2/SimpleFragmentShader.fragmentshader" ) vertex_data = [-1.0, -1.0, 0.0, 1.0, -1.0, 0.0, 0.0, 1.0, 0.0] vertex_buffer = glGenBuffers(1); # GLFloat = c_types.c_float array_type = GLfloat * len(vertex_data) # array_type = c_types.c_float_array_9 so unpack values of vertex array x = array_type(*vertex_data) glBindBuffer(GL_ARRAY_BUFFER, vertex_buffer) glBufferData(GL_ARRAY_BUFFER, len(vertex_data) * 4, array_type(*vertex_data), GL_STATIC_DRAW) while glfw.get_key(window,glfw.KEY_ESCAPE) != glfw.PRESS and not glfw.window_should_close(window): glClear(GL_COLOR_BUFFER_BIT) glUseProgram(program_id) # Bind vertex buffer data to the attribute 0 in our shader. # Note: This can also be done in the VAO itself (see vao_test.py) # Enable the vertex attribute at element[0], in this case that's the triangle's vertices # this could also be color, normals, etc. It isn't necessary to disable these # 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*) ) # Draw the triangle ! glDrawArrays(GL_TRIANGLES, 0, 3) #3 indices starting at 0 -> 1 triangle # Not strictly necessary because we only have glDisableVertexAttribArray(0) # Swap front and back buffers glfw.swap_buffers(window) # Poll for and process events glfw.poll_events() # note braces around vertex_buffer and vertex_array_id. # These 2 functions expect arrays of values glDeleteBuffers(1, [vertex_buffer]) glDeleteProgram(program_id) glDeleteVertexArrays(1, [vertex_array_id]) glfw.terminate()
def main(): if not opengl_init(): return # Enable key events glfw.set_input_mode(window,glfw.STICKY_KEYS,GL_TRUE) # 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); vertex_array_id = glGenVertexArrays(1) glBindVertexArray( vertex_array_id ) program_id = common.LoadShaders( ".\\shaders\\Tutorial5\\TransformVertexShader.vertexshader", ".\\shaders\\Tutorial5\\TextureFragmentShader.fragmentshader" ) # Get a handle for our "MVP" uniform matrix_id = glGetUniformLocation(program_id, "MVP"); # Projection matrix : 45 Field of View, 4:3 ratio, display range : 0.1 unit <-> 100 units projection = mat4.perspective(45.0, 4.0 / 3.0, 0.1, 100.0) # Camera matrix view = mat4.lookat(vec3(4,3,-3), # Camera is at (4,3,3), in World Space vec3(0,0,0), # and looks at the origin vec3(0,1,0)) # Model matrix : an identity matrix (model will be at the origin) model = mat4.identity() # Our ModelViewProjection : multiplication of our 3 matrices mvp = projection * view * model texture = load_image(".\\content\\uvtemplate.bmp") texture_id = glGetUniformLocation(program_id, "myTextureSampler") # Our vertices. Tree consecutive floats give a 3D vertex; Three consecutive vertices give a triangle. # A cube has 6 faces with 2 triangles each, so this makes 6*2=12 triangles, and 12*3 vertices vertex_data = [ -1.0,-1.0,-1.0, -1.0,-1.0, 1.0, -1.0, 1.0, 1.0, 1.0, 1.0,-1.0, -1.0,-1.0,-1.0, -1.0, 1.0,-1.0, 1.0,-1.0, 1.0, -1.0,-1.0,-1.0, 1.0,-1.0,-1.0, 1.0, 1.0,-1.0, 1.0,-1.0,-1.0, -1.0,-1.0,-1.0, -1.0,-1.0,-1.0, -1.0, 1.0, 1.0, -1.0, 1.0,-1.0, 1.0,-1.0, 1.0, -1.0,-1.0, 1.0, -1.0,-1.0,-1.0, -1.0, 1.0, 1.0, -1.0,-1.0, 1.0, 1.0,-1.0, 1.0, 1.0, 1.0, 1.0, 1.0,-1.0,-1.0, 1.0, 1.0,-1.0, 1.0,-1.0,-1.0, 1.0, 1.0, 1.0, 1.0,-1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0,-1.0, -1.0, 1.0,-1.0, 1.0, 1.0, 1.0, -1.0, 1.0,-1.0, -1.0, 1.0, 1.0, 1.0, 1.0, 1.0, -1.0, 1.0, 1.0, 1.0,-1.0, 1.0] # 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] 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) 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) glUseProgram(program_id) # Send our transformation to the currently bound shader, # in the "MVP" uniform glUniformMatrix4fv(matrix_id, 1, GL_FALSE,mvp.data) # 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 0. No particular reason for 0, 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*) ) # Draw the triangle ! glDrawArrays(GL_TRIANGLES, 0, 12*3) #3 indices starting at 0 -> 1 triangle # Not strictly necessary because we only have glDisableVertexAttribArray(0) glDisableVertexAttribArray(1) # Swap front and back buffers glfw.swap_buffers(window) # Poll for and process events glfw.poll_events() # note braces around vertex_buffer and vertex_array_id. # These 2 functions expect arrays of values glDeleteBuffers(1, [vertex_buffer]) glDeleteBuffers(1, [uv_buffer]) glDeleteProgram(program_id) glDeleteTextures([texture_id]) glDeleteVertexArrays(1, [vertex_array_id]) glfw.terminate()
def is_stopped(self): return glfw.get_key(self.handle, self.terminate_key) == glfw.PRESS\ or glfw.window_should_close(self.handle)
def computeMatricesFromInputs(window): global lastTime global position global horizontalAngle global verticalAngle global initialFoV global ViewMatrix global ProjectionMatrix # glfwGetTime is called only once, the first time this function is called if lastTime == None: lastTime = glfw.get_time() # Compute time difference between current and last frame currentTime = glfw.get_time() deltaTime = currentTime - lastTime # Get mouse position xpos,ypos = glfw.get_cursor_pos(window) # Reset mouse position for next frame glfw.set_cursor_pos(window, 1024/2, 768/2); # Compute new orientation horizontalAngle += mouseSpeed * float(1024.0/2.0 - xpos ); verticalAngle += mouseSpeed * float( 768.0/2.0 - ypos ); # Direction : Spherical coordinates to Cartesian coordinates conversion direction = vec3( mathf.cos(verticalAngle) * mathf.sin(horizontalAngle), mathf.sin(verticalAngle), mathf.cos(verticalAngle) * mathf.cos(horizontalAngle) ) # Right vector right = vec3( mathf.sin(horizontalAngle - 3.14/2.0), 0.0, mathf.cos(horizontalAngle - 3.14/2.0) ) # Up vector up = vec3.cross( right, direction ) # Move forward if glfw.get_key( window, glfw.KEY_UP ) == glfw.PRESS or glfw.get_key( window, glfw.KEY_W ) == glfw.PRESS: position += direction * deltaTime * speed; # Move backward if glfw.get_key( window, glfw.KEY_DOWN ) == glfw.PRESS or glfw.get_key( window, glfw.KEY_S ) == glfw.PRESS: position -= direction * deltaTime * speed # Strafe right if glfw.get_key( window, glfw.KEY_RIGHT ) == glfw.PRESS or glfw.get_key( window, glfw.KEY_D ) == glfw.PRESS: position += right * deltaTime * speed # Strafe left if glfw.get_key( window, glfw.KEY_LEFT ) == glfw.PRESS or glfw.get_key( window, glfw.KEY_A ) == glfw.PRESS: position -= right * deltaTime * speed FoV = initialFoV# - 5 * glfwGetMouseWheel(); # Now GLFW 3 requires setting up a callback for this. It's a bit too complicated for this beginner's tutorial, so it's disabled instead. # Projection matrix : 45 Field of View, 4:3 ratio, display range : 0.1 unit <-> 100 units ProjectionMatrix = mat4.perspective(FoV, 4.0 / 3.0, 0.1, 100.0) # Camera matrix ViewMatrix = mat4.lookat( position, # Camera is here position+direction, # and looks here : at the same position, plus "direction" up # Head is up (set to 0,-1,0 to look upside-down) ) # For the next frame, the "last time" will be "now" lastTime = currentTime
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()
def main(): 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); glEnable(GL_CULL_FACE) vertex_array_id = glGenVertexArrays(1) glBindVertexArray( vertex_array_id ) program_id = common.LoadShaders( ".\\shaders\\Tutorial6\\TransformVertexShader.vertexshader", ".\\shaders\\Tutorial6\\TextureFragmentShader.fragmentshader" ) # Get a handle for our "MVP" uniform matrix_id = glGetUniformLocation(program_id, "MVP"); texture = load_image(".\\content\\uvtemplate.bmp") texture_id = glGetUniformLocation(program_id, "myTextureSampler") # Our vertices. Tree consecutive floats give a 3D vertex; Three consecutive vertices give a triangle. # A cube has 6 faces with 2 triangles each, so this makes 6*2=12 triangles, and 12*3 vertices vertex_data = [ -1.0,-1.0,-1.0, -1.0,-1.0, 1.0, -1.0, 1.0, 1.0, 1.0, 1.0,-1.0, -1.0,-1.0,-1.0, -1.0, 1.0,-1.0, 1.0,-1.0, 1.0, -1.0,-1.0,-1.0, 1.0,-1.0,-1.0, 1.0, 1.0,-1.0, 1.0,-1.0,-1.0, -1.0,-1.0,-1.0, -1.0,-1.0,-1.0, -1.0, 1.0, 1.0, -1.0, 1.0,-1.0, 1.0,-1.0, 1.0, -1.0,-1.0, 1.0, -1.0,-1.0,-1.0, -1.0, 1.0, 1.0, -1.0,-1.0, 1.0, 1.0,-1.0, 1.0, 1.0, 1.0, 1.0, 1.0,-1.0,-1.0, 1.0, 1.0,-1.0, 1.0,-1.0,-1.0, 1.0, 1.0, 1.0, 1.0,-1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0,-1.0, -1.0, 1.0,-1.0, 1.0, 1.0, 1.0, -1.0, 1.0,-1.0, -1.0, 1.0, 1.0, 1.0, 1.0, 1.0, -1.0, 1.0, 1.0, 1.0,-1.0, 1.0] # 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] 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) # vsync and glfw do not play nice. when vsync is enabled mouse movement is jittery. common.disable_vsyc() 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) 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) # 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*) ) # Draw the triangle ! glDrawArrays(GL_TRIANGLES, 0, 12*3) #3 indices starting at 0 -> 1 triangle # Not strictly necessary because we only have glDisableVertexAttribArray(0) glDisableVertexAttribArray(1) # Swap front and back buffers glfw.swap_buffers(window) # Poll for and process events glfw.poll_events() # !Note braces around vertex_buffer and uv_buffer. # glDeleteBuffers expects a list of buffers to delete glDeleteBuffers(1, [vertex_buffer]) glDeleteBuffers(1, [uv_buffer]) glDeleteProgram(program_id) glDeleteTextures([texture_id]) glDeleteVertexArrays(1, [vertex_array_id]) glfw.terminate()