I would like to make a 3D viewer which is controllable from mouse input with OpenGL.
The camera moves around the object using a polar coordinate system. I use Euler angle and glm::lookat, this system works with some limitation. At this case, pitch and yaw should be changed from mouse inputs, however, we have to care about gimbal lock. So I make a limitation to the range of pitch.
This is a part of code
auto V = camera.getViewMatrix();
float xOffset = x - lastX_pos;
float yOffset = lastY_pos - y;
lastX_pos = x;
lastY_pos = y;
float sensitivity = 0.05;
xOffset *= sensitivity;
yOffset *= sensitivity;
yaw += xOffset;
pitch += yOffset;
if (pitch > 89.0f)
pitch = 89.0f;
if (pitch < -89.0f)
pitch = -89.0f;
glm::vec3 cameraPos;
cameraPos.x = distance * cos(glm::radians(yaw)) * cos(glm::radians(pitch));
cameraPos.y = distance * sin(glm::radians(pitch));
cameraPos.z = distance * sin(glm::radians(yaw)) * cos(glm::radians(pitch));
glm::vec3 up = glm::vec3(0.0f, 1.0f, 0.0f);
glm::vec3 cameraDirection = glm::normalize(cameraPos);
glm::vec3 cameraRight = glm::normalize(glm::cross(up, cameraDirection));
glm::vec3 cameraUp = glm::cross(cameraDirection, cameraRight);
V = glm::lookAt(cameraPos + sphereCenter, sphereCenter, cameraUp);
camera.setViewMatrix(V);
I would like to move the camera without any limitations like Meshlab viewer. So I think I have to use not Euler angle but quaternion and calculate view matrix without glm::lookat.
If I did so, how I would correctly deal with mouse input and calculate camera position and direction from quaternion?
Related
I´m trying to implements a bullet so I have this free movement first person camera. I got this camera from learnopengl.com this is the coding:
// Default camera values
const float YAW = -90.0f;
const float PITCH = 0.0f;
const float SPEED = 2.5f;
const float SENSITIVITY = 0.1f;
const float ZOOM = 45.0f;
// An abstract camera class that processes input and calculates the corresponding Euler Angles, Vectors and Matrices for use in OpenGL
class Camera
{
public:
// Camera Attributes
glm::vec3 Position;
glm::vec3 Front;
glm::vec3 Up;
glm::vec3 Right;
glm::vec3 WorldUp;
// Euler Angles
float Yaw;
float Pitch;
// Camera options
float MovementSpeed;
float MouseSensitivity;
float Zoom;
// Constructor with vectors
Camera(glm::vec3 position = glm::vec3(0.0f, 0.0f, 0.0f), glm::vec3 up = glm::vec3(0.0f, 1.0f, 0.0f), float yaw = YAW, float pitch = PITCH) : Front(glm::vec3(0.0f, 0.0f, -1.0f)), MovementSpeed(SPEED), MouseSensitivity(SENSITIVITY), Zoom(ZOOM)
{
Position = position;
WorldUp = up;
Yaw = yaw;
Pitch = pitch;
updateCameraVectors();
}
// Constructor with scalar values
Camera(float posX, float posY, float posZ, float upX, float upY, float upZ, float yaw, float pitch) : Front(glm::vec3(0.0f, 0.0f, -1.0f)), MovementSpeed(SPEED), MouseSensitivity(SENSITIVITY), Zoom(ZOOM)
{
Position = glm::vec3(posX, posY, posZ);
WorldUp = glm::vec3(upX, upY, upZ);
Yaw = yaw;
Pitch = pitch;
updateCameraVectors();
}
// Returns the view matrix calculated using Euler Angles and the LookAt Matrix
glm::mat4 GetViewMatrix()
{
return glm::lookAt(Position, Position + Front, Up);
}
// Processes input received from any keyboard-like input system. Accepts input parameter in the form of camera defined ENUM (to abstract it from windowing systems)
void ProcessKeyboard(Camera_Movement direction, float deltaTime)
{
float velocity = MovementSpeed * deltaTime;
if (direction == FORWARD)
Position += Front * velocity;
if (direction == BACKWARD)
Position -= Front * velocity;
if (direction == LEFT)
Position -= Right * velocity;
if (direction == RIGHT)
Position += Right * velocity;
}
// Processes input received from a mouse input system. Expects the offset value in both the x and y direction.
void ProcessMouseMovement(float xoffset, float yoffset, GLboolean constrainPitch = true)
{
xoffset *= MouseSensitivity;
yoffset *= MouseSensitivity;
Yaw += xoffset;
Pitch += yoffset;
// Make sure that when pitch is out of bounds, screen doesn't get flipped
if (constrainPitch)
{
if (Pitch > 89.0f)
Pitch = 89.0f;
if (Pitch < -89.0f)
Pitch = -89.0f;
}
// Update Front, Right and Up Vectors using the updated Euler angles
updateCameraVectors();
}
// Processes input received from a mouse scroll-wheel event. Only requires input on the vertical wheel-axis
void ProcessMouseScroll(float yoffset)
{
if (Zoom >= 1.0f && Zoom <= 45.0f)
Zoom -= yoffset;
if (Zoom <= 1.0f)
Zoom = 1.0f;
if (Zoom >= 45.0f)
Zoom = 45.0f;
}
private:
// Calculates the front vector from the Camera's (updated) Euler Angles
void updateCameraVectors()
{
// Calculate the new Front vector
glm::vec3 front;
front.x = cos(glm::radians(Yaw)) * cos(glm::radians(Pitch));
front.y = sin(glm::radians(Pitch));
front.z = sin(glm::radians(Yaw)) * cos(glm::radians(Pitch));
Front = glm::normalize(front);
// Also re-calculate the Right and Up vector
Right = glm::normalize(glm::cross(Front, WorldUp)); // Normalize the vectors, because their length gets closer to 0 the more you look up or down which results in slower movement.
Up = glm::normalize(glm::cross(Right, Front));
}
};
So now I want to create a bullet that starts from
model = glm::translate(model, camara.Position+7.0f*camara.Front);
The issue is that as I try to move the camera the object rotates with it which I know why but I don't know how to fix it, I have tried something like this:
model = glm::rotate(model, glm::radians(camara.Pitch), glm::vec3(1.0f, 0.0f, 0.0f));
model = glm::rotate(model, -glm::radians(camara.Yaw), glm::vec3(0.0f, 1.0f, 0.0f));
trying to sync the rotations but it's not working.
I want to store the position because then I want the bullets to go straight no matter where I move. Thank you.
This is how I always want it to look:
This is how it rotates as I move:
I am having trouble about understand the translate the camera. I already can successfully rotate the camera, but I am still confused about translating the camera. I include the code about how to rotate the camera, Since translating and rotating need to use the lookat function. The homework says translating the camera means that both the eye and the center should be moved with the same amount. I understand I can change the parameters in the lookat function to implement this.
The definition of lookat function is below:
Lookat(cameraPos, center, up)
glm::vec3 cameraPos = glm::vec3(0.0f, 0.0f, 10.0f);
glm::vec3 center(0.0f, 0.0f, 0.0f);
glm::vec3 cameraUp = glm::vec3(0.0f, 1.0f, 0.0f);
modelViewProjectionMatrix.Perspective(glm::radians(fov), float(width) / float(height), 0.1f, 100.0f);
modelViewProjectionMatrix.LookAt(cameraPos, center, cameraUp);
void CursorPositionCallback(GLFWwindow* lWindow, double xpos, double ypos)
{
int state = glfwGetMouseButton(window, GLFW_MOUSE_BUTTON_LEFT);
if (state == GLFW_PRESS)
{
if (firstMouse)
{
lastX = xpos;
lastY = ypos;
firstMouse = false;
}
float xoffset = xpos - lastX;
float yoffset = lastY- ypos;
lastX = xpos;
lastY = ypos;
yaw += xoffset;
pitch += yoffset;
glm::vec3 front;
front.x = center[0] + 5.0f*cos(glm::radians(yaw)) * cos(glm::radians(pitch));
front.y = center[1] + 5.0f*sin(glm::radians(pitch));
front.z = center[1] + 5.0f*sin(glm::radians(yaw)) * cos(glm::radians(pitch));
cameraPos = front;
}
}
If you want to translate the camera by an offset, then you've to add the same vector (glm::vec3 offset) to the camera position (cameraPos) and the camera target (center):
center = center + offset;
cameraPos = cameraPos + offset;
When you calculate a new target of the camera (center), by a pitch and yaw angle, then you've to update the up vector (cameraUp) of the camera, too:
glm::vec3 front(
cos(glm::radians(pitch)) * cos(glm::radians(yaw)),
sin(glm::radians(pitch)),
cos(glm::radians(pitch)) * sin(glm::radians(yaw))
);
glm::vec3 up(
-sin(glm::radians(pitch)) * cos(glm::radians(yaw)),
cos(glm::radians(pitch)),
-sin(glm::radians(pitch)) * sin(glm::radians(yaw))
);
cameraPos = center + front * 5.0f;
cameraUp = up;
To translate the camera along the x axis (from left to right) in viewspace you've to calculate the vector to the right by the Cross product of the vector to the target (front) and the up vector (cameraUp or up):
glm::vec3 right = glm::cross(front, up);
The y axis (from bottom to top) in viewspace, is the up vector.
To translate about the scalars (float trans_x) and (trans_y), the scaled right and up vector have to be add to the camera position (cameraPos) and the camera target (center):
center = center + right * trans_x + up * trans_y;
cameraPos = cameraPos + right * trans_x + up * trans_y;
Use the manipulated vectors to set the view matrix:
modelViewProjectionMatrix.LookAt(cameraPos, center, cameraUp);
I'm trying to implement a camera all by myself in OpenGL (I use glfw and gml).
As for now, I don't have any class for it. I will create it later. So here is my try on coding the camera movements; it works fine with simple mouse movements, but otherwise, the camera tilts sideways. I'm still new to OpenGL so I don't have a lot to show but here is illustrated my problem: http://imgur.com/a/p9xXQ
I have a few (global as for now) variables :
float lastX = 0.0f, lastY = 0.0f, yaw = 0.0f, pitch = 0.0f;
glm::vec3 cameraPos(0.0f, 0.0f, 3.0f);
glm::vec3 cameraUp(0.0f, 1.0f, 0.0f); // As a reminder, x points to the right, y points upwards and z points towards you
glm::vec3 cameraFront(0.0f, 0.0f, -1.0f);
With these, I can create a view matrix this way :
glm::mat4 view;
view = glm::lookAt(cameraPos, cameraPos + cameraFront, cameraUp);
I want to be able to move my camera perpendicularly (yaw) and laterally (pitch), i.e. up, down, right, left on my screen. For this, it is enough to rotate the cameraFront vector and the cameraUp vector appropriately and then update the view matrix with the updated vectors.
My Cursor Position Callback looks like this :
glm::vec3 rotateAroundAxis(glm::vec3 toRotate, float angle, glm::vec3 axisDirection, glm::vec3 axisPoint) { // angle in radians
toRotate -= axisPoint;
glm::mat4 rotationMatrix(1.0f);
rotationMatrix = glm::rotate(rotationMatrix, angle, axisDirection);
glm::vec4 result = rotationMatrix*glm::vec4(toRotate, 1.0f);
toRotate = glm::vec3(result.x, result.y, result.z);
toRotate += axisPoint;
return toRotate;
}
void mouseCallback(GLFWwindow* window, double xpos, double ypos) {
const float maxPitch = float(M_PI) - float(M_PI) / 180.0f;
glm::vec3 cameraRight = -glm::cross(cameraUp, cameraFront);
float xOffset = xpos - lastX;
float yOffset = ypos - lastY;
lastX = xpos;
lastY = ypos;
float sensitivity = 0.0005f;
xOffset *= sensitivity;
yOffset *= sensitivity;
yaw += xOffset; // useless here
pitch += yOffset;
if (pitch > maxPitch) {
yOffset = 0.0f;
}
if (pitch < -maxPitch) {
yOffset = 0.0f;
}
cameraFront = rotateAroundAxis(cameraFront, -xOffset, cameraUp, cameraPos);
cameraFront = rotateAroundAxis(cameraFront, -yOffset, cameraRight, cameraPos);
cameraUp = rotateAroundAxis(cameraUp, -yOffset, cameraRight, cameraPos);
}
As I said, it works fine for simple up-down, left-right camera movements, but when I start to move my mouse in circles or like a madman, the camera starts to rotate longitudinally (roll).
I've tried to force cameraRight.y = cameraPos.y so that the cameraRight vector doesn't tilt upwards/downwards due to numerical errors but it doesn't solve the problem. I've also tried to add a (global) cameraRight vector to keep track of it instead of computing it every time so the end of the function looks like this :
cameraFront = rotateAroundAxis(cameraFront, -xOffset, cameraUp, cameraPos);
cameraRight = rotateAroundAxis(cameraRight, -xOffset, cameraUp, cameraPos);
cameraFront = rotateAroundAxis(cameraFront, -yOffset, cameraRight, cameraPos);
cameraUp = rotateAroundAxis(cameraUp, -yOffset, cameraRight, cameraPos);
but it doesn't solve the problem. Any pieces of advice ?
It seems you have global X-axis to the right, Y-axis going deep in the screen and Z-axis going up. And you local camera axis system is similar.
The desired behaviour is rotate the camera over its current position, left-right mouse movement is rotation around global Z, and up-dowm mouse movement is rotation around local X. Think a bit around these rotations until you understand them well, and why one is around global but the other around local directions. Imagine a security camera and its movements to visualize the axis systems and rotations.
The goal is getting the parameters used to define the View transformation by lookAtfunction.
First rotate around local X. We convert this local vector into global axis system by inverting the current View-matrix, you call view
glm::vec3 currGlobalX = glm::normalize((glm::inverse(view) * glm::vec4(1.0, 0.0, 0.0, 0.0)).xyz);
We need to rotate not only the cameraUp vector, but also the current target defined in global coordinates, what you call cameraPos + cameraFront:
cameraUp = rotateAroundAxis(cameraUp, -yOffset, currGlobalX, glm::vec3(0.0f, 0.0f, 0.0f)); //vector, not needed to translate
cameraUp = glm::normalize(cameraUp);
currenTarget = rotateAroundAxis(currenTarget, -yOffset, currGlobalX, cameraPos); //point, need translation
Now rotate around global Z-axis
cameraUp = rotateAroundAxis(cameraUp, -xOffset, glm::vec3(0.0f, 0.0f, 1.0f), glm::vec3(0.0f, 0.0f, 0.0f)); //vector, not needed to translate
cameraUp = glm::normalize(cameraUp);
currenTarget = rotateAroundAxis(currenTarget, -xOffset, glm::vec3(0.0f, 0.0f, 1.0f), cameraPos); //point, need translation
Finally, update view:
view = glm::lookAt(cameraPos, currenTarget, cameraUp);
I am trying to convert moving around the xz plane to movement around a sphere. Originally, I had my camera moving forward at a constant speed at a constant height on the y axis. The user can move left/right by adjusting the yaw, however they can not move up/down or roll. Here is how I accomplished that:
float turnRate = 1.0;
float stepDist = 0.1;
if (keys['d']) {
yaw += M_PI * (turnRate / 180.0);
}
if (keys['a']) {
yaw += M_PI * (-turnRate / 180.0);
}
position.x += stepDist * sinf(yaw);
position.z += stepDist * cosf(yaw + M_PI);
...
glm::mat4 P = glm::rotate(pitch, glm::vec3(-1.0, 0.0, 0.0));
glm::mat4 Y = glm::rotate(yaw, glm::vec3(0.0, -1.0, 0.0));
glm::mat4 T = glm::translate(position);
glm::mat4 C = T * Y * P;
This worked well for me. Now what I am trying to achieve is instead of moving across the xz plane, I would like to move across the surface of a sphere. I still want to be moving forward at a constant speed at a constant radius from the center of the sphere with only allowing adjustment of the yaw. This is what I have currently:
float turnRate = 1.0;
float stepDist = 0.01;
step += stepDist;
if (keys['d']) {
yaw += M_PI * (turnRate / 180.0);
}
if (keys['a']) {
yaw += M_PI * (-turnRate / 180.0);
}
pitch = M_PI / 8.0; // angle the camera down towards the sphere a bit
glm::vec3 f = glm::vec3(sinf(yaw), 0.0, cosf(yaw + M_PI));
glm::vec3 up = glm::vec3(0.0, 1.0, 0.0);
glm::vec3 forward = glm::normalize(f);
right = glm::cross(up, forward);
float sphereRadius = 50.0;
float camRadius = sphereRadius + 8.0;
radius = glm::vec3(0.0, camRadius, 0.0);
...
glm::mat4 P = glm::rotate(pitch, glm::vec3(-1.0, 0.0, 0.0));
glm::mat4 Y = glm::rotate(yaw, glm::vec3(0.0, -1.0, 0.0));
glm::mat4 T = glm::translate(radius);
glm::mat4 S = glm::rotate(step, right);
glm::mat4 C = S * T * Y * P;
This works when the camera is simply moving forward. However, the problem is that when the yaw is changing (the user is turning right/left) and the step gets to certain values the sphere will start rotating in the wrong direction underneath the camera. It is not an instant switch. It seems to be reversed when step is between increments of PI to 2PI (i.e. it is reversed between pi and 2pi, 3pi and 4pi, etc..).
Any ideas on how I might fix this or what I am doing wrong?
UPDATE:
Here is a similar example of what I am trying to achieve:
http://www.youtube.com/watch?v=izVtTcq_his&t=0m23s
Except I want to be able to rotate the camera at smaller intervals than 90 degrees. If anyone has any links to example code/tutorials of how to achieve this I would really appreciate it.
Basically, I need to change the eye and up vectors correctly when pressing the left key (turning the view to right). My implementation is as follows but it does not seem to pass the tests. Anyone can help?
// Transforms the camera left around the "crystal ball" interface
void Transform::left(float degrees, vec3& eye, vec3& up) {
// YOUR CODE FOR HW1 HERE
eye = rotate(degrees, vec3(0, 1, 0)) * eye;
up = rotate(degrees, vec3(0, 1, 0)) * up;
}
The rotation function takes two arguments degree and axis, and returns the rotation matrix which is a 3 by 3 matrix:
mat3 Transform::rotate(const float degrees, const vec3& axis) {
// YOUR CODE FOR HW1 HERE
mat3 rot, I(1.0);
mat3 a_x;
a_x[0][0] = 0;
a_x[0][1] = -axis[2];
a_x[0][2] = axis[1];
a_x[1][0] = axis[2];
a_x[1][1] = 0;
a_x[1][2] = -axis[0];
a_x[2][0] = -axis[1];
a_x[2][1] = axis[0];
a_x[2][2] = 0;
float theta = degrees / 180 * pi;
rot = I * cos(theta) + glm::outerProduct(axis, axis) *(1-cos(theta)) + a_x*sin(theta);
return rot;
}
Try if something like this fixes it:
glm::mat3 Transform::rotate(float angle, const glm::vec3& axis) {
glm::mat3 a_x( 0.0f, axis.z, -axis.y,
-axis.z, 0.0f, axis.x,
axis.y, -axis.x, 0.0f);
angle = glm::radians(angle);
return glm::mat3() * cos(angle) + sin(angle) * a_x
+ (1.0f - cos(angle)) * glm::outerProduct(axis, axis);
}
I googled around and find a solution:
// Transforms the camera left around the "crystal ball" interface
void Transform::left(float degrees, vec3& eye, vec3& up) {
// YOUR CODE FOR HW1 HERE
eye = eye * rotate(degrees, up);
}
The rotation function is correct.