Search code examples
c++openglscalingcoordinate-transformation

OpenGL Scale Triangle Mesh To Unit Cube


I'm trying to load in a triangle mesh from an .off file and show the triangle mesh centered at the origin and scaled to fit in the unit cube. But for some reason I'm off by a large factor and it looks like

enter image description here

The way I'm doing this is finding the extrema of the mesh, and using that to offset the surface by that amount.

float avgX = (maxX + minX) / 2;
float avgY = (maxY + minY) / 2;
float avgZ = (maxZ + minZ) / 2;
Vector3f center(avgX, avgY, avgZ);
Vector3f offset = Vector3f(0, 0, 0) - center;
Translation3f translation(offset);

cout << "offset is: " << endl << offset << endl;

double d_theta = (M_PI / 180);
AngleAxisf rotation(d_theta, Vector3f(0, 0, 1));

float scaleX = (float) 1 / (abs(maxX - minX));
float scaleY = (float) 1 / (abs(maxY - minY));
float scaleZ = (float) 1 / (abs(maxZ - minZ));
AlignedScaling3f scale = AlignedScaling3f(scaleX, scaleY, scaleZ);

I then put it into a vector of surfaces with

Vector3f translatedCenter = translation * rotation * scale * center;

VertexBufferObject VBO;
VBO.init();
VBO.update(Vertices);
program.bindVertexAttribArray("position", VBO);

VertexBufferObject VBO_N;
VBO_N.init();
VBO_N.update(FlatNormals);
program.bindVertexAttribArray("normals", VBO_N);

cout << "updated normals" << endl;

VertexBufferObject VBO_C;
VBO_C.init();
VBO_C.update(C);
program.bindVertexAttribArray("color",VBO_C);

cout << "updated color " << endl;

Surface* s = new Surface(VBO, Vertices, translation, rotation, scale, percentScale, translatedCenter, SmoothNormals, FlatNormals, C);

And I pass it to the Vertex Shader as "model"

Affine3f model = s->getTranslation() * s->getRotation() * s->getScale();
glUniformMatrix4fv(program.uniform("model"), 1, GL_FALSE, model.data()); 

This is all being done using the Eigen library (https://eigen.tuxfamily.org/dox/group__TutorialGeometry.html#TutorialGeoTransform)

No matter what I try I'm off by a little bit. What am I doing wrong?


Solution

  • Swap translation and rotation:

     Affine3f model = s->getRotation() * s->getTranslation() * s->getScale();
    

    Note, the translation moves the center of the object to the center of the view. After that the rotation matrix rotates around the this center.

    If you don't have any projection matrix, then the view space is the normalized device space where each coordinate is in range [-1, 1]. This mean the length of a side is 2 = 1 - (-1). You have to respect this when you calculate the scale:

    float scaleX = (float) 2 / (abs(maxX - minX));
    float scaleY = (float) 2 / (abs(maxY - minY));
    float scaleZ = (float) 2 / (abs(maxZ - minZ));