basic async mechanism
[vg.git] / vg.h
diff --git a/vg.h b/vg.h
index ada54695aee189dc37a0583dceabc5cd6c17786d..7ddd04ef839871dc19b845c60a23d7a02043ec78 100644 (file)
--- a/vg.h
+++ b/vg.h
@@ -1,4 +1,4 @@
-/* Copyright (C) 2021-2022 Harry Godden (hgn) - All Rights Reserved */
+/* Copyright (C) 2021-2023 Harry Godden (hgn) - All Rights Reserved */
 
 /*
  
 
 */
 
-#ifndef VG_STATIC
-  #define VG_STATIC 
-#endif
-
-/* API */
-VG_STATIC void vg_enter( int argc, char *argv[], const char *window_name );
-
-/* Thread 1 */
-VG_STATIC void vg_preload(void);
-VG_STATIC void vg_load(void);
-
-/* Main thread */
-VG_STATIC void vg_launch_opt(void);
-VG_STATIC void vg_start(void);
-
-VG_STATIC void vg_framebuffer_resize(int w, int h);
-VG_STATIC void vg_update(void);
-VG_STATIC void vg_update_fixed(void);
-VG_STATIC void vg_update_post(void);
-
-VG_STATIC void vg_render(void);
-VG_STATIC void vg_ui(void);
-
 #ifndef VG_HEADER_H
   #define VG_HEADER_H
 
@@ -93,6 +70,31 @@ VG_STATIC void vg_ui(void);
   #ifndef _WIN32
     #include <execinfo.h>
   #endif
+
+VG_STATIC void vg_print_backtrace(void)
+{
+#ifndef _WIN32
+
+   void *array[20];
+   char **strings;
+   int size, i;
+
+   size = backtrace( array, 20 );
+   strings = backtrace_symbols( array, size );
+
+   if( strings != NULL ){
+      vg_error( "---------------- gnu backtrace -------------\n" );
+
+      for( int i=0; i<size; i++ )
+         vg_info( "%s\n", strings[i] );
+
+      vg_error( "---------------- gnu backtrace -------------\n" );
+   }
+
+   free( strings );
+
+#endif
+}
   
   #ifdef VG_GAME
     #include "dep/glad/glad.h"
@@ -104,6 +106,7 @@ VG_STATIC void vg_ui(void);
     #include "vg_m.h"
     #include "vg_io.h"
     #include "vg_log.h"
+    #include "vg_async.h"
     #include "vg_steam.h"
 
   //#define VG_SYNC_DEBUG
@@ -114,6 +117,25 @@ VG_STATIC void vg_ui(void);
     #define VG_SYNC_LOG(...)
   #endif
 
