Problems with OpenGL rotation - c++

In my OpenGL application, I have a camera which is controlled using the keyboard (movement) and mouse (looking around).
Everythings been working perfectly fine up until now, I have noticed that if I move my camera above 300 in the Y axis, it starts to mess up when moving the mouse. For example, if I go to Y =310, and move the mouse up, as it starts to look up it starts turning to the left as well.
I am not sure what the reason for this is. Can anyone help?
Heres the code to work out forward and up position for gluLookAt()
double cosR, cosP, cosY; //temp values for sin/cos from
double sinR, sinP, sinY; //the inputed roll/pitch/yaw
if(Yaw > 359) Yaw = 0;
if(Pitch > 359) Pitch = 0;
if(Yaw < 0) Yaw = 359;
if(Pitch < 0) Pitch = 359;
cosY = cosf(Yaw*3.1415/180);
cosP = cosf(Pitch*3.1415/180);
cosR = cosf(Roll*3.1415/180);
sinY = sinf(Yaw*3.1415/180);
sinP = sinf(Pitch*3.1415/180);
sinR = sinf(Roll*3.1415/180);
//forward position
forwardPos.x = sinY * cosP*360;
forwardPos.y = sinP * 360;
forwardPos.z = cosP * -cosY*360;
//up position
upPos.x = -cosY * sinR - sinY * sinP * cosR;
upPos.y = cosP * cosR;
upPos.z = -sinY * sinR - sinP * cosR * -cosY;

Gimble Lock. It is explained here.
Quaternions are the standard solution to this problem.
Briefly, when two axis angles approach each other in your above calculation, it causes a loss of available movement. You need a 4th degree of freedom to prevent this - and this is what Quaternion math allow.

Related

Moving an object in the direction of the camera

I'm making a project where I need to move a player in any direction using an analog stick. I'm limited to specific functions and I only have the positions of the camera and the player and the analog stick. The camera is always pointed to the player.
vec2 &leftStick = getLeftStick(-1); // results in an x and a y, both ranging from -1 to 1.
vec3 *playerPos = getTrans(player);
vec3 *cameraPos = getCameraPos(player, 0);
playerPos->x += leftStick.x * 10.0f;
playerPos->z -= leftStick.y * 10.0f;
This code works to move the player, however its using the orientation of the world. I need it where holding up on the analog stick (left stick y = 1) makes the player go forward, no matter what way the player/camera are facing.
My solution, thank you #Borgleader for a majority of it.
I found an equation to find the distance and velocity for the x and z online, then I tested a bunch of combinations until it worked properly. Not a good way to do this but it worked out.
// this all replaces the last two lines of the previous code snippet
float speed = 30.0f;
float d = sqrt(powf(playerPos->x - cameraPos->x, 2) + powf(playerPos->z - cameraPos->z, 2));
float vx = (speed/d)*(playerPos->x - cameraPos->x);
float vz = (speed/d)*(playerPos->z - cameraPos->z);
playerPos->x -= leftStick.x * vz;
playerPos->z += leftStick.x * vx;
playerPos->x += leftStick.y * vx;
playerPos->z += leftStick.y * vz;

Problems with my OpenGL Camera movement

I seem to be having problems with my OpenGl camera. When I first created it, everything worked fine. However since importing models and creating objects, I've noticed weird things happening.
Firstly, heres my code for movement:
float xRot = (Pitch / 180 * 3.141592654f),
yRot = (Yaw / 180 * 3.141592654f);
float sinX = float(sin(xRot)) * myInput.Sensitivity,
sinY = float(sin(yRot)) * myInput.Sensitivity,
cosY = float(cos(yRot)) * myInput.Sensitivity;
if(myInput.Keys['W']) //Forwards
{
curPos.x += sinY;
curPos.z -= cosY;
curPos.y += sinX;
}
else if(myInput.Keys['S']) //Backwards
{
curPos.x -= sinY;
curPos.z += cosY;
curPos.y -= sinX;
}
if(myInput.Keys['A']) //Left
{
curPos.x -= cosY;
curPos.z -= sinY;
}
else if(myInput.Keys['D']) //Right
{
curPos.x += cosY;
curPos.z += sinY;
}
//Move camera up and down
if(myInput.Keys['Q'])
curPos.y-= myInput.Sensitivity; //up
else if(myInput.Keys['E'])
curPos.y+= myInput.Sensitivity; //down
//Check col
if(curPos.y < 0)
curPos.y = 0;
else if(curPos.y >= 300) //Gimbal lock encountered
curPos.y = 299;
Secondly, heres my movement for calculating gluLookAt:
double cosR, cosP, cosY; //temp values for sin/cos from
double sinR, sinP, sinY; //the inputed roll/pitch/yaw
cosY = cosf(Yaw*3.1415/180);
cosP = cosf(Pitch*3.1415/180);
cosR = cosf(Roll*3.1415/180);
sinY = sinf(Yaw*3.1415/180);
sinP = sinf(Pitch*3.1415/180);
sinR = sinf(Roll*3.1415/180);
//forward position
forwardPos.x = sinY * cosP*360;
forwardPos.y = sinP * 360;
forwardPos.z = cosP * -cosY*360;
//up position
upPos.x = -cosY * sinR - sinY * sinP * cosR;
upPos.y = cosP * cosR;
upPos.z = -sinY * sinR - sinP * cosR * -cosY;
Basically I've noticed that if the camera goes above 300 in the Y-Axis then the view starts rotating, the same thing happens if I move too far in the x/z axis.
Can anyone see whats wrong with my code? Am I working in deg when I should be working in rad?
I haven't checked your code but this type of issue is notorious when using Euler angles for 3D rotations.
It's called gimbal lock (I see you have a comment in your code that shows you're aware of it) and the easiest solution to overcoming it is to switch to using quaternions to calculate your rotation matrices.
There's a really good OpenGL article on the Wiki here.

