我试图用OpenGL制作太阳能系统。 每当我添加一个行星时,我需要弹出转换矩阵,以便我可以重新开始下一个。这仅适用于2个行星。我能够添加第一颗行星(地球)并让它绕太阳旋转。然后我使用glPopMatrix()并添加第二个围绕太阳旋转的行星,这再次正常。但是当我尝试添加第三颗行星并做同样的事情(首先弹出堆栈并让它围绕太阳转动)时,看起来转换矩阵没有被重置而第三颗行星绕第二颗行星旋转就像第一和第二个行星围绕太阳旋转一样。
这是我的paintGL()的代码:
void PlanetsView::paintGL ()
{
this->dayOfYear = (this->dayOfYear+1);
this->hourOfDay = (this->hourOfDay+1) % 24;
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glLoadIdentity();
// store current matrix
glMatrixMode( GL_MODELVIEW );
gluLookAt(camPosx ,camPosy ,camPosz,
camViewx,camViewy,camViewz,
camUpx, camUpy, camUpz );
//Draw Axes
glDisable( GL_LIGHTING );
glBegin(GL_LINES);
glColor3f(1.0, 0.0, 0.0);
glVertex3f(0.0, 0.0, 0.0);
glVertex3f(10.0, 0.0, 0.0);
glColor3f(0.0, 1.0, 0.0);
glVertex3f(0.0, 0.0, 0.0);
glVertex3f(0.0, 10.0, 0.0);
glColor3f(0.0, 0.0, 1.0);
glVertex3f(0.0, 0.0, 0.0);
glVertex3f(0.0, 0.0, 10.0);
glEnd();
glEnable( GL_LIGHTING );
glPushMatrix();
// rotate the plane of the elliptic
glRotated ( 5.0, 1.0, 0.0, 0.0 );
// draw the sun
GLfloat diff [] = { 0.7f , 0.5f , 0.0f };
glMaterialfv ( GL_FRONT, GL_DIFFUSE, diff );
//glutSolidSphere( 3.0, 25, 25 );
solidSphere(3.0, 25, 25);
// rotate the earth around the sun
glRotated( (GLdouble)(360.0 * dayOfYear /365.0), 0.0, 1.0, 0.0 );
glTranslated ( 4.0, 0.0, 0.0 );
// rotate the earth around its axis
glRotated( (GLdouble)(360.0 * hourOfDay/24.0), 0.0, 1.0, 0.0 );
// draw the earth
GLfloat diff2 [] = { 0.2f , 0.2f , 0.8f };
glMaterialfv ( GL_FRONT, GL_DIFFUSE, diff2 );
solidSphere(0.3, 25, 25);
glPopMatrix();
// rotate the new planet around the sun
glRotated( (GLdouble)(360.0 * dayOfYear /150.0), 0.0, 1.0, 0.0 );
glTranslated ( 6.0, 0.0, 0.0 );
// rotate the new planet around its axis
glRotated( (GLdouble)(360.0 * hourOfDay/36.0), 0.0, 1.0, 0.0 );
// draw the new planet
GLfloat diff3 [] = { 1.0f , 0.0f , 0.0f }; // red color
glMaterialfv ( GL_FRONT, GL_DIFFUSE, diff3 );
solidSphere(0.4, 25, 25);
glPopMatrix(); // looks like this pop doesn't do anything
/* From here, when adding a 3rd planet, it fails */
// rotate a 3rd planet around the sun
glRotated( (GLdouble)(360.0 * dayOfYear /800.0), 0.0, 1.0, 0.0 );
glTranslated ( 6.0, 0.0, 0.0 );
// rotate a 3rd planet around its axis
glRotated( (GLdouble)(360.0 * hourOfDay/12.0), 0.0, 1.0, 0.0 );
// draw the 3rd planet
GLfloat diff4 [] = { 1.0f , 1.0f , 0.0f }; // red color
glMaterialfv ( GL_FRONT, GL_DIFFUSE, diff4 );
solidSphere(0.3, 25, 25);
glPopMatrix();
}
这是solidSphere的代码:
void solidSphere(GLdouble radius, GLint slices, GLint stacks)
{
glBegin(GL_LINE_LOOP);
GLUquadricObj* quadric = gluNewQuadric();
gluQuadricDrawStyle(quadric, GLU_FILL);
gluSphere(quadric, radius, slices, stacks);
gluDeleteQuadric(quadric);
glEnd();
}
答案 0 :(得分:1)
glPopMatrix(); // looks like this pop doesn't do anything
在此之前,你已经将最后一些东西从堆栈中弹出了几行。
如果您打算在调用glPopMatrix ()
后第二次拨打glEnable( GL_LIGHTING )
来恢复存在的矩阵,那么您需要在第一次glPushMatrix ()
之后立即拨打电话glPopMatrix ()
{1}}。并且您需要再次重复该过程,以便您对glPopMatrix ()
的第三次调用也不会使堆栈下溢。
我得到的印象是你不太清楚堆栈是如何工作的。