X-Git-Url: https://harrygodden.com/git/?p=vg.git;a=blobdiff_plain;f=vg_camera.h;fp=vg_camera.h;h=9fd660bbd0ac1c133191b3f8685fa1c3b35e62ab;hp=0000000000000000000000000000000000000000;hb=1c305409e8eca9cf8449d681df73208956ce14df;hpb=1abb54856257b10f6a20a4980a31930c59e3d37c diff --git a/vg_camera.h b/vg_camera.h new file mode 100644 index 0000000..9fd660b --- /dev/null +++ b/vg_camera.h @@ -0,0 +1,91 @@ +#pragma once +#include "vg_m.h" + +typedef struct vg_camera vg_camera; +struct vg_camera{ + /* Input */ + v3f angles; + v3f pos; + f32 fov, nearz, farz; + + /* Output */ + m4x3f transform, + transform_inverse; + + struct vg_camera_mtx{ + m4x4f p, + v, + pv; + } + mtx, + mtx_prev; +}; + +static void vg_camera_lerp_angles( v3f a, v3f b, f32 t, v3f d ){ + d[0] = vg_alerpf( a[0], b[0], t ); + d[1] = vg_lerpf( a[1], b[1], t ); + d[2] = vg_lerpf( a[2], b[2], t ); +} + +/* lerp position, fov, and angles */ +static void vg_camera_lerp( vg_camera *a, vg_camera *b, f32 t, vg_camera *d ){ + v3_lerp( a->pos, b->pos, t, d->pos ); + vg_camera_lerp_angles( a->angles, b->angles, t, d->angles ); + d->fov = vg_lerpf( a->fov, b->fov, t ); +} + +static void vg_camera_copy( vg_camera *a, vg_camera *d ){ + v3_copy( a->pos, d->pos ); + v3_copy( a->angles, d->angles ); + d->fov = a->fov; +} + +static void vg_m4x3_transform_camera( m4x3f m, vg_camera *cam ){ + m4x3_mulv( m, cam->pos, cam->pos ); + + v3f v0; + v3_angles_vector( cam->angles, v0 ); + m3x3_mulv( m, v0, v0 ); + v3_normalize( v0 ); + v3_angles( v0, cam->angles ); +} + +/* + * 1) [angles, pos] -> transform + */ +static void vg_camera_update_transform( vg_camera *cam ){ + v4f qyaw, qpitch, qcam; + q_axis_angle( qyaw, (v3f){ 0.0f, 1.0f, 0.0f }, -cam->angles[0] ); + q_axis_angle( qpitch, (v3f){ 1.0f, 0.0f, 0.0f }, -cam->angles[1] ); + + q_mul( qyaw, qpitch, qcam ); + q_m3x3( qcam, cam->transform ); + v3_copy( cam->pos, cam->transform[3] ); +} + +/* + * 2) [transform] -> transform_inverse, view matrix + */ +static void vg_camera_update_view( vg_camera *cam ){ + m4x4_copy( cam->mtx.v, cam->mtx_prev.v ); + m4x3_invert_affine( cam->transform, cam->transform_inverse ); + m4x3_expand( cam->transform_inverse, cam->mtx.v ); +} + +/* + * 3) [fov,nearz,farz] -> projection matrix + */ +static void vg_camera_update_projection( vg_camera *cam ){ + m4x4_copy( cam->mtx.p, cam->mtx_prev.p ); + m4x4_projection( cam->mtx.p, cam->fov, + (float)vg.window_x / (float)vg.window_y, + cam->nearz, cam->farz ); +} + +/* + * 4) [projection matrix, view matrix] -> previous pv, new pv + */ +static void vg_camera_finalize( vg_camera *cam ){ + m4x4_copy( cam->mtx.pv, cam->mtx_prev.pv ); + m4x4_mul( cam->mtx.p, cam->mtx.v, cam->mtx.pv ); +}