active ragdolls
[carveJwlIkooP6JGAAIwe30JlM.git] / scene.h
diff --git a/scene.h b/scene.h
index d6cfb0a081b2c2ab2959bcb75f7e643053012689..d8fac1ad524a05672feabee916237ddfbeac8acf 100644 (file)
--- a/scene.h
+++ b/scene.h
 #ifndef SCENE_H
 #define SCENE_H
 
-#include "vg/vg.h"
+#include "common.h"
 #include "model.h"
+#include "bvh.h"
 
-typedef struct scene scene;
-typedef struct bvh_node bvh_node;
+typedef struct scene_context scene_context;
+typedef struct scene_vert scene_vert;
 
-struct scene
+#pragma pack(push,1)
+
+/* 32 byte vertexs, we don't care about the normals too much,
+ *    maybe possible to bring down uv to i16s too */
+struct scene_vert
 {
-   glmesh mesh;
+   v3f co;        /* 3*32 */
+   v2f uv;        /* 2*32 */
+   i8  norm[4];   /* 4*8 */
+   u16 flags; /* only for the cpu. its junk on the gpu */
+   u16 unused[3];
+};
 
-   model_vert *verts;
-   u32 *indices;
-   
-   struct 
-   {
-      bvh_node *nodes;
-      u32 node_count;
-   }
-   bvh;
+#pragma pack(pop)
 
-   u32 vertex_count,
-       indice_count,
-       vertex_cap,
-       indice_cap;
+/* 
+ * 1. this should probably be a CONTEXT based approach unlike this mess.
+ * take a bit of the mdl_context ideas and redo this header. its messed up
+ * pretty bad right now.
+ */
 
-   boxf bbx;
+struct scene_context
+{
+   scene_vert *arrvertices;
+   u32 *arrindices;
 
-   u32 shadower_count,
-       shadower_cap;
+   u32 vertex_count, indice_count,
+       max_vertices, max_indices;
 
-   submodel submesh;
+   boxf bbx;
+   mdl_submesh submesh;
 };
 
-GLuint tex_dual_noise;
-
-static void scene_init( scene *pscene )
+static u32 scene_mem_required( scene_context *ctx )
 {
-   pscene->verts = NULL;
-   pscene->indices = NULL;
-   pscene->vertex_count = 0;
-   pscene->indice_count = 0;
-   pscene->shadower_count = 0;
-   pscene->shadower_cap = 0;
-   pscene->submesh.indice_start = 0;
-   pscene->submesh.indice_count = 0;
-
-   v3_fill( pscene->bbx[0],  999999.9f );
-   v3_fill( pscene->bbx[1], -999999.9f );
-
-   static int noise_ready = 0;
-   if( !noise_ready )
-   {
-      noise_ready = 1;
-
-      u8 *buf = malloc( 256*256*2 );
-
-      for( int i=0; i<256*256; i++ )
-      {
-         u8 val = rand()&0xff;
-         buf[i*2] = val;
-      }
+   u32 vertex_length = vg_align8(ctx->max_vertices * sizeof(scene_vert)),
+       index_length  = vg_align8(ctx->max_indices  * sizeof(u32));
 
-      for( int y=0; y<256; y++ )
-      {
-         for( int x=0; x<256; x++ )
-         {
-            u8 *pr = &buf[(y*256+x)*2],
-               *pg = &buf[(((y+17)&0xff)*256+((x+37)&0xff))*2+1];
-            *pg = *pr;
-         }
-      }
-      
-      /* TODO: This texture should be delted somewhere */
-      glGenTextures( 1, &tex_dual_noise );
-      glBindTexture( GL_TEXTURE_2D, tex_dual_noise );
-      glTexImage2D( GL_TEXTURE_2D, 0, GL_RG, 256, 256, 0, GL_RG,
-            GL_UNSIGNED_BYTE, buf );
+   return vertex_length + index_length;
+}
 
-      vg_tex2d_linear();
-      vg_tex2d_repeat();
+static 
+void scene_init( scene_context *ctx, u32 max_vertices, u32 max_indices )
+{
+   ctx->vertex_count = 0;
+   ctx->indice_count = 0;
+   ctx->max_vertices = max_vertices;
+   ctx->max_indices = max_indices;
+   ctx->arrindices = NULL; /* must be filled out by user */
+   ctx->arrvertices = NULL;
 
-      free( buf );
-   }
+   memset( &ctx->submesh, 0, sizeof(mdl_submesh) );
+
+   v3_fill( ctx->bbx[0],  999999.9f );
+   v3_fill( ctx->bbx[1], -999999.9f );
 }
 
