Sign in to follow this  

OpenGL Quaternions and a rotating ball

This topic is 4379 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

Hey, I'm having some problems to get a ball rotating. I have a ball moving along the XZ-plane which I want to get rotating nicely. This leads me to what seems to be one of the most usual problems regarding rotating (glrotatef since I use opengl): it's kinda hard to rotate something around two world-axis (non object-local). I've read about the quaternions on a few sites and finally decided to do as in the NeHe-tutorial (http://nehe.gamedev.net/data/lessons/lesson.asp?lesson=Quaternion_Camera_Class) which seems ideal for this. What I do is that I calculate how far the ball has moved in the Z and X-direction and translates that to how many degrees the ball have rotated. I keep track of these angles of rotation about the absolute X and Z-axis. Since two rotations won't do it I create to quaternions, one for each axis:
GLfloat Matrix[16];
glQuaternion result, xaxis, zaxis;
xaxis.CreateFromAxisAngle(1.0, 0.0, 0.0, player->getRotationX());
zaxis.CreateFromAxisAngle(0.0, 0.0, 1.0, player->getRotationZ());
result = xaxis*zaxis;
result.CreateMatrix(Matrix);
glMultMatrixf(Matrix);
But I still get odd rotations. For example, when the rotation around the X-axis is 90 degrees and I move along the X-axis the ball rotates around the Y-axis, which is exactly what happens when you use glrotatef twice (since the Z-axis points downwards after the rotation around the X-axis). I've been trying to get these silly quaternions to work the last 4 hrs and I'm starting to get kinda irritated on them :) Does anyone have any ideas?

Share this post


Link to post
Share on other sites
Quote:
Original post by noof
GLfloat Matrix[16];
glQuaternion result, xaxis, zaxis;
xaxis.CreateFromAxisAngle(1.0, 0.0, 0.0, player->getRotationX());
zaxis.CreateFromAxisAngle(0.0, 0.0, 1.0, player->getRotationZ());
result = xaxis*zaxis;
result.CreateMatrix(Matrix);
glMultMatrixf(Matrix);

But I still get odd rotations. For example, when the rotation around the X-axis is 90 degrees and I move along the X-axis the ball rotates around the Y-axis, which is exactly what happens when you use glrotatef twice (since the Z-axis points downwards after the rotation around the X-axis). I've been trying to get these silly quaternions to work the last 4 hrs and I'm starting to get kinda irritated on them :)
Using quaternions is gaining you absolutely nothing here. In short, if one can't make something work with matrices, they probably won't be able to get it to work with quaternions; the latter has some advantages over the former, but the fundamental properties of the two representations are the same.

So I'd drop the quaternions for now. As for getting the ball to roll in a somewhat realistic way, here's what occurs to me (short of an actual physics-based simulation). The axis of the ball's rotation is perpendicular to a) the ball's direction of motion, and b) the normal of the surface on which it is moving. In this case it is always uniquely defined, so you can just take the normalized cross product of the velocity and up vectors. Then, you can find the amount of rotation from the ball's circumference and the distance it's traveled. You can acumulate this angle over time and then feed the axis-angle pair to glRotate().

There might be other issues involved if your ball changes direction. This is a place where your quat class may come in handy (not because it has any special properties with respect to matrices, but rather just because you already have it available).

Share this post


Link to post
Share on other sites
Making a quaternion from euler angles, like you're doing there, is sort of like making a fancy decorated bavarian custard from spoiled milk. It's still going to taste bad. Use quaternions (or matrices) to keep track of the orientation of the ball. Don't use the "xaxis, zaxis" thing. Don't use euler angles anywhere.

Share this post


Link to post
Share on other sites
Quote:
Original post by noof
GLfloat Matrix[16];
glQuaternion result, xaxis, zaxis;
xaxis.CreateFromAxisAngle(1.0, 0.0, 0.0, player->getRotationX());
zaxis.CreateFromAxisAngle(0.0, 0.0, 1.0, player->getRotationZ());
result = xaxis*zaxis;
result.CreateMatrix(Matrix);
glMultMatrixf(Matrix);


Just to chime in, my first reaction to this code was "wow, this is incredibly... pointless". You probably fell for the silly "quaternions are the magical solution to all your rotation problems" and decided to just throw some in without being explained or looking up what they are, how they work and why they work.

So you create two quaternions, which are doing exactly the same thing as matrices would have and end up with a completely wasteful way to do:
glRotate(a,1,0,0);
glRotate(b,0,0,1);
just that now there is a lot of useless back and forth between all possible representations.

