调整视口大小,裁剪场景

时间:2011-05-05 08:39:53

标签: opengl viewport transformation crop

我有一个由OpenGL绘制到可调整大小窗口的3D场景。现在,当窗口调整大小时,我不想缩放视口,而是希望将场景保持为固定大小并显示其中较大部分(或裁剪场景图像)。这是我目前的代码:

GLfloat ratio;

// Protect against a divide by zero
if ( height == 0 )
    height = 1;

ratio = ( GLfloat )width / ( GLfloat )height;
// Setup our viewport.
glViewport( 0, 0, ( GLint )width, ( GLint )height );

// change to the projection matrix and set our viewing volume.
glMatrixMode( GL_PROJECTION );
glLoadIdentity( );

gluPerspective( 60.0f, ratio, 0.1f, 1000.0f );
// Switch back to the modelview
glMatrixMode( GL_MODELVIEW );

如果我保持比例固定,那么场景图像只是缩放,但我想保持固定的大小,只是显示更宽的视图。关于这个的任何想法?

2 个答案:

答案 0 :(得分:3)

调整fov参数。从技术上讲,如果使用 glFrustum 而不是 gluPerspective 完成,您想要做的更容易。

// Protect against a divide by zero
if ( height == 0 )
    height = 1;

// Setup our viewport.
glViewport( 0, 0, ( GLint )width, ( GLint )height );

// change to the projection matrix and set our viewing volume.
glMatrixMode( GL_PROJECTION );
glLoadIdentity( );

// supply some sensefull value for this; ideally let the user adjust it somehow
exterm float Zoom;

// near far should tightly wrap the actually visible set of objects. Hardcoded values
// like 0.1 ... 1000.f are problematic. Also your choosen value range slices your viewport
// into 10000 depth slices. Say you get only a 16 bit depth buffer already in the lineary
// slicing ortho projection a OpenGL length units in depth would recieve only about 6 
// slices. In perspective mode the slice density follows a 1/depth law. So already at depth
// 10 you'll run into depth resolution problems.
glFrustum(-Zoom * width, Zoom * width, -Zoom * height, Zoom * height, near, far);

// Switch back to the modelview
glMatrixMode( GL_MODELVIEW );

请注意此代码属于显示功能。任何在窗口重塑处理程序中设置视口和投影的教程都是非常糟糕的样式;不要跟着它。

答案 1 :(得分:0)

理想情况下,由于您已将视口设置为0,0,宽度,高度,因此图像应保持相同的大小。你能检查一下你为图像发送的坐标吗?这是保持不变还是随宽度/高度一起缩放?你能发布添加顶点的代码吗?