c++ - 将 OpenGL 中的特定相机 View 保存为图像

标签 c++ opengl

我有一个带有对象的 3D 场景,我想保存该对象的 View ,该 View 与我当前查看的屏幕不同。 所以我想我只需要做这样的事情(伪代码):

PushMatrix()
LoadIdentity()
TranslateAndRotate()
gluperspective()
setViewport()
DrawScene()
saveScreenshot()
PopMatrix()

但我只得到一张我相机当前 View 的照片,而不是我指定的那个。 我是不是忘记了什么?

编辑: 由于下面的答案,我尝试了以下代码:

void ScenePhotograph(GLubyte* Target, float *Translation, float RotationAroundY)
{
    glMatrixMode(GL_PROJECTION);
    gluPerspective(54.0f, (GLfloat)openGLControl1->Width / (GLfloat)openGLControl1->Height, 1.0f, 3000.0f);
    glViewport(0,0,openGLControl1->Width, openGLControl1->Height);
    glMatrixMode(GL_MODELVIEW);
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
    glLoadIdentity();   
    glTranslatef(Translation[0],Translation[1],Translation[2]);
    glRotatef(RotationAroundY, 0,1,0);
    openGLControl1_OnDrawGL(NULL,System::EventArgs::Empty);
    openGLControl1->Refresh();
    glReadPixels(0, 0, openGLControl1->Width, openGLControl1->Height, GL_RGB, GL_UNSIGNED_BYTE, Target);

    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
    glLoadIdentity();   
    cam->SetView();
    openGLControl1_OnDrawGL(NULL,System::EventArgs::Empty);
    openGLControl1->Refresh();
    glutSwapBuffers();
}

这让我在 glutSwapBuffers() 发生了访问冲突; 有什么想法吗?

最佳答案

首先,确保您没有在代码中混合使用不同的矩阵。要获取屏幕截图,您需要像平时在屏幕上查看它一样准确定位相机,但是,在交换缓冲区之前,您需要从当前帧缓冲区读取像素并将其存储为图像。

所以,你需要的是这样的东西:

glMatrixMode(GL_PROJECTION);
gluPerspective();
glMatrixMode(GL_MODELVIEW);
glClear(); // clear buffers here
loadIdendity();
setCameraPosition();
TranslateRotate();
DrawScene();
screenShot();

// do again to set your camera to correct position
glClear(); // clear buffers here
loadIdendity();
setCameraPosition();
TranslateRotate();
DrawScene();
swapBuffers();

如您所见,screenShot 负责从当前帧缓冲区读取像素并将其保存为图像。因此,再次执行所有操作以将相机定位到正确的位置

关于c++ - 将 OpenGL 中的特定相机 View 保存为图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16463044/

相关文章:

macos - Cocoa 的 OpenGL 上下文 (OS X)

opengl - 在 OpenGL 中使用 RGB 纹理作为 alpha 值/子像素字体渲染

c++ - 为什么VC++编译器使用boost\range\iterator.hpp

c++ - 在 C++ 中处理抽象数据类型时使用 * 运算符

opengl - 为什么无法在多个视口(viewport)中显示同一对象?

c - 图形驱动程序 "hello world"示例?

windows - 为什么 OpenGL 和 CUDA 上下文内存贪婪?

c++ - 用于图像处理的重载 [ ] [ ] 运算符

c++ - 找出类型

c++ - 为什么 gzwrite vector 与 gzwrite 数组不同,数组值相同?