OpenGL在收到输入时重新绘制场景

OpenGL redraw scene when receive an input

本文关键字:绘制 新绘制 输入 OpenGL      更新时间:2023-10-16

我在visual C++应用程序中实现了一个线程,该线程在OpenGL窗口中绘制了一系列与立方体向量相关的立方体,这些立方体具有中心、侧面和级别。它是这个类对象的向量,就像一棵树,有不同的层次和分层。在主要的阐述过程中,这个对象中的多维数据集发生了变化:添加、删除。。。在阐述的每一步。。。

只有在完成每一步后,我才需要重新绘制(刷新)OpenGL窗口的内容,以获得多维数据集列表的动态表示。

我的意思是:

  • 第一步完成后,我将数组传递给OpenGL线程,即绘制
  • 第二步运行,OpenGL窗口的内容位于第一个立方体中
  • 第二步完成后,OpenGL的内容用新的立方体进行了更新
  • 等等

OpenGL线程它处于后台模式线程。。。我只需要看到立方体的演变,只有当我做详细说明时。。。现在,问题是,对于glutMainLoop()语句,情况是连续的。。。它太重或崩溃了,即使是一个带有Nvidia Quadro 4000的系统…OpenGL窗口显示了,但被阻塞,无法移动,有时是灰色的,或者什么都不显示。

以下是我的一段代码(所有与OpenGL相关的代码):

#include <iostream>
#include <opencvcv.h>
#include <opencvhighgui.h>
#include <opencv2highguihighgui.hpp>
#include <windows.h>
#include <process.h>
#include <queue>
#include <array>
#include <vector>
#include <GL/glut.h>
#include <GL/freeglut.h>
using namespace std;
using namespace cv;

 //Premessa delle funzioni di posizionamento con mouse 
  void mouseCB(int button, int stat, int x, int y);
  void mouseMotionCB(int x, int y);
  //funzioni di inizializzazione e pulizia
  bool initSharedMem();
 void clearSharedMem();
 void initLights();
 void setCamera(float posX, float posY, float posZ, float targetX, float targetY, float    targetZ);
  void toOrtho();
 void toPerspective();
 //variabili e costanti
 const int   SCREEN_WIDTH    = 640;
 const int   SCREEN_HEIGHT   = 480;
const float CAMERA_DISTANCE = 10.0f;
int screenWidth;
int screenHeight;
bool mouseLeftDown;
 bool mouseRightDown;
 bool mouseMiddleDown;
 float mouseX, mouseY;
float cameraAngleX;
 float cameraAngleY;
float cameraDistance;
int drawMode;
 ///////////////////////////////////////////////////////////////////////////////
 // Funzione inizializzazione OpenGL standard
 ///////////////////////////////////////////////////////////////////////////////
void init()
{
glShadeModel(GL_SMOOTH);
glPixelStorei(GL_UNPACK_ALIGNMENT, 4);
glHint(GL_PERSPECTIVE_CORRECTION_HINT,GL_NICEST);
glEnable(GL_DEPTH_TEST);
glEnable(GL_LIGHTING); 
glEnable(GL_TEXTURE_2D);
glEnable(GL_CULL_FACE);
glEnable(GL_COLOR_MATERIAL);
initLights();
 }
 ///////////////////////////////////////////////////////////////////////////////
 // Funzione di inizializzazione globale delle variabili
 ///////////////////////////////////////////////////////////////////////////////
bool initSharedMem()
{
screenWidth = SCREEN_WIDTH;
screenHeight = SCREEN_HEIGHT;
mouseLeftDown = mouseRightDown = mouseMiddleDown = false;
mouseX = mouseY = 0;
cameraAngleX = cameraAngleY = 0.0f;
//cameraDistance = CAMERA_DISTANCE;
cameraDistance = 0.3f;
drawMode = 0; // 0:pieno, 1: solo contorni, 2:punti
return true;
}
 ///////////////////////////////////////////////////////////////////////////////
 // Funzione di pulitura variabili globali
 ///////////////////////////////////////////////////////////////////////////////
void clearSharedMem()
{
 }
 ///////////////////////////////////////////////////////////////////////////////
 // Inizializzazione Luci
 ///////////////////////////////////////////////////////////////////////////////