+/* API */
+VG_STATIC void vg_enter( int argc, char *argv[], const char *window_name );
+
+/* Thread 1 */
+VG_STATIC void vg_preload(void);
+VG_STATIC void vg_load(void);
+
+/* Main thread */
+VG_STATIC void vg_launch_opt(void);
+VG_STATIC void vg_start(void);
+
+VG_STATIC void vg_framebuffer_resize(int w, int h);
+VG_STATIC void vg_update(void);
+VG_STATIC void vg_update_fixed(void);
+VG_STATIC void vg_update_post(void);
+
+VG_STATIC void vg_render(void);
+VG_STATIC void vg_ui(void);
+
 struct vg
 {
    /* Engine sync */
@@ -148,7 +170,17 @@ struct vg
        samples,
        window_should_close;
 
-   float refresh_rate;
+   int display_refresh_rate,
+       fps_limit;             /* 0: use vsync, >0: cap fps to this, no vsync */
+
+   enum vsync_feature
+   {
+      k_vsync_feature_disabled=0,
+      k_vsync_feature_enabled=1,
+      k_vsync_feature_enabled_adaptive=2,
+      k_vsync_feature_error=3
+   }
+   vsync_feature;
 
    double mouse_pos[2];
    v2f mouse_delta,
@@ -157,11 +189,13 @@ struct vg
    /* Runtime */
    double time,
           time_delta,
-          frame_delta,
-          time_real,
-          time_real_last,
           time_rate,
-          accumulator;
+
+          time_fixed_accumulator,
+          time_fixed_extrapolate,
+          time_frame_delta;
+
+   u64 time_hp, time_hp_last, time_spinning;
 
    int fixed_iterations;
 
@@ -176,9 +210,7 @@ struct vg
    engine_stage;
 
    /* graphics */
-#if 0
    m4x4f pv;
-#endif
    enum quality_profile
    {
       k_quality_profile_high = 0,
@@ -207,10 +239,8 @@ VG_STATIC void _vg_ensure_engine_running(void)
    enum engine_status status = vg.engine_status;
    SDL_AtomicUnlock( &vg.sl_context );
 
-   if( status != k_engine_status_running )
-   {
-      while(1) 
-      {
+   if( status != k_engine_status_running ){
+      while(1) {
          VG_SYNC_LOG( "[%d] No longer running...\n");
          SDL_Delay(1000);
       }
@@ -221,13 +251,11 @@ VG_STATIC enum vg_thread_purpose vg_thread_purpose(void)
 {
    SDL_AtomicLock( &vg.sl_context );
 
-   if( vg.thread_id_main == SDL_GetThreadID(NULL) )
-   {
+   if( vg.thread_id_main == SDL_GetThreadID(NULL) ){
       SDL_AtomicUnlock( &vg.sl_context );
       return k_thread_purpose_main;
    }
-   else
-   {
+   else{
       SDL_AtomicUnlock( &vg.sl_context );
       return k_thread_purpose_loader;
    }
@@ -241,14 +269,12 @@ VG_STATIC void vg_acquire_thread_sync(void)
 {
    /* We dont want to do anything if this is the main thread */
 
-   if( vg_thread_purpose() == k_thread_purpose_loader )
-   {
+   if( vg_thread_purpose() == k_thread_purpose_loader ){
       VG_SYNC_LOG( "[%d] vg_acquire_thread_sync()\n" );
       _vg_ensure_engine_running();
 
       SDL_AtomicLock( &vg.sl_context );
-      if( vg.context_ownership_depth == 0 )
-      {
+      if( vg.context_ownership_depth == 0 ){
          vg.context_ownership_depth ++;
          vg.exec_context = 1;
          SDL_AtomicUnlock( &vg.sl_context );
@@ -262,8 +288,7 @@ VG_STATIC void vg_acquire_thread_sync(void)
          SDL_GL_MakeCurrent( vg.window, vg.gl_context );
          VG_SYNC_LOG( "[%d] granted\n" );
       }
-      else
-      {
+      else{
          vg.context_ownership_depth ++;
          VG_SYNC_LOG( "[%d] granted\n" );
          SDL_AtomicUnlock( &vg.sl_context );
@@ -277,15 +302,13 @@ VG_STATIC void vg_acquire_thread_sync(void)
  */
 VG_STATIC void vg_release_thread_sync(void)
 {
-   if( vg_thread_purpose() == k_thread_purpose_loader )
-   {
+   if( vg_thread_purpose() == k_thread_purpose_loader ){
       VG_SYNC_LOG( "[%d] vg_release_thread_sync()\n" );
 
       SDL_AtomicLock( &vg.sl_context );
       vg.context_ownership_depth --;
 
-      if( vg.context_ownership_depth == 0 )
-      {
+      if( vg.context_ownership_depth == 0 ){
          SDL_AtomicUnlock( &vg.sl_context );
          VG_SYNC_LOG( "[%d] Releasing context.\n" );
          SDL_GL_MakeCurrent( NULL, NULL );
@@ -300,8 +323,7 @@ VG_STATIC void _vg_run_synced(void)
 {
    SDL_AtomicLock( &vg.sl_context );
 
-   if( vg.exec_context != 0 )
-   {
+   if( vg.exec_context != 0 ){
       VG_SYNC_LOG( "[%d] _vg_run_synced() (%d).\n", vg.exec_context );
       vg.exec_context = 0;
       SDL_AtomicUnlock( &vg.sl_context );
@@ -321,8 +343,7 @@ VG_STATIC void _vg_run_synced(void)
       VG_SYNC_LOG( "[%d] Re-engaging.\n" );
       SDL_GL_MakeCurrent( vg.window, vg.gl_context );
    }
-   else
-   {
+   else{
       VG_SYNC_LOG( "[%d] Nothing to do.\n" );
       SDL_AtomicUnlock( &vg.sl_context );
    }
@@ -352,15 +373,15 @@ VG_STATIC void vg_checkgl( const char *src_info );
 
 /* Diagnostic */
 VG_STATIC struct vg_profile vg_prof_update = {.name="update()"},
-                            vg_prof_render = {.name="render()"};
+                            vg_prof_render = {.name="render()"},
+                            vg_prof_swap   = {.name="swap"};
 
 VG_STATIC void vg_checkgl( const char *src_info )
 {
    int fail = 0;
 
    GLenum err;
-   while( (err = glGetError()) != GL_NO_ERROR )
-   {
+   while( (err = glGetError()) != GL_NO_ERROR ){
       vg_error( "(%s) OpenGL Error: #%d\n", src_info, err );
       fail = 1;
    }
@@ -372,19 +393,17 @@ VG_STATIC void vg_checkgl( const char *src_info )
 VG_STATIC void vg_bake_shaders(void)
 {
    vg_acquire_thread_sync();
-
-#if 0
-   vg_function_push( (struct vg_cmd)
-   {
-      .name = "shaders",
-      .function = vg_shaders_live_recompile
-   });
-#endif
+   vg_console_reg_cmd( "reload_shaders", vg_shaders_live_recompile, NULL );
 
    vg_shaders_compile();
    vg_release_thread_sync();
 }
 
+void test_async_runner( void *payload, u32 size )
+{
+   vg_success( "Async call test (%p, %u)\n", payload, size );
+}
+
 VG_STATIC void _vg_load_full(void)
 {
    vg_preload();
@@ -397,28 +416,24 @@ VG_STATIC void _vg_load_full(void)
 
    /* client */
    vg_load();
+
+   vg_async_item *test_async = vg_async_alloc( 0 );
+   vg_async_dispatch( test_async, test_async_runner );
 }
 
 VG_STATIC void _vg_process_events(void)
 {
    /* Update timers */
-   vg.time_real_last = vg.time_real;
-   vg.time_real = (double)SDL_GetTicks64() / 1000.0;
-   vg.frame_delta = vg.time_real-vg.time_real_last;
-   
    v2_zero( vg.mouse_wheel );
    v2_zero( vg.mouse_delta );
 
    /* SDL event loop */
    SDL_Event event;
-   while( SDL_PollEvent( &event ) )
-   {
-      if( event.type == SDL_KEYDOWN )
-      {
+   while( SDL_PollEvent( &event ) ){
+      if( event.type == SDL_KEYDOWN ){
          console_proc_key( event.key.keysym );
       }
-      else if( event.type == SDL_MOUSEWHEEL )
-      {
+      else if( event.type == SDL_MOUSEWHEEL ){
          vg.mouse_wheel[0] += event.wheel.preciseX;
          vg.mouse_wheel[1] += event.wheel.preciseY;
       }
@@ -431,38 +446,31 @@ VG_STATIC void _vg_process_events(void)
       {
          vg_input_controller_event( &event );
       }
-      else if( event.type == SDL_MOUSEMOTION )
-      {
+      else if( event.type == SDL_MOUSEMOTION ){
          vg.mouse_delta[0] += event.motion.xrel;
          vg.mouse_delta[1] += event.motion.yrel;
       }
-      else if( event.type == SDL_WINDOWEVENT )
-      {
-         if( event.window.event == SDL_WINDOWEVENT_SIZE_CHANGED )
-         {
+      else if( event.type == SDL_WINDOWEVENT ){
+         if( event.window.event == SDL_WINDOWEVENT_SIZE_CHANGED ){
             int w, h;
             SDL_GL_GetDrawableSize( vg.window, &w, &h );
 
-            if( !w || !h )
-            {
+            if( !w || !h ){
                vg_warn( "Got a invalid framebuffer size: "
                         "%dx%d... ignoring\n", w, h );
             }
-            else
-            {
+            else{
                vg.window_x = w;
                vg.window_y = h;
 
                vg_framebuffer_resize(w,h);
             }
          }
-         else if( event.window.event == SDL_WINDOWEVENT_CLOSE )
-         {
+         else if( event.window.event == SDL_WINDOWEVENT_CLOSE ){
             vg.window_should_close = 1;
          }
       }
-      else if( event.type == SDL_TEXTINPUT )
-      {
+      else if( event.type == SDL_TEXTINPUT ){
          console_proc_utf8( event.text.text );
       }
    }
@@ -483,25 +491,25 @@ VG_STATIC void _vg_gameloop_update(void)
 
    /* Fixed update loop */
    vg.engine_stage = k_engine_stage_update_fixed;
-   vg.accumulator += vg.time_delta;
 
    vg.fixed_iterations = 0;
    vg_lines.allow_input = 1;
-   while( vg.accumulator >= (VG_TIMESTEP_FIXED-0.00125) )
-   {
+   vg.time_fixed_accumulator += vg.time_delta;
+
+   while( vg.time_fixed_accumulator >= VG_TIMESTEP_FIXED ){
       vg_update_fixed();
       vg_lines.allow_input = 0;
 
-      vg.accumulator -= VG_TIMESTEP_FIXED;
-      vg.accumulator  = VG_MAX( 0.0, vg.accumulator );
+      vg.time_fixed_accumulator -= VG_TIMESTEP_FIXED;
+      //vg.accumulator  = VG_MAX( 0.0, vg.accumulator );
 
       vg.fixed_iterations ++;
-      if( vg.fixed_iterations == 8 )
-      {
+      if( vg.fixed_iterations == 8 ){
          break;
       }
    }
    vg_lines.allow_input = 1;
+   vg.time_fixed_extrapolate = vg.time_fixed_accumulator / VG_TIMESTEP_FIXED;
 
    vg.engine_stage = k_engine_stage_update;
    vg_update_post();
@@ -512,8 +520,7 @@ VG_STATIC void _vg_gameloop_render(void)
 {
    vg_profile_begin( &vg_prof_render );
 
-   if( vg.is_loaded )
-   {
+   if( vg.is_loaded ){
       /* render */
       vg.engine_stage = k_engine_stage_rendering;
       vg_render();
@@ -525,36 +532,48 @@ VG_STATIC void _vg_gameloop_render(void)
 
          /* TODO */
          ui_set_mouse( vg.mouse_pos[0], vg.mouse_pos[1], 0 );
+
+         int frame_target = vg.display_refresh_rate;
+
+         if( vg.fps_limit > 0 ){
+            frame_target = vg.fps_limit;
+         }
          
          vg_profile_drawn( 
-               (struct vg_profile *[]){&vg_prof_update,&vg_prof_render}, 2,
-               (1.0f/(float)vg.refresh_rate)*1000.0f, 
+               (struct vg_profile *[]){
+                  &vg_prof_update,&vg_prof_render,&vg_prof_swap}, 3,
+               (1.0f/(float)frame_target)*1000.0f, 
                (ui_rect){ 4, 4, 250, 0 }, 0
          );
 
-         if( vg_profiler )
-         {
+         if( vg_profiler ){
+            char perf[256];
             
-            char perf[128];
-            
-            snprintf( perf, 127, 
+            snprintf( perf, 255, 
                   "x: %d y: %d\n"
-                  "refresh: %.1f (%.1fms)\n"
+                  "refresh: %d (%.1fms)\n"
                   "samples: %d\n"
-                  "iterations: %d (acc: %.3fms%%)\n",
+                  "iterations: %d (acc: %.3fms%%)\n"
+                  "time: real(%.2f) delta(%.2f) rate(%.2f)\n"
+#ifdef _WIN32
+                  "      extrap(%.2f) frame(%.2f) spin( %llu )\n",
+#else
+                  "      extrap(%.2f) frame(%.2f) spin( %lu )\n",
+#endif
                   vg.window_x, vg.window_y, 
-                  vg.refresh_rate, (1.0f/vg.refresh_rate)*1000.0f,
+                  frame_target, (1.0f/(float)frame_target)*1000.0f,
                   vg.samples, 
                   vg.fixed_iterations, 
-                  (vg.accumulator/VG_TIMESTEP_FIXED)*100.0f );
+                  (vg.time_fixed_accumulator/VG_TIMESTEP_FIXED)*100.0f,
+                  vg.time, vg.time_delta, vg.time_rate,
+                  vg.time_fixed_extrapolate, vg.time_frame_delta,
+                  vg.time_spinning );
 
-            ui_text( (ui_rect){258, 4+24+12,0,0},perf, 1,0);
+            ui_text( (ui_rect){258, 4+24+12+12,0,0},perf, 1,0);
          }
 
          /* FIXME */
-#if 0
          audio_debug_ui( vg.pv );
-#endif
          vg_ui();
          _vg_console_draw();
          
@@ -566,71 +585,146 @@ VG_STATIC void _vg_gameloop_render(void)
    vg_profile_end( &vg_prof_render );
 }
 
+VG_STATIC int vg_framefilter( double dt )
+{
+   if( (vg.fps_limit <= 0) && (vg.vsync_feature != k_vsync_feature_error) ){
+      /* turn on vsync if not enabled */
+
+      enum vsync_feature requested = k_vsync_feature_enabled;
+      if( vg.fps_limit < 0 ) requested = k_vsync_feature_enabled_adaptive;
+
+      if( vg.vsync_feature != requested ){
+         vg_info( "Setting swap interval\n" );
+
+         int swap_interval = 1;
+         if( requested == k_vsync_feature_enabled_adaptive ) swap_interval = -1;
+
+         if( SDL_GL_SetSwapInterval( swap_interval ) == -1 ){
+            if( requested == k_vsync_feature_enabled ){
+               vg_error( "Vsync is not supported by your system\n" );
+               vg_warn( "You may be overriding it in your"
+                        " graphics control panel.\n" );
+            }
+            else{
+               vg_error( "Adaptive Vsync is not supported by your system\n" );
+            }
+
+            vg.vsync_feature = k_vsync_feature_error;
+            vg.fps_limit = vg.display_refresh_rate;
+
+            /* TODO: Make popup to notify user that this happened */
+            return 1;
+         }
+         else{
+            vg_success( "Vsync enabled (%d)\n", requested );
+            vg.vsync_feature = requested;
+         }
+      }
+
+      return 0;
+   }
+
+   if( vg.vsync_feature != k_vsync_feature_disabled ){
+      SDL_GL_SetSwapInterval( 0 );
+      vg.vsync_feature = k_vsync_feature_disabled;
+   }
+   
+   if( vg.fps_limit < 25 ) vg.fps_limit = 25;
+   if( vg.fps_limit > 300 ) vg.fps_limit = 300;
+
+   double min_frametime = 1.0/(double)vg.fps_limit;
+   if( vg.time_frame_delta < min_frametime ){
+      /* TODO: we can use high res nanosleep on Linux here */
+      double sleep_ms = (min_frametime-vg.time_frame_delta) * 1000.0;
+      u32 ms = (u32)floor( sleep_ms );
+
+      if( ms ){
+         SDL_Delay( ms );
+      }
+      else{
+         vg.time_spinning ++;
+      }
+
+      return 1;
+   }
+
+   return 0;
+}
+
 VG_STATIC void _vg_gameloop(void)
 {
-   vg.accumulator = 0.75f * (1.0f/60.0f);
+   //vg.time_fixed_accumulator = 0.75f * (1.0f/60.0f);
+
+   vg.time_hp = SDL_GetPerformanceCounter();
+   vg.time_hp_last = vg.time_hp;
 
    int post_start = 0;
-   while(1)
-   {
+   while(1){
+   
+      vg.time_hp = SDL_GetPerformanceCounter();
+      u64 udt = vg.time_hp - vg.time_hp_last;
+      vg.time_hp_last = vg.time_hp;
+
+      double dt = (double)udt / (double)SDL_GetPerformanceFrequency();
+
+      vg.time_frame_delta += dt;
+
+      if( vg_framefilter( dt ) )
+         continue;
+
+      vg_profile_begin( &vg_prof_swap );
+      SDL_GL_SwapWindow( vg.window );
+      _vg_run_synced();
+      vg_profile_end( &vg_prof_swap );
+
+      vg.time_delta = vg.time_frame_delta * vg.time_rate;
+      vg.time += vg.time_delta;
+
+      vg_run_async_checked();
       _vg_process_events();
 
       if( vg.window_should_close )
          break;
-
-      /* scaled time */
-      vg.time_delta = vg.frame_delta * vg.time_rate;
-      vg.time += vg.time_delta;
       
-      if( vg.is_loaded )
-      {
-         if( !post_start )
-         {
+      if( vg.is_loaded ){
+         if( !post_start ){
             vg_start();
             post_start = 1;
          }
       }
-      else
-      {
+      else{
          _vg_loader_render();
       }
 
       _vg_gameloop_update();
       _vg_gameloop_render();
-      audio_push_console_vol();
 
-      SDL_GL_SwapWindow( vg.window );
-      _vg_run_synced();
+      vg.time_frame_delta = 0.0;
+      vg.time_spinning = 0;
    }
 }
 
 VG_STATIC void _vg_process_launch_opts_internal( int argc, char *argv[] )
 {
    char *arg;
-   while( vg_argp( argc, argv ) )
-   {
-      if( (arg = vg_opt_arg( 'w' )) )
-      {
+   while( vg_argp( argc, argv ) ){
+      if( (arg = vg_opt_arg( 'w' )) ){
          vg.window_x = atoi( arg );
       }
 
-      if( (arg = vg_opt_arg( 'h' )) )
-      {
+      if( (arg = vg_opt_arg( 'h' )) ){
          vg.window_y = atoi( arg );
       }
 
-      if( (arg = vg_long_opt_arg( "samples" )) )
-      {
+      if( (arg = vg_long_opt_arg( "samples" )) ){
          vg.samples = VG_MAX( 0, VG_MIN( 8, atoi( arg ) ) );
       }
 
-      if(  vg_long_opt( "use-libc-malloc" ) )
-      {
+      if(  vg_long_opt( "use-libc-malloc" ) ){
          vg_mem.use_libc_malloc = 1;
       }
 
-      if( vg_long_opt( "high-performance" ) )
-      {
+      if( vg_long_opt( "high-performance" ) ){
          vg.quality_profile = k_quality_profile_low;
       }
 
@@ -642,8 +736,7 @@ VG_STATIC void _vg_init_window( const char *window_name )
 {
    vg_info( "SDL_INIT\n" );
 
-   if( SDL_Init( SDL_INIT_VIDEO ) != 0  )
-   {
+   if( SDL_Init( SDL_INIT_VIDEO ) != 0  ){
       vg_error( "SDL_Init failed: %s\n", SDL_GetError() );
       exit(0);
    }
@@ -670,62 +763,82 @@ VG_STATIC void _vg_init_window( const char *window_name )
     * Get monitor information 
     */
    vg_info( "Getting display count\n" );
-   int display_count = 0, display_index = 0, mode_index = 0;
-   if( (display_count = SDL_GetNumVideoDisplays()) < 1 )
-   {
-      vg_error( "SDL_GetNumVideoDisplays returned: %i\n", display_count );
+   int display_count = 0, 
+       display_index = 0, 
+       mode_index = 0;
+
+#ifdef VG_DEVWINDOW
+   vg.window_x = 1600;
+   vg.window_y = 1000;
+#else
+
+   SDL_DisplayMode video_mode;
+   if( SDL_GetDesktopDisplayMode( display_index, &video_mode ) ){
+      vg_error( "SDL_GetDesktopDisplayMode failed: %s\n", SDL_GetError() );
+      SDL_Quit();
       exit(0);
    }
 
-   /* TODO: Allow chosing the modes at startup */
-   vg_info( "Getting display mode\n" );
-   SDL_DisplayMode mode = { SDL_PIXELFORMAT_UNKNOWN, 0, 0, 0, 0 };
-   if( SDL_GetDisplayMode( display_index, mode_index, &mode ) != 0 )
-   {
-      vg_error( "SDL_GetDisplayMode failed: %s", SDL_GetError() );
-      exit(0);
-   }
+   vg.display_refresh_rate = video_mode.refresh_rate;
+   vg.window_x = video_mode.w;
+   vg.window_y = video_mode.h;
+#endif
 
-   vg.refresh_rate = mode.refresh_rate;
+#ifndef _WIN32
+       SDL_SetHint( "SDL_VIDEO_X11_XINERAMA", "1" );
+       SDL_SetHint( "SDL_VIDEO_X11_XRANDR", "0" );
+       SDL_SetHint( "SDL_VIDEO_X11_XVIDMODE", "0" );
+#endif
 
-   vg_info( "CreateWindow\n" );
+   vg_info( "CreateWindow( %d %d @%dhz )\n", vg.window_x, vg.window_y,
+                                             vg.display_refresh_rate );
 
    /* TODO: Allow selecting closest video mode from launch opts */
    if((vg.window = SDL_CreateWindow( window_name,
-                                     SDL_WINDOWPOS_UNDEFINED,
-                                     SDL_WINDOWPOS_UNDEFINED,
-                                     mode.w, mode.h,
+
+#ifdef VG_DEVWINDOW
+         0, 0, vg.window_x, vg.window_y, 
+         SDL_WINDOW_BORDERLESS|SDL_WINDOW_OPENGL|SDL_WINDOW_INPUT_GRABBED
+      ))){}
+#else
+                                     0, 0,
+                                     vg.window_x, vg.window_y,
 
                                      SDL_WINDOW_FULLSCREEN_DESKTOP | 
                                      SDL_WINDOW_OPENGL |
-                                     SDL_WINDOW_INPUT_GRABBED )))
+                                     SDL_WINDOW_INPUT_GRABBED 
+                                     )))
    {
+      if( SDL_SetWindowDisplayMode( vg.window, &video_mode ) ){
+         vg_error( "SDL_SetWindowDisplayMode failed: %s", SDL_GetError() );
+         SDL_Quit();
+         exit(0);
+      }
    }
-   else
-   {
+#endif
+   else{
       vg_error( "SDL_CreateWindow failed: %s", SDL_GetError() );
       exit(0);
    }
 
+   SDL_RaiseWindow( vg.window );
+
    vg_info( "CreateContext\n" );
 
    /* 
     * OpenGL loading 
     */
-   if( (vg.gl_context = SDL_GL_CreateContext(vg.window) ))
-   {
+   if( (vg.gl_context = SDL_GL_CreateContext(vg.window) )){
       SDL_GL_GetDrawableSize( vg.window, &vg.window_x, &vg.window_y );
       vg_success( "Window created (%dx%d)\n", vg.window_x, vg.window_y );
    }
-   else
-   {
+   else{
       vg_error( "SDL_GL_CreateContext failed: %s\n", SDL_GetError() );
       SDL_Quit();
       exit(0);
    }
 
-   if( !gladLoadGLLoader((GLADloadproc)SDL_GL_GetProcAddress) ) 
-   {
+   if( !gladLoadGLLoader((GLADloadproc)SDL_GL_GetProcAddress) ) {
       vg_error( "Glad Failed to initialize\n" );
       SDL_GL_DeleteContext( vg.gl_context );
       SDL_Quit();
@@ -735,22 +848,28 @@ VG_STATIC void _vg_init_window( const char *window_name )
    const unsigned char* glver = glGetString( GL_VERSION );
    vg_success( "Load setup complete, OpenGL version: %s\n", glver );
 
-   vg_info( "Setting swap interval\n" );
-
-   if( SDL_GL_SetSwapInterval( -1 ) == -1 )
-   {
-      vg_warn( "Adaptive Vsync not supported\n" );
+   SDL_GL_SetSwapInterval(0); /* disable vsync while loading */
 
-      if( SDL_GL_SetSwapInterval( 1 ) == -1 )
-      {
-         vg_fatal_exit_loop( "Cannot enable Vsync! You might be overriding it"
-                             " in your graphics control panel.\n" );
+   SDL_DisplayMode dispmode;
+   if( !SDL_GetWindowDisplayMode( vg.window, &dispmode ) ){
+      if( dispmode.refresh_rate ){
+         vg.display_refresh_rate = dispmode.refresh_rate;
       }
-      else
-         vg_success( "Using vsync\n" );
    }
-   else
-      vg_success( "Using adaptive Vsync\n" );
+
+   if( vg.display_refresh_rate < 25 || vg.display_refresh_rate > 300 ){
+      vg.display_refresh_rate = 60;
+   }
+
+   vg_info( "Display refresh rate: %d\n", dispmode.refresh_rate );
+
+#ifdef _WIN32
+   vg.fps_limit = vg.display_refresh_rate;
+#else
+   /* request vsync by default on linux to avoid screen tearing.
+    * this does have its own issues with compositing on X11. */
+   vg.fps_limit = 0;
+#endif
 }
 
 VG_STATIC void vg_enter( int argc, char *argv[], const char *window_name )
@@ -759,9 +878,12 @@ VG_STATIC void vg_enter( int argc, char *argv[], const char *window_name )
 
    /* Systems init */
    vg_alloc_quota();
-   _vg_log_init();
    _vg_console_init();
+   
+   vg_console_reg_var( "fps_limit", &vg.fps_limit, k_var_dtype_i32, 0 );
    _vg_init_window( window_name );
+
+   vg_async_init();
    
    SDL_SetRelativeMouseMode(1);
    vg.thread_id_main = SDL_GetThreadID(NULL);
@@ -807,41 +929,17 @@ VG_STATIC void vg_fatal_exit_loop( const char *error )
     *    TODO: this on windows?
     */
 
-#ifndef _WIN32
-
-   void *array[20];
-   char **strings;
-   int size, i;
-
-   size = backtrace( array, 20 );
-   strings = backtrace_symbols( array, size );
-
-   if( strings != NULL )
-   {
-      vg_error( "---------------- gnu backtrace -------------\n" );
-
-      for( int i=0; i<size; i++ )
-         vg_info( "%s\n", strings[i] );
-
-      vg_error( "---------------- gnu backtrace -------------\n" );
-   }
-
-   free( strings );
-
-#endif
-
+   vg_print_backtrace();
    vg_error( "Fatal error: %s\n", error );
 
    SDL_AtomicLock( &vg.sl_context );
-   if( vg.engine_status == k_engine_status_none )
-   {
+   if( vg.engine_status == k_engine_status_none ){
       SDL_AtomicUnlock( &vg.sl_context );
 
       /* TODO: Correct shutdown before other systems */
       exit(0);
    }
-   else
-   {
+   else{
       SDL_AtomicUnlock( &vg.sl_context );
       
       vg_acquire_thread_sync();
@@ -852,8 +950,7 @@ VG_STATIC void vg_fatal_exit_loop( const char *error )
       SDL_AtomicUnlock( &vg.sl_context );
 
       /* Notify other thread for curtosey */
-      if( vg_thread_purpose() == k_thread_purpose_main )
-      {
+      if( vg_thread_purpose() == k_thread_purpose_main ){
          SDL_AtomicLock( &vg.sl_context );
 
          if( vg.exec_context != 0 )
@@ -864,8 +961,7 @@ VG_STATIC void vg_fatal_exit_loop( const char *error )
 
       vg_audio_free();
 
-      while(1)
-      {
+      while(1){
          _vg_process_events();
          if( vg.window_should_close )
             break;
@@ -879,7 +975,7 @@ VG_STATIC void vg_fatal_exit_loop( const char *error )
          glBlendFunc(GL_ONE_MINUS_DST_ALPHA, GL_DST_ALPHA);
          glBlendEquation(GL_FUNC_ADD);
 
-         glClearColor( 0.15f + sinf(vg.time_real)*0.1f, 0.0f, 0.0f,1.0f );
+         glClearColor( 0.15f + sinf(vg.time)*0.1f, 0.0f, 0.0f,1.0f );
          glClear( GL_COLOR_BUFFER_BIT );
          glViewport( 0,0, vg.window_x, vg.window_y );