gpt4 book ai didi

c++ - 缩放 3D 形状(OpenGL 和 C++)

转载 作者:行者123 更新时间:2023-11-28 02:37:50 27 4
gpt4 key购买 nike

我在 OpenGL 中创建了一个程序来绘制一些形状。我希望用户能够根据需要放大形状。这是绘制形状的代码:

/*Initialise the required OpenGL functions*/
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glMatrixMode(GL_PROJECTION);
glPushMatrix();
glLoadIdentity();
glOrtho(0.0, screenWidth, screenHeight, 0.0, -1.0, 10.0);
glMatrixMode(GL_MODELVIEW);
glPushMatrix();
glLoadIdentity();
glDisable(GL_CULL_FACE);
glClear(GL_DEPTH_BUFFER_BIT);

/*Draw a square*/
glColor3f(1, 0, 0);
glBegin(GL_QUADS);
glVertex2f(screenWidth * 0.75, screenHeight * 0.08333);
glVertex2f(screenWidth * 0.75, screenHeight * 0.16666);
glVertex2f(screenWidth * 0.86666, screenHeight * 0.16666);
glVertex2f(screenWidth * 0.86666, screenHeight * 0.08333);
glEnd();
glColor3f(0, 0, 0);

/*Let the user zoom*/
if (GetAsyncKeyState(VK_UP))
{
/*"zoom" is a global variable*/
zoom += 0.005;
}

glScaled(1 + zoom, 1 + zoom, 1);

/*Everything that is drawn from this point on (A sphere and a cube) should be scaled*/
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
glTranslatef(-0.3, 0, 0);
glutSolidSphere(3, 20, 20);

glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
glTranslatef(0.55, 0.36, 0);
glutSolidCube(0.05);

glMatrixMode(GL_PROJECTION);
glPopMatrix();
glMatrixMode(GL_MODELVIEW);
glPopMatrix();

glutSwapBuffers();

代码正确绘制了形状,但无法缩放形状。我在其他一些函数中使用了类似的代码,所以我认为这可能是因为我使用的是 3D 形状,或者它可能与我多次调用“glMatrixMode”有关。无论哪种方式,我应该如何更改我的代码,以便根据用户输入缩放立方体和球体,但不影响第一个正方形?

最佳答案

glScaled() 改变当前矩阵。因此,一旦您调用 glLoadIdentity(),您就会撤消缩放。您正在对应该消除的 glMatrixMode() 和 glLoadIdentity() 进行大量不必要的调用。所以尝试更像这样的事情:

// You probably don't really need to do these, but if you do, do it once up top.
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();

glPushMatrix(); // Save the current matrix
glScaled(1 + zoom, 1 + zoom, 1); // Scale it

/*Everything that is drawn from this point on (A sphere and a cube) should be scaled*/
glTranslatef(-0.3, 0, 0);
glutSolidSphere(3, 20, 20);

glTranslatef(0.55, 0.36, 0);
glutSolidCube(0.05);

glPopMatrix(); // Undo the glScaled() call above

glutSwapBuffers();

关于c++ - 缩放 3D 形状(OpenGL 和 C++),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26936685/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com