aboutsummaryrefslogtreecommitdiffstats
path: root/camera.c
blob: 0e90e610d5a8176f3f46b6c9513406fc8c2fe9fd (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
/*
 * Copyright (C) 2018 Tomasz Kramkowski <tk@the-tk.com>
 * SPDX-License-Identifier: MIT
 */
#include <assert.h>
#include <math.h>
#include <stdlib.h>

#include "camera.h"
#include "math.h"

#define PITCH_LIMIT (PI * 0.99)

// camera_clamp: clamp camera pitch and normalize yaw
void camera_clamp(struct camera *cam)
{
	assert(cam != NULL);

	cam->yaw = fmod(cam->yaw, 2 * PI);
	if (cam->pitch > PITCH_LIMIT / 2)
		cam->pitch = PITCH_LIMIT / 2;
	else if (cam->pitch < -PITCH_LIMIT / 2)
		cam->pitch = -PITCH_LIMIT / 2;
}

// camera_dir: get the camera facing vector
void camera_dir(vec3 out, struct camera *cam)
{
	assert(out != NULL);
	assert(cam != NULL);

	out[0] = cosf(cam->pitch) * cosf(cam->yaw);
	out[1] = sinf(cam->pitch);
	out[2] = cosf(cam->pitch) * sinf(cam->yaw);
}

// camera_lookat: get the camera view matrix
void camera_lookat(mat4x4 out, struct camera *cam)
{
	vec3 at, dir;

	assert(out != NULL);
	assert(cam != NULL);

	camera_dir(dir, cam);
	vec3_add(at, cam->pos, dir);
	mat4x4_look_at(out, cam->pos, at, (vec3){ 0, 1, 0 });
}