Switching projection

I have a program that needs to be able to switch between orthographic and perspective projection at run time. The function below if being called every time the user switches projection:

void COpenGLManager::SetupRenderingContext()
{
//Set the viewport
GLsizei W = (GLsizei)m_pPanel->Width,
H = (GLsizei)m_pPanel->Height;
glViewport(0, 0, W, H);

  glMatrixMode(GL_PROJECTION);
  glLoadIdentity();

  //Ortho
  if (!m_bPerspective)
  {
        m_fRotX = m_fRotY = 0.0;
        if (W <= H)
              glOrtho (-m_fBoxSize/2, m_fBoxSize/2, -m_fBoxSize/2*H/W,
                    m_fBoxSize/2*H/W, m_fBoxSize/2, -m_fBoxSize/2);
        else
        glOrtho (-m_fBoxSize/2*W/H, m_fBoxSize/2*W/H, -m_fBoxSize/2,
                          m_fBoxSize/2, m_fBoxSize/2, -m_fBoxSize/2);
  }
  //Perspective
  else
  {
        m_fTransX = m_fTransY = 0.0;
        GLfloat fAspect = (GLfloat)m_pPanel->Width/(GLfloat)m_pPanel->Height;
        gluPerspective(40, fAspect, 1.0, -500.0);
  }

  glMatrixMode(GL_MODELVIEW);
  glLoadIdentity();

}

For some reason, this code doesn’t change the projection, even if m_bPerspective is being changed. I’m probably just being stupid here, but what am I missing? Why isn’t it working?

Your call to both Ortho and Perspective are wrong.

First, W and H are integers, which means you get integer division when dividing the two. Integer division is not the same as the division you probably expect, so declare H and W as floatingpoint values instead of integers.

Second, in Perspective, the near and far planes must be positive, and the far plane must be larger than the near plane.

Thanks for pointing that out, but it still doesn’t work. The problem isn’t that to projection is messed up, but that it never switches projection. It is always orthographic.

If you haven’t done so allready try putting a puts("***") or something before the gluPerspective call. This will quickly let you know if this call is executed when it should be. If this turns out to be the case I can see no reason why you would be stuck with an ortho projection. I bet the gluPerspective call never gets executed.

No, the call is being executed. I’ve checked with the debugger.

Hmm, the code looks ok, I guess it should work.A few questions.

Are you using more than one rendering context? If yes, always the same one being activated?
If you glGetXX(GL_PROJECTION_MATRIX,projmx) before and after the gluPerspective call, does the matrix change?
Anything from glGetError?
If you step through the gluPerspective call, does it call glLoadMatrix or glMultMatrix at any time?

I have no calls to glLoadMatrix or glMultMatrix, and I don’t have several rendering contexts.
I found something strange though. If I resize the window the rendering context switches as it’s supposed to. However, all the resize function does is call the SetupRenderingContext function I posted above. It seems the problem is somewhere else in my code.
Thanks for the help anyway.