85 lines
2.5 KiB
C
85 lines
2.5 KiB
C
#include "camera.h"
|
|
#include "SDL3/SDL_keyboard.h"
|
|
#include "cglm/mat4.h"
|
|
#include "cglm/cam.h"
|
|
#include "cglm/vec3.h"
|
|
#include <SDL3/SDL_mouse.h>
|
|
#include <cglm/util.h>
|
|
#include <math.h>
|
|
|
|
static float mouse_x, mouse_y;
|
|
|
|
Camera Camera_default = {
|
|
.position = {0.0f, 0.0f, 3.0f},
|
|
.forward = {0.0f, 0.0f, -1.0f},
|
|
.yaw = -1.5707963268f, // -90 deg in radians
|
|
.pitch = 0
|
|
};
|
|
|
|
void camera_tick(Camera *camera) {
|
|
// Mouse input
|
|
SDL_GetRelativeMouseState(&mouse_x, &mouse_y);
|
|
camera->yaw += mouse_x * glm_rad(MOUSE_SENSITIVITY);
|
|
camera->pitch -= mouse_y * glm_rad(MOUSE_SENSITIVITY);
|
|
// Restrict pitch
|
|
if (camera->pitch > glm_rad(89.0f))
|
|
camera->pitch = glm_rad(89.0f);
|
|
if (camera->pitch < glm_rad(-89.0f))
|
|
camera->pitch = glm_rad(-89.0f);
|
|
|
|
// Camera Direction
|
|
camera->forward[0] = cosf(camera->yaw) * cosf(camera->pitch);
|
|
camera->forward[1] = sinf(camera->pitch);
|
|
camera->forward[2] = sinf(camera->yaw) * cosf(camera->pitch);
|
|
glm_normalize(camera->forward);
|
|
|
|
vec3 camera_right;
|
|
vec3 up = {0.0f, 1.0f ,0.0f};
|
|
glm_cross(up, camera->forward, camera_right);
|
|
glm_normalize(camera_right);
|
|
|
|
// Move camera based on wasd;
|
|
const bool *keyboardState = SDL_GetKeyboardState(NULL);
|
|
if (keyboardState[SDL_SCANCODE_W]) {
|
|
vec3 calc_buff;
|
|
glm_vec3_scale(camera->forward, MOVEMENT_SPEED, calc_buff);
|
|
glm_vec3_add(camera->position, calc_buff, camera->position);
|
|
}
|
|
if (keyboardState[SDL_SCANCODE_S]) {
|
|
vec3 calc_buff;
|
|
glm_vec3_scale(camera->forward, MOVEMENT_SPEED, calc_buff);
|
|
glm_vec3_sub(camera->position, calc_buff, camera->position);
|
|
}
|
|
if (keyboardState[SDL_SCANCODE_A]) {
|
|
vec3 calc_buff;
|
|
glm_vec3_scale(camera_right, MOVEMENT_SPEED, calc_buff);
|
|
glm_vec3_add(camera->position, calc_buff, camera->position);
|
|
}
|
|
if (keyboardState[SDL_SCANCODE_D]) {
|
|
vec3 calc_buff;
|
|
glm_vec3_scale(camera_right, MOVEMENT_SPEED, calc_buff);
|
|
glm_vec3_sub(camera->position, calc_buff, camera->position);
|
|
}
|
|
}
|
|
|
|
void camera_calc_mvp(mat4 *mvp_result, Camera *camera) {
|
|
// Get position to look and up vector
|
|
vec3 camera_target;
|
|
glm_vec3_add(camera->position , camera->forward, camera_target);
|
|
vec3 up = {0.0f, 1.0f ,0.0f};
|
|
|
|
mat4 model;
|
|
glm_mat4_identity(model);
|
|
|
|
mat4 view;
|
|
glm_lookat(camera->position, camera_target, up, view);
|
|
|
|
mat4 projection;
|
|
float fov = glm_rad(45.0f); // fov y
|
|
float aspect = 800.0f / 600.0f;
|
|
float near = 0.1f;
|
|
float far = 100.0f;
|
|
glm_perspective(fov, aspect, near, far, projection);
|
|
|
|
glm_mat4_mulN((mat4*[]){&projection, &view, &model}, 3, *mvp_result);
|
|
}
|