foot alignment
[carveJwlIkooP6JGAAIwe30JlM.git] / main.c
diff --git a/main.c b/main.c
index 8a812289e010d81301a5ce25ec26ef3de5417187..61f0a584dd137bff175213a381b34a64d648c5b4 100644 (file)
--- a/main.c
+++ b/main.c
@@ -1,4 +1,5 @@
 #define VG_3D
+#define VG_FRAMEBUFFER_RESIZE 1
 #include "vg/vg.h"
 
 /* Resources */
@@ -7,24 +8,65 @@ vg_tex2d tex_grid = { .path = "textures/grid.qoi" };
 vg_tex2d tex_sky = { .path = "textures/sky.qoi" };
 vg_tex2d tex_gradients = { .path = "textures/gradients.qoi",
                            .flags = VG_TEXTURE_CLAMP };
+vg_tex2d tex_cement = { .path = "textures/cement512.qoi" };
+vg_tex2d tex_pallet = { .path = "textures/ch_gradient.qoi" };
+
 vg_tex2d *texture_list[] =
 {
    &tex_norwey,
    &tex_gradients,
    &tex_grid,
-   &tex_sky
+   &tex_sky,
+   &tex_cement,
+   &tex_pallet
 };
 
+SHADER_DEFINE( shader_blit,
+   "layout (location=0) in vec2 a_co;"
+   "out vec2 aUv;"
+   ""
+       "void main()"
+       "{"
+               "gl_Position = vec4(a_co*2.0-1.0,0.0,1.0);"
+      "aUv = a_co;"
+       "}",
+
+   /* Fragment */
+       "out vec4 FragColor;"
+       ""
+   "uniform sampler2D uTexMain;"
+   ""
+   "in vec2 aUv;"
+   ""
+       "void main()"
+       "{"
+      "FragColor = texture( uTexMain, aUv );"
+       "}"
+       ,
+       UNIFORMS({ "uTexMain" })
+)
+
 /* Convars */
 static int freecam = 0;
 static int debugview = 0;
 static int debugsdf = 0;
 static int sv_debugcam = 0;
+static int sv_phys = 0;
+static int thirdperson = 0;
+static int clock_divider = 1;
+static int replay_record = 0;
+
+static m4x3f *replay_buffer = NULL;
+static int replay_buffer_frame = 0;
+
+#define REPLAY_LENGTH 120*60
 
 /* Components */
 #include "road.h"
 #include "scene.h"
 #include "ik.h"
+#include "character.h"
+#include "terrain.h"
 
 int main( int argc, char *argv[] )
 { 
@@ -35,48 +77,62 @@ m4x3f world_matrix;
 
 static struct gplayer
 {
+   /* Physics */
    v3f co, v, a;
    v4f rot;
-   float vswitch, slip_last;
+   float vswitch, slip, slip_last,
+         reverse;
+
+   float iY;   /* Yaw inertia */
+   int in_air;
+
+   /* Input */
+   v2f joy_l;
 
    v3f view;
    v2f look_dir;  /* TEMP */
+   v2f board_xy;
+   float grab;
+   float pitch;
 
-   m4x3f to_world, to_local;
+   v3f land_target;
+   v3f land_target_log[12];
+   int land_log_count;
+   m3x3f vr;
 
-   glmesh mesh;
+   m4x3f to_world, to_local;
    
-   submodel legl,
-            legu,
-            board,
-            torso,
-            wheels;
+   struct character mdl;
+
+   v3f handl_target, handr_target,
+       handl, handr;
 }
 player;
 
 static struct gworld
 {
-   glmesh skydome;
-   
-   scene foliage,    /* Tree shader */
-         geo,        /* Std shader, collisions */
-         detail;     /* Std shader, no collisions */
-
+   scene geo;
    submodel terrain,
             terrain_rocks,
             terrain_road;
 }
 world;
 
+static struct grender
+{
+   GLuint fb_background,
+          rgb_background;
+
+   glmesh fsquad;
+}
+render;
+
 static void player_transform_update(void)
 {
    q_m3x3( player.rot, player.to_world );
    v3_copy( player.co, player.to_world[3] );
 
-   v4f inv;
-   q_inv( player.rot, inv );
-   q_m3x3( inv, player.to_local );
-   v3_negate( player.co, player.to_local[3] );
+   m4x3_invert_affine( player.to_world, player.to_local );
 }
 
 static int reset_player( int argc, char const *argv[] )
@@ -91,15 +147,47 @@ static int reset_player( int argc, char const *argv[] )
    return 0;
 }
 