void initLights()
{
GLfloat lightKa[] = {.2f, .2f, .2f, 1.0f};  // luce ambientale
GLfloat lightKd[] = {.7f, .7f, .7f, 1.0f};  // luce diffusa
GLfloat lightKs[] = {1, 1, 1, 1};           // luce speculare
glLightfv(GL_LIGHT0, GL_AMBIENT, lightKa);
glLightfv(GL_LIGHT0, GL_DIFFUSE, lightKd);
glLightfv(GL_LIGHT0, GL_SPECULAR, lightKs);
// posizione delle luci
float lightPos[4] = {0, 0, 20, 1}; 
glLightfv(GL_LIGHT0, GL_POSITION, lightPos);
//Attiva tutti i settaggi delle luci
glEnable(GL_LIGHT0);                        }
 ///////////////////////////////////////////////////////////////////////////////
 //  Posizione della telecamera e direzioni
 ///////////////////////////////////////////////////////////////////////////////
 void setCamera(float posX, float posY, float posZ, float targetX, float targetY, float   targetZ)
{
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
gluLookAt(posX, posY, posZ, targetX, targetY, targetZ, 0, 1, 0); // eye(x,y,z),  focal(x,y,z), up(x,y,z)
 }
///////////////////////////////////////////////////////////////////////////////
// Impostazione proiezione ortogonale
///////////////////////////////////////////////////////////////////////////////
 void toOrtho()
{
// Imposta il viewport di tutta la finestra
glViewport(0, 0, (GLsizei)screenWidth, (GLsizei)screenHeight);
// Imposta il frustum di visione
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glOrtho(0, screenWidth, 0, screenHeight, -1, 1);
// passaggio a modelview per interattività
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
}

 ///////////////////////////////////////////////////////////////////////////////
 // Impostazione come perspective
///////////////////////////////////////////////////////////////////////////////
void toPerspective()
{ 
// Imposta il viewport di tutta la finestra
glViewport(0, 0, (GLsizei)screenWidth, (GLsizei)screenHeight);
//frustum perspective
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
//gluPerspective(60.0f, (float)(screenWidth)/screenHeight, 1.0f, 1000.0f);
gluPerspective(60.0f, (float)(screenWidth)/screenHeight, 10.0f, 0.0f); // FOV,   AspectRatio, NearClip, FarClip
// switch to modelview matrix in order to set scene
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
}
   ///////////////////////////////////////////////////////////////////////////////
  //  Funzione ricorsiva di disegno
  ///////////////////////////////////////////////////////////////////////////////
  void addraw(cubo temp)
 {
//se non ci sono sottocubi
   if (temp.lista_sottocubi.size() == 0)
   {        
        if (temp.livello == LMAXI) {
             double centro[3]={(temp.V[6].x)/2, (temp.V[6].y)/2,         (temp.V[6].z)/2};
             glPushMatrix();
             glTranslatef(centro[0],centro[1],centro[2]);
             glColor3ub(0,0,255);
             glutSolidCube(temp.lato);
             glPopMatrix();
        }
}
//se i sottocubi ci sono
else {
    for (int i=0;i<(int)temp.lista_sottocubi.size();i++){
            addraw(temp.lista_sottocubi[i]);
        }
 }
}
 ///////////////////////////////////////////////////////////////////////////////
 // Funzione disegno principale
 ///////////////////////////////////////////////////////////////////////////////
 void draw()
{
// clear buffer
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT);
glPushMatrix();
//spostamento del disegno
glTranslatef(0, 0, -cameraDistance);
glRotatef(cameraAngleX, 1, 0, 0);   // pitch
glRotatef(cameraAngleY, 0, 1, 0);   // heading
//lancio funzione di disegno vera e propria
addraw(prova);
//reset
glPopMatrix();
glutSwapBuffers();
 }
 //////////////////////////////////////////////////////////////////////////////
 //  Funzione di reshape
 ///////////////////////////////////////////////////////////////////////////////
void reshape(int w, int h)
{
 screenWidth = w;
  screenHeight = h;
 toPerspective();
 }
   ///////////////////////////////////////////////////////////////////////////////
    //  Funzione di refresh temporizzato della finestra
    ///////////////////////////////////////////////////////////////////////////////
    void timerCB(int millisec){
glutTimerFunc(millisec, timerCB, millisec);
glutPostRedisplay();
  }
 ///////////////////////////////////////////////////////////////////////////////
// Funzione rilevamento movimenti del mouse
///////////////////////////////////////////////////////////////////////////////
void Motion(int x,int y)
{
if(mouseLeftDown)
{
    cameraAngleY += (x - mouseX);
    cameraAngleX += (y - mouseY);
    mouseX = x;
    mouseY = y;
}
if(mouseRightDown)
{
    cameraDistance -= (y - mouseY) * 0.2f;
    mouseY = y;
    }
 }
  ///////////////////////////////////////////////////////////////////////////////
 // Funzione per rilevamento bottoni mouse
 ///////////////////////////////////////////////////////////////////////////////
