-
Notifications
You must be signed in to change notification settings - Fork 0
/
camera.py
94 lines (83 loc) · 2.95 KB
/
camera.py
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
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
import pygame as pg
from matrix_functions import *
class Camera:
def __init__(self, render, position):
self.render = render
self.position = np.array([*position, 1.0])
self.forward = np.array([0, 0, 1, 1])
self.up = np.array([0, 1, 0, 1])
self.right = np.array([1, 0, 0, 1])
self.h_fov = np.pi / 2 - np.pi / 90
self.v_fov = self.h_fov * (render.HEIGHT / render.WIDTH)
self.near_plane = 0.1
self.far_plane = 100
self.moving_speed = 0.5
self.rotation_speed = 0.02
def control(self):
key = pg.key.get_pressed()
if key[pg.K_a]:
self.position -= self.right * self.moving_speed
if key[pg.K_d]:
self.position += self.right * self.moving_speed
if key[pg.K_w]:
self.position += self.forward * self.moving_speed
if key[pg.K_s]:
self.position -= self.forward * self.moving_speed
if key[pg.K_q]:
self.position += self.up * self.moving_speed
if key[pg.K_e]:
self.position -= self.up * self.moving_speed
if key[pg.K_k]:
self.forward = np.array([0, 0, 1, 1])
self.up = np.array([0, 1, 0, 1])
self.right = np.array([1, 0, 0, 1])
"""
When doing a 180 using up, everything except right is multiplied by -1
"""
if key[pg.K_LEFT]:
self.camera_yaw(self.rotation_speed)
if key[pg.K_RIGHT]:
self.camera_yaw(-self.rotation_speed)
if key[pg.K_UP]:
self.camera_pitch(-self.rotation_speed)
if key[pg.K_DOWN]:
self.camera_pitch(self.rotation_speed)
if key[pg.K_8]:
self.camera_roll(self.rotation_speed)
if key[pg.K_9]:
self.camera_roll(-self.rotation_speed)
def camera_yaw(self, theta):
rotate = rotate_y(theta)
self.forward = self.forward @ rotate
self.right = self.right @ rotate
self.up = self.up @ rotate
def camera_pitch(self, theta):
rotate = rotate_x(theta)
self.forward = self.forward @ rotate
self.right = self.right @ rotate
self.up = self.up @ rotate
def camera_roll(self, theta):
rotate = rotate_z(theta)
self.forward = self.forward @ rotate
self.right = self.right @ rotate
self.up = self.up @ rotate
def translate_matrix(self):
x, y, z, w = self.position
return np.array([
[1, 0, 0, 0],
[0, 1, 0, 1],
[0, 0, 1, 0],
[-x, -y, -z, 1]
])
def rotate_matrix(self):
rx, ry, rz, w = self.right
fx, fy, fz, w = self.forward
ux, uy, uz, w = self.up
return np.array([
[rx, ux, fx, 0],
[ry, uy, fy, 0],
[rz, uz, fz, 0],
[0, 0, 0, 1]
])
def camera_matrix(self):
return self.translate_matrix() @ self.rotate_matrix()