Search code examples
openglzoomingglulookat

OpenGL - set a good distance without glScalef


I try to set a good distance for the full view of a particles disk and in the same time have a valid line scale which represents the current value for the scale of the disk as a function of zooming with mouse.

The scene has the following parameters :

w_width = 600;
w_height = 600;
g_nearPlane = 0.1f;
g_farPlane = 1000.0f;

I do graphics initialization of 3D scene with the following code sample :

// Reset line scale value
lineScaleValue = 100.0f;
// Initialize View
glViewport(0, 0, w_width, w_height);

glMatrixMode(GL_PROJECTION); // Select The Projection Matrix
glLoadIdentity(); // Reset The Projection Matrix

// Perspective with angle set to 45 degrees
gluPerspective(45.0f, (float) w_width / w_height, g_nearPlane, g_farPlane);  

glMatrixMode(GL_MODELVIEW); // Select The Modelview Matrix
glLoadIdentity(); // Reset The Modelview Matrixi

gluLookAt (0.0, 0.0, 3, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0);
glScalef(0.03f, 0.03f, 0.03f);

The above values for gluLookAt and glScalef have been chosen approximately, i.e manually without having an accurate calculation.

I would like to have only a full view for the disk (white particles). For this, I know the maximum and minimum in the (x,y) plane of the disk : -25 < x <25 and -22 < y < 22.

from this post set z good distance, I could do (with Fov/2 = 45 degrees) :

z_distance = 25*tan(pi/4) + dist = 50 

with dist = 25 to be in front of the disk.

So can I do directly in my sample code (instead of

gluLookAt (0.0, 0.0, 3, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0);
    glScalef(0.03f, 0.03f, 0.03f);

) :

gluLookAt (0.0, 0.0, 50, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0);

?

Thanks


Solution

  • The optimal distance can be calculated by the formula given in the post you already linked (not sure how you came to the z_distance equation?):

    visible_range = 2 * tan(fov/2) * distance
    

    In your case:

    visible_range = 50 (-25 to 25)
    =>
    50 = 2 * tan(fov/2) * distance
    distance = 50 / (2 * tan(fov/2)) = 25 / tan(fov/2)
    

    Since the half field of view is in you're case 45° and tan(45°) = 1, the optimal solution is

    distance = 25