How to get a change in mouse position difference using Cocoa?

I'm using opengl and trying to create a first person camera. All examples use GLUT and I need to get the mouse differential in cocoa. But I'm running into issues which appers to be tied with mouseMoved being called as soon as the mouse is moved (which is to be expected). Is there a way to make this mroe accurate? Or a simialer function like GLUTS glutMouseFunc?
Current attempt:
-(void)mouseMoved:(NSEvent *)event{
static bool wrap = false;
if(!wrap){
NSPoint eventLocation = [event locationInWindow];
float centerX = self.frame.size.width/2 + [self window].frame.origin.x;
float centerY = self.frame.size.height/2 + [self window].frame.origin.y;
CGPoint mousePointCenter = CGPointMake(centerX, centerY);
CGWarpMouseCursorPosition(mousePointCenter);
int dx = eventLocation.x - self.frame.size.width/2 ;
int dy = eventLocation.y - self.frame.size.height/2 ;
const float mousespeed = 0.001;
angles.x += dx * mousespeed;
angles.y += dy * mousespeed;
if(angles.x < -M_PI)
angles.x += M_PI * 2;
else if(angles.x > M_PI)
angles.x -= M_PI * 2;
if(angles.y < -M_PI / 2)
angles.y = -M_PI / 2;
if(angles.y > M_PI / 2)
angles.y = M_PI / 2;
lookat.x = sinf(angles.x) * cosf(angles.y);
lookat.y = sinf(angles.y);
lookat.z = cosf(angles.x) * cosf(angles.y);
CGWarpMouseCursorPosition(mousePointCenter);
[self setNeedsDisplay:YES];
}
else{
wrap = true;
}
}
I'm not sure I followed what your code is supposed to be doing, but repeatedly warping the mouse cursor to a center point is rarely the right thing to do.
First, you can use the deltaX and deltaY values of the NSEvent.
Perhaps you want to do CGAssociateMouseAndMouseCursorPosition(false) to disassociate the mouse from the cursor position. When you do that, the on-screen cursor no longer moves with the mouse. You can hide it or reposition it (yes, you'd warp it once in this case). Also, events no longer have changes in their absolute position. But they do still carry delta movement values which reflect the mouse movements.

Rotating around a sphere using OpenGL and gluLookAt

Alright, so I'm trying to click and drag to rotate around an object using C++ and OpenGL. The way I have it is to use gluLookAt centered at the origin and I'm getting coordinates for the eye by using parametric equations for a sphere (eyex = 2* cos(theta) * sin(phi); eyey = 2* sin(theta) * sin(phi); eyez = 2* cos(phi);). This works mostly, as I can click and rotate horizontally, but when I try to rotate vertically it makes tight circles instead of rotating vertically. I'm trying to get the up vector by using the position of the camera and a vecter at a 90 degree angle along the x-z plane and taking the cross product of that.
The code I have is as follows:
double dotProduct(double v1[], double v2[]) {
return v1[0]*v2[0] + v1[1]*v2[1] + v1[2]*v2[2];
}
void mouseDown(int button, int state, int x, int y) {
if (button == GLUT_LEFT_BUTTON && state == GLUT_DOWN ) {
xpos = x;
ypos = y;
}
}
void mouseMovement(int x, int y) {
diffx = x - xpos;
diffy = y - ypos;
xpos = x;
ypos = y;
}
void camera (void) {
theta += 2*PI * (-diffy/glutGet(GLUT_SCREEN_HEIGHT));
phi += PI * (-diffx/glutGet(GLUT_WINDOW_WIDTH));
eyex = 2* cos(theta) * sin(phi);
eyey = 2* sin(theta) * sin(phi);
eyez = 2* cos(phi);
double rightv[3], rightt[3], eyes[3];
rightv[0] = 2* cos(theta + 2/PI) * sin(phi);
rightv[1] = 0;
rightv[2] = 2* cos(phi);
rightt[0] = rightv[0];
rightt[1] = rightv[1];
rightt[2] = rightv[2];
rightv[0] = rightv[0] / sqrt(dotProduct(rightt, rightt));
rightv[1] = rightv[1] / sqrt(dotProduct(rightt, rightt));
rightv[2] = rightv[2] / sqrt(dotProduct(rightt, rightt));
eyes[0] = eyex;
eyes[1] = eyey;
eyes[2] = eyez;
upx = (eyey/sqrt(dotProduct(eyes,eyes)))*rightv[2] + (eyez/sqrt(dotProduct(eyes,eyes)))*rightv[1];
upy = (eyez/sqrt(dotProduct(eyes,eyes)))*rightv[0] + (eyex/sqrt(dotProduct(eyes,eyes)))*rightv[2];
upz = (eyex/sqrt(dotProduct(eyes,eyes)))*rightv[1] + (eyey/sqrt(dotProduct(eyes,eyes)))*rightv[0];
diffx = 0;
diffy = 0;
}
I am somewhat basing things off of this but it doesn't work, so I tried my way instead.
This isn't exactly a solution for the way you are doing it but I did something similar the other day. I did it by using DX's D3DXMatrixRotationAxis and D3DXVec3TransformCoord The math behind the D3DXMatrixRotationAxis method can be found at the bottom of the following page: D3DXMatrixRotationAxis Math use this if you are unable to use DX. This will allow you to rotate around any axis you pass in. In my object code I keep track of a direction and up vector and I simply rotate each of these around the axis of movement(in your case the yaw and pitch).
To implement the fixed distance camera like this I would simply do the dot product of the current camera location and the origin location (if this never changes then you can simply do it once.) and then move the camera to the origin rotate it the amount you need then move it back with its new direction and up values.

opengl trackball

I am trying to rotate opengl scene using track ball. The problem i am having is i am getting rotations opposite to direction of my swipe on screen. Here is the snippet of code.
prevPoint.y = viewPortHeight - prevPoint.y;
currentPoint.y = viewPortHeight - currentPoint.y;
prevPoint.x = prevPoint.x - centerx;
prevPoint.y = prevPoint.y - centery;
currentPoint.x = currentPoint.x - centerx;
currentPoint.y = currentPoint.y - centery;
double angle=0;
if (prevPoint.x == currentPoint.x && prevPoint.y == currentPoint.y) {
return;
}
double d, z, radius = viewPortHeight * 0.5;
if(viewPortWidth > viewPortHeight) {
radius = viewPortHeight * 0.5f;
} else {
radius = viewPortWidth * 0.5f;
}
d = (prevPoint.x * prevPoint.x + prevPoint.y * prevPoint.y);
if (d <= radius * radius * 0.5 ) { /* Inside sphere */
z = sqrt(radius*radius - d);
} else { /* On hyperbola */
z = (radius * radius * 0.5) / sqrt(d);
}
Vector refVector1(prevPoint.x,prevPoint.y,z);
refVector1.normalize();
d = (currentPoint.x * currentPoint.x + currentPoint.y * currentPoint.y);
if (d <= radius * radius * 0.5 ) { /* Inside sphere */
z = sqrt(radius*radius - d);
} else { /* On hyperbola */
z = (radius * radius * 0.5) / sqrt(d);
}
Vector refVector2(currentPoint.x,currentPoint.y,z);
refVector2.normalize();
Vector axisOfRotation = refVector1.cross(refVector2);
axisOfRotation.normalize();
angle = acos(refVector1*refVector2);
I recommend artificially setting prevPoint and currentPoint to (0,0) (0,1) and then stepping through the code (with a debugger or with your eyes) to see if each part makes sense to you, and the angle of rotation and axis at the end of the block are what you expect.
If they are what you expect, then I'm guessing the error is in the logic that occurs after that. i.e. you then take the angle and axis and convert them to a matrix which gets multiplied to move the model. A number of convention choices happen in this pipeline --which if swapped can lead to the type of bug you're having:
Whether the formula assumes the angle is winding left or right handedly around the axis.
Whether the transformation is meant to rotate an object in the world or meant to rotate the camera.
Whether the matrix is meant to operate by multiplication on the left or right.
Whether rows or columns of matrices are contiguous in memory.