BlockGame/gl/Camera.cpp
2022-02-06 22:53:29 +01:00

100 lines
2.6 KiB
C++

//
// Created by lukas on 05.02.22.
//
#define GL_GLEXT_PROTOTYPES
#include <valarray>
#include <glm/vec3.hpp>
#include <glm/ext/matrix_transform.hpp>
#include <GL/gl.h>
#include <glm/ext/matrix_clip_space.hpp>
#include "Camera.h"
#include "../blocks/BlockRenderer.h"
void Camera::setPos(double x, double y, double z) {
this->x = x;
this->y = y;
this->z = z;
updateCameraPos();
}
void Camera::setRotation(double rotx, double roty) {
rx = rotx;
ry = roty;
updateCameraPos();
}
void Camera::updateCameraPos() {
// Projection matrix : 45° Field of View, 4:3 ratio, display range : 0.1 unit <-> 100 units
glm::mat4 Projection = glm::perspective(glm::radians(45.0f), (float) width / (float) height, 0.1f, 100.0f);
// Or, for an ortho camera :
//glm::mat4 Projection = glm::ortho(-10.0f,10.0f,-10.0f,10.0f,0.0f,100.0f); // In world coordinates
//
// float rotation = M_PI;
//
// float x = cos(rotation);
// float y = sin(rotation);
const float radius = 5.0f;
double camX = sin(rx) * radius;
double camZ = cos(rx) * radius;
double camY = sin(ry) * radius;
glm::mat4 View = glm::lookAt(
glm::vec3(2.0f, 2.0f, 3.0f), // and looks at the origin
glm::vec3(camX, camZ, camY), // Camera is at (4,3,3), in World Space
glm::vec3(0, 0, 1) // Head is up (set to 0,-1,0 to look upside-down)
);
auto View2 = glm::translate(View, glm::vec3(x, -y, -z));
// Model matrix : an identity matrix (model will be at the origin)
glm::mat4 Model = glm::mat4(1.0f);
// Our ModelViewProjection : multiplication of our 3 matrices
glm::mat4 mvp = Projection * View2 * Model; // Remember, matrix multiplication is the other way around
// todo not really generic if we call blockrenderer here
glUniformMatrix4fv((int) BlockRenderer::getInstance()->getMVPhandle(), 1, GL_FALSE, &mvp[0][0]);
}
Camera::Camera(double width, double height) : width(width), height(height) {}
void Camera::setWindowSize(double width, double height) {
this->width = width;
this->height = height;
}
void Camera::addRotaion(double rotx, double roty) {
rx -= rotx / 300;
ry += roty / 300;
// limit to 2pi
rx = std::fmod(rx, (2 * M_PI));
ry = std::fmod(ry, (2 * M_PI));
ry = fmin(ry, M_PI / 2.0f);
ry = fmax(ry, -M_PI / 2.0f);
updateCameraPos();
}
void Camera::addPos(double x, double y, double z) {
this->x += x;
this->y += y;
this->z += z;
updateCameraPos();
}
double Camera::getxangle() const {
return rx;
}
double Camera::getyangle() const {
return ry;
}