2014-11-14 142 views
0

我在OpenGL中創建了一個繪製一些形狀的程序。我希望用戶能夠放大形狀,如果他們想。這是繪製形狀的代碼:縮放3D形狀(OpenGL和C++)

/*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」有關。無論哪種方式,我應該如何更改我的代碼,以便立方體和球體根據用戶輸入進行縮放,但第一個平方不受影響?

回答

2

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(); 
+0

這也將擴展翻譯。如果你不想要,那麼對每個對象執行glPushMatrix/glScaled/glutSolidXXXX()/ glPopMatrix。 – 2014-11-14 18:55:02