Search code examples
javaopenglscale

OPENGL - Maintain object's original aspect ratio


i'm reading and loading .obj files, i want to have 4 different view ports all with different perspectives, my main problem is trying to keep the original aspect ration of the object and prevent it from changing with window re-size or transformations like rotation.

This is what i'm trying to get: enter image description here

This is what i'm getting (in fullscreen): enter image description here

A portion of my display code:

GL2 gl = drawable.getGL().getGL3bc();
        gl.glEnable(GL_DEPTH_TEST);
        gl.glDepthFunc(GL_LEQUAL);
        gl.glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
        gl.glOrtho(xMin - (0.1 * (xMax - xMin)), xMax
                + (0.1 * (xMax - xMin)), yMin - (0.1 * (yMax - yMin)), yMax
                + (0.1 * (yMax - yMin)), zMin - (0.1 * (zMax - zMin)), zMax
                + (0.1 * (zMax - zMin)));
        gl.glMatrixMode(GL_PROJECTION);
        gl.glViewport(0, 0, width / 2, height / 2);
        gl.glLoadIdentity();
        gl.glPushMatrix();
        gl.glRotatef(-90f, 1f, 0f, 0f);
        draw(gl);
        gl.glPopMatrix();
        gl.glViewport(width / 2, height / 2, width / 2, height / 2);
        gl.glLoadIdentity();
        gl.glPushMatrix();
        gl.glRotated(-90, 0, 1, 0);
        draw(gl);
        gl.glPopMatrix();
        gl.glViewport(0, height / 2, width / 2, height / 2);
        gl.glLoadIdentity();
        gl.glPushMatrix();
        draw(gl);
        gl.glPopMatrix();

xMax,yMin are the maximum and minimum values of the x axis in the points given in the .obj file. height and width are the current dimensions of the window.


Solution

  • xMax,yMin are the maximum and minimum values of the x axis in the points given in the .obj file. height and width are the current dimensions of the window.

    Well, this is most likely your problem. By setting an orthogonal view that relies on the minimum and maximum values of each coordinate, you will be actually distorting the object, because such a region doesn't have the same aspect ratio as the window. To make it clearer, if you were to put the entire model inside a box and take a picture of it, the application would stretch it so that the Y and X coordinates (assuming Y as the up-down axis) make part of the entire viewport. This would be seen as enlarging the "picture"'s width, or squeezing the height.

    So you should adjust these parameters to remove the distortion. Since the model is tall (larger in Y than X), I suggest applying this trick before setting the orthogonal view:

    xMin = xMin * width / height;
    xMax = xMax * width / height;