nonlocal stuff again
[carveJwlIkooP6JGAAIwe30JlM.git] / world.h
diff --git a/world.h b/world.h
index a7b5a587b1e0a55318dc1de1990de5db456579f4..809397151e854c64b4508ceaf139a8e0e1c40c88 100644 (file)
--- a/world.h
+++ b/world.h
@@ -4,11 +4,11 @@
 
 #include "common.h"
 
-static int ray_world( v3f pos, v3f dir, ray_hit *hit );
-
 #ifndef WORLD_H
 #define WORLD_H
 
+typedef struct world_instance world_instance;
+
 #include "vg/vg_loader.h"
 
 #include "network.h"
@@ -18,220 +18,332 @@ static int ray_world( v3f pos, v3f dir, ray_hit *hit );
 #include "rigidbody.h"
 #include "bvh.h"
 #include "model.h"
+#include "entity.h"
+#include "font.h"
 
-#include "traffic.h" /*TODO: -> world_traffic.h */
+#include "shaders/scene_standard.h"
+#include "shaders/scene_standard_alphatest.h"
+#include "shaders/scene_vertex_blend.h"
+#include "shaders/scene_terrain.h"
+#include "shaders/scene_depth.h"
+#include "shaders/scene_position.h"
 
-#include "shaders/terrain.h"
-#include "shaders/sky.h"
-#include "shaders/planeinf.h"
-#include "shaders/standard.h"
-#include "shaders/vblend.h"
-#include "shaders/gpos.h"
-#include "shaders/fscolour.h"
-#include "shaders/alphatest.h"
+#include "shaders/model_sky.h"
 
 enum { k_max_ui_segments = 8 };
-enum { k_max_ui_splits_per_segment = 16 };
 
-enum { k_max_ui_elements = k_max_ui_segments*k_max_ui_splits_per_segment };
+enum { k_max_ui_elements = k_max_ui_segments };
 enum { k_max_element_verts = 10 };
 enum { k_max_element_indices = 20 };
 
 enum { k_route_ui_max_verts = k_max_ui_elements*k_max_element_verts };
 enum { k_route_ui_max_indices = k_max_ui_elements*k_max_element_indices };
 
-static struct gworld
+enum logic_type
 {
-   struct subworld_gen
-   {
-      
-   }
-   subworld_gen;
+   k_logic_type_relay         = 1,
+   k_logic_type_chance        = 2,
+   k_logic_type_achievement   = 3
+};
 
