tags:

views:

84

answers:

2

How can I scale a random 3d model to fit in an opengl viewport? I am able to center the model in the middle of the view port. How do I scale it to fit it in the viewport. The model could be an airplane, a cone, an 3d object or any other random model.

Appreciate any help.

+3  A: 

You'll need the following information:

  • r: the radius of the object's bounding sphere
  • z: the distance from the object to the camera
  • fovy: the vertical field of view (let's say in degrees) of the camera, as you might have passed it to gluPerspective

Make a little sketch of the situation, find the right triangle in there, and deduce the maximum radius of a sphere that would fit exactly. Given the above parameters, you should find r_max = z * sin(fovy*M_PI/180 / 2).

From that, the scale factor is r_max / r.

All this assumes that the viewport is wider than it is high; if it's not, you should derive fovx first, and use that instead of fovy.

Thomas
A: 

Thanks for the response. I can get it in the center of the viewport but it does not scale well to fit the viewport. Here is the code I have.

Where am I going wrong? Appreciate your help. ...

glViewport(lowerLeft.x, lowerLeft.y, size.x, size.y);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
GLfloat aspect = (float)(size.x)/(float)(size.y);
GLfloat diam = 2 * boundingSphere.radius;
GLfloat zNear = 0.01f;
GLfloat zFar = zNear+diam;
GLfloat rMax = 0.0f;
glTranslatef(0, 0, -7);
ymax = zNear * tanf(fieldOfView * M_PI / 360.0);
ymin = -ymax;
xmin = ymin * aspect;
xmax = ymax * aspect;

rMax = (7 + diam) * sin((double)((fieldOfView * M_PI)/180)/2);
zoom = (float)(diam/2.0f)/rMax;
glMatrixMode(GL_PROJECTION);
glFrustumf(xmin * zoom, xmax * zoom, ymin * zoom, ymax * zoom, zNear, zFar);

....
John Qualis