As pointed out above, your problem isn't using quaterions or converting Euler angles to quaternions, but the fact that you are using Euler angles at all. They are extremely useless for just about everything that isn't a typical shooter style first person camera. NEVER try and store an orientation as Euler angles, there is just no useful way to add additional rotations, unless you start converting them (ALL angles) to a (SINGLE) matrix/quaternion, apply the new rotation to that and convert back. And at this point you should realize that storing a matrix or quaternion instead of constantly converting from/to a useless representation is saving you a lot of work and trouble.

Share this post


Link to post
Share on other sites
We all have to start somewhere :)

Quote:
Original post by jyk
Then, you can find the amount of rotation from the ball's circumference and the distance it's traveled. You can acumulate this angle over time and then feed the axis-angle pair to glRotate().

I actually tried that one before I found out about quaternion which makes it kinda hard to accumulate the rotation (unless you use matrices, which I didn't think of)

Quote:
Original post by Trienco
You probably fell for the silly "quaternions are the magical solution to all your rotation problems" and decided to just throw some in without being explained or looking up what they are, how they work and why they work.

100% correct, although I started realizing that quaternions aren't as magic as I thought when I thought about them and couldn't grasp why they would solve my problem (just thought that was part of the other silly "quaternions are so hard to understand that you don't wanna waste your time doing it")

So, after reading your thoughts (thanks a lot for them btw!) I'm thinking of the following solution:
1) cross velocity vector with up-vector (plane normal) to get the vector the ball is spinning around
2) get number of degrees the ball has rotatet around that vector
3) convert that spin to a quaternion like:
glQuaternion rot;
rot.CreateFromAxisAngle(degrees, spinvector.x, spinvector.y, spinvector.z);

4) "add" that rotation to the rotation accumulator:
total = total*rot;

5) rotate the ball:
GLfloat Matrix[16];
total .CreateMatrix(Matrix);
glMultMatrixf(Matrix);


Does this sound any better? :)

[Edited by - noof on January 20, 2006 4:54:11 AM]

Share this post


Link to post
Share on other sites
Quote:
Original post by noof
(just thought that was part of the other silly "quaternions are so hard to understand that you don't wanna waste your time doing it")


That depends on how deeply you want to understand them. But usually we only care about unit quaternions, so reducing it to axis and angle can already get you somewhere. Completely without worrying too much about all the implications of having complex numbers with not just i, but also j,k and all their properties.

Quote:

I'm thinking of the following solution:


If I get you right you plan to store the total rotation/orientation as a quaternion and just add (well, multiply) the rotation for each update. That would be pretty much the way to do it.

Keep in mind that quaternions are smaller, not as problematic as deorthonormalizing matrices and quat-quat multiplication is a bit cheaper. But transforming something by a quaternion is a good bit more expensive. So they are usually only of interest if you really need to save memory or expect to concatenate lots of transformations so the cheaper multiplication is worth the more expensive transformation.

Share this post


Link to post
Share on other sites
Quote:
Original post by Trienco
If I get you right you plan to store the total rotation/orientation as a quaternion and just add (well, multiply) the rotation for each update.
Yeah, that's the solution I'm thinking about trying later today.

Quote:
Original post by TriencoKeep in mind that quaternions are smaller, not as problematic as deorthonormalizing matrices and quat-quat multiplication is a bit cheaper. But transforming something by a quaternion is a good bit more expensive. So they are usually only of interest if you really need to save memory or expect to concatenate lots of transformations so the cheaper multiplication is worth the more expensive transformation.

Ok, I don't think it'll make a huge difference in my project, but it always good to know :)

Quote:
Original post by Trienco
But usually we only care about unit quaternions

That makes me think of another question. Do I have to normalize the quaternion after doing the "multiplication" ? like:

total = total*rot;
total = total / sqrt(w^2+x^2+y^2+z^2)

because I think only x^2+y^2+z^2=1 and not w^2+x^2+y^2+z^2=1, since I will get a unit vector as the "vector part" of the quaternion, but the angle will be arbitrary, or?

Share this post


Link to post
Share on other sites
Quote:
Original post by noof
That makes me think of another question. Do I have to normalize the quaternion after doing the "multiplication" ?


Mathematically? No, the result should also be a unit quaternion.
Technically? Every once in a while, because discrete representations of real numbers (ie. float/double) will introduce small errors that can add up. As sqrt can be kind of expensive it might be worth to check if a conditional might be better (or just normalize after every 100 or whatever multiplications). And yes, you normalize the whole thing, not just part of it (which means you can drop one -preferably positive- component if you really need every byte you can get).

Share this post


