Как GluDisplayFunc, glutMainLoop в glfw?

У меня есть небольшая программа, использующая переполнение, и по многим причинам мне нужно использовать glfw сейчас. Поскольку я никогда не использовал glfw, у меня много проблем. Основными из них являются функции: glutDisplayFunc, glutReshapeFunc, glutIdleFunc и glutMainLoop. Я только что узнал, что в glfw нет эквивалентных функций. Как мне изменить мою программу?

Моя программа о конусе, вращающемся в трех измерениях.

У меня есть функция displaycone:

void displayCone(void){

    // clear the drawing buffer.
    glClear(GL_COLOR_BUFFER_BIT);  //

    // set matrix mode
    glMatrixMode(GL_MODELVIEW);
    // clear model view matrix
    glLoadIdentity();
    // multiply view matrix to current matrix
    gluLookAt(3.0, 3.0, 3.0-4.5, 0.0, 0.0,-4.5,0,1,0);

    // ******
    glPushMatrix();


    glTranslatef(0.0, 0.0, -4.5);

    glBegin(GL_LINES);

    glColor3f (1.0, 1.0, 0.0);
    glVertex3f(0.0, 0.0, 0.0);
    glVertex3f(2.0, 0.0, 0.0);

    glColor3f (1.0, 1.0, 0.0);
    glVertex3f(0.0, 0.0, 0.0);
    glVertex3f(0.0, 2.0, 0.0);

    glColor3f (1.0, 1.0, 0.0);
    glVertex3f(0.0, 0.0, 0.0);
    glVertex3f(0.0, 0.0, 2.0);
    glEnd();

    glPopMatrix();

    // clear the drawing buffer.


    // traslate the draw by z = -4.0
    // Note this when you decrease z like -8.0 the drawing will looks far , or smaller.
    glTranslatef(0.0,0.0,-4.5);
    // Red color used to draw.
    glColor3f(0.8, 0.2, 0.1);
    // changing in transformation matrix.
    // rotation about X axis
    glRotatef(xRotated,1.0,0.0,0.0);
    // rotation about Y axis
    glRotatef(yRotated,0.0,1.0,0.0);
    // rotation about Z axis
    glRotatef(zRotated,0.0,0.0,1.0);

    // scaling transfomation
    glScalef(1.0,1.0,1.0);
    // built-in (glut library) function , draw you a Cone.

    // move the peak of the cone to the origin
    glTranslatef(0.0, 0.0, -height);

    glutSolidCone(base,height,slices,stacks);
    // Flush buffers to screen
    // gluLookAt(3,3,3,0,0,-4.5,0,1,0); <----------------------- delete

    glFlush();
    // sawp buffers called because we are using double buffering
    // glutSwapBuffers();

}

функция reshapecone:

void reshapeCone(int x, int y)
{
    if (y == 0 || x == 0) return;  //Nothing is visible then, so return
    //Set a new projection matrix
    glMatrixMode(GL_PROJECTION);
    glLoadIdentity();
    //Angle of view:40 degrees
    //Near clipping plane distance: 0.5
    //Far clipping plane distance: 20.0

    gluPerspective(35.0,(GLdouble)x/(GLdouble)y,0.5,20.0);

    glViewport(0,0,x,y);  //Use the whole window for rendering
}

и функция idleCone:

void idleCone(void)
{
    for(int j = 1; j<10000 ; j++){
        double i = dati[j+1][0];

        int win = glfwGetWindow();

        if(i == 0.)      break; 

        xRotated = 180/M_PI*(dati[j][0]);
        yRotated = 180/M_PI*(dati[j][1]);
        zRotated = 180/M_PI*(dati[j][2]);

        displayCone();
        xRotated += 0.;
        yRotated += 0.;
        zRotated += 0.;
        displayCone();

    }
}

В моей предыдущей программе я имел в main:

glfwInit(&argc, argv);
//double buffering used to avoid flickering problem in animation
glutInitDisplayMode(GLUT_SINGLE | GL_RGB);
//glfwInitWindowSize(800,700);

glfwCreateWindow(800,700,"Rotation of the top",NULL,NULL);
glPolygonMode(GL_FRONT_AND_BACK,GL_LINE);
xRotated = yRotated = zRotated = 0.0;
xRotated=0.0;
yRotated=0.0;
glClearColor(0.0,0.0,0.0,0.0);

glutDisplayFunc(displayCone);
glutReshapeFunc(reshapeCone);
glutIdleFunc(idleCone);

glutMainLoop();  

person Jatos    schedule 03.08.2019    source источник


Ответы (1)


При использовании glfw необходимо создать собственный цикл приложения. Обратите внимание: перед вызовом любой инструкции OpenGL важно сделать контекст OpenGL текущим с помощью glfwMakeContextCurrent. например.:

GLFWwindow *wnd = glfwCreateWindow(800,700,"Rotation of the top",NULL,NULL);
glfwMakeContextCurrent(wnd);

// do the OpenGL initialization
// [...]

while (!glfwWindowShouldClose(wnd))
{
    // do the drawing
    displayCone();

    glfwSwapBuffers(wnd);
    glfwPollEvents();
}

Вместо glutReshapeFunc вы можете установить обратный вызов размера с помощью glfwSetWindowSizeCallback: например:

glfwSetWindowSizeCallback(wnd, reshapeCone);
void reshapeCone(GLFWwindow* window, int x, int y)
{
    // [...]
}  
person Rabbid76    schedule 03.08.2019
comment
когда я компилирую, я получаю: примечание: пересекает инициализацию «GLFWwindow * wnd» - person Jatos; 03.08.2019
comment
@Jatos Извините, но я не вижу вашего фактического кода и не знаю, в какой строке возникает ошибка. I строка GLFWwindow *wnd = glfwCreateWindow(...) в выражении switch? - person Rabbid76; 03.08.2019
comment
Теперь я решил это, поместив GLFWwindow из оператора switch. Когда я компилирую код на терминале Mac, он говорит: «Неопределенные символы для архитектуры x86_64: _glfwCreateWindow, на которые ссылается: _main в ccR3zGkL.o». - person Jatos; 03.08.2019
comment
@Jatos Возможно OpenGL 3.3/ 4.1 на Mac OSX 10.9 с использованием библиотеки GLFW может помочь - person Rabbid76; 03.08.2019