fixed nan propogation error
[carveJwlIkooP6JGAAIwe30JlM.git] / camera.h
1 #ifndef CAMERA_H
2 #define CAMERA_H
3
4 #include "common.h"
5
6 typedef struct camera camera;
7
8 struct camera
9 {
10 /* Input */
11 v3f angles;
12 v3f pos;
13 float fov, nearz, farz;
14
15 /* Output */
16 m4x3f transform,
17 transform_inverse;
18
19 struct camera_mtx{
20 m4x4f p,
21 v,
22 pv;
23 }
24 mtx,
25 mtx_prev;
26 }
27 static main_camera, gate_camera;
28
29 VG_STATIC void camera_lerp_angles( v3f a, v3f b, float t, v3f d )
30 {
31 d[0] = vg_alerpf( a[0], b[0], t );
32 d[1] = vg_lerpf( a[1], b[1], t );
33 d[2] = vg_lerpf( a[2], b[2], t );
34 }
35
36 VG_STATIC void camera_lerp( camera *a, camera *b, float t, camera *d )
37 {
38 v3_lerp( a->pos, b->pos, t, d->pos );
39 d->angles[0] = vg_alerpf( a->angles[0], b->angles[0], t );
40 d->angles[1] = vg_lerpf( a->angles[1], b->angles[1], t );
41 d->angles[2] = vg_lerpf( a->angles[2], b->angles[2], t );
42 d->fov = vg_lerpf( a->fov, b->fov, t );
43 }
44
45 /*
46 * 1) [angles, pos] -> transform
47 */
48 VG_STATIC void camera_update_transform( camera *cam )
49 {
50 v4f qyaw, qpitch, qcam;
51 q_axis_angle( qyaw, (v3f){ 0.0f, 1.0f, 0.0f }, -cam->angles[0] );
52 q_axis_angle( qpitch, (v3f){ 1.0f, 0.0f, 0.0f }, -cam->angles[1] );
53
54 q_mul( qyaw, qpitch, qcam );
55 q_m3x3( qcam, cam->transform );
56 v3_copy( cam->pos, cam->transform[3] );
57 }
58
59 /*
60 * 2) [transform] -> transform_inverse, view matrix
61 */
62 VG_STATIC void camera_update_view( camera *cam )
63 {
64 m4x4_copy( cam->mtx.v, cam->mtx_prev.v );
65 m4x3_invert_affine( cam->transform, cam->transform_inverse );
66 m4x3_expand( cam->transform_inverse, cam->mtx.v );
67 }
68
69 /*
70 * 3) [fov,nearz,farz] -> projection matrix
71 */
72 VG_STATIC void camera_update_projection( camera *cam )
73 {
74 m4x4_copy( cam->mtx.p, cam->mtx_prev.p );
75 m4x4_projection( cam->mtx.p, cam->fov,
76 (float)vg.window_x / (float)vg.window_y,
77 cam->nearz, cam->farz );
78 }
79
80 /*
81 * 4) [projection matrix, view matrix] -> previous pv, new pv
82 */
83 VG_STATIC void camera_finalize( camera *cam )
84 {
85 m4x4_copy( cam->mtx.pv, cam->mtx_prev.pv );
86 m4x4_mul( cam->mtx.p, cam->mtx.v, cam->mtx.pv );
87 }
88
89 /*
90 * http://www.terathon.com/lengyel/Lengyel-Oblique.pdf
91 */
92 VG_STATIC void m4x4_clip_projection( m4x4f mat, v4f plane )
93 {
94 v4f c =
95 {
96 (vg_signf(plane[0]) + mat[2][0]) / mat[0][0],
97 (vg_signf(plane[1]) + mat[2][1]) / mat[1][1],
98 -1.0f,
99 (1.0f + mat[2][2]) / mat[3][2]
100 };
101
102 v4_muls( plane, 2.0f / v4_dot(plane,c), c );
103
104 mat[0][2] = c[0];
105 mat[1][2] = c[1];
106 mat[2][2] = c[2] + 1.0f;
107 mat[3][2] = c[3];
108 }
109
110 /*
111 * Undoes the above operation
112 */
113 VG_STATIC void m4x4_reset_clipping( m4x4f mat, float ffar, float fnear )
114 {
115 mat[0][2] = 0.0f;
116 mat[1][2] = 0.0f;
117 mat[2][2] = -(ffar + fnear) / (ffar - fnear);
118 mat[3][2] = -2.0f * ffar * fnear / (ffar - fnear);
119 }
120
121 #endif /* CAMERA_H */