+static int playermodel( int argc, char const *argv[] )
+{
+   if( argc < 1 ) return 0;
+   
+   glmesh old_mesh = player.mdl.mesh;
+
+   if( character_load( &player.mdl, argv[0] ) )
+      mesh_free( &old_mesh );
+
+   return 1;
+}
+
 void vg_register(void)
 {
    scene_register();
+   character_shader_register();
+   SHADER_INIT( shader_blit );
 }
 
 void vg_start(void)
 {
+   replay_buffer = malloc( sizeof(m4x3f) * REPLAY_LENGTH * (PART_COUNT) );
+
    vg_tex2d_init( texture_list, vg_list_size( texture_list ) );
    
+   vg_convar_push( (struct vg_convar){
+      .name = "frame",
+      .data = &replay_buffer_frame,
+      .data_type = k_convar_dtype_i32,
+      .opt_i32 = { .min=0, .max=REPLAY_LENGTH-1, .clamp=1 },
+      .persistent = 0
+   });
+
+   vg_convar_push( (struct vg_convar){
+      .name = "rec",
+      .data = &replay_record,
+      .data_type = k_convar_dtype_i32,
+      .opt_i32 = { .min=0, .max=1, .clamp=1 },
+      .persistent = 0
+   });
+
    vg_convar_push( (struct vg_convar){
       .name = "freecam",
       .data = &freecam,
@@ -132,6 +220,30 @@ void vg_start(void)
       .persistent = 1
    });
 
+   vg_convar_push( (struct vg_convar){
+      .name = "phys",
+      .data = &sv_phys,
+      .data_type = k_convar_dtype_i32,
+      .opt_i32 = { .min=0, .max=1, .clamp=1 },
+      .persistent = 1
+   });
+
+   vg_convar_push( (struct vg_convar){
+      .name = "thirdperson",
+      .data = &thirdperson,
+      .data_type = k_convar_dtype_i32,
+      .opt_i32 = { .min=0, .max=1, .clamp=1 },
+      .persistent = 1
+   });
+
+   vg_convar_push( (struct vg_convar){
+      .name = "div",
+      .data = &clock_divider,
+      .data_type = k_convar_dtype_i32,
+      .opt_i32 = { .min=0, .max=1, .clamp=0 },
+      .persistent = 1
+   });
+
        vg_function_push( (struct vg_cmd){
                .name = "reset",
                .function = reset_player
@@ -139,271 +251,254 @@ void vg_start(void)
    
    v3f lightDir = { 0.1f, 0.8f, 0.2f };
    v3_normalize( lightDir );
-   
-   /* Unpack player */
-   model *char_dev = vg_asset_read( "models/char_dev.mdl" );
-   model_unpack( char_dev, &player.mesh );
-   player.legl = *submodel_get( char_dev, "legl" );
-   player.legu = *submodel_get( char_dev, "legu" );
-   player.board = *submodel_get( char_dev, "skateboard" );
-   player.torso = *submodel_get( char_dev, "torso" );
-   player.wheels = *submodel_get( char_dev, "wheels" );
-   free(char_dev);
+
+   character_load( &player.mdl, "ch_default" );
    
    /* Setup scene */
    scene_init( &world.geo );
-   scene_init( &world.detail );
-   scene_init( &world.foliage );
-   
-   model *mworld = vg_asset_read( "models/free_dev.mdl" );
-   model *mtest = vg_asset_read( "models/test.mdl" );
-
-   model *msky = vg_asset_read( "models/skydome.mdl" );
-   model_unpack( msky, &world.skydome );
-   free( msky );
-   
-   scene_add_model( &world.geo, mworld, submodel_get( mworld, "terrain" ),
-         (v3f){0.0f,0.0f,0.0f}, 0.0f, 1.0f );
-   scene_copy_slice( &world.geo, &world.terrain );
+   model *mworld = vg_asset_read( "models/mp_dev.mdl" );
 
-   scene_add_model( &world.geo, mworld, submodel_get( mworld, "terrain_rocks" ),
+   scene_add_model( &world.geo, mworld, submodel_get( mworld, "mp_dev" ),
          (v3f){0.0f,0.0f,0.0f}, 0.0f, 1.0f );
-   scene_copy_slice( &world.geo, &world.terrain_rocks );
-   
-   submodel *ptree = submodel_get( mtest, "tree" ),
-            *pt_groundcover[] = 
-       {
-         submodel_get( mtest, "bush" ),
-         submodel_get( mtest, "bush" ),
-         submodel_get( mtest, "blubber" ),
-       };
-
-   /* Sprinkle some trees in the terrain areas */
-   v3f range;
-   v3_sub( world.geo.bbx[1], world.geo.bbx[0], range );
-   
-#ifdef VG_RELEASE
-   int const ktree_count = 8000,
-             kfoliage_count = 200000;
-#else
-   int const ktree_count = 200,
-             kfoliage_count = 0;
-#endif
-
-   for( int i=0; i<ktree_count; i++ )
-   {
-      v3f pos = { vg_randf(), 0.0f, vg_randf() }, 
-          norm;
-      
-      v3_muladd( world.geo.bbx[0], pos, range, pos );
-      
-      if( sample_scene_height( &world.geo, pos, norm ) )
-      {
-         if( v3_dot( norm, (v3f){ 0.0f, 1.0f, 0.0f } ) > 0.9f )
-         {
-            scene_add_model( &world.foliage, mtest, ptree,
-                  pos, vg_randf() * VG_TAUf, vg_randf() * 0.5f + 0.5f );
-         }
-      }
-   }
 
-   for( int i=0; i<kfoliage_count; i++ )
-   {
-      v3f pos = { vg_randf(), 0.0f, vg_randf() }, 
-          norm;
+   free( mworld );
+   scene_upload( &world.geo );
+   bvh_create( &world.geo );
 
-      v3_muladd( world.geo.bbx[0], pos, range, pos );
-      
-      if( sample_scene_height( &world.geo, pos, norm ) )
-      {
-         if( v3_dot( norm, (v3f){ 0.0f, 1.0f, 0.0f } ) > 0.7f )
-         {
-            scene_add_model( &world.foliage, mtest, 
-                  pt_groundcover[rand()%vg_list_size(pt_groundcover)],
-                  pos, vg_randf() * VG_TAUf, vg_randf() * 0.5f + 0.5f );
-         }
-      }
-   }
 
-   scene_add_model( &world.geo, mworld, submodel_get( mworld, "road" ),
-         (v3f){0.0f,0.0f,0.0f}, 0.0f, 1.0f );
-   scene_copy_slice( &world.geo, &world.terrain_road );
+   reset_player( 0, NULL );
+   player_transform_update();
 
-   scene_add_model( &world.detail, mworld, submodel_get( mworld, "art" ),
-         (v3f){0.0f,0.0f,0.0f}, 0.0f, 1.0f );
+   /* Create framebuffers */
+   glGenFramebuffers( 1, &render.fb_background );
+   glBindFramebuffer( GL_FRAMEBUFFER, render.fb_background );
 
-   free( mtest );
-   free( mworld );
+   glGenTextures( 1, &render.rgb_background );
+   glBindTexture( GL_TEXTURE_2D, render.rgb_background );
+   glTexImage2D( GL_TEXTURE_2D, 0, GL_RGB, vg_window_x, vg_window_y, 
+         0, GL_RGB, GL_UNSIGNED_BYTE, NULL);
 
-   scene_compute_occlusion( &world.foliage );
+   glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR );
+   glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR );
+   glFramebufferTexture2D( GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, 
+         GL_TEXTURE_2D, 
+         render.rgb_background, 0);
 
-   scene_upload( &world.foliage );
-   scene_upload( &world.geo );
-   scene_upload( &world.detail );
-   
-   reset_player( 0, NULL );
-   player_transform_update();
+   {
+      float quad[] = { 0.0f, 0.0f, 1.0f, 1.0f, 0.0f, 1.0f,
+                       0.0f, 0.0f, 1.0f, 0.0f, 1.0f, 1.0f };
+
+      glGenVertexArrays( 1, &render.fsquad.vao );
+      glGenBuffers( 1, &render.fsquad.vbo );
+      glGenBuffers( 1, &render.fsquad.ebo );
+      glBindVertexArray( render.fsquad.vao );
+      glBindBuffer( GL_ARRAY_BUFFER, render.fsquad.vbo );
+      glBufferData( GL_ARRAY_BUFFER, sizeof(quad), quad, GL_STATIC_DRAW );
+      glBindVertexArray( render.fsquad.vao );
+      glVertexAttribPointer( 0, 2, GL_FLOAT, GL_FALSE, 
+            sizeof(float)*2, (void*)0 );
+      glEnableVertexAttribArray( 0 );
+      VG_CHECK_GL();
+   }
 }
 
-v3f head;
+static float ktimestep = 1.0f/60.0f;
 
-void vg_update(void)
+static void player_freecam(void)
 {
-   float timestep = 1.0f/60.0f;
+   m4x3f cam_rot;
+   m4x3_identity( cam_rot );
+   m4x3_rotate_y( cam_rot, -player.look_dir[0] );
+   m4x3_rotate_x( cam_rot, -player.look_dir[1] );
 
-   if( freecam )
-   {
-      m4x3f cam_rot;
-      m4x3_identity( cam_rot );
-      m4x3_rotate_y( cam_rot, -player.look_dir[0] );
-      m4x3_rotate_x( cam_rot, -player.look_dir[1] );
+   v3f lookdir = { 0.0f, 0.0f, -1.0f },
+       sidedir = { 1.0f, 0.0f,  0.0f };
+   
+   m4x3_mulv( cam_rot, lookdir, lookdir );
+   m4x3_mulv( cam_rot, sidedir, sidedir );
+   
+   float movespeed = 5.0f;
+   static v2f mouse_last,
+              view_vel = { 0.0f, 0.0f };
 
-      v3f lookdir = { 0.0f, 0.0f, -1.0f },
-          sidedir = { 1.0f, 0.0f,  0.0f };
-      
-      m4x3_mulv( cam_rot, lookdir, lookdir );
-      m4x3_mulv( cam_rot, sidedir, sidedir );
-      
-      float movespeed = 5.0f;
-      static v2f mouse_last,
-                 view_vel = { 0.0f, 0.0f };
-      static v3f move_vel = { 0.0f, 0.0f, 0.0f };
+   static v3f move_vel = { 0.0f, 0.0f, 0.0f };
 
-      if( vg_get_button_down( "primary" ) )
-      {
-         v2_copy( vg_mouse, mouse_last );
-      }
-      else if( vg_get_button( "primary" ) )
-      {
-         v2f delta;
-         v2_sub( vg_mouse, mouse_last, delta );
-         v2_copy( vg_mouse, mouse_last );
+   if( vg_get_button_down( "primary" ) )
+      v2_copy( vg_mouse, mouse_last );
+   else if( vg_get_button( "primary" ) )
+   {
+      v2f delta;
+      v2_sub( vg_mouse, mouse_last, delta );
+      v2_copy( vg_mouse, mouse_last );
 
-         v2_muladds( view_vel, delta, 0.005f, view_vel );
-      }
-      
-      v2_muls( view_vel, 0.75f, view_vel );
-      v2_add( view_vel, player.look_dir, player.look_dir );
-      player.look_dir[1] = 
-         vg_clampf( player.look_dir[1], -VG_PIf*0.5f, VG_PIf*0.5f );
-
-      if( vg_get_button( "forward" ) )
-         v3_muladds( move_vel, lookdir, timestep * movespeed, move_vel );
-      if( vg_get_button( "back" ) )
-         v3_muladds( move_vel, lookdir, timestep *-movespeed, move_vel );
-      if( vg_get_button( "left" ) )
-         v3_muladds( move_vel, sidedir, timestep *-movespeed, move_vel );
-      if( vg_get_button( "right" ) )
-         v3_muladds( move_vel, sidedir, timestep * movespeed, move_vel );
-
-      v3_muls( move_vel, 0.75f, move_vel );
-      v3_add( move_vel, player.view, player.view );
+      v2_muladds( view_vel, delta, 0.005f, view_vel );
    }
    
+   v2_muls( view_vel, 0.75f, view_vel );
+   v2_add( view_vel, player.look_dir, player.look_dir );
+   player.look_dir[1] = 
+      vg_clampf( player.look_dir[1], -VG_PIf*0.5f, VG_PIf*0.5f );
 
-   static int in_air = 1;
+   if( vg_get_button( "forward" ) )
+      v3_muladds( move_vel, lookdir, ktimestep * movespeed, move_vel );
+   if( vg_get_button( "back" ) )
+      v3_muladds( move_vel, lookdir, ktimestep *-movespeed, move_vel );
+   if( vg_get_button( "left" ) )
+      v3_muladds( move_vel, sidedir, ktimestep *-movespeed, move_vel );
+   if( vg_get_button( "right" ) )
+      v3_muladds( move_vel, sidedir, ktimestep * movespeed, move_vel );
+
+   v3_muls( move_vel, 0.75f, move_vel );
+   v3_add( move_vel, player.view, player.view );
+}
 
-   v3f ground_pos, ground_norm;
-   v3_copy( player.co, ground_pos );
+static void apply_gravity( v3f vel, float const timestep )
+{
+   v3f gravity = { 0.0f, -9.6f, 0.0f };
+   v3_muladds( vel, gravity, timestep, vel );
+}
 
-   if( sample_scene_height( &world.geo, ground_pos, ground_norm ) )
-   {
-#if 0
-      v3f localup;
-      m3x3_mulv( player.to_world, (v3f){0.0f,1.0f,0.0f}, localup );
-      v3_normalize(localup);
-      v3_normalize(ground_norm);
+static void player_start_air(void)
+{
+   player.in_air = 1;
 
-      float angle = v3_dot( localup, ground_norm );
-      v3f axis; 
-      v3_cross( localup, ground_norm, axis );
+   float pstep = ktimestep*10.0f;
 
-      if( angle < 0.999f && !in_air )
-      {
-         v4f correction;
-         q_axis_angle( correction, axis, acosf(angle) );
-         q_mul( correction, player.rot, player.rot );
-      }
-#endif
-   }
+   float best_velocity_mod = 0.0f,
+         best_velocity_delta = -9999.9f;
+
+   v3f axis, vup;
+   m3x3_mulv( player.to_world, (v3f){0.0f,1.0f,0.0f}, vup );
+   v3_cross( vup, player.v, axis );
+   v3_normalize( axis );
+   player.land_log_count = 0;
    
-   if( freecam )
-      return;
+   m3x3_identity( player.vr );
 
-   if( in_air )
+   for( int m=0;m<=5; m++ )
    {
-      v3f pco, pco1, pv;
-      
-      float pstep = timestep*10.0f;
+      float vmod = ((float)m / 5.0f)*0.09f;
 
-      v3f gravity = { 0.0f, -9.6f, 0.0f };
+      v3f pco, pco1, pv;
       v3_copy( player.co, pco );
       v3_copy( player.v, pv );
 
-      v3f targetn;
+      /* 
+       * Try different 'rotations' of the velocity to find the best possible
+       * landing normal. This conserves magnitude at the expense of slightly
+       * unrealistic results
+       */
 
-      for( int i=0; i<20; i++ )
+      m3x3f vr;
+      v4f vr_q;
+
+      q_axis_angle( vr_q, axis, vmod );
+      q_m3x3( vr_q, vr );
+
+      for( int i=0; i<50; i++ )
       {
          v3_copy( pco, pco1 );
-         v3_muladds( pv, gravity, pstep, pv );
-         v3_muladds( pco, pv, pstep, pco );
+         apply_gravity( pv, pstep );
 
-         vg_line( pco, pco1, i&0x1?0xff000000:0xffffffff );
+         m3x3_mulv( vr, pv, pv );
+         v3_muladds( pco, pv, pstep, pco );
          
-         v3f sh;
-         v3_copy( pco, sh );
-         sample_scene_height( &world.geo, sh, targetn );
+         ray_hit contact;
+         v3f vdir;
 
-         if( sh[1] >= pco[1] )
-         {
-            v3f localup;
-            m3x3_mulv( player.to_world, (v3f){0.0f,1.0f,0.0f}, localup );
+         v3_sub( pco, pco1, vdir );
+         contact.dist = v3_length( vdir );
+         v3_divs( vdir, contact.dist, vdir);
 
-            float angle = v3_dot( localup, targetn );
-            v3f axis; 
-            v3_cross( localup, targetn, axis );
+         if( bvh_raycast( &world.geo, pco1, vdir, &contact ))
+         {
+            float land_delta = v3_dot( pv, contact.normal );
 
-            if( angle < 0.99f )
+            if( (land_delta < 0.0f) && (land_delta > best_velocity_delta) )
             {
-               v4f correction;
-               q_axis_angle( correction, axis, acosf(angle)*0.1f );
-               q_mul( correction, player.rot, player.rot );
+               best_velocity_delta = land_delta;
+               best_velocity_mod = vmod;
+
+               v3_copy( contact.pos, player.land_target );
+
+               q_axis_angle( vr_q, axis, vmod*0.1f );
+               q_m3x3( vr_q, player.vr );
             }
 
+            v3_copy( contact.pos, 
+                  player.land_target_log[player.land_log_count ++] );
             break;
          }
       }
+   }
 
-      if( ground_pos[1] > player.co[1] )
+   //v3_rotate( player.v, best_velocity_mod, axis, player.v );
+   
+   return;
+   v3_muls( player.v, best_velocity_mod, player.v );
+}
+
+static int sample_if_resistant( v3f pos )
+{
+   v3f ground, norm;
+   v3_copy( pos, ground );
+
+   if( bvh_scene_sample( &world.geo, ground, norm ) )
+   {
+      v3f angle;
+      v3_copy( player.v, angle );
+      v3_normalize( angle );
+      float resistance = v3_dot( norm, angle );
+
+      if( resistance < 0.25f )
       {
-         in_air = 0;
+         v3_copy( ground, pos );
+         return 1;
       }
    }
 
-   if( vg_get_button( "forward" ) )
-   {
-      v3f dir = { 0.0f, 0.0f, -1.0f };
+   return 0;
+}
 
-      m3x3_mulv( player.to_world, dir, dir );
-      v3_muladds( player.v, dir, 5.0f * timestep, player.v );
-   }
+static float stable_force( float current, float diff )
+{
+   float new = current + diff;
 
-   /* Get front and back contact points */
+   if( new * current < 0.0f )
+      return 0.0f;
 
-   v3f contact_front, contact_back, fwd, fwd1, contact_norm, vup, vside;
-   v3f axis;
+   return new;
+}
 
-   m3x3_mulv( player.to_world, (v3f){0.0f,0.0f,-1.0f}, fwd );
-   m4x3_mulv( player.to_world, (v3f){ 0.15f,0.0f,-1.0f}, contact_norm );
-   m4x3_mulv( player.to_world, (v3f){-0.15f,0.0f,-1.0f}, contact_front );
-   m4x3_mulv( player.to_world, (v3f){ 0.00f,0.0f, 1.0f}, contact_back );
-   m3x3_mulv( player.to_world, (v3f){0.0f,1.0f,0.0f}, vup );
-   m3x3_mulv( player.to_world, (v3f){1.0f,0.0f,0.0f}, vside );
+static void player_physics_ground(void)
+{
+   /* 
+    * Getting surface collision points,
+    * the contact manifold is a triangle for simplicity.
+    */
+   v3f contact_front, contact_back, fwd, fwd1, contact_norm, vup, vside,
+       axis;
+   
+   float klength = 0.65f;
+   m3x3_mulv( player.to_world, (v3f){ 0.0f, 0.0f,-1.0f}, fwd );
+   m4x3_mulv( player.to_world, (v3f){ 0.15f,0.0f,-klength}, contact_norm );
+   m4x3_mulv( player.to_world, (v3f){-0.15f,0.0f,-klength}, contact_front );
+   m4x3_mulv( player.to_world, (v3f){ 0.00f,0.0f, klength}, contact_back );
+   m3x3_mulv( player.to_world, (v3f){ 0.0f, 1.0f, 0.0f}, vup );
+   m3x3_mulv( player.to_world, (v3f){ 1.0f, 0.0f, 0.0f}, vside );
+
+   v3f cn0, cn1, cn2;
+   
+   int contact_count = 
+      sample_if_resistant( contact_front ) +
+      sample_if_resistant( contact_back ) +
+      sample_if_resistant( contact_norm );
    
-   int all_contacting = 
-      sample_scene_height( &world.geo, contact_front, NULL ) &&
-      sample_scene_height( &world.geo, contact_back, NULL ) &&
-      sample_scene_height( &world.geo, contact_norm, NULL );
+   if( contact_count < 3 )
+   {
+      player_start_air();
+      return;
+   }
 
    v3f norm;
    v3f v0, v1;
@@ -419,99 +514,236 @@ void vg_update(void)
    float angle = v3_dot( vup, norm );
    v3_cross( vup, norm, axis );
 
-   if( angle < 0.999f && !in_air )
+   if( angle < 0.999f )
    {
       v4f correction;
       q_axis_angle( correction, axis, acosf(angle) );
       q_mul( correction, player.rot, player.rot );
    }
 
+   float resistance = v3_dot( norm, player.v );
 
-   v3f gravity = { 0.0f, -9.6f, 0.0f };
-   v3_muladds( player.v, gravity, timestep, player.v );
-
-   if( !in_air )
+   if( resistance >= 0.0f )
    {
-      float resistance = v3_dot( norm, player.v );
-
-      if( resistance >= 0.0f )
-         in_air = 1;
-      else
-      {
-         v3_muladds( player.v, norm, -resistance, player.v );
-      }
+      player_start_air();
+      return;
+   }
+   else
+   {
+      v3_muladds( player.v, norm, -resistance, player.v );
    }
-
-   /* vg_info( "%.3f | %.3f\n", player.v[1], resistance ); */
-   v3_muladds( player.co, player.v, timestep, player.co );
    
+   /* This is where velocity integration used to be */
+
    float slip = 0.0f;
-   float yawamt = 0.0f;
 
-   if( !in_air )
+   player.co[1] = (contact_front[1]+contact_back[1])*0.5f;
+
+   v3f vel;
+   m3x3_mulv( player.to_local, player.v, vel );
+
+   /* Calculate local forces */
+
+   slip = fabsf(-vel[0] / vel[2]) * vg_signf(vel[0]);
+   if( fabsf( slip ) > 1.2f )
+      slip = vg_signf( slip ) * 1.2f;
+   player.slip = slip;
+   player.reverse = -vg_signf(vel[2]);
+
+   float substep = ktimestep * 0.2f;
+   for( int i=0; i<5; i++ )
    {
-      player.co[1] = (contact_front[1]+contact_back[1])*0.5f;
+      vel[2] = stable_force( vel[2], vg_signf( vel[2] ) * -0.02f*substep );
+      vel[0] = stable_force( vel[0], vg_signf( vel[0] ) * -7.0f *substep );
+   }
+   
+   m3x3_mulv( player.to_world, vel, player.v );
+
+   if( vg_get_button( "yawl" ) )
+      player.iY +=  3.6f * ktimestep;
+   if( vg_get_button( "yawr" ) )
+      player.iY -=  3.6f * ktimestep;
+   
+   float steer = vg_get_axis( "horizontal" );
+   player.iY -= vg_signf(steer)*powf(steer,2.0f) * 1.5f * ktimestep;
+   
+   /* Too much lean and it starts to look like a snowboard here */
+   v2_lerp( player.board_xy, (v2f){ slip*0.25f, 0.0f }, 
+         ktimestep*5.0f, player.board_xy);
+}
 
-      v3f vel;
-      m3x3_mulv( player.to_local, player.v, vel );
+static void draw_cross(v3f pos,u32 colour)
+{
+   v3f p0, p1;
+   v3_add( (v3f){ 1.0f,0.0f,0.0f}, pos, p0 );
+   v3_add( (v3f){-1.0f,0.0f,0.0f}, pos, p1 );
+   vg_line( p0, p1, colour );
+   v3_add( (v3f){0.0f, 1.0f,0.0f}, pos, p0 );
+   v3_add( (v3f){0.0f,-1.0f,0.0f}, pos, p1 );
+   vg_line( p0, p1, colour );
+   v3_add( (v3f){0.0f,0.0f, 1.0f}, pos, p0 );
+   v3_add( (v3f){0.0f,0.0f,-1.0f}, pos, p1 );
+   vg_line( p0, p1, colour );
+}
 
-      /* Calculate local forces */
+static void player_physics_air(void)
+{
+   /* Debug prediciton */
 
-      slip = (-vel[0] / vel[2]) * player.vswitch;
-      if( fabsf( slip ) > 1.2f )
-         slip = vg_signf( slip ) * 1.2f;
+   m3x3_mulv( player.vr, player.v, player.v );
+   for( int i=0; i<player.land_log_count; i++ )
+      draw_cross( player.land_target_log[i], 0xff00ffff );
 
-      
-      if( player.slip_last*slip < 0.0f && fabsf(slip) > 0.7f )
+   draw_cross( player.land_target, 0xff0000ff );
+
+   v3f ground_pos, ground_norm;
+   v3_copy( player.co, ground_pos );
+
+   if( bvh_scene_sample( &world.geo, ground_pos, ground_norm ) )
+   {
+      if( ground_pos[1] > player.co[1] )
       {
-         vg_warn( "SWITCH\n" );
-         player.vswitch = -player.vswitch;
-         slip = -slip;
+         player.in_air = 0;
+         return;
       }
+   }
+   
+   /* Prediction 
+    *
+    * TODO: Find best landing surface and guide player towords it
+    */
+   float pstep = ktimestep*10.0f;
 
-      player.slip_last = slip;
+   v3f pco, pco1, pv;
+   v3_copy( player.co, pco );
+   v3_copy( player.v, pv );
 
-      float substep = timestep * 0.2f;
+   for( int i=0; i<50; i++ )
+   {
+      v3_copy( pco, pco1 );
+      apply_gravity( pv, pstep );
+      v3_muladds( pco, pv, pstep, pco );
+
+      //vg_line( pco, pco1, i&0x1?0xff000000:0xffffffff );
       
-      for( int i=0; i<5; i++ )
+      ray_hit contact;
+      v3f vdir;
+
+      v3_sub( pco, pco1, vdir );
+      contact.dist = v3_length( vdir );
+      v3_divs( vdir, contact.dist, vdir);
+
+      if( bvh_raycast( &world.geo, pco1, vdir, &contact ))
       {
-         if( fabsf(vel[2]) >= 0.02f*substep )
-            vel[2] += vg_signf( vel[2] ) * -0.02f * substep;
-         if( fabsf(vel[0]) >= 6.0f*substep )
-            vel[0] += vg_signf( vel[0] ) * -6.0f * substep;
-      }
-      
-      m3x3_mulv( player.to_world, vel, player.v );
+         v3f localup;
+         m3x3_mulv( player.to_world, (v3f){0.0f,1.0f,0.0f}, localup );
 
-      if( vg_get_button( "yawl" ) )
-         yawamt =  1.6f * timestep;
-      if( vg_get_button( "yawr" ) )
-         yawamt = -1.6f * timestep;
-      
-      yawamt -= vg_get_axis( "horizontal" ) * 1.6f * timestep;
+         float angle = v3_dot( localup, contact.normal );
+         v3f axis; 
+         v3_cross( localup, contact.normal, axis );
+         
+         if( angle < 0.99f )
+         {
+            v4f correction;
+            q_axis_angle( correction, axis, acosf(angle)*0.05f );
+            q_mul( correction, player.rot, player.rot );
+         }
+
+         draw_cross( contact.pos, 0xffff0000 );
 
+         break;
+      }
    }
+
+   player.iY -= vg_get_axis( "horizontal" ) * 3.6f * ktimestep;
+   
+   v2f target = {0.0f,0.0f};
+   v2_muladds( target, (v2f){ vg_get_axis("h1"), vg_get_axis("v1") },
+               player.grab, target );
+   v2_lerp( player.board_xy, target, ktimestep*3.0f, player.board_xy );
+}
+
+static void player_animate(void);
+static void player_update(void)
+{
+   static int clock = 0;
+
+   clock ++;
+   if( clock >= clock_divider )
+      clock = 0;
    else
+      return;
+
+   /* temp */
+   if( freecam )
+   {
+      player_freecam();
+      return;
+   }
+   
+   if( vg_get_axis("grabl")>0.0f)
+      reset_player(0,NULL);
+   if( vg_get_button( "push" ) )
    {
-      yawamt -= vg_get_axis( "horizontal" ) * 3.6f * timestep;
+      v3f dir = { 0.0f, 0.0f, -1.0f };
 
-      v4f pitch;
-      q_axis_angle( pitch, vside, vg_get_axis( "vertical" ) * 3.6f *timestep );
-      q_mul( pitch, player.rot, player.rot );
+      m3x3_mulv( player.to_world, dir, dir );
+      v3_muladds( player.v, dir, 5.0f * ktimestep, player.v );
    }
 
-   v4f rotate;
-   q_axis_angle( rotate, vup, yawamt );
+   float horizontal = vg_get_axis("horizontal"),
+         vertical = vg_get_axis("vertical");
+
+   player.joy_l[0] = vg_signf(horizontal) * powf( horizontal, 2.0f );
+   player.joy_l[1] = vg_signf(vertical) * powf( vertical, 2.0f );
+
+   /* Integrate velocity */
+   if( sv_phys )
+   {
+      apply_gravity( player.v, ktimestep );
+      v3_muladds( player.co, player.v, ktimestep, player.co );
+   }
+
+   /* Integrate inertia */
+   v4f rotate; v3f vup = {0.0f,1.0f,0.0f};
+   m3x3_mulv( player.to_world, vup, vup );
+
+   static float siY = 0.0f;
+
+   float lerpq = player.in_air? 0.04f: 0.3f;
+   siY = vg_lerpf( siY, player.iY, lerpq );
+
+   q_axis_angle( rotate, vup, siY );
    q_mul( rotate, player.rot, player.rot );
 
    player.look_dir[0] = atan2f( player.v[0], -player.v[2] );
+   player.look_dir[1] = atan2f( -player.v[1], sqrtf(player.v[0]*player.v[0]+
+                                       player.v[2]*player.v[2]) ) * 0.3f;
+
+   player.iY = 0.0f; /* temp */
+
+   if( player.in_air )
+      player_physics_air();
+
+   if( !player.in_air )
+      player_physics_ground();
    
-   /* Creating a skeleton of the player dynamically */
-   float kheight = 1.8f,
-         kleg = 0.6f;
+   /* Camera and character */
+
+   player_transform_update();
+   q_normalize(player.rot);
+   player_animate();
+}
 
-   v2f ac;
+void vg_update(void)
+{
+   player_update();
+   bvh_debug( &world.geo, player.co );
+}
 
+static void player_animate(void)
+{
+   /* Camera position */
    static v3f last_vel = { 0.0f, 0.0f, 0.0f };
    static v3f momentum, bob;
 
@@ -519,7 +751,6 @@ void vg_update(void)
    v3_copy( player.v, last_vel );
 
    v3_add( momentum, player.a, momentum );
-   
    v3_lerp( momentum, (v3f){0.0f,0.0f,0.0f}, 0.1f, momentum );
    v3f target;
    
@@ -527,169 +758,256 @@ void vg_update(void)
    momentum[1] = vg_clampf( momentum[1], -0.2f, 5.0f );
    momentum[2] = vg_clampf( momentum[2], -2.0f, 2.0f );
    v3_copy( momentum, target );
-   
    v3_lerp( bob, target, 0.2f, bob );
 
    /* Head */
-   float lslip = fabsf(slip); //vg_minf( 0.4f, slip );
-   head[0] =  0.0f;//(-sinf(lslip)*0.9f * kheight) * 0.44f;
-   head[1] =  (0.3f + cosf(lslip)*0.5f) * kheight;
-   head[2] =  0.0f;
+   float lslip = fabsf(player.slip); //vg_minf( 0.4f, slip );
+                              
+   float grabt = vg_get_axis( "grabr" )*0.5f+0.5f;
+   player.grab = vg_lerpf( player.grab, grabt, 0.04f );
+
+   float kheight = 2.0f,
+         kleg = 0.6f;
+
+   v3f head;
+   head[0] = 0.0f;
+   head[1] = (0.3f+cosf(lslip)*0.5f*(1.0f-player.grab*0.7f)) * kheight;
+   head[2] = 0.0f;
 
    v3f offset;
    m3x3_mulv( player.to_local, bob, offset );
-   offset[0] *= 0.25f;
+
+   offset[0] *= 0.3333f;
    offset[1] *= -0.25f;
    offset[2] *= 0.7f;
-   v3_muladds( head, offset, 1.0f, head );
-
-   player_transform_update();
+   v3_muladds( head, offset, 0.7f, head );
+   head[1] = vg_clampf( head[1], 0.3f, kheight );
 
-   m4x3_mulv( player.to_world, head, head );
-   v3_copy( head, player.view );
-
-   q_normalize(player.rot);
-}
-
-static void debug_grid( v3f at )
-{
-   v3f base;
-   v3_floor( at, base );
-
-   for( int y=0; y<16; y++ )
-   {
-      vg_line( (v3f){ base[0] - 8, base[1], base[2]+y-8 },
-               (v3f){ base[0] + 8, base[1], base[2]+y-8 },
-               0x40ffffff );
-   }
-   for( int x=0; x<16; x++ )
+#if 0
+   if( !freecam )
    {
-      vg_line( (v3f){ base[0]+x-8, base[1], base[2]-8 },
-               (v3f){ base[0]+x-8, base[1], base[2]+8 },
-               0x40ffffff );
+      v3_copy( head, player.view );
+      v3f camoffs = {-0.2f,-0.6f,0.00f};
+      v3_add( player.view, camoffs, player.view );
    }
-}
-
-static void draw_player(void)
-{
-   mesh_bind( &player.mesh );
-   float const kleg_upper = 0.53f,
-               kleg_lower = 0.5f;
+#endif
 
-   /* Create IK targets */
-   struct ik_basic ik_leg_l = { .l1 = kleg_upper, .l2 = kleg_lower },
-                   ik_leg_r = { .l1 = kleg_upper, .l2 = kleg_lower };
 
-   v3f butt, fwd;
+   /* 
+    * Animation blending
+    * ===========================================
+    */
 
-   m4x3_mulv( player.to_world, (v3f){ 0.0f,0.16f,-0.4f }, ik_leg_r.end );
-   m4x3_mulv( player.to_world, (v3f){ 0.0f,0.16f, 0.3f }, ik_leg_l.end );
-   m4x3_mulv( player.to_world, (v3f){ -0.6f,0.5f,-0.4f }, ik_leg_r.pole );
-   m4x3_mulv( player.to_world, (v3f){ -0.6f,0.5f,0.35f }, ik_leg_l.pole );
+   static float fslide = 0.0f;
+   static float fdirz = 0.0f;
+   static float fdirx = 0.0f;
+   static float fstand = 0.0f;
+   static float ffly = 0.0f;
 
-   m3x3_mulv( player.to_world, (v3f){ 0.2f,-0.55f,0.0f}, butt );
-   v3_add( butt, player.view, butt );
+   float speed = v3_length( player.v );
+   
+   fstand = vg_lerpf(fstand, 1.0f-vg_clampf(speed*0.03f,0.0f,1.0f),0.1f);
+   fslide = vg_lerpf(fslide, vg_clampf(lslip+fabsf(offset[0])*0.2f,
+            0.0f,1.0f), 0.04f);
+   fdirz = vg_lerpf(fdirz, player.reverse > 0.0f? 1.0f: 0.0f, 0.04f );
+   fdirx = vg_lerpf(fdirx, player.slip < 0.0f?    1.0f: 0.0f, 0.04f );
+   ffly = vg_lerpf(ffly, player.in_air?           1.0f: 0.0f, 0.04f );
+
+   character_pose_reset( &player.mdl );
+
+   float amt_air = ffly*ffly,
+         amt_ground = 1.0f-amt_air,
+         amt_std = (1.0f-fslide) * amt_ground,
+         amt_stand = amt_std * fstand,
+         amt_aero = amt_std * (1.0f-fstand),
+         amt_slide = amt_ground * fslide;
+
+   character_final_pose( &player.mdl, offset, &pose_stand, amt_stand );
+   character_final_pose( &player.mdl, offset, &pose_aero, amt_aero*fdirz );
+   character_final_pose( &player.mdl, offset, 
+         &pose_aero_reverse, amt_aero * (1.0f-fdirz) );
+   character_final_pose( &player.mdl, offset, &pose_slide, amt_slide*fdirx );
+   character_final_pose( &player.mdl, offset, 
+         &pose_slide1, amt_slide*(1.0f-fdirx) );
+
+   character_final_pose( &player.mdl, (v3f){0.0f,0.0f,0.0f}, 
+         &pose_fly, amt_air );
+
+   if( !freecam )
+   {
+      v3_copy( player.mdl.cam_pos, player.view );
+      v3_muladds( player.view, offset, 0.7f, player.view );
+      player.view[1] = vg_clampf( player.view[1], 0.3f, kheight );
+   }
 
-   m3x3_mulv( player.to_world, (v3f){0.0f,0.0f,-1.0f}, fwd );
-   v3_muladds( butt, fwd, 0.1f, ik_leg_r.base );
-   v3_muladds( butt, fwd,-0.1f, ik_leg_l.base );
+   /* 
+    * Additive effects
+    * ==========================
+    */
+   struct ik_basic *arm_l = &player.mdl.ik_arm_l,
+                   *arm_r = &player.mdl.ik_arm_r;
+
+   v3f localv;
+   m3x3_mulv( player.to_local, player.v, localv );
+   v3_muladds( arm_l->end, localv, -0.01f, arm_l->end );
+   v3_muladds( arm_r->end, localv, -0.01f, arm_r->end );
+
+   /* New board transformation */
+   v4f board_rotation; v3f board_location;
+
+   v4f rz, rx;
+   q_axis_angle( rz, (v3f){ 0.0f, 0.0f, 1.0f }, player.board_xy[0] );
+   q_axis_angle( rx, (v3f){ 1.0f, 0.0f, 0.0f }, player.board_xy[1] );
+   q_mul( rx, rz, board_rotation );
+   
+   v3f *mboard = player.mdl.matrices[k_chpart_board];// player.mboard;
+   q_m3x3( board_rotation, mboard );
+   m3x3_mulv( mboard, (v3f){ 0.0f, -0.5f, 0.0f }, board_location );
+   v3_add( (v3f){0.0f,0.5f,0.0f}, board_location, board_location );
+   v3_copy( board_location, mboard[3] );
 
-   /* Compute IK */
-   m4x3f mleg_l, mknee_l, mleg_r, mknee_r, mboard;
 
-   ik_basic( &ik_leg_r, mleg_r, mknee_r );
-   ik_basic( &ik_leg_l, mleg_l, mknee_l );
+   float wheel_r = offset[0]*-0.4f;
+   v4f qwheel;
+   q_axis_angle( qwheel, (v3f){0.0f,1.0f,0.0f}, wheel_r );
    
-   /* Draw */
-   vg_tex2d_bind( &tex_grid, 0 );
-   scene_tree_sway = 0.0f;
+   q_m3x3( qwheel, player.mdl.matrices[k_chpart_wb] );
+
+   m3x3_transpose( player.mdl.matrices[k_chpart_wb],
+                   player.mdl.matrices[k_chpart_wf] );
+   v3_copy( player.mdl.offsets[k_chpart_wb], 
+         player.mdl.matrices[k_chpart_wb][3] );
+   v3_copy( player.mdl.offsets[k_chpart_wf], 
+         player.mdl.matrices[k_chpart_wf][3] );
+   
+   m4x3_mul( mboard, player.mdl.matrices[k_chpart_wb],
+                     player.mdl.matrices[k_chpart_wb] );
+   m4x3_mul( mboard, player.mdl.matrices[k_chpart_wf],
+                     player.mdl.matrices[k_chpart_wf] );
 
-   mesh_bind( &player.mesh );
-   m4x4f mat;
+   m4x3_mulv( mboard, player.mdl.ik_leg_l.end, player.mdl.ik_leg_l.end );
+   m4x3_mulv( mboard, player.mdl.ik_leg_r.end, player.mdl.ik_leg_r.end );
 
-   SHADER_USE(shader_standard_lit);
 
-       glUniformMatrix4fv( SHADER_UNIFORM( shader_standard_lit, "uPv" ), 
-         1, GL_FALSE, (float *)vg_pv );
-   glUniform1i( SHADER_UNIFORM( shader_standard_lit, "uTexMain" ), 0 );
-   vg_tex2d_bind( &tex_grid, 0 );
+   v3_copy( player.mdl.ik_arm_l.end, player.handl_target );
+   v3_copy( player.mdl.ik_arm_r.end, player.handr_target );
 
-   GLint kuMdl = SHADER_UNIFORM( shader_standard_lit, "uMdl" );
-   
-   float kscale = 0.7f;
-   glUniform4f( SHADER_UNIFORM(shader_standard_lit,"uColour"), 
-         0.9f*kscale,0.6f*kscale,0.1f*kscale,1.0f );
+   if( 1||player.in_air )
+   {
+      float tuck = player.board_xy[1],
+            tuck_amt = fabsf( tuck ) * (1.0f-fabsf(player.board_xy[0]));
+      
+      float crouch = player.grab*0.3f;
+      v3_muladds( player.mdl.ik_body.base, (v3f){0.0f,-1.0f,0.0f}, 
+            crouch, player.mdl.ik_body.base );
+      v3_muladds( player.mdl.ik_body.end, (v3f){0.0f,-1.0f,0.0f}, 
+            crouch*1.2f, player.mdl.ik_body.end );
 
-   m4x3_expand( player.to_world, mat );
-       glUniformMatrix4fv( kuMdl, 1, GL_FALSE, (float *)mat );
-   submodel_draw( &player.board );
+      if( tuck < 0.0f )
+      {
+         //foot_l *= 1.0f-tuck_amt*1.5f;
 
-   glUniform4f( SHADER_UNIFORM(shader_standard_lit,"uColour"), 
-         0.2f*kscale,0.3f*kscale,1.0f*kscale,1.0f );
-   submodel_draw( &player.wheels );
+         if( player.grab > 0.1f )
+         {
+            m4x3_mulv( mboard, (v3f){0.1f,0.14f,0.6f}, 
+                  player.handl_target );
+         }
+      }
+      else
+      {
+         //foot_r *= 1.0f-tuck_amt*1.4f;
 
-   glEnable(GL_BLEND);
-   glBlendFunc(GL_SRC_ALPHA, GL_ONE);
-   glBlendEquation(GL_FUNC_ADD);
-   glDisable( GL_DEPTH_TEST );
-   glUniform4f( SHADER_UNIFORM(shader_standard_lit,"uColour"), 
-         0.2f*kscale,0.3f*kscale,1.0f*kscale,0.2f );
+         if( player.grab > 0.1f )
+         {
+            m4x3_mulv( mboard, (v3f){0.1f,0.14f,-0.6f}, 
+                  player.handr_target );
+         }
+      }
+   }
 
-   m4x3_expand( mleg_l, mat );
-       glUniformMatrix4fv( kuMdl, 1, GL_FALSE, (float *)mat );
-   submodel_draw( &player.legu );
+   v3_lerp( player.handl, player.handl_target, 0.1f, player.handl );
+   v3_lerp( player.handr, player.handr_target, 0.1f, player.handr );
 
-   m4x3_expand( mknee_l, mat );
-       glUniformMatrix4fv( kuMdl, 1, GL_FALSE, (float *)mat );
-   submodel_draw( &player.legl );
+   v3_copy( player.handl, player.mdl.ik_arm_l.end );
+   v3_copy( player.handr, player.mdl.ik_arm_r.end );
 
-   m4x3_expand( mleg_r, mat );
-       glUniformMatrix4fv( kuMdl, 1, GL_FALSE, (float *)mat );
-   submodel_draw( &player.legu );
+   /* Head rotation */
 
-   m4x3_expand( mknee_r, mat );
-       glUniformMatrix4fv( kuMdl, 1, GL_FALSE, (float *)mat );
-   submodel_draw( &player.legl );
+   static float rhead = 0.0f;
+   rhead = vg_lerpf( rhead,
+         vg_clampf(atan2f( localv[2], -localv[0] ),-1.0f,1.0f), 0.04f );
+   player.mdl.rhead = rhead;
+}
 
-   m4x3f mbutt;
-   m3x3_copy( player.to_world, mbutt );
-   v3_copy( butt, mbutt[3] );
+static void draw_player(void)
+{
+   /* Draw */
+   vg_tex2d_bind( &tex_pallet, 0 );
 
-   m4x3_expand( mbutt, mat );
-       glUniformMatrix4fv( kuMdl, 1, GL_FALSE, (float *)mat );
-   submodel_draw( &player.torso );
+   m4x3_copy( player.to_world, player.mdl.mroot );
+   character_eval( &player.mdl );
+   character_draw( &player.mdl, 1.0f );
+}
 
-   glDisable(GL_BLEND);
-   glEnable( GL_DEPTH_TEST );
+static void vg_framebuffer_resize( int w, int h )
+{
+   glBindTexture( GL_TEXTURE_2D, render.rgb_background );
+   glTexImage2D( GL_TEXTURE_2D, 0, GL_RGB, w, h, 0, 
+         GL_RGB, GL_UNSIGNED_BYTE, NULL );
 }
 
 void vg_render(void) 
 {
+   glBindFramebuffer( GL_FRAMEBUFFER, 0 );
    glViewport( 0,0, vg_window_x, vg_window_y );
 
    glDisable( GL_DEPTH_TEST );
    glClearColor( 0.1f, 0.0f, 0.2f, 1.0f );
-   glClearColor(141.0f/255.0f, 176.0f/255.0f, 215.0f/255.0f,1.0f);
+   glClearColor(111.0f/255.0f, 46.0f/255.0f, 45.0f/255.0f,1.0f);
+
+   glClearColor( powf(0.066f,1.0f/2.2f), 
+                 powf(0.050f,1.0f/2.2f), 
+                 powf(0.046f,1.0f/2.2f), 1.0f );
    glClear( GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT );
 
    v3f pos_inv;
-   v3_negate( player.view, pos_inv );
+   static v3f cam_lerped = {0.0f,0.0f,0.0f};
+   v3_lerp( cam_lerped, player.view, 0.08f, cam_lerped );
 
-   float speed = v3_length( player.v );
+   if( !freecam  )
+      m4x3_mulv( player.to_world, cam_lerped, pos_inv );
+   else
+      v3_add( player.co, player.view, pos_inv );
+   v3_negate( pos_inv, pos_inv );
+
+   static float vertical_lerp = 0.0f;
+   vertical_lerp = vg_lerpf( vertical_lerp, pos_inv[1], 1.0f );
+   v3f final = { pos_inv[0], vertical_lerp, pos_inv[2] };
+
+   float speed = freecam? 0.0f: v3_length( player.v );
    v3f shake = { vg_randf()-0.5f, vg_randf()-0.5f, vg_randf()-0.5f };
    v3_muls( shake, speed*0.01f, shake );
 
+   static v2f cam_lerped_dir;
+   
+   v2_lerp( cam_lerped_dir, player.look_dir, 0.04f, cam_lerped_dir );
+
    m4x3_identity( world_matrix );
    m4x3_rotate_x( world_matrix, 
-         freecam? player.look_dir[1]: 0.5f+shake[1]*0.04f );
-   m4x3_rotate_y( world_matrix, player.look_dir[0]+shake[0]*0.02f );
-   m4x3_translate( world_matrix, pos_inv );
+         freecam? 
+         cam_lerped_dir[1]: 
+         0.6f+shake[1]*0.04f+player.look_dir[1] );
+
+   m4x3_rotate_y( world_matrix, 
+         freecam?
+         cam_lerped_dir[0]:
+         player.look_dir[0]+shake[0]*0.02f );
+   m4x3_translate( world_matrix, final );
    
    m4x4f world_4x4;
    m4x3_expand( world_matrix, world_4x4 );
-
    m4x4_projection( vg_pv, 
-         freecam? 90.0f: 130.0f,
+         freecam? 60.0f: 120.0f,
          (float)vg_window_x / (float)vg_window_y, 
          0.01f, 1000.0f );
    m4x4_mul( vg_pv, world_4x4, vg_pv );
@@ -700,66 +1018,91 @@ void vg_render(void)
 
    glEnable( GL_DEPTH_TEST );
    
-   scene_foliage_shader_use();
-   m4x4f temp1;
-   m4x4_identity( temp1 );
-       glUniformMatrix4fv( SHADER_UNIFORM( shader_debug_vcol, "uMdl" ), 
-         1, GL_FALSE, (float *)temp1 );
-
-   vg_tex2d_bind( &tex_norwey, 0 );
-   scene_tree_sway = 0.1f;
-
-   scene_bind( &world.foliage );
-   scene_draw( &world.foliage );
-   if( debugsdf )
-      scene_debugsdf( &world.foliage );
-   
-   SHADER_USE(shader_unlit);
-   m4x4f temp2;
-   m4x4_identity(temp2);
-   //m4x4_translate( temp2, player.co );
-       glUniformMatrix4fv( SHADER_UNIFORM( shader_unlit, "uMdl" ), 
-         1, GL_FALSE, (float *)temp2 );
-       glUniformMatrix4fv( SHADER_UNIFORM( shader_unlit, "uPv" ), 
-         1, GL_FALSE, (float *)vg_pv );
-
-   glUniform1i( SHADER_UNIFORM( shader_unlit, "uTexMain" ), 0 );
-   vg_tex2d_bind( &tex_sky, 0 );
-
+   /* 
+    * Draw world
+    */
    SHADER_USE(shader_standard_lit);
 
+   m4x3f identity_matrix;
+   m4x3_identity( identity_matrix );
+
        glUniformMatrix4fv( SHADER_UNIFORM( shader_standard_lit, "uPv" ), 
          1, GL_FALSE, (float *)vg_pv );
-   glUniform1i( SHADER_UNIFORM( shader_standard_lit, "uTexMain" ), 0 );
-
-       glUniformMatrix4fv( SHADER_UNIFORM( shader_standard_lit, "uMdl" ), 
-         1, GL_FALSE, (float *)temp1 );
+       glUniformMatrix4x3fv( SHADER_UNIFORM( shader_standard_lit, "uMdl" ), 
+         1, GL_FALSE, (float *)identity_matrix );
 
    vg_tex2d_bind( &tex_grid, 0 );
+   glUniform1i( SHADER_UNIFORM( shader_standard_lit, "uTexMain" ), 0 );
 
-   scene_bind( &world.geo );
    glUniform4f( SHADER_UNIFORM(shader_standard_lit,"uColour"), 
-         0.2f,0.36f,0.25f,1.0f );
-   submodel_draw( &world.terrain );
+         0.4f,0.4f,0.4f,1.0f );
+
+   scene_bind( &world.geo );
+   scene_draw( &world.geo );
+
+   if( !replay_record )
+   {
+      m4x3f *base = &replay_buffer[(PART_COUNT)*replay_buffer_frame];
+
+      for( int i=0; i<PART_COUNT; i++ )
+         m4x3_copy( base[i], player.mdl.matrices[i] );
+
+      replay_buffer_frame ++;
+
+      if( replay_buffer_frame == REPLAY_LENGTH )
+         replay_buffer_frame = 0;
+
+      vg_tex2d_bind( &tex_pallet, 0 );
+      character_draw( &player.mdl, 0.0f );
+      player_animate();
+   }
 
-   glUniform4f( SHADER_UNIFORM(shader_standard_lit,"uColour"), 
-         0.2f,0.2f,0.21f,1.0f );
-   submodel_draw( &world.terrain_rocks );
 
-   glUniform4f( SHADER_UNIFORM(shader_standard_lit,"uColour"), 
-         0.4f,0.4f,0.4f,1.0f );
-   submodel_draw( &world.terrain_road );
    
-   scene_bind( &world.detail );
-   scene_draw( &world.detail );
+   /* Copy the RGB of what we have into the background buffer */
+   glBindFramebuffer( GL_READ_FRAMEBUFFER, 0 );
+   glBindFramebuffer( GL_DRAW_FRAMEBUFFER, render.fb_background );
+   glBlitFramebuffer( 0,0, vg_window_x, vg_window_y, 
+                      0,0, vg_window_x, vg_window_y,
+                      GL_COLOR_BUFFER_BIT,
+                      GL_LINEAR );
+   
+   /* Clear out the colour buffer, but keep depth */
+   glBindFramebuffer( GL_FRAMEBUFFER, 0 );
+   glClearColor( 0.0f, 0.0f, 0.0f, 0.0f );
+
+#if 1
+   glClear( GL_COLOR_BUFFER_BIT );
+#else
+   glClear( GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT );
+#endif
 
+   if( !freecam )
    draw_player();
 
+   /* Draw back in the background */
+   glEnable(GL_BLEND);
+   glDisable(GL_DEPTH_TEST);
+   glBlendFunc(GL_ONE_MINUS_DST_ALPHA, GL_DST_ALPHA);
+   glBlendEquation(GL_FUNC_ADD);
+   
+   SHADER_USE( shader_blit );
+
+   glUniform1i( SHADER_UNIFORM(shader_blit,"uTexMain"), 0 );
+   glActiveTexture(GL_TEXTURE0);
+   glBindTexture( GL_TEXTURE_2D, render.rgb_background );
+
+   glBindVertexArray( render.fsquad.vao );
+   glDrawArrays( GL_TRIANGLES, 0, 6 );
+
+   glDisable(GL_BLEND);
+
+   /* Other shite */
    glDisable( GL_DEPTH_TEST );
    vg_lines_drawall( (float *)vg_pv );
 
    /* Debugger camera */
-   glViewport( 0,0, 512, 512 );
+   glViewport( 0,0, 800, 800 );
    glClearColor( 0.1f, 0.0f, 0.2f, 1.0f );
    glClear( GL_DEPTH_BUFFER_BIT );
 
@@ -789,6 +1132,20 @@ void vg_render(void)
    vg_lines_drawall( (float *)vg_pv );
 
    glViewport( 0,0, vg_window_x, vg_window_y );
+
+
+   if( replay_record )
+   {
+      m4x3f *base = &replay_buffer[(PART_COUNT)*replay_buffer_frame];
+
+      for( int i=0; i<PART_COUNT; i++ )
+         m4x3_copy( player.mdl.matrices[i], base[i] );
+
+      replay_buffer_frame ++;
+
+      if( replay_buffer_frame == REPLAY_LENGTH )
+         replay_buffer_frame = 0;
+   }
 }
 
 void vg_ui(void)
@@ -800,20 +1157,23 @@ void vg_ui(void)
    
    snprintf( buf, 20, "%.2f %.2f %.2f m/s", 
          player.a[0], player.a[1], player.a[2] );
-
    gui_text( (ui_px [2]){ 0, 20 }, buf, 1, k_text_align_left );
 
+   snprintf( buf, 20, "pos %.2f %.2f %.2f", 
+         player.co[0], player.co[1], player.co[2] );
+   gui_text( (ui_px [2]){ 0, 40 }, buf, 1, k_text_align_left );
+
    if( vg_gamepad_ready )
    {
       for( int i=0; i<6; i++ )
       {
          snprintf( buf, 20, "%.2f", vg_gamepad.axes[i] );
-         gui_text( (ui_px [2]){ 0, (i+2)*20 }, buf, 1, k_text_align_left );
+         gui_text( (ui_px [2]){ 0, (i+3)*20 }, buf, 1, k_text_align_left );
       }
    }
    else
    {
-      gui_text( (ui_px [2]){ 0, 40 }, 
+      gui_text( (ui_px [2]){ 0, 60 }, 
             "Gamepad not ready", 1, k_text_align_left );
    }
 }