0

I was going through the Hello GL Example in the Qt documentation.

They have some code which helps in rotation the scene with mouse drag.

void GLWidget::mouseMoveEvent(QMouseEvent *event)
{
    int dx = event->x() - lastPos.x();
    int dy = event->y() - lastPos.y();

    if (event->buttons() & Qt::LeftButton) {
       setXRotation(xRot + 8 * dy);
       setYRotation(yRot + 8 * dx);
    } else if (event->buttons() & Qt::RightButton) {
       setXRotation(xRot + 8 * dy);
       setZRotation(zRot + 8 * dx);
    }
   lastPos = event->pos();
}

And

 void GLWidget::setXRotation(int angle)
{
   qNormalizeAngle(angle);
   if (angle != xRot) {
       xRot = angle;
       emit xRotationChanged(angle);
       updateGL();
   }
}

I can understand that they are trying to calculate the change in x/y coordinates during the process of drag.

But how are they mapping it to rotating the scene ? Documentation lacks an explanation on what is being done.

Also, whats with these magic numbers 8 ?

Amit Tomar
  • 4,800
  • 6
  • 50
  • 83
  • Sometimes, or rather, very often, the numbers are derived empirically. Different numbers are tried and the best, the magic ones, picked. – user1095108 Jan 27 '15 at 09:36

2 Answers2

2

OpenGL is basically a pencil to draw stuff. There's no such thing like a scene. You, the programmer create a bunch of variables and then, when its time to draw something use those to move around the pencil that is OpenGL.

In your particular case there are some variables xRot, yRot and zRot that are used in the creation of the transformation chain that's applied for drawing the object. The actual drawing happens in GLWidget::paintGL; I annotated it for you:

 void GLWidget::paintGL()
 {
     glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
     glLoadIdentity(); // reset transformation state
     glTranslatef(0.0, 0.0, -10.0); // apply translation to transformation
     glRotatef(xRot / 16.0, 1.0, 0.0, 0.0); // apply rotation on x
     glRotatef(yRot / 16.0, 0.0, 1.0, 0.0); // apply rotation on x
     glRotatef(zRot / 16.0, 0.0, 0.0, 1.0); // apply rotation on x
     logo->draw(); // draw logo using the currently set transformation
 }
datenwolf
  • 159,371
  • 13
  • 185
  • 298
  • I understand this part. My particular concern was those special numbers appearing in the code. Why is the change in mouse positions being multiplied/divide by these magic numbers (8,16) ? – Amit Tomar Jan 28 '15 at 16:37
  • @AmitTomar: These are just (hardcoded) scaling factors. They have no special meaning other than give the interaction a certain "feel". In a more sophisticated implementation (say an arcball) the scaling may even depend on the position of the pointer relative to where the motion started. – datenwolf Jan 28 '15 at 22:41
-1

emit xRotationChanged(angle) - rotates your scene on x-axis

8 handles your mouse sensitivity

Dwyche
  • 1
  • 1