2017-01-02 1906 views
1

在这里,我有两个循环。第一个循环处理图形几秒钟,然后代码进入第二个循环。我在第一个循环中通过glutMainLoopEvent处理图形事件。在第二个循环开始之前,我想关闭图形窗口。看起来命令glutLeaveMainLoop无法关闭窗口。在第一次循环之后,我应该用什么其他函数强制关闭窗口?如何关闭一个openGL窗口

#include <stdio.h> 
#include <GL/freeglut.h> 
#include <boost/thread/thread.hpp> // for sleep 

void cback_render() 
{ 
    if(!glutGetWindow()) 
     return ; 
    static float rotations = 0; 

    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); 

    glLoadIdentity(); 
    glRotatef(rotations, 0, 0, 1); 

    glBegin(GL_TRIANGLES); 
     glVertex3f(0,0,0); 
     glVertex3f(1,0,0); 
     glVertex3f(0,1,0); 
    glEnd(); 

    glutSwapBuffers(); 

    if (++rotations > 360) rotations -= 360; 
} 

void timer(int) 
{ 
    if(!glutGetWindow()) 
     return ; 
    glutPostRedisplay(); 
    glutMainLoopEvent(); 
    glutTimerFunc(30, timer, 1); 
} 

int main(int argc, char **argv) 
{ 
    glutInit(&argc, argv); 
    glutInitDisplayMode(GLUT_DOUBLE | GLUT_DEPTH); 
    glutInitWindowPosition(100, 100); 
    glutInitWindowSize(512, 512); 
    glutSetOption(GLUT_ACTION_ON_WINDOW_CLOSE, GLUT_ACTION_GLUTMAINLOOP_RETURNS); 

    glutCreateWindow("freegluttest"); 
    glutDisplayFunc (cback_render); 
    glutTimerFunc(30, timer, 1); 

    long i=0; 
    while(glutGetWindow() && i< 30) 
    { 
     printf("[%ld]\n",i); 
     i++; 
     glutMainLoopEvent(); 
     boost::this_thread::sleep(boost::posix_time::milliseconds(100)); 
    } 
    glutMainLoopEvent(); 

    glutLeaveMainLoop(); // does not work 
    glutMainLoopEvent(); 

    // do something else .... 
    while(1) 
    { 
     // other calculations 
     boost::this_thread::sleep(boost::posix_time::milliseconds(100)); 
    } 

    return 0; 
} 
+0

这是过剩还是freeglut?我对glut标签感到困惑。 – CroCo

+0

@CroCo,谢谢你的提及。 – ar2015

+0

我对freeglut不熟悉,但是你确定在终止“glutLeaveMainLoop()”之后可以调用这个“glutMainLoopEvent()”吗?另外,您是否尝试通过单击x标记按钮来终止窗口? – CroCo

回答

0

从freeglut文档确定在http://freeglut.sourceforge.net/docs/api.php#EventProcessing

功能使用的是glutLeaveMainLoop()是简单地阻止过剩的主循环,如果它是由glutMainLoop()glutMainLoopEvent()启动。

既然你在你的例子中自己控制循环,glutLeaveMainLoop()将不会做任何事情。

它的目的是为了留下过剩的主循环如果过剩,你不是在控制它。

由于你有一个while(1)在100ms睡眠结束时,应用程序将不会做任何事情,当它到达那里后,所有的框架已被渲染。如果你想破坏窗口使用一些窗口功能,如glutDestroyWindow()

+0

我认为'glutDestroyWindow()'用于添加回调。我不认为它会破坏窗户。第二个循环代表我的程序将执行另一个计算。我无法删除第二个循环。我严格需要关闭窗口而不终止程序。 – ar2015

+0

你确定你使用的是哪种版本的GLUT?检查这个链接它说,函数'glutDestroyWindow()'完全符合我的想法。 https://www.opengl.org/resources/libraries/glut/spec3/node19.html – Harish

+0

对不起,我犯了一个错误。代码使用: 'if(glutGetWindow()) \t \t \t glutDestroyWindow(glutGetWindow()); \t glutMainLoopEvent(); \t glutMainLoopEvent();' – ar2015