有效的OpenGL上下文
时间:2020-03-05 18:40:18 来源:igfitidea点击:
在我的代码中如何以及在什么阶段创建有效的OpenGL上下文?即使是简单的OpenGL代码,我也遇到错误。
解决方案
回答
从" comp.graphics.api.opengl"上的帖子看来,大多数新手在第一个OpenGL程序上都投入了大量精力。在大多数情况下,该错误是由于甚至在创建有效的OpenGL上下文之前调用OpenGL函数引起的。 OpenGL是一种状态机。只有在机器启动并嗡嗡作响的就绪状态下,机器才能投入使用。
以下是一些简单的代码,用于创建有效的OpenGL上下文:
#include <stdlib.h> #include <GL/glut.h> // Window attributes static const unsigned int WIN_POS_X = 30; static const unsigned int WIN_POS_Y = WIN_POS_X; static const unsigned int WIN_WIDTH = 512; static const unsigned int WIN_HEIGHT = WIN_WIDTH; void glInit(int, char **); int main(int argc, char * argv[]) { // Initialize OpenGL glInit(argc, argv); // A valid OpenGL context has been created. // You can call OpenGL functions from here on. glutMainLoop(); return 0; } void glInit(int argc, char ** argv) { // Initialize GLUT glutInit(&argc, argv); glutInitDisplayMode(GLUT_DOUBLE); glutInitWindowPosition(WIN_POS_X, WIN_POS_Y); glutInitWindowSize(WIN_WIDTH, WIN_HEIGHT); glutCreateWindow("Hello OpenGL!"); return; }
笔记:
- 这里感兴趣的调用是" glutCreateWindow()"。它不仅创建了一个窗口,而且还创建了一个OpenGL上下文。
- 用glutCreateWindow()创建的窗口在调用glutMainLoop()之前是不可见的。