Link to post
Share on other sites
Tried the new idea and I still have the same problem. In every frame I do (rotation is the rotation accumulator as a quaternion, velocity is the normalized ball velocity vector):
Vector3D spinAxis = velocity.crossProduct(Vector3D(0,1,0)); // velocity is normalized
float rotationAngle = <calculates angle here>;
if(!rotation) {
// first frame
rotation = new Quaternion(rotationAngle, spinAxis.getX(), spinAxis.getY(), spinAxis.getZ());
} else {
// other frames
*rotation = (*rotation)*Quaternion(rotationAngle, spinAxis.getX(), spinAxis.getY(), spinAxis.getZ());
}
rotation->normalize(); // just to be sure
glMultMatrixf(...);
Which gives me exactly the same results :( But when I think of it I would be kinda surprised if it had worked. Let's say for example that I have a really sucky frame rate and start by rolling 90 degrees of the ball along the Z-axis before frame 1. Then I turn around 90 degrees and roll the same distance along the X-axis before frame 2. In the first frame I will have:
rotation = Quaternion(90, 1, 0, 0);
and in the next frame:
rotation = rotation*Quaternion(90, 0, 0, 1);
which seems to be exactly what I had in my first attempt to use quaternions. I'm obviously missing something here, any more ideas? :)

*edit* It's working now, YEY! :D And it looks damn sweet :) I replaced:
  *rotation = (*rotation)*Quaternion(rotationAngle, spinAxis.getX(), spinAxis.getY(), spinAxis.getZ());
with:
  *rotation = Quaternion(rotationAngle, spinAxis.getX(), spinAxis.getY(), spinAxis.getZ())*(*rotation);
If someone has an explanation for why it should be that way and not the other, feel free to post a reply. (And thanks for all the help, really appreciated!)

[Edited by - noof on January 20, 2006 10:51:21 AM]

Share this post


Link to post
Share on other sites
Because, as you noticed, neither matrix nor quaternion multiplication is commutative. Order matters and in this case is making the difference between rotating around the local axis (after all previous rotations have been applied) and the global axis (before previous rotations were applied). As you calculate your rotation axis in world coordinates (as far as I can tell), you also need to multiply the other way round. But which one is "right" pretty much depends on whether you swapped quaternions in your multiplication function or not. I would guess some people do, simply because it allows to use quat*=other_quat instead of having to write quat=otherquat*quat all the time.

Share this post


Link to post
Share on other sites
Ok, at least I understand those quaternions more then before. Thanks for the help!!

Share this post


Link to post
Share on other sites

This topic is 4379 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this  

  • Similar Content

    • By xhcao
      Does sync be needed to read texture content after access texture image in compute shader?
      My simple code is as below,
      glUseProgram(program.get());
      glBindImageTexture(0, texture[0], 0, GL_FALSE, 3, GL_READ_ONLY, GL_R32UI);
      glBindImageTexture(1, texture[1], 0, GL_FALSE, 4, GL_WRITE_ONLY, GL_R32UI);
      glDispatchCompute(1, 1, 1);
      // Does sync be needed here?
      glUseProgram(0);
      glBindFramebuffer(GL_READ_FRAMEBUFFER, framebuffer);
      glFramebufferTexture2D(GL_READ_FRAMEBUFFER, GL_COLOR_ATTACHMENT0,
                                     GL_TEXTURE_CUBE_MAP_POSITIVE_X + face, texture[1], 0);
      glReadPixels(0, 0, kWidth, kHeight, GL_RED_INTEGER, GL_UNSIGNED_INT, outputValues);
       
      Compute shader is very simple, imageLoad content from texture[0], and imageStore content to texture[1]. Does need to sync after dispatchCompute?
    • By Jonathan2006
      My question: is it possible to transform multiple angular velocities so that they can be reinserted as one? My research is below:
      // This works quat quaternion1 = GEQuaternionFromAngleRadians(angleRadiansVector1); quat quaternion2 = GEMultiplyQuaternions(quaternion1, GEQuaternionFromAngleRadians(angleRadiansVector2)); quat quaternion3 = GEMultiplyQuaternions(quaternion2, GEQuaternionFromAngleRadians(angleRadiansVector3)); glMultMatrixf(GEMat4FromQuaternion(quaternion3).array); // The first two work fine but not the third. Why? quat quaternion1 = GEQuaternionFromAngleRadians(angleRadiansVector1); vec3 vector1 = GETransformQuaternionAndVector(quaternion1, angularVelocity1); quat quaternion2 = GEQuaternionFromAngleRadians(angleRadiansVector2); vec3 vector2 = GETransformQuaternionAndVector(quaternion2, angularVelocity2); // This doesn't work //quat quaternion3 = GEQuaternionFromAngleRadians(angleRadiansVector3); //vec3 vector3 = GETransformQuaternionAndVector(quaternion3, angularVelocity3); vec3 angleVelocity = GEAddVectors(vector1, vector2); // Does not work: vec3 angleVelocity = GEAddVectors(vector1, GEAddVectors(vector2, vector3)); static vec3 angleRadiansVector; vec3 angularAcceleration = GESetVector(0.0, 0.0, 0.0); // Sending it through one angular velocity later in my motion engine angleVelocity = GEAddVectors(angleVelocity, GEMultiplyVectorAndScalar(angularAcceleration, timeStep)); angleRadiansVector = GEAddVectors(angleRadiansVector, GEMultiplyVectorAndScalar(angleVelocity, timeStep)); glMultMatrixf(GEMat4FromEulerAngle(angleRadiansVector).array); Also how do I combine multiple angularAcceleration variables? Is there an easier way to transform the angular values?
    • By dpadam450
      I have this code below in both my vertex and fragment shader, however when I request glGetUniformLocation("Lights[0].diffuse") or "Lights[0].attenuation", it returns -1. It will only give me a valid uniform location if I actually use the diffuse/attenuation variables in the VERTEX shader. Because I use position in the vertex shader, it always returns a valid uniform location. I've read that I can share uniforms across both vertex and fragment, but I'm confused what this is even compiling to if this is the case.
       
      #define NUM_LIGHTS 2
      struct Light
      {
          vec3 position;
          vec3 diffuse;
          float attenuation;
      };
      uniform Light Lights[NUM_LIGHTS];
       
       
    • By pr033r
      Hello,
      I have a Bachelor project on topic "Implenet 3D Boid's algorithm in OpenGL". All OpenGL issues works fine for me, all rendering etc. But when I started implement the boid's algorithm it was getting worse and worse. I read article (http://natureofcode.com/book/chapter-6-autonomous-agents/) inspirate from another code (here: https://github.com/jyanar/Boids/tree/master/src) but it still doesn't work like in tutorials and videos. For example the main problem: when I apply Cohesion (one of three main laws of boids) it makes some "cycling knot". Second, when some flock touch to another it scary change the coordination or respawn in origin (x: 0, y:0. z:0). Just some streng things. 
      I followed many tutorials, change a try everything but it isn't so smooth, without lags like in another videos. I really need your help. 
      My code (optimalizing branch): https://github.com/pr033r/BachelorProject/tree/Optimalizing
      Exe file (if you want to look) and models folder (for those who will download the sources):
      http://leteckaposta.cz/367190436
      Thanks for any help...

    • By Andrija
      I am currently trying to implement shadow mapping into my project , but although i can render my depth map to the screen and it looks okay , when i sample it with shadowCoords there is no shadow.
      Here is my light space matrix calculation
      mat4x4 lightViewMatrix; vec3 sun_pos = {SUN_OFFSET * the_sun->direction[0], SUN_OFFSET * the_sun->direction[1], SUN_OFFSET * the_sun->direction[2]}; mat4x4_look_at(lightViewMatrix,sun_pos,player->pos,up); mat4x4_mul(lightSpaceMatrix,lightProjMatrix,lightViewMatrix); I will tweak the values for the size and frustum of the shadow map, but for now i just want to draw shadows around the player position
      the_sun->direction is a normalized vector so i multiply it by a constant to get the position.
      player->pos is the camera position in world space
      the light projection matrix is calculated like this:
      mat4x4_ortho(lightProjMatrix,-SHADOW_FAR,SHADOW_FAR,-SHADOW_FAR,SHADOW_FAR,NEAR,SHADOW_FAR); Shadow vertex shader:
      uniform mat4 light_space_matrix; void main() { gl_Position = light_space_matrix * transfMatrix * vec4(position, 1.0f); } Shadow fragment shader:
      out float fragDepth; void main() { fragDepth = gl_FragCoord.z; } I am using deferred rendering so i have all my world positions in the g_positions buffer
      My shadow calculation in the deferred fragment shader:
      float get_shadow_fac(vec4 light_space_pos) { vec3 shadow_coords = light_space_pos.xyz / light_space_pos.w; shadow_coords = shadow_coords * 0.5 + 0.5; float closest_depth = texture(shadow_map, shadow_coords.xy).r; float current_depth = shadow_coords.z; float shadow_fac = 1.0; if(closest_depth < current_depth) shadow_fac = 0.5; return shadow_fac; } I call the function like this:
      get_shadow_fac(light_space_matrix * vec4(position,1.0)); Where position is the value i got from sampling the g_position buffer
      Here is my depth texture (i know it will produce low quality shadows but i just want to get it working for now):
      sorry because of the compression , the black smudges are trees ... https://i.stack.imgur.com/T43aK.jpg
      EDIT: Depth texture attachment:
      glTexImage2D(GL_TEXTURE_2D, 0,GL_DEPTH_COMPONENT24,fbo->width,fbo->height,0,GL_DEPTH_COMPONENT,GL_FLOAT,NULL); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); glFramebufferTexture2D(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_TEXTURE_2D, fbo->depthTexture, 0);
  • Popular Now