码迷,mamicode.com
首页 > 编程语言 > 详细

python下学习opengl之简单窗口

时间:2018-04-16 12:06:41      阅读:1339      评论:0      收藏:0      [点我收藏+]

标签:教程   name   imp   get   org   core   命令行   安装   inpu   

最近在看一个opengl教程:https://learnopengl.com/Introduction,写的深入浅出,非常不错,而且有中文的翻译版:https://learnopengl-cn.github.io/

出于加深学习效果,自己试着用Python重新实现原教程中的C++代码

1. 操作系统:Windows 10

2. 安装Python: https://www.python.org/downloads/, 我用的是3.6.3

3. 安装pyOpenGl: 安装完python后默认会同时安装pip, 将pip加入默认路径,在windows命令行窗口输入 pip install PyOpenGL

4. 下载GLFW:在http://www.glfw.org/download.html 下载 32-bit Windows binaries,下到的压缩文件解压后,得到库文件lib-vc2015/glfw3.dll

5. 下载GLFW的python 接口文件:在https://github.com/rougier/pyglfw 下载glfw.py,并将其和上一步得到的库文件放到python默认的库目录或当前开发代码的同级目录中

6. 创建window.py文件,代码如下:

#! /usr/bin/env python
# -*- coding: utf-8 -*-

import sys, os
import OpenGL.GL as gl
import glfw

WIN_WIDTH = 800
WIN_HEIGHT = 600

def framebuffer_size_callback(window, width, height):
    gl.glViewport(0, 0, width, height)

def processInput(window):
    if glfw.glfwGetKey(window, glfw.GLFW_KEY_ESCAPE) == glfw.GLFW_PRESS:
        glfw.glfwSetWindowShouldClose()

def main():
    glfw.glfwInit()
    glfw.glfwWindowHint(glfw.GLFW_CONTEXT_VERSION_MAJOR, 3)
    glfw.glfwWindowHint(glfw.GLFW_CONTEXT_VERSION_MINOR, 3)
    glfw.glfwWindowHint(glfw.GLFW_OPENGL_PROFILE, glfw.GLFW_OPENGL_CORE_PROFILE)

    window = glfw.glfwCreateWindow(WIN_WIDTH, WIN_HEIGHT, "学习OpenGL".encode(), 0, 0)
    if window == 0:
        print("failed to create window")
        glfw.glfwTerminate()

    glfw.glfwMakeContextCurrent(window)
    glfw.glfwSetFramebufferSizeCallback(window, framebuffer_size_callback)

    while not glfw.glfwWindowShouldClose(window):
        processInput(window)
        gl.glClearColor(0.2, 0.3, 0.3, 1.0)
        gl.glClear(gl.GL_COLOR_BUFFER_BIT)
        glfw.glfwSwapBuffers(window)
        glfw.glfwPollEvents()

glfw.glfwTerminate()

if __name__ == "__main__":
    main()

该段代码执行后得到的效果如下:

技术分享图片

以上代码是对opengl教程中hello window章节的python实现,原来的C++代码见 https://learnopengl.com/Getting-started/Hello-Window

python下学习opengl之简单窗口

标签:教程   name   imp   get   org   core   命令行   安装   inpu   

原文地址:https://www.cnblogs.com/wndf6122/p/8855045.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!