2023-04-01 07:16:14 +08:00
|
|
|
#include "camera.h"
|
2023-04-20 09:19:54 +08:00
|
|
|
#include <stdio.h>
|
2023-04-02 08:21:02 +08:00
|
|
|
|
2023-04-05 03:02:49 +08:00
|
|
|
#include "maths.h"
|
2023-04-01 07:16:14 +08:00
|
|
|
|
2023-04-05 03:02:49 +08:00
|
|
|
#define ROTATION_SPEED PI
|
2023-04-16 09:17:11 +08:00
|
|
|
#define TRANSLATIONAL_SPEED 1.f
|
2023-04-01 07:16:14 +08:00
|
|
|
|
2023-04-02 07:41:32 +08:00
|
|
|
static void move(Camera* camera, float t);
|
2023-04-20 07:28:17 +08:00
|
|
|
static void castRays(Camera* camera);
|
|
|
|
|
|
|
|
int camera_init(Camera* camera, sf::Vector2f pos, float direction, unsigned int resolution, float fov)
|
|
|
|
{
|
|
|
|
camera->pos = pos;
|
|
|
|
camera->direction = direction;
|
|
|
|
camera->resolution = resolution;
|
|
|
|
camera->fov = fov;
|
|
|
|
|
|
|
|
camera->rays = (CameraRay*)malloc(sizeof(CameraRay)*resolution);
|
|
|
|
return 1;
|
|
|
|
}
|
2023-04-01 07:16:14 +08:00
|
|
|
|
2023-04-16 09:17:11 +08:00
|
|
|
void camera_update(Camera* camera, float t)
|
2023-04-01 07:16:14 +08:00
|
|
|
{
|
2023-04-16 09:17:11 +08:00
|
|
|
if (!camera) return;
|
2023-04-02 07:41:32 +08:00
|
|
|
move(camera, t);
|
2023-04-20 07:28:17 +08:00
|
|
|
castRays(camera);
|
2023-04-02 07:41:32 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
static void move(Camera* camera, float t)
|
|
|
|
{
|
|
|
|
int forward = 0;
|
|
|
|
int rotation = 0;
|
|
|
|
if (sf::Keyboard::isKeyPressed(sf::Keyboard::F))
|
|
|
|
forward += 1;
|
|
|
|
if (sf::Keyboard::isKeyPressed(sf::Keyboard::S))
|
|
|
|
forward -= 1;
|
|
|
|
if (sf::Keyboard::isKeyPressed(sf::Keyboard::T))
|
|
|
|
rotation +=1;
|
|
|
|
if (sf::Keyboard::isKeyPressed(sf::Keyboard::R))
|
|
|
|
rotation -=1;
|
|
|
|
|
|
|
|
float magnitude = forward * t * TRANSLATIONAL_SPEED;
|
2023-04-20 07:28:17 +08:00
|
|
|
sf::Vector2f offset(magnitude * cos(camera->direction), magnitude * sin(camera->direction));
|
2023-04-02 07:41:32 +08:00
|
|
|
|
|
|
|
camera->pos += offset;
|
|
|
|
camera->direction += rotation * t * ROTATION_SPEED;
|
|
|
|
}
|
2023-04-20 07:28:17 +08:00
|
|
|
|
|
|
|
void camera_destroy(Camera *camera)
|
|
|
|
{
|
|
|
|
free(camera->rays);
|
|
|
|
}
|
|
|
|
|
|
|
|
static void castRays(Camera* camera)
|
|
|
|
{
|
|
|
|
float rayDirectionStep = camera->fov / (float)camera->resolution;
|
2023-04-20 09:19:54 +08:00
|
|
|
float rayDirection = camera->direction - camera->fov/2.f + rayDirectionStep/2.f;
|
2023-04-20 07:28:17 +08:00
|
|
|
for (unsigned int i = 0; i < camera->resolution; i++) {
|
|
|
|
camera->rays[i].direction = rayDirection;
|
2023-05-01 07:10:01 +08:00
|
|
|
camera->rays[i].distance = level_rayCast(camera->pos, rayDirection, &camera->rays[i].tileData);
|
2023-04-20 07:28:17 +08:00
|
|
|
|
2023-04-20 09:19:54 +08:00
|
|
|
rayDirection += rayDirectionStep;
|
2023-04-20 07:28:17 +08:00
|
|
|
}
|
|
|
|
}
|