void Mouse(int button, int state, int x, int y)
{
mouseX = x;
mouseY = y;
if(button == GLUT_LEFT_BUTTON)
{
    if(state == GLUT_DOWN)
    {
        mouseLeftDown = true;
    }
    else if(state == GLUT_UP)
        mouseLeftDown = false;
}
 else if(button == GLUT_RIGHT_BUTTON)
 {
    if(state == GLUT_DOWN)
    {
        mouseRightDown = true;
    }
    else if(state == GLUT_UP)
        mouseRightDown = false;
 }
 else if(button == GLUT_MIDDLE_BUTTON)
 {
    if(state == GLUT_DOWN)
    {
        mouseMiddleDown = true;
    }
    else if(state == GLUT_UP)
        mouseMiddleDown = false;
   }
  }
   ///////////////////////////////////////////////////////////////////////////////
  // Inizializzazione di GLUT
  ///////////////////////////////////////////////////////////////////////////////
  void initGLUT(){
 //parametri fake per il lancio di InitGlut
char *myargv[1];
int myargc = 1;
myargv[0]=strdup("MyOpenGL");
//Inizializzazione Glut basso livello
glutInit(&myargc,myargv);
//Lancio funzioni di settaggio finestra,visualizzazione ed altro
glutInitDisplayMode( GLUT_RGBA| GLUT_DOUBLE | GLUT_DEPTH |GLUT_STENCIL);    
glutInitWindowSize(screenWidth, screenHeight);
glutInitWindowPosition(850,100);
glutCreateWindow("Ricostruzione attuale");
    //callback delle funzioni richiamate
    glutDisplayFunc(draw);
    glutTimerFunc(33,timerCB,33);
    glutReshapeFunc(reshape);
    glutMouseFunc(Mouse);
    glutMotionFunc(Motion);
}
  ///////////////////////////////////////////////////////////////////////////////
 //  Thread richiamato per lanciare OPENGL
 ///////////////////////////////////////////////////////////////////////////////
void DRAW3D (void *param){
//abbassa priorità del thread a backgroud
if(!SetThreadPriority(GetCurrentThread(), THREAD_MODE_BACKGROUND_BEGIN))
    {
        dwError = GetLastError();
        if (ERROR_THREAD_MODE_ALREADY_BACKGROUND == dwError)
        _tprintf(TEXT("Gia' in backgroundn"));
        else _tprintf(TEXT("Errore nell'entrare in modalita' background (%d)n"), dwError);
    }
    // Lancia funzione di inizializzazione variabili globali
    initSharedMem();
    //initiGLUT
    initGLUT();
    init();
    //ciclo OpenGL
    glutMainLoop();
    _endthread();

}

其中prova是从一个类实例化的立方体对象的向量容器,该类通过6个顶点和边(lato)和级别的大小定义立方体。

用一个简单的一级"读取和绘制"函数删除递归函数"addraw"(没有递归性)解决了问题(窗口显示正确的1°级别立方体,可旋转,可缩放…没有崩溃或窗口阻塞),但我需要在每个分支中绘制所有最大级别的立方体。。。所以我需要向量的递归扫描。。。

所以,我不知道该怎么做。。。有人能帮我吗?

1) 如何仅在需要时刷新OpenGL绘图?2) 如何使用OpenGL线程绘制包含在多级矢量中的一系列立方体?

我使用的是Windows 7 64位、freeglut 2.8.1 下的Visual C++2010

最简单的方法是创建一个显示回调,并使用类似glutPostRedisplay (...)的方法向线程的主循环发出信号,以调用显示回调。在GLUT中,该函数基本上递增一个计数器,该计数器在主循环的每次迭代结束时重置,如果窗口的值>0,则告诉GLUT窗口脏了(需要重新绘制)。

信号量在这里会被高估,当你需要防止同时访问资源时,它们很有用。这根本不是你需要的。解决这个问题最复杂的方法是让绘制线程处于休眠状态,直到它收到重新绘制的信号。对于非交互式渲染来说,这是一种可以接受的方法,但对于交互式渲染,检查上述"脏"标志的简单忙等待循环将完成任务(事实上,我相信GLUT主循环的一些实现就是这样工作的)。

我建议在这里避免GLUT的原因是,一些实现(例如OSX附带的版本)在次线程中运行其主循环时存在已知问题。

您是否尝试在代码中使用信号量?以下是有关它的更多信息。