-static void *buffer_reserve( void *buffer, u32 count, u32 *cap, u32 amount, 
-      size_t emsize )
+void scene_supply_buffer( scene_context *ctx, void *buffer )
 {
-   if( count+amount > *cap )
-   {
-      *cap = VG_MAX( (*cap)*2, (*cap)+amount );
-      
-      return realloc( buffer, (*cap) * emsize );
-   }
+   u32 vertex_length = vg_align8( ctx->max_vertices * sizeof(scene_vert) );
 
-   return buffer;
+   ctx->arrvertices = buffer;
+   ctx->arrindices  = (u32*)(((u8*)buffer) + vertex_length);
+}
+
+static void scene_vert_pack_norm( scene_vert *vert, v3f norm, f32 blend ){
+   v3f n;
+   v3_muls( norm, 127.0f, n );
+   v3_minv( n, (v3f){  127.0f,  127.0f,  127.0f }, n );
+   v3_maxv( n, (v3f){ -127.0f, -127.0f, -127.0f }, n );
+   vert->norm[0] = n[0];
+   vert->norm[1] = n[1];
+   vert->norm[2] = n[2];
+   vert->norm[3] = blend * 127.0f;
 }
 
 /* 
  * Append a model into the scene with a given transform
  */
-static void scene_add_model( scene *pscene, model *mdl, submodel *submodel,
-      v3f pos, float yaw, float scale )
+static void scene_add_mdl_submesh( scene_context *ctx, mdl_context *mdl, 
+                                      mdl_submesh *sm, m4x3f transform )
 {
-   pscene->verts = buffer_reserve( pscene->verts, pscene->vertex_count, 
-         &pscene->vertex_cap, submodel->vertex_count, sizeof(model_vert) );
-   pscene->indices = buffer_reserve( pscene->indices, pscene->indice_count,
-         &pscene->indice_cap, submodel->indice_count, sizeof(u32) );
-   
-   /* Transform and place vertices */
-   model_vert *src_verts = submodel_vert_data( mdl, submodel );
-   u32 *src_indices = submodel_indice_data( mdl, submodel );
-   
-   m4x3f mtx;
-   m4x3_identity( mtx );
-   m4x3_translate( mtx, pos );
-   m4x3_rotate_y( mtx, yaw );
-   m4x3_scale( mtx, scale );
-
-   boxf bbxnew;
-   box_copy( submodel->bbx, bbxnew );
-   m4x3_transform_aabb( mtx, bbxnew );
-   box_concat( pscene->bbx, bbxnew );
-   
-   m3x3f rotation;
-   m4x3_to_3x3( mtx, rotation );
-
-   float rand_hue = vg_randf();
-
-   for( u32 i=0; i<submodel->vertex_count; i++ )
-   {
-      model_vert *pvert = &pscene->verts[ pscene->vertex_count+i ],
-                 *src = &src_verts[ i ];
-
-      m4x3_mulv( mtx, src->co, pvert->co );
-      m3x3_mulv( rotation, src->norm, pvert->norm );
-
-      v4_copy( src->colour, pvert->colour );
-      v2_copy( src->uv, pvert->uv );
-      
-      float rel_y = src->co[1] / submodel->bbx[1][1];
-      pvert->colour[0] = rel_y;
-      pvert->colour[2] = rand_hue;
+   if( ctx->vertex_count + sm->vertex_count > ctx->max_vertices ){
+      vg_fatal_error( "Scene vertex buffer overflow (%u exceeds %u)\n",
+                        ctx->vertex_count + sm->vertex_count, 
+                        ctx->max_vertices );
    }
 
-   for( u32 i=0; i<submodel->indice_count; i++ )
-   {
-      u32 *pidx = &pscene->indices[ pscene->indice_count+i ];
-      *pidx = src_indices[i] + pscene->vertex_count;
+   if( ctx->indice_count + sm->indice_count > ctx->max_indices ){
+      vg_fatal_error( "Scene index buffer overflow (%u exceeds %u)\n",
+                        ctx->indice_count + sm->indice_count,
+                        ctx->max_indices );
    }
 
-   pscene->vertex_count += submodel->vertex_count;
-   pscene->indice_count += submodel->indice_count;
-}
+   mdl_vert   *src_verts = mdl_arritm( &mdl->verts, sm->vertex_start );
+   scene_vert *dst_verts = &ctx->arrvertices[ ctx->vertex_count ];
 
-static void scene_add_foliage( scene *pscene, model *mdl, submodel *submodel,
-      m4x3f transform )
-{
-   pscene->verts = buffer_reserve( pscene->verts, pscene->vertex_count, 
-         &pscene->vertex_cap, submodel->vertex_count, sizeof(model_vert) );
-   pscene->indices = buffer_reserve( pscene->indices, pscene->indice_count,
-         &pscene->indice_cap, submodel->indice_count, sizeof(u32) );
+   u32 *src_indices    =  mdl_arritm( &mdl->indices, sm->indice_start ),
+       *dst_indices    = &ctx->arrindices[ ctx->indice_count ];
    
    /* Transform and place vertices */
-   model_vert *src_verts = submodel_vert_data( mdl, submodel );
-   u32 *src_indices = submodel_indice_data( mdl, submodel );
-   
    boxf bbxnew;
-   box_copy( submodel->bbx, bbxnew );
-   m4x3_transform_aabb( transform, bbxnew );
-   box_concat( pscene->bbx, bbxnew );
+   box_init_inf( bbxnew );
+   m4x3_expand_aabb_aabb( transform, bbxnew, sm->bbx );
+   box_concat( ctx->bbx, bbxnew );
+
+   m3x3f normal_matrix;
+   m3x3_copy( transform, normal_matrix );
+   v3_normalize( normal_matrix[0] );
+   v3_normalize( normal_matrix[1] );
+   v3_normalize( normal_matrix[2] );
    
-   float rand_hue = vg_randf();
-   for( u32 i=0; i<submodel->vertex_count; i++ )
-   {
-      model_vert *pvert = &pscene->verts[ pscene->vertex_count+i ],
-                 *src = &src_verts[ i ];
+   for( u32 i=0; i<sm->vertex_count; i++ ){
+      mdl_vert   *src   = &src_verts[i];
+      scene_vert *pvert = &dst_verts[i];
 
       m4x3_mulv( transform, src->co, pvert->co );
-      m3x3_mulv( transform, src->norm, pvert->norm );
 
-      v4_copy( src->colour, pvert->colour );
-      v2_copy( src->uv, pvert->uv );
+      v3f normal;
+      m3x3_mulv( normal_matrix, src->norm, normal );
+      scene_vert_pack_norm( pvert, normal, src->colour[0]*(1.0f/255.0f) );
       
-      float rel_y = src->co[1] / submodel->bbx[1][1];
-      pvert->colour[0] = rel_y;
-      pvert->colour[2] = rand_hue;
+      v2_copy( src->uv, pvert->uv );
    }
 
-   for( u32 i=0; i<submodel->indice_count; i++ )
-   {
-      u32 *pidx = &pscene->indices[ pscene->indice_count+i ];
-      *pidx = src_indices[i] + pscene->vertex_count;
-   }
+   u32 real_indices = 0;
+   for( u32 i=0; i<sm->indice_count/3; i++ ){
+      u32 *src = &src_indices[i*3],
+          *dst = &dst_indices[real_indices];
 
-   pscene->vertex_count += submodel->vertex_count;
-   pscene->indice_count += submodel->indice_count;
-}
+      v3f ab, ac, tn;
+      v3_sub( src_verts[src[2]].co, src_verts[src[0]].co, ab );
+      v3_sub( src_verts[src[1]].co, src_verts[src[0]].co, ac );
+      v3_cross( ac, ab, tn );
 
-static void scene_copy_slice( scene *pscene, submodel *sm )
-{
-   sm->indice_start = pscene->submesh.indice_start;
-   sm->indice_count = pscene->indice_count - sm->indice_start;
+#if 0
+      if( v3_length2( tn ) <= 0.00001f )
+         continue;
+#endif
 
-   sm->vertex_start = pscene->submesh.vertex_start;
-   sm->vertex_count = pscene->vertex_count - sm->vertex_start;
-   
-   pscene->submesh.indice_start = pscene->indice_count;
-   pscene->submesh.vertex_start = pscene->vertex_count;
-}
+      dst[0] = src[0] + ctx->vertex_count;
+      dst[1] = src[1] + ctx->vertex_count;
+      dst[2] = src[2] + ctx->vertex_count;
 
-static void scene_upload( scene *pscene )
-{
-   mesh_upload( &pscene->mesh,
-         pscene->verts, pscene->vertex_count,
-         pscene->indices, pscene->indice_count );
+      real_indices += 3;
+   }
 
-   vg_info( "Scene upload\n" );
-   vg_info( "   indices:%u\n", pscene->indice_count );
-   vg_info( "   verts:%u\n", pscene->vertex_count );
-}
+   if( real_indices != sm->indice_count )
+      vg_warn( "Zero area triangles in model\n" );
 
-float scene_tree_sway = 0.1f;
+   ctx->vertex_count += sm->vertex_count;
+   ctx->indice_count += real_indices;
+}
 
-#if 0
-static void scene_foliage_shader_use(void)
+/*
+ * One by one adders for simplified access (mostly procedural stuff)
+ */
+static void scene_push_tri( scene_context *ctx, u32 tri[3] )
 {
-   SHADER_USE( shader_debug_vcol );
+   if( ctx->indice_count + 3 > ctx->max_indices )
+      vg_fatal_error( "Scene indice buffer overflow (%u exceeds %u)\n",
+                        ctx->indice_count+3, ctx->max_indices );
 
-       glUniformMatrix4fv( SHADER_UNIFORM( shader_debug_vcol, "uPv" ), 
-         1, GL_FALSE, (float *)vg_pv );
-
-   glUniform1i( SHADER_UNIFORM( shader_debug_vcol, "uMode" ), debugview );
-   glUniform1i( SHADER_UNIFORM( shader_debug_vcol, "uTexMain" ), 0 );
-   
-   glUniform1i( SHADER_UNIFORM( shader_debug_vcol, "uTexGradients" ), 1 );
-   vg_tex2d_bind( &tex_gradients, 1 );
+   u32 *dst = &ctx->arrindices[ ctx->indice_count ];
 
-   glUniform1i( SHADER_UNIFORM( shader_debug_vcol, "uTexNoise" ), 2 );
-   glActiveTexture( GL_TEXTURE2 );
-   glBindTexture( GL_TEXTURE_2D, tex_dual_noise );
+   dst[0] = tri[0];
+   dst[1] = tri[1];
+   dst[2] = tri[2];
 
-   glUniform1f( SHADER_UNIFORM( shader_debug_vcol, "uTime" ), vg_time );
-   glUniform1f( SHADER_UNIFORM( shader_debug_vcol, "uSwayAmt" ), 
-         scene_tree_sway );
+   ctx->indice_count += 3;
 }
-#endif
 
-static void scene_bind( scene *pscene )
+static void scene_push_vert( scene_context *ctx, scene_vert *v )
 {
-   mesh_bind( &pscene->mesh );
-}
+   if( ctx->vertex_count + 1 > ctx->max_vertices )
+      vg_fatal_error( "Scene vertex buffer overflow (%u exceeds %u)\n",
+                        ctx->vertex_count+1, ctx->max_vertices );
 
-static void scene_draw( scene *pscene )
-{
-   mesh_drawn( 0, pscene->indice_count );
+   scene_vert *dst = &ctx->arrvertices[ ctx->vertex_count ];
+   *dst = *v;
+
+   ctx->vertex_count ++;
 }
 
-static void scene_register(void)
+static void scene_copy_slice( scene_context *ctx, mdl_submesh *sm )
 {
+   sm->indice_start = ctx->submesh.indice_start;
+   sm->indice_count = ctx->indice_count - sm->indice_start;
+
+   sm->vertex_start = ctx->submesh.vertex_start;
+   sm->vertex_count = ctx->vertex_count - sm->vertex_start;
+   
+   ctx->submesh.indice_start = ctx->indice_count;
+   ctx->submesh.vertex_start = ctx->vertex_count;
 }
 
+static void scene_set_vertex_flags( scene_context *ctx, 
+                                       u32 start, u32 count, u16 flags ){
+   for( u32 i=0; i<count; i++ )
+      ctx->arrvertices[ start + i ].flags = flags;
+}
 
-/* Physics segment */
+struct scene_upload_info{
+   scene_context *ctx;
+   glmesh *mesh;
+};
 
-static int triangle_raycast2d( v3f pA, v3f pB, v3f pC, v3f ray, float *height )
+static void async_scene_upload( void *payload, u32 size )
 {
-       v2f v0, v1, v2, vp, vp2;
-       float d, bca = 0.f, bcb = 0.f, bcc = 0.f;
+   struct scene_upload_info *info = payload;
+
+   //assert( mesh->loaded == 0 );
    
-   v0[0] = pB[0] - pA[0];
-   v0[1] = pB[2] - pA[2];
-   v1[0] = pC[0] - pA[0];
-   v1[1] = pC[2] - pA[2];
-   v2[0] = pB[0] - pC[0];
-   v2[1] = pB[2] - pC[2];
-       
-       d = 1.f / (v0[0]*v1[1] - v1[0]*v0[1]);
+   glmesh *mesh = info->mesh;
+   scene_context *ctx = info->ctx;
 
-#if 0
-       /* Backface culling */
-       if( v2_cross( v0, v1 ) > 0.f )
-               return;
-#endif
+   glGenVertexArrays( 1, &mesh->vao );
+   glGenBuffers( 1, &mesh->vbo );
+   glGenBuffers( 1, &mesh->ebo );
+   glBindVertexArray( mesh->vao );
 
-   vp[0] = ray[0] - pA[0];
-   vp[1] = ray[2] - pA[2];
+   size_t stride = sizeof(scene_vert);
 
-   if( v2_cross( v0, vp ) > 0.f ) return 0;
-   if( v2_cross( vp, v1 ) > 0.f ) return 0;
-       
-   vp2[0] = ray[0] - pB[0];
-   vp2[1] = ray[2] - pB[2];
+   glBindBuffer( GL_ARRAY_BUFFER, mesh->vbo );
+   glBufferData( GL_ARRAY_BUFFER, ctx->vertex_count*stride, 
+                 ctx->arrvertices, GL_STATIC_DRAW );
 
-   if( v2_cross( vp2, v2 ) > 0.f ) return 0;
+   glBindVertexArray( mesh->vao );
+   glBindBuffer( GL_ELEMENT_ARRAY_BUFFER, mesh->ebo );
+   glBufferData( GL_ELEMENT_ARRAY_BUFFER, ctx->indice_count*sizeof(u32),
+                 ctx->arrindices, GL_STATIC_DRAW );
+   
+   /* 0: coordinates */
+   glVertexAttribPointer( 0, 3, GL_FLOAT, GL_FALSE, stride, (void*)0 );
+   glEnableVertexAttribArray( 0 );
 
-   bcb = (vp[0]*v1[1] - v1[0]*vp[1]) * d;
-   bcc = (v0[0]*vp[1] - vp[0]*v0[1]) * d;
-   bca = 1.f - bcb - bcc;
-                               
-   *height = pA[1]*bca + pB[1]*bcb + pC[1]*bcc;
-   return 1;
-}
+   /* 1: normal */
+   glVertexAttribPointer( 1, 4, GL_BYTE, GL_TRUE,
+         stride, (void *)offsetof(scene_vert, norm) );
+   glEnableVertexAttribArray( 1 );
 
-/* Temporary */
-static int sample_scene_height( scene *pscene, v3f pos, v3f norm )
-{
-   for( int i=0; i<pscene->indice_count/3; i++ )
-   {
-      u32 *tri = &pscene->indices[i*3];
+   /* 2: uv */
+   glVertexAttribPointer( 2, 2, GL_FLOAT, GL_FALSE, 
+         stride, (void *)offsetof(scene_vert, uv) );
+   glEnableVertexAttribArray( 2 );
 
-      float *pA = pscene->verts[tri[0]].co,
-            *pB = pscene->verts[tri[1]].co,
-            *pC = pscene->verts[tri[2]].co;
-      
-      float height;
-      if( triangle_raycast2d( pA, pB, pC, pos, &height ))
-      {
-         pos[1] = height;
-         
-         if( norm )
-         {
-            v3f v0, v1;
-            v3_sub( pA, pB, v0 );
-            v3_sub( pC, pB, v1 );
-            v3_cross( v1, v0, norm );
-            v3_normalize( norm );
-         }
+   VG_CHECK_GL_ERR();
 
-         return 1;
-      }
-   }
-   return 0;
-}
-
-static void sample_scene_normal( scene *pscene, v3f pos, v3f normal )
-{
-   for( int i=0; i<pscene->indice_count/3; i++ )
-   {
-      u32 *tri = &pscene->indices[i*3];
-      
-      float height;
-      if( triangle_raycast2d( 
-            pscene->verts[ tri[0] ].co,
-            pscene->verts[ tri[1] ].co,
-            pscene->verts[ tri[2] ].co, pos, &height ))
-      {
-         v3f v0, v1;
-
-         v3_sub( pscene->verts[ tri[1] ].co,
-                 pscene->verts[ tri[0] ].co,
-                 v0 );
-
-         v3_sub( pscene->verts[ tri[2] ].co,
-                 pscene->verts[ tri[0] ].co,
-                 v1 );
-
-         v3_cross( v0, v1, normal );
-         v3_normalize( normal );
-         return;
-      }
-   }
+   mesh->indice_count = ctx->indice_count;
+   mesh->loaded = 1;
 
-   normal[0] = 0.0f;
-   normal[1] = 1.0f;
-   normal[2] = 0.0f;
+   vg_info( "Scene upload ( XYZ_f32 UV_f32 XYZW_i8 )[ u32 ]\n" );
+   vg_info( "   indices:%u\n", ctx->indice_count );
+   vg_info( "   verts:%u\n",   ctx->vertex_count );
 }
 
-struct bvh_node
+static void scene_upload_async( scene_context *ctx, glmesh *mesh )
 {
-   boxf bbx;
+   vg_async_item *call = vg_async_alloc( sizeof(struct scene_upload_info) );
 
-   /* if il is 0, this is a leaf */
-   u32 il, count;
-   union{ u32 ir, start; };
-};
+   struct scene_upload_info *info = call->payload;
+   info->mesh = mesh;
+   info->ctx = ctx;
 
-static void bvh_update_bounds( scene *s, u32 inode )
-{
-   bvh_node *node = &s->bvh.nodes[ inode ];
-
-   box_init_inf( node->bbx );
-   for( u32 i=0; i<node->count; i++ )
-   {
-      u32 idx = node->start+i;
-      model_vert *pa = &s->verts[ s->indices[idx*3+0] ],
-                 *pb = &s->verts[ s->indices[idx*3+1] ],
-                 *pc = &s->verts[ s->indices[idx*3+2] ];
-      
-     box_addpt( node->bbx, pa->co );
-     box_addpt( node->bbx, pb->co );
-     box_addpt( node->bbx, pc->co );
-   }
+   vg_async_dispatch( call, async_scene_upload );
 }
 
-static void bvh_subdiv( scene *s, u32 inode )
+static
+vg_async_item *scene_alloc_async( scene_context *scene, glmesh *mesh,
+                                  u32 max_vertices, u32 max_indices )
 {
-   bvh_node *node = &s->bvh.nodes[ inode ];
+   scene_init( scene, max_vertices, max_indices );
+   u32 buf_size = scene_mem_required( scene );
 
-   v3f extent;
-   v3_sub( node->bbx[1], node->bbx[0], extent );
+   u32 hdr_size = vg_align8(sizeof(struct scene_upload_info));
+   vg_async_item *call = vg_async_alloc( hdr_size + buf_size );
 
-   int axis = 0;
-   if( extent[1] > extent[0] ) axis = 1;
-   if( extent[2] > extent[axis] ) axis = 2;
+   struct scene_upload_info *info = call->payload;
 
-   float split = node->bbx[0][axis] + extent[axis]*0.5f;
+   info->mesh = mesh;
+   info->ctx = scene;
 
-   /* To beat: 121,687 / 136,579 
-    *          136,375
-    */
+   void *buffer = ((u8*)call->payload)+hdr_size;
+   scene_supply_buffer( scene, buffer );
 
-   float avg = 0.0;
-   for( u32 t=0; t<node->count; t++ )
-   {
-      u32 *ti = &s->indices[(node->start+t)*3];
-      float a = s->verts[ti[0]].co[axis],
-             b = s->verts[ti[1]].co[axis],
-             c = s->verts[ti[2]].co[axis];
-      avg += (a+b+c)/3.0;
-   }
-   avg /= (float)node->count;
+   return call;
+}
 
-   split = avg;
 
-   i32 i = node->start,
-       j = i + node->count-1;
+/*
+ * BVH implementation
+ */
+
+static void scene_bh_expand_bound( void *user, boxf bound, u32 item_index )
+{
+   scene_context *s = user;
+   scene_vert *pa = &s->arrvertices[ s->arrindices[item_index*3+0] ],
+              *pb = &s->arrvertices[ s->arrindices[item_index*3+1] ],
+              *pc = &s->arrvertices[ s->arrindices[item_index*3+2] ];
    
-   while( i <= j )
-   {
-      u32 *ti = &s->indices[i*3];
-
-      float a = s->verts[ti[0]].co[axis],
-            b = s->verts[ti[1]].co[axis],
-            c = s->verts[ti[2]].co[axis];
-
-      if( ((a+b+c) / 3.0f) < split )
-         i ++;
-      else
-      {
-         /* Swap triangle indices */
-         u32 *tj = &s->indices[j*3];
-         u32 temp[3];
-         temp[0] = ti[0];
-         temp[1] = ti[1];
-         temp[2] = ti[2];
-
-         ti[0] = tj[0];
-         ti[1] = tj[1];
-         ti[2] = tj[2];
-
-         tj[0] = temp[0];
-         tj[1] = temp[1];
-         tj[2] = temp[2];
-
-         j --;
-      }
-   }
+  box_addpt( bound, pa->co );
+  box_addpt( bound, pb->co );
+  box_addpt( bound, pc->co );
+}
 
-   u32 left_count = i - node->start;
-   if( left_count == 0 || left_count == node->count ) return;
+static float scene_bh_centroid( void *user, u32 item_index, int axis )
+{
+   scene_context *s = user;
+   scene_vert *pa = &s->arrvertices[ s->arrindices[item_index*3+0] ],
+              *pb = &s->arrvertices[ s->arrindices[item_index*3+1] ],
+              *pc = &s->arrvertices[ s->arrindices[item_index*3+2] ];
 
-   u32 il = s->bvh.node_count ++,
-       ir = s->bvh.node_count ++;
+   #if 0
 
-   struct bvh_node *lnode = &s->bvh.nodes[il],
-                   *rnode = &s->bvh.nodes[ir];
+   float min, max;
 
-   lnode->start = node->start;
-   lnode->count = left_count;
-   rnode->start = i;
-   rnode->count = node->count - left_count;
+   min = vg_minf( pa->co[axis], pb->co[axis] );
+   max = vg_maxf( pa->co[axis], pb->co[axis] );
+   min = vg_minf( min, pc->co[axis] );
+   max = vg_maxf( max, pc->co[axis] );
 
-   node->il = il;
-   node->ir = ir;
-   node->count = 0;
+   return (min+max) * 0.5f;
 
-   bvh_update_bounds( s, il );
-   bvh_update_bounds( s, ir );
-   bvh_subdiv( s, il );
-   bvh_subdiv( s, ir );
+   #else
+   return (pa->co[axis] + pb->co[axis] + pc->co[axis]) * (1.0f/3.0f);
+   #endif
 }
 
-static void bvh_create( scene *s )
+static void scene_bh_swap( void *user, u32 ia, u32 ib )
 {
-   u32 triangle_count = s->indice_count / 3;
-   s->bvh.nodes = malloc( sizeof(struct bvh_node) * (triangle_count*2-1) );
+   scene_context *s = user;
 
-   bvh_node *root = &s->bvh.nodes[0];
-   s->bvh.node_count = 1;
-   
-   root->il = 0;
-   root->ir = 0;
-   root->count = triangle_count;
-   root->start = 0;
+   u32 *ti = &s->arrindices[ia*3];
+   u32 *tj = &s->arrindices[ib*3];
 
-   bvh_update_bounds( s, 0 );
-   bvh_subdiv( s, 0 );
+   u32 temp[3];
+   temp[0] = ti[0];
+   temp[1] = ti[1];
+   temp[2] = ti[2];
 
-   s->bvh.nodes = 
-      realloc( s->bvh.nodes, sizeof(struct bvh_node) * s->bvh.node_count );
+   ti[0] = tj[0];
+   ti[1] = tj[1];
+   ti[2] = tj[2];
 
-   vg_success( "BVH done, size: %u/%u\n", s->bvh.node_count,
-                                          (triangle_count*2-1) );
+   tj[0] = temp[0];
+   tj[1] = temp[1];
+   tj[2] = temp[2];
 }
 
-static void bvh_debug_node( scene *s, u32 inode, v3f pos, u32 colour )
+static void scene_bh_debug( void *user, u32 item_index )
 {
-   struct bvh_node *node = &s->bvh.nodes[ inode ];
-
-   if( (pos[0] >= node->bbx[0][0] && pos[0] <= node->bbx[1][0]) &&
-       (pos[2] >= node->bbx[0][2] && pos[2] <= node->bbx[1][2]) )
-   {
-      if( !node->count )
-      {
-         vg_line_boxf( node->bbx, colour );
-
-         bvh_debug_node( s, node->il, pos, colour );
-         bvh_debug_node( s, node->ir, pos, colour );
-      }
-      else
-      {
-         vg_line_boxf( node->bbx, 0xff00ff00 );
-         for( u32 i=0; i<node->count; i++ )
-         {
-            u32 idx = (node->start+i)*3;
-
-            model_vert *pa = &s->verts[ s->indices[ idx+0 ] ],
-                       *pb = &s->verts[ s->indices[ idx+1 ] ],
-                       *pc = &s->verts[ s->indices[ idx+2 ] ];
-
-            vg_line( pa->co, pb->co, 0xff0000ff );
-            vg_line( pb->co, pc->co, 0xff0000ff );
-            vg_line( pc->co, pa->co, 0xff0000ff );
-         }
-      }
-   }
-}
-
-static void bvh_debug( scene *s, v3f pos )
-{
-   bvh_debug_node( s, 0, pos, 0x4000ffa8 );
+   scene_context *s = user;
+   u32 idx = item_index*3;
+   scene_vert *pa = &s->arrvertices[ s->arrindices[ idx+0 ] ],
+              *pb = &s->arrvertices[ s->arrindices[ idx+1 ] ],
+              *pc = &s->arrvertices[ s->arrindices[ idx+2 ] ];
+
+   vg_line( pa->co, pb->co, 0xff0000ff );
+   vg_line( pb->co, pc->co, 0xff0000ff );
+   vg_line( pc->co, pa->co, 0xff0000ff );
 }
 
-typedef struct ray_hit ray_hit;
-struct ray_hit
+static void scene_bh_closest( void *user, u32 index, v3f point, v3f closest )
 {
-   float dist;
-   u32 *tri;
-   v3f pos, normal;
-};
+   scene_context *s = user;
 
-int ray_aabb( boxf box, v3f co, v3f dir, float dist )
-{
-   v3f v0, v1;
-   float tmin, tmax;
-
-   v3_sub( box[0], co, v0 );
-   v3_sub( box[1], co, v1 );
-   v3_div( v0, dir, v0 );
-   v3_div( v1, dir, v1 );
-   
-   tmin = vg_minf( v0[0], v1[0] );
-   tmax = vg_maxf( v0[0], v1[0] );
-   tmin = vg_maxf( tmin, vg_minf( v0[1], v1[1] ));
-   tmax = vg_minf( tmax, vg_maxf( v0[1], v1[1] ));
-   tmin = vg_maxf( tmin, vg_minf( v0[2], v1[2] ));
-   tmax = vg_minf( tmax, vg_maxf( v0[2], v1[2] ));
-
-   return tmax >= tmin && tmin < dist && tmax > 0;
-}
-
-static int bvh_ray_tri( scene *sc, u32 *tri, v3f co, v3f dir, ray_hit *hit )
-{
    v3f positions[3];
+   u32 *tri = &s->arrindices[ index*3 ];
    for( int i=0; i<3; i++ )
-      v3_copy( sc->verts[tri[i]].co, positions[i] );
-   
-   float t;
-   if(ray_tri( positions, co, dir, &t ))
-   {
-      if( t < hit->dist )
-      {
-         hit->dist = t;
-         hit->tri = tri;
-         return 1;
-      }
-   }
+      v3_copy( s->arrvertices[tri[i]].co, positions[i] );
 
-   return 0;
+   closest_on_triangle_1( point, positions, closest );
 }
 
-static int bvh_ray( scene *s, u32 inode, v3f co, v3f dir, ray_hit *hit )
+static bh_system bh_system_scene = 
 {
-   bvh_node *node = &s->bvh.nodes[ inode ];
-   
-   if( !ray_aabb( node->bbx, co, dir, hit->dist )) 
-      return 0;
-
-   int count = 0;
+   .expand_bound = scene_bh_expand_bound,
+   .item_centroid = scene_bh_centroid,
+   .item_closest = scene_bh_closest,
+   .item_swap = scene_bh_swap,
+   .item_debug = scene_bh_debug,
+   .system_type = 0x1
+};
 
-   if( node->count )
-   {
-      for( u32 i=0; i<node->count; i++ )
-      {
-         u32 *indices = &s->indices[ (node->start+i)*3 ];
-         count += bvh_ray_tri( s, indices, co, dir, hit );
-      }
-   }
-   else
-   {
-      count += bvh_ray( s, node->il, co, dir, hit );
-      count += bvh_ray( s, node->ir, co, dir, hit );
-   }
+/*
+ * An extra step is added onto the end to calculate the hit normal
+ */
+static int scene_raycast( scene_context *s, bh_tree *bh, 
+                             v3f co, v3f dir, ray_hit *hit, u16 ignore )
+{
+   hit->tri = NULL;
 
-   return count;
-}
+   bh_iter it;
+   bh_iter_init_ray( 0, &it, co, dir, hit->dist );
+   i32 idx;
 
-static int bvh_raycast( scene *s, v3f co, v3f dir, ray_hit *hit )
-{
-   v3f pb;
-   v3_muladds( co, dir, hit->dist, pb );
+   while( bh_next( bh, &it, &idx ) ){
+      u32 *tri = &s->arrindices[ idx*3 ];
 
-   int count = bvh_ray( s, 0, co, dir, hit );
+      if( s->arrvertices[tri[0]].flags & ignore )  continue;
 
-   if( count )
-   {
-      //vg_line( co, pb, 0xff00ffff );
+      v3f vs[3];
+      for( u32 i=0; i<3; i++ )
+         v3_copy( s->arrvertices[tri[i]].co, vs[i] );
+      
+      f32 t;
+      if( ray_tri( vs, co, dir, &t, 0 ) ){
+         if( t < hit->dist ){
+            hit->dist = t;
+            hit->tri = tri;
+         }
+      }
+   }
 
+   if( hit->tri ){
       v3f v0, v1;
       
-      float *pa = s->verts[hit->tri[0]].co,
-            *pb = s->verts[hit->tri[1]].co,
-            *pc = s->verts[hit->tri[2]].co;
+      float *pa = s->arrvertices[hit->tri[0]].co,
+            *pb = s->arrvertices[hit->tri[1]].co,
+            *pc = s->arrvertices[hit->tri[2]].co;
 
       v3_sub( pa, pb, v0 );
       v3_sub( pc, pb, v1 );
@@ -642,128 +435,14 @@ static int bvh_raycast( scene *s, v3f co, v3f dir, ray_hit *hit )
       v3_normalize( hit->normal );
       v3_muladds( co, dir, hit->dist, hit->pos );
    }
-   else
-   {
-      //vg_line( co, pb, 0xff0000ff );
-   }
-
-   return count;
-}
-
-static int bvh_select_triangles( scene *s, boxf box, u32 *triangles, int len )
-{
-   /* TODO: use this stack system on the raycast function */
-   int count = 0;
-   u32 stack[100];
-   u32 depth = 2;
-
-   stack[0] = 0;
-   stack[1] = s->bvh.nodes[0].il;
-   stack[2] = s->bvh.nodes[0].ir;
-   
-   while(depth)
-   {
-      bvh_node *inode = &s->bvh.nodes[ stack[depth] ];
-      if( box_overlap( inode->bbx, box ) )
-      {
-         if( inode->count )
-         {
-            if( count + inode->count >= len )
-            {
-               vg_error( "Maximum buffer reached!\n" );
-               return count;
-            }
-
-            for( u32 i=0; i<inode->count; i++ )
-               triangles[ count ++ ] = (inode->start+i)*3;
-
-            depth --;
-         }
-         else
-         {
-            if( depth+1 >= vg_list_size(stack) )
-            {
-               vg_error( "Maximum stack reached!\n" );
-               return count;
-            }
-
-            stack[depth] = inode->il;
-            stack[depth+1] = inode->ir;
-            depth ++;
-         }
-      }
-      else
-      {
-         depth --;
-      }
-   }
 
-   return count;
+   return hit->tri?1:0;
 }
 
-static int bvh_scene_sample_node_h( scene *s, u32 inode, v3f pos, v3f norm )
+static bh_tree *scene_bh_create( void *lin_alloc, scene_context *s )
 {
-   bvh_node *node = &s->bvh.nodes[ inode ];
-
-   if( (pos[0] >= node->bbx[0][0] && pos[0] <= node->bbx[1][0]) &&
-       (pos[2] >= node->bbx[0][2] && pos[2] <= node->bbx[1][2]) )
-   {
-      if( !node->count )
-      {
-         if( bvh_scene_sample_node_h( s, node->il, pos, norm )) return 1;
-         if( bvh_scene_sample_node_h( s, node->ir, pos, norm )) return 1;
-      }
-      else
-      {
-         for( u32 i=0; i<node->count; i++ )
-         {
-            u32 idx = (node->start+i)*3;
-            model_vert *pa = &s->verts[ s->indices[ idx+0 ] ],
-                       *pb = &s->verts[ s->indices[ idx+1 ] ],
-                       *pc = &s->verts[ s->indices[ idx+2 ] ];
-            
-            float height;
-            if( triangle_raycast2d( pa->co, pb->co, pc->co, pos, &height ))
-            {
-               pos[1] = height;
-               
-               if( norm )
-               {
-                  v3f v0, v1;
-                  v3_sub( pa->co, pb->co, v0 );
-                  v3_sub( pc->co, pb->co, v1 );
-                  v3_cross( v1, v0, norm );
-                  v3_normalize( norm );
-               }
-
-               return 1;
-            }
-         }
-      }
-   }
-
-   return 0;
-}
-
-static int bvh_scene_sample_h( scene *s, v3f pos, v3f norm)
-{
-   return bvh_scene_sample_node_h( s, 0, pos, norm );
-}
-
-static int bvh_scene_sample( scene *s, v3f pos, ray_hit *hit )
-{
-   hit->dist = INFINITY;
-
-   v3f ray_pos;
-   v3_add( pos, (v3f){0.0f,4.0f,0.0f}, ray_pos );
-
-   if( bvh_raycast( s, ray_pos, (v3f){0.0f,-1.0f,0.0f}, hit ))
-   {
-      pos[1] = hit->pos[1];
-      return 1;
-   }
-
-   return 0;
+   u32 triangle_count = s->indice_count / 3;
+   return bh_create( lin_alloc, &bh_system_scene, s, triangle_count, 2 );
 }
 
 #endif