我正在尝试在网上阅读一些OpenGL教程.问题是我找到了一些旧的gluPerspective()
.gluPerspective在OpenGL 3.0中已弃用,在3.1中已删除.
我可以用什么功能代替?
我正在使用安装了最新FreeGlut的C++.
您必须手动计算矩阵,然后将其传递给OpenGL.
这段代码基于gluPerspective文档.
void BuildPerspProjMat(float *m, float fov, float aspect, float znear, float zfar) { float f = 1/tan(fov * PI_OVER_360); m[0] = f/aspect; m[1] = 0; m[2] = 0; m[3] = 0; m[4] = 0; m[5] = f; m[6] = 0; m[7] = 0; m[8] = 0; m[9] = 0; m[10] = (zfar + znear) / (znear - zfar); m[11] = -1; m[12] = 0; m[13] = 0; m[14] = 2*zfar*znear / (znear - zfar); m[15] = 0; }
有一个名为OpenGL Mathematics的C++库可能很有用.
我还是OpenGL 3.1 API的新手,但你需要更新GPU上的矩阵,然后在你的顶点着色器中使用它来获得正确的视角.以下代码只使用glUniform4fv将矩阵加载到视频卡上.
{ glUseProgram(shaderId); glUniformMatrix4fv(glGetUniformLocation(shaderId, "u_proj_matrix"), 1, GL_FALSE, theProjectionMatrix); RenderObject(); glUseProgram(0); }
来自随机博客的简单顶点着色器(通过堆栈溢出找到).
attribute vec4 a_position; attribute vec4 a_color; varying vec4 v_color; uniform mat4 u_proj_matrix; uniform mat4 u_model_matrix; void main() { mat4 mvp_matrix = u_proj_matrix * u_model_matrix; v_color = a_color; gl_Position = mvp_matrix * a_position; }
使用GLM.
glm::mat4 projection = glm::perspective( // FOV & aspect 60.0f, 16.0f / 10.0f, // Near and far planes 0.001f, 1000f); // If you're using the now deprecated matrix stacks glMatrixMode(GL_PROJECTION); glLoadMatrixf(glm::value_ptr(projection)); // if you're using the new shader based pipelines GLint projectionUniformLocation = ...; glUniformMatrix4fv(projectionUniformLocation, 1, GL_FALSE, glm::value_ptr(projection));
注意,如果你已经GLM_FORCE_RADIANS
定义了那么你应该在透视函数中使用弧度,而不是度...
glm::mat4 projection = glm::perspective( // FOV & aspect PI / 3.0f, 16.0f / 10.0f, // Near and far planes 0.001f, 1000f);
从我的一个旧项目中复制:
// The following code is a fancy bit of math that is eqivilant to calling: // gluPerspective( fieldOfView/2.0f, width/height , 0.1f, 255.0f ) // We do it this way simply to avoid requiring glu.h GLfloat zNear = 0.1f; GLfloat zFar = 255.0f; GLfloat aspect = float(width)/float(height); GLfloat fH = tan( float(fieldOfView / 360.0f * 3.14159f) ) * zNear; GLfloat fW = fH * aspect; glFrustum( -fW, fW, -fH, fH, zNear, zFar );