-   /* gameplay */
-   struct respawn_point
-   {
-      v3f co;
-      v4f q;
-      char name[32];
+enum geo_type
+{
+   k_geo_type_solid = 0,
+   k_geo_type_nonsolid = 1,
+   k_geo_type_water = 2
+};
+
+static const float k_light_cube_size = 8.0f;
+
+struct world_instance {
+   /* Fixed items
+    * -------------------------------------------------------
+    */
+
+   void *heap;
+   char  world_name[ 64 ];
+   enum world_status{
+      k_world_status_unloaded = 0,
+      k_world_status_loading = 1,
+      k_world_status_loaded = 2
    }
-   spawns[32];
-   u32 spawn_count;
+   status;
 
-   struct subworld_routes
-   {
-      struct route_node
-      {
-         v3f co, right, up, h;
-         u32 next[2];
+   struct{
+      boxf depthbounds;
+      int depth_computed;
 
-         u32 special_type, special_id, current_refs, ref_count;
-         u32 route_ids[4];    /* Gates can be linked into up to four routes */
-      }
-      *nodes;
+      float height;
+      int enabled;
+      v4f plane;
+   }
+   water;
+
+   /* STD140 */
+   struct ub_world_lighting{
+      v4f g_cube_min,
+          g_cube_inv_range;
+
+      v4f g_water_plane,
+          g_depth_bounds;
+
+      v4f g_daysky_colour;
+      v4f g_nightsky_colour;
+      v4f g_sunset_colour;
+      v4f g_ambient_colour;
+      v4f g_sunset_ambient;
+      v4f g_sun_colour;
+      v4f g_sun_dir;
+      v4f g_board_0;
+      v4f g_board_1;
+
+      float g_water_fog;
+      float g_time;
+      float g_realtime;
+      float g_shadow_length;
+      float g_shadow_spread;
+
+      float g_time_of_day;
+      float g_day_phase;
+      float g_sunset_phase;
+
+      int g_light_preview;
+      int g_shadow_samples;
+
+      int g_debug_indices;
+      int g_debug_complexity;
+   }
+   ub_lighting;
+   GLuint ubo_lighting;
+   int    ubo_bind_point;
+
+   GLuint tbo_light_entities,
+          tex_light_entities,
+          tex_light_cubes;
+
+   float probabilities[3];
+
+   v3i light_cubes;
+
+   struct framebuffer heightmap;
+
+   /*
+    * Dynamically allocated when world_load is called.
+    *
+    *                  the following arrays index somewhere into this linear 
+    *                  allocator
+    *
+    * (world_gen.h)
+    * --------------------------------------------------------------------------
+    */
+
+   /*
+    * Main world .mdl 
+    */
+   mdl_context meta;
+
+   GLuint *textures;
+   u32 texture_count;
+
+   struct world_surface{
+      mdl_material info;
+      mdl_submesh sm_geo,
+                  sm_no_collide;
+   }
+   * surfaces;
+   u32 surface_count;
+
+   mdl_array_ptr ent_spawn,
+                 ent_gate,
+                 ent_light,
+                 ent_route_node,
+                 ent_path_index,
+                 ent_checkpoint,
+                 ent_route,
+                 ent_water,
+
+                 ent_audio_clip,
+                 ent_audio,
+                 ent_volume;
+
+   ent_gate *rendering_gate;
+
+   /* logic 
+    * ----------------------------------------------------
+    */
+
+   /* world geometry */
+   scene *scene_geo, 
+         *scene_no_collide,
+         *scene_lines;
+
+   /* spacial mappings */
+   bh_tree *audio_bh,
+           *volume_bh,
+           *geo_bh;
+
+   /* graphics */
+   glmesh mesh_route_lines;
+   glmesh mesh_geo, 
+          mesh_no_collide,
+          mesh_water;
+
+   rb_object rb_geo;
+};
+
+struct world_global{
+   /*
+    * Allocated as system memory
+    * --------------------------------------------------------------------------
+    */
+   void *heap;
+
+   /* rendering */
+   glmesh skydome;
+   glmesh mesh_gate;
+   mdl_submesh sm_gate_surface,
+               sm_gate_marker[4];
+
+   double sky_time, sky_rate, sky_target_rate;
+
+   u32 current_run_version;
+   double time, rewind_from, rewind_to, last_use;
+
+   /* water rendering */
+   struct{
+      struct framebuffer fbreflect, fbdepth;
+   }
+   water;
 
-      u32 node_count,
-          node_cap;
+   /* split flap display */
+   struct{
+      glmesh mesh_base, mesh_display;
+      mdl_submesh sm_base;
+      u32 active_route_board;
 
-      struct route
-      {
-         u32 track_id;
-         v4f colour;
+      u32 w, h;
+      float *buffer;
+   }
+   sfd;
 
-         u32 start;
-         mdl_submesh sm;
-         
-         int active;
-         float factive;
+   v3f render_gate_pos;
+   int in_volume;
 
-         double best_lap, latest_pass; /* Session */
+   int switching_to_new_world;
 
-         struct 
-         {
-            GLuint vao, vbo, ebo;
+   world_instance worlds[4];
+   u32            world_count;
+   u32            active_world;
 
-            u32  indices_head;
-            u32  vertex_head;
+   /* text particles */
+   font3d font;
 
-            float last_notch;
+   struct timer_text{
+      char text[8];
+      m4x3f transform;
+      ent_gate *gate;
+      ent_route *route;
+   }
+   timer_texts[4];
+   u32 timer_text_count;
 
-            struct route_ui_segment
-            {
-               float length;
-               u32 vertex_start, vertex_count,
-                   index_start, index_count, notches;
-            }
-            segments[k_max_ui_segments];
+   struct text_particle{
+      rb_object obj;
+      m4x3f mlocal;
+      ent_glyph *glyph;
+      v4f colour;
 
-            u32 segment_start, segment_count, fade_start, fade_count;
-            double fade_timer_start;
-            float xpos;
-         }
-         ui;
+      m4x3f mdl;
+   }
+   text_particles[6*4];
+   u32 text_particle_count;
+}
+static world_global;
 
-         m4x3f scoreboard_transform;
-      }
-      *routes;
+VG_STATIC world_instance *get_active_world( void )
+{
+   return &world_global.worlds[ world_global.active_world ];
+}
 
-      double last_interaction;
+/*
+ * API
+ */
 
-      u32 route_count,
-          route_cap;
+VG_STATIC 
+int ray_hit_is_ramp( world_instance *world, ray_hit *hit );
 
-      struct route_gate
-      {
-         struct teleport_gate
-         { 
-            v3f co[2];
-            v4f q[2];
-            v2f dims;
-
-            m4x3f to_world, recv_to_world, transport;
-         } 
-         gate;
-         
-         u32 node_id;
-
-         struct route_timing
-         {
-            u32 version; /* Incremented on every teleport */
-            double time;
-         } 
-         timing;
-      }
-      *gates;
+VG_STATIC 
+struct world_surface *ray_hit_surface( world_instance *world, ray_hit *hit );
 
-      struct route_collector
-      {
-         struct route_timing timing;
-      }
-      *collectors;
+VG_STATIC 
+void ray_world_get_tri( world_instance *world, ray_hit *hit, v3f tri[3] );
 
-      u32 gate_count,
-          gate_cap,
-          collector_count,
-          collector_cap;
+VG_STATIC 
+int ray_world( world_instance *world, v3f pos, v3f dir, ray_hit *hit );
 
-      u32 active_gate,
-          current_run_version;
+VG_STATIC
+ent_spawn *world_find_closest_spawn( world_instance *world, v3f position )
+{
+   ent_spawn *rp = NULL, *r;
+   float min_dist = INFINITY;
 
-      scene scene_lines;
+   for( u32 i=0; i<mdl_arrcount(&world->ent_spawn); i++ ){
+      r = mdl_arritm( &world->ent_spawn, i );
+      float d = v3_dist2( r->transform.co, position );
+      
+      if( d < min_dist ){
+         min_dist = d;
+         rp = r;
+      }
    }
-   routes;
 
-   struct subworld_sfd
-   {
-      scene mesh;
-      mdl_submesh *sm_module, *sm_card;
-      glmesh temp;
-
-      struct sfd_instance
-      {
-         float *buffer;
-
-         u32 w,h;
-      } 
-      tester;
+   if( !rp ){
+      if( mdl_arrcount(&world->ent_spawn) ){
+         vg_warn( "Invalid distances to spawns.. defaulting to first one.\n" );
+         return mdl_arritm( &world->ent_spawn, 0 );
+      }
+      else{
+         vg_error( "There are no spawns in the level!\n" );
+      }
    }
-   sfd;
-
-   /* Paths */
-   traffic_node traffic[128];
-   u32 traffic_count;
-
-#if 0
-   traffic_driver van_man[6];
-#endif
-   
-   /* Physics */
-   
-   /* Rendering & geometry */
-   scene geo, foliage;
-   rigidbody rb_geo;
 
-   /* TODO Maybe make this less hardcoded */
-   mdl_submesh sm_geo_std_oob, sm_geo_std, sm_geo_vb,
-               sm_foliage_main, sm_foliage_alphatest,
-               sm_graffiti, sm_subworld, sm_terrain;
-
-   glmesh skybox, skydome;
-   mdl_submesh dome_upper, dome_lower;
-
-   glmesh cars;
-   mdl_submesh car_holden;
-
-   /* Load time */
+   return rp;
+}
 
-   struct instance_cache
-   {
-      mdl_header *mdl;
-      u32 pstr_file;
+VG_STATIC
+ent_spawn *world_find_spawn_by_name( world_instance *world, const char *name )
+{
+   ent_spawn *rp = NULL, *r;
+   for( u32 i=0; i<mdl_arrcount(&world->ent_spawn); i++ ){
+      r = mdl_arritm( &world->ent_spawn, i );
+      if( !strcmp( mdl_pstr(&world->meta, r->pstr_name), name ) ){
+         rp = r;
+         break;
+      }
    }
-   * instance_cache;
-   u32 instance_cache_count,
-       instance_cache_cap;
 
-   v3f render_gate_pos;
-   int active_route_board;
+   if( !rp )
+      vg_warn( "No spawn named '%s'\n", name );
+
+   return rp;
 }
-world;
 
 /*
- * API
+ * Submodules
  */
 
-static int ray_hit_is_ramp( ray_hit *hit );
-static int ray_hit_is_terrain( ray_hit *hit );
-static void ray_world_get_tri( ray_hit *hit, v3f tri[3] );
-static int ray_world( v3f pos, v3f dir, ray_hit *hit );
+VG_STATIC float
+   k_day_length            = 30.0f; /* minutes */
+
+VG_STATIC int   k_debug_light_indices = 0,
+                k_debug_light_complexity = 0,
+                k_light_preview = 0;
 
-/*
- * Submodules
- */
 #include "world_routes.h"
 #include "world_sfd.h"
 #include "world_render.h"
 #include "world_water.h"
+#include "world_volumes.h"
 #include "world_gen.h"
 #include "world_gate.h"
 
@@ -241,96 +353,328 @@ static int ray_world( v3f pos, v3f dir, ray_hit *hit );
  * -----------------------------------------------------------------------------
  */
 
-static void world_init(void)
+VG_STATIC int world_stop_sound( int argc, const char *argv[] )
 {
-   shader_terrain_register();
-   shader_sky_register();
-   shader_planeinf_register();
-   shader_gpos_register();
-   shader_fscolour_register();
-   shader_alphatest_register();
+   world_instance *world = get_active_world();
+   return 0;
+}
 
-   vg_info( "Loading world resources\n" );
+VG_STATIC void world_init(void)
+{
+   VG_VAR_F32( k_day_length );
+   VG_VAR_I32( k_debug_light_indices );
+   VG_VAR_I32( k_debug_light_complexity );
+   VG_VAR_I32( k_light_preview );
 
-   VG_REQUIRED_ASSET( mdl_header*, mcars, mdl_load, "models/rs_cars.mdl" );
-   VG_REQUIRED_ASSET( mdl_header*, msky,  mdl_load, "models/rs_skydome.mdl" );
+   world_global.sky_rate = 1.0;
+   world_global.sky_target_rate = 1.0;
 
-   mdl_node *nholden = mdl_node_from_name( mcars, "holden" );
-   world.car_holden = *mdl_node_submesh( mcars, nholden, 0 );
+   shader_scene_standard_register();
+   shader_scene_standard_alphatest_register();
+   shader_scene_vertex_blend_register();
+   shader_scene_terrain_register();
+   shader_scene_depth_register();
+   shader_scene_position_register();
 
-   mdl_node *nlower = mdl_node_from_name( msky, "dome_lower" ),
-            *nupper = mdl_node_from_name( msky, "dome_upper" );
+   shader_model_sky_register();
+
+   vg_info( "Loading world resources\n" );
    
-   world.dome_lower = *mdl_node_submesh( msky, nlower, 0 );
-   world.dome_upper = *mdl_node_submesh( msky, nupper, 0 );
+   vg_linear_clear( vg_mem.scratch );
+
+   mdl_context msky;
+   mdl_open( &msky, "models/rs_skydome.mdl", vg_mem.scratch );
+   mdl_load_metadata_block( &msky, vg_mem.scratch );
+   mdl_load_mesh_block( &msky, vg_mem.scratch );
+   mdl_close( &msky );
 
    vg_acquire_thread_sync();
    {
-      mdl_unpack_glmesh( mcars, &world.cars );
-      mdl_unpack_glmesh( msky, &world.skydome );
+      mdl_unpack_glmesh( &msky, &world_global.skydome );
    }
    vg_release_thread_sync();
 
-   vg_free(mcars);
-   vg_free(msky);
-
    /* Other systems */
    vg_info( "Loading other world systems\n" );
 
-   vg_loader_highwater( world_render_init, world_render_free, NULL );
-   vg_loader_highwater( world_sfd_init, world_sfd_free, NULL );
-   vg_loader_highwater( world_water_init, world_water_free, NULL );
-   vg_loader_highwater( world_gates_init, world_gates_free, NULL );
-   vg_loader_highwater( world_routes_init, world_routes_free, NULL );
+   vg_loader_step( world_render_init, NULL );
+   vg_loader_step( world_sfd_init, NULL );
+   vg_loader_step( world_water_init, NULL );
+   vg_loader_step( world_gates_init, NULL );
+   vg_loader_step( world_routes_init, NULL );
+
+   /* Allocate dynamic world memory arena */
+   u32 max_size = 76*1024*1024;
+   world_global.heap = vg_create_linear_allocator( vg_mem.rtmemory, max_size,
+                                                   VG_MEMORY_SYSTEM );
+}
+
+typedef struct ent_call ent_call;
+struct ent_call{
+   ent_index ent;
+   u32 function;
+   void *data;
+};
+
+VG_STATIC void entity_call( world_instance *world, ent_call *call );
+
+VG_STATIC void ent_volume_call( world_instance *world, ent_call *call )
+{
+   ent_volume *volume = mdl_arritm( &world->ent_volume, call->ent.index );
+   if( !volume->target.type ) return;
+
+   if( call->function == k_ent_function_trigger ){
+      call->ent = volume->target;
+
+      if( volume->type == k_volume_subtype_particle ){
+         float *co = alloca( sizeof(float)*3 );
+         co[0] = vg_randf()*2.0f-1.0f;
+         co[1] = vg_randf()*2.0f-1.0f;
+         co[2] = vg_randf()*2.0f-1.0f;
+         m4x3_mulv( volume->to_world, co, co );
+
+         call->function = k_ent_function_particle_spawn;
+         call->data = co;
+         entity_call( world, call );
+      }
+      else
+         entity_call( world, call );
+   }
+}
+
+VG_STATIC void ent_audio_call( world_instance *world, ent_call *call )
+{
+   ent_audio *audio = mdl_arritm( &world->ent_audio, call->ent.index );
+
+   v3f sound_co;
+
+   if( call->function == k_ent_function_particle_spawn ){
+      v3_copy( call->data, sound_co );
+   }
+   else if( call->function == k_ent_function_trigger ){
+      v3_copy( audio->transform.co, sound_co );
+   }
+   else
+      vg_fatal_exit_loop( "ent_audio_call (invalid function id)" );
+
+   float chance = vg_randf()*100.0f,
+         bar = 0.0f;
+
+   for( u32 i=0; i<audio->clip_count; i++ ){
+      ent_audio_clip *clip = mdl_arritm( &world->ent_audio_clip, 
+                                          audio->clip_start+i );
+
+      float mod = world->probabilities[ audio->probability_curve ],
+            p   = clip->probability * mod;
+
+      bar += p;
+
+      if( chance < bar ){
+
+         audio_lock();
+
+         if( audio->behaviour == k_channel_behaviour_unlimited ){
+            audio_oneshot_3d( &clip->clip, sound_co,
+                              audio->transform.s[0],
+                              audio->volume );
+         }
+         else if( audio->behaviour == k_channel_behaviour_discard_if_full ){
+            audio_channel *ch = 
+               audio_get_group_idle_channel( audio->group, 
+                                             audio->max_channels );
+
+            if( ch ){
+               audio_channel_init( ch, &clip->clip, audio->flags );
+               audio_channel_group( ch, audio->group );
+               audio_channel_set_spacial( ch, sound_co, audio->transform.s[0] );
+               audio_channel_edit_volume( ch, audio->volume, 1 );
+               ch = audio_relinquish_channel( ch );
+            }
+         }
+         else if( audio->behaviour == k_channel_behaviour_crossfade_if_full){
+            audio_channel *ch =
+               audio_get_group_idle_channel( audio->group,
+                                             audio->max_channels );
+
+            /* group is full */
+            if( !ch ){
+               audio_channel *existing = 
+                  audio_get_group_first_active_channel( audio->group );
+
+               if( existing ){
+                  if( existing->source == &clip->clip ){
+                     audio_unlock();
+                     return;
+                  }
+                 
+                  existing->group = 0;
+                  existing = audio_channel_fadeout(existing, audio->crossfade);
+               }
+
+               ch = audio_get_first_idle_channel();
+            }
+
+            if( ch ){
+               audio_channel_init( ch, &clip->clip, audio->flags );
+               audio_channel_group( ch, audio->group );
+               audio_channel_fadein( ch, audio->crossfade );
+               ch = audio_relinquish_channel( ch );
+            }
+         }
+
+         audio_unlock();
+         return;
+      }
+   }
 }
 
-static void world_free( void *_ )
+VG_STATIC void entity_call( world_instance *world, ent_call *call )
 {
-   mesh_free( &world.cars );
-   mesh_free( &world.skydome );
+   if( call->ent.type == k_ent_volume ){
+      ent_volume_call( world, call );
+   } else if( call->ent.type == k_ent_audio ){
+      ent_audio_call( world, call );
+   }
 }
 
-static void world_update( v3f pos )
+VG_STATIC void world_update( world_instance *world, v3f pos )
 {
-   world_routes_update();
-   world_routes_debug();
+   world_global.sky_time += world_global.sky_rate * vg.time_delta;
+   world_global.sky_rate = vg_lerp( world_global.sky_rate, 
+                                    world_global.sky_target_rate, 
+                                    vg.time_delta * 5.0 );
+
+   world_routes_update_timer_texts( world );
+   world_routes_update( world );
+   //world_routes_debug( world );
+
+   /* ---- SFD ------------ */
    
-   int closest = 0;
-   float min_dist = INFINITY;
+   if( mdl_arrcount( &world->ent_route ) ){
+      u32 closest = 0;
+      float min_dist = INFINITY;
 
-   for( int i=0; i<world.routes.route_count; i++ )
-   {
-      float d = v3_dist2( world.routes.routes[i].scoreboard_transform[3], pos );
+      for( u32 i=0; i<mdl_arrcount( &world->ent_route ); i++ ){
+         ent_route *route = mdl_arritm( &world->ent_route, i );
+         float dist = v3_dist2( route->board_transform[3], pos );
+
+         if( dist < min_dist ){
+            min_dist = dist;
+            closest = i;
+         }
+      }
 
-      if( d < min_dist )
+      if( (world_global.sfd.active_route_board != closest) 
+          || network_scores_updated )
       {
-         min_dist = d;
-         closest = i;
+         network_scores_updated = 0;
+         world_global.sfd.active_route_board = closest;
+
+         ent_route *route = mdl_arritm( &world->ent_route, closest );
+         u32 id = route->official_track_id;
+
+         if( id != 0xffffffff ){
+            struct netmsg_board *local_board = 
+               &scoreboard_client_data.boards[id];
+
+            for( int i=0; i<13; i++ ){
+               sfd_encode( i, &local_board->data[27*i] );
+            }
+         }else{
+            sfd_encode( 0, mdl_pstr( &world->meta, route->pstr_name ) );
+            sfd_encode( 1, "No data" );
+         }
       }
    }
+   sfd_update();
 
-   if( (world.active_route_board != closest) || network_scores_updated )
-   {
-      network_scores_updated = 0;
-      world.active_route_board = closest;
-      struct subworld_sfd *sfd = &world.sfd;
+   static float random_accum = 0.0f;
+   random_accum += vg.time_delta;
 
-      struct route *route = &world.routes.routes[closest];
+   u32 random_ticks = 0;
 
-      u32 id = route->track_id;
+   while( random_accum > 0.1f ){
+      random_accum -= 0.1f;
+      random_ticks ++;
+   }
 
-      if( id != 0xffffffff )
-      {
-         struct netmsg_board *local_board = &scoreboard_client_data.boards[id];
+   float radius = 25.0f;
+   boxf volume_proximity;
+   v3_add( pos, (v3f){ radius, radius, radius }, volume_proximity[1] );
+   v3_sub( pos, (v3f){ radius, radius, radius }, volume_proximity[0] );
+
+   bh_iter it;
+   bh_iter_init( 0, &it );
+   int idx;
+
+   int in_volume = 0;
+
+   while( bh_next( world->volume_bh, &it, volume_proximity, &idx ) ){
+      ent_volume *volume = mdl_arritm( &world->ent_volume, idx );
 
-         for( int i=0; i<13; i++ )
+      boxf cube = {{-1.0f,-1.0f,-1.0f},{1.0f,1.0f,1.0f}};
+      
+      if( volume->type == k_volume_subtype_trigger ){
+         v3f local;
+         m4x3_mulv( volume->to_local, pos, local );
+
+         if( (fabsf(local[0]) <= 1.0f) &&
+             (fabsf(local[1]) <= 1.0f) &&
+             (fabsf(local[2]) <= 1.0f) )
          {
-            sfd_encode( &sfd->tester, i, &local_board->data[27*i] );
+            in_volume = 1;
+            vg_line_boxf_transformed( volume->to_world, cube, 0xff00ff00 );
+
+            if( !world_global.in_volume ){
+               ent_call basecall;
+               basecall.ent.index = idx;
+               basecall.ent.type = k_ent_volume;
+               basecall.function = k_ent_function_trigger;
+               basecall.data = NULL;
+
+               entity_call( world, &basecall );
+            }
+         }
+         else
+            vg_line_boxf_transformed( volume->to_world, cube, 0xff0000ff );
+      }
+      else if( volume->type == k_volume_subtype_particle ){
+         vg_line_boxf_transformed( volume->to_world, cube, 0xff00c0ff );
+
+         for( int j=0; j<random_ticks; j++ ){
+            ent_call basecall;
+            basecall.ent.index = idx;
+            basecall.ent.type = k_ent_volume;
+            basecall.function = k_ent_function_trigger;
+            basecall.data = NULL;
+
+            entity_call( world, &basecall );
          }
       }
    }
-   
-   sfd_update( &world.sfd.tester );
+   world_global.in_volume = in_volume;
+
+#if 0
+   if( k_debug_light_indices )
+   {
+      for( int i=0; i<world->light_count; i++ ){
+         struct world_light *light = &world->lights[i];
+         struct classtype_world_light *inf = light->inf;
+
+         u32 colour = 0xff000000;
+         u8 r = inf->colour[0] * 255.0f,
+            g = inf->colour[1] * 255.0f,
+            b = inf->colour[2] * 255.0f;
+
+         colour |= r;
+         colour |= g << 8;
+         colour |= b << 16;
+
+         vg_line_pt3( light->node->co, 0.25f, colour );
+      }
+   }
+
+#endif
 }
 
 /* 
@@ -339,33 +683,234 @@ static void world_update( v3f pos )
  * -----------------------------------------------------------------------------
  */
 
-static void ray_world_get_tri( ray_hit *hit, v3f tri[3] )
+VG_STATIC void ray_world_get_tri( world_instance *world,
+                                  ray_hit *hit, v3f tri[3] )
 {
    for( int i=0; i<3; i++ )
-      v3_copy( world.geo.verts[ hit->tri[i] ].co, tri[i] );
+      v3_copy( world->scene_geo->arrvertices[ hit->tri[i] ].co, tri[i] );
+}
+
+VG_STATIC int ray_world( world_instance *world,
+                         v3f pos, v3f dir, ray_hit *hit )
+{
+   return scene_raycast( world->scene_geo, world->geo_bh, pos, dir, hit );
+}
+
+/*
+ * Cast a sphere from a to b and see what time it hits
+ */
+VG_STATIC int spherecast_world( world_instance *world,
+                                v3f pa, v3f pb, float r, float *t, v3f n )
+{
+   bh_iter it;
+   bh_iter_init( 0, &it );
+
+   boxf region;
+   box_init_inf( region );
+   box_addpt( region, pa );
+   box_addpt( region, pb );
+   
+   v3_add( (v3f){ r, r, r}, region[1], region[1] );
+   v3_add( (v3f){-r,-r,-r}, region[0], region[0] );
+
+   v3f dir;
+   v3_sub( pb, pa, dir );
+
+   v3f dir_inv;
+   dir_inv[0] = 1.0f/dir[0];
+   dir_inv[1] = 1.0f/dir[1];
+   dir_inv[2] = 1.0f/dir[2];
+
+   int hit = -1;
+   float min_t = 1.0f;
+
+   int idx;
+   while( bh_next( world->geo_bh, &it, region, &idx ) ){
+      u32 *ptri = &world->scene_geo->arrindices[ idx*3 ];
+      v3f tri[3];
+
+      boxf box;
+      box_init_inf( box );
+
+      for( int j=0; j<3; j++ ){
+         v3_copy( world->scene_geo->arrvertices[ptri[j]].co, tri[j] );
+         box_addpt( box, tri[j] );
+      }
+
+      v3_add( (v3f){ r, r, r}, box[1], box[1] );
+      v3_add( (v3f){-r,-r,-r}, box[0], box[0] );
+
+      if( !ray_aabb1( box, pa, dir_inv, 1.0f ) )
+         continue;
+      
+      float t;
+      v3f n1;
+      if( spherecast_triangle( tri, pa, dir, r, &t, n1 ) ){
+         if( t < min_t ){
+            min_t = t;
+            hit = idx;
+            v3_copy( n1, n );
+         }
+      }
+   }
+
+   *t = min_t;
+   return hit;
 }
 
-static int ray_world( v3f pos, v3f dir, ray_hit *hit )
+VG_STATIC 
+struct world_surface *world_tri_index_surface( world_instance *world, 
+                                                 u32 index )
 {
-   return scene_raycast( &world.geo, pos, dir, hit );
+   for( int i=1; i<world->surface_count; i++ ){
+      struct world_surface *surf = &world->surfaces[i];
+
+      if( (index >= surf->sm_geo.vertex_start) &&
+          (index  < surf->sm_geo.vertex_start+surf->sm_geo.vertex_count ) )
+      {
+         return surf;
+      }
+   }
+
+   return &world->surfaces[0];
 }
 
-static int ray_hit_is_terrain( ray_hit *hit )
+VG_STATIC struct world_surface *world_contact_surface( world_instance *world,
+                                                         rb_ct *ct )
 {
-   u32 valid_start = 0,
-       valid_end   = world.sm_terrain.vertex_count;
+   return world_tri_index_surface( world, ct->element_id );
+}
 
-   return (hit->tri[0] >= valid_start) &&
-          (hit->tri[0]  < valid_end);
+VG_STATIC struct world_surface *ray_hit_surface( world_instance *world,
+                                                 ray_hit *hit )
+{
+   return world_tri_index_surface( world, hit->tri[0] );
 }
 
-static int ray_hit_is_ramp( ray_hit *hit )
+/* 
+ * -----------------------------------------------------------------------------
+ *                              Audio sampling
+ * -----------------------------------------------------------------------------
+ */
+
+VG_STATIC 
+enum audio_sprite_type world_audio_sample_sprite_random(v3f origin, v3f output);
+VG_STATIC void world_audio_sample_distances( v3f co, int *index, float *value );
+
+#include "audio.h"
+
+/*
+ * Trace out a random point, near the player to try and determine water areas
+ */
+VG_STATIC 
+enum audio_sprite_type world_audio_sample_sprite_random(v3f origin, v3f output)
+{
+   v3f chance = { (vg_randf()-0.5f) * 30.0f, 
+                  8.0f,
+                  (vg_randf()-0.5f) * 30.0f };
+   
+   v3f pos;
+   v3_add( chance, origin, pos );
+
+   ray_hit contact;
+   contact.dist = vg_minf( 16.0f, pos[1] );
+
+   world_instance *world = get_active_world();
+   
+   if( ray_world( world, pos, (v3f){0.0f,-1.0f,0.0f}, &contact ) ){
+      struct world_surface *mat = ray_hit_surface( world, &contact );
+
+      if( mat->info.surface_prop == k_surface_prop_grass){
+         v3_copy( contact.pos, output );
+         return k_audio_sprite_type_grass;
+      }
+      else{
+         return k_audio_sprite_type_none;
+      }
+   }
+
+   output[0] = pos[0];
+   output[1] = 0.0f;
+   output[2] = pos[2];
+
+   float dist = fabsf(output[1] - origin[1]);
+   
+   if( world->water.enabled && dist<=40.0f )
+      return k_audio_sprite_type_water;
+   else
+      return k_audio_sprite_type_none;
+}
+
+VG_STATIC void world_audio_sample_distances( v3f co, int *index, float *value )
 {
-   u32 valid_start = world.sm_geo_std.vertex_start,
-       valid_end   = world.sm_geo_vb.vertex_start;
+   float inr3 = 0.57735027,
+         inr2 = 0.70710678118;
+
+   v3f sample_directions[] = {
+      { -1.0f,  0.0f,  0.0f },
+      {  1.0f,  0.0f,  0.0f },
+      {  0.0f,  0.0f,  1.0f },
+      {  0.0f,  0.0f, -1.0f },
+      {  0.0f,  1.0f,  0.0f },
+      {  0.0f, -1.0f,  0.0f },
+      { -inr3,  inr3,  inr3 },
+      {  inr3,  inr3,  inr3 },
+      { -inr3,  inr3, -inr3 },
+      {  inr3,  inr3, -inr3 },
+      { -inr2,  0.0f,  inr2 },
+      {  inr2,  0.0f,  inr2 },
+      { -inr2,  0.0f, -inr2 },
+      {  inr2,  0.0f, -inr2 },
+   };
+
+   static int si = 0;
+   static float distances[16];
+
+   ray_hit ray;
+   ray.dist = 5.0f;
+
+   v3f rc, rd, ro;
+   v3_copy( sample_directions[ si ], rd );
+   v3_add( co, (v3f){0.0f,1.5f,0.0f}, ro );
+   v3_copy( ro, rc );
+
+   float dist = 200.0f;
+
+   for( int i=0; i<10; i++ ){
+      if( ray_world( get_active_world(), rc, rd, &ray ) ){
+         dist = (float)i*5.0f + ray.dist;
+         break;
+      }
+      else{
+         v3_muladds( rc, rd, ray.dist, rc );
+      }
+   }
+
+   distances[si] = dist;
+
+   if( vg_lines.draw ){
+      for( int i=0; i<14; i++ ){
+         if( distances[i] != 200.0f ){
+            u32 colours[] = { VG__RED, VG__BLUE, VG__GREEN,
+                              VG__CYAN, VG__YELOW, VG__PINK,
+                              VG__WHITE };
+
+            u32 colour = colours[i%7];
+
+            v3f p1;
+            v3_muladds( ro, sample_directions[i], distances[i], p1 );
+            vg_line( ro, p1, colour );
+            vg_line_pt3( p1, 0.1f, colour );
+         }
+      }
+   }
+
+   *index = si;
+   *value = dist;
 
-   return (hit->tri[0] >= valid_start) &&
-          (hit->tri[0]  < valid_end);
+   si ++;
+   if( si >= 14 )
+      si = 0;
 }
 
 #endif /* WORLD_H */