1 /* Copyright (C) 2021-2022 Harry Godden (hgn) - All Rights Reserved */
7 | | .---------------------------------------------------------.
8 |API| | vg_enter( int argc, char *argv[], const char *window_name |
9 | | '---------------------------------------------------------'
12 |IMP| vg_launch_opt(void) <--.
14 | | |'---------------'
16 | | |'-----------------------------------| 1 |------.
19 | | | |IMP| vg_preload(void)
22 | | | | |IMP| vg_load(void)
24 |IMP| | vg_framebuffer_resize(void) |
26 |IMP| | |.------------- vg_start(void) ---------------'
29 |IMP| | vg_update(void)
34 |IMP| | '- vg_update_fixed(void)
39 |IMP| | vg_update_post(void)
42 |IMP| | vg_render(void)
52 | | .-------------------------------------.
53 |API| | vg_fatal_exit_loop( const char *err ) |
54 | | '-------------------------------------'
59 |IMP| '- vg_framebuffer_resize(void)
69 VG_STATIC
void vg_enter( int argc
, char *argv
[], const char *window_name
);
72 VG_STATIC
void vg_preload(void);
73 VG_STATIC
void vg_load(void);
76 VG_STATIC
void vg_launch_opt(void);
77 VG_STATIC
void vg_start(void);
79 VG_STATIC
void vg_framebuffer_resize(int w
, int h
);
80 VG_STATIC
void vg_update(void);
81 VG_STATIC
void vg_update_fixed(void);
82 VG_STATIC
void vg_update_post(void);
84 VG_STATIC
void vg_render(void);
85 VG_STATIC
void vg_ui(void);
90 #include "vg_platform.h"
98 #include "dep/glad/glad.h"
99 #include "submodules/SDL/include/SDL.h"
100 #include "vg_stdint.h"
102 void vg_register_exit( void( *funcptr
)(void), const char *name
);
107 #include "vg_steam.h"
109 //#define VG_SYNC_DEBUG
111 #define VG_SYNC_LOG(STR,...) \
112 vg_info(STR,SDL_GetThreadID(NULL),##__VA_ARGS__)
114 #define VG_SYNC_LOG(...)
121 SDL_GLContext gl_context
;
123 SDL_SpinLock sl_context
;
124 SDL_sem
*sem_allow_exec
,
128 SDL_threadID thread_id_main
,
130 thread_id_with_opengl_context
;
131 int context_ownership_depth
;
137 k_engine_status_none
,
138 k_engine_status_running
,
139 k_engine_status_crashed
142 const char *str_const_engine_err
;
145 /* Window information */
166 int fixed_iterations
;
171 k_engine_stage_update
,
172 k_engine_stage_update_fixed
,
173 k_engine_stage_rendering
,
184 k_quality_profile_high
= 0,
185 k_quality_profile_low
= 1,
189 VG_STATIC vg
= { .time_rate
= 1.0 };
191 enum vg_thread_purpose
193 k_thread_purpose_nothing
,
194 k_thread_purpose_main
,
195 k_thread_purpose_loader
198 VG_STATIC
void vg_fatal_exit_loop( const char *error
);
201 * Checks if the engine is running
203 VG_STATIC
void _vg_ensure_engine_running(void)
205 /* Check if the engine is no longer running */
206 SDL_AtomicLock( &vg
.sl_context
);
207 enum engine_status status
= vg
.engine_status
;
208 SDL_AtomicUnlock( &vg
.sl_context
);
210 if( status
!= k_engine_status_running
)
214 VG_SYNC_LOG( "[%d] No longer running...\n");
220 VG_STATIC
enum vg_thread_purpose
vg_thread_purpose(void)
222 SDL_AtomicLock( &vg
.sl_context
);
224 if( vg
.thread_id_main
== SDL_GetThreadID(NULL
) )
226 SDL_AtomicUnlock( &vg
.sl_context
);
227 return k_thread_purpose_main
;
231 SDL_AtomicUnlock( &vg
.sl_context
);
232 return k_thread_purpose_loader
;
237 * Sync execution so that the OpenGL context is switched onto this thread.
238 * Anything after this call will be in a valid context.
240 VG_STATIC
void vg_acquire_thread_sync(void)
242 /* We dont want to do anything if this is the main thread */
244 if( vg_thread_purpose() == k_thread_purpose_loader
)
246 VG_SYNC_LOG( "[%d] vg_acquire_thread_sync()\n" );
247 _vg_ensure_engine_running();
249 SDL_AtomicLock( &vg
.sl_context
);
250 if( vg
.context_ownership_depth
== 0 )
252 vg
.context_ownership_depth
++;
254 SDL_AtomicUnlock( &vg
.sl_context
);
256 /* wait until told we can go */
257 VG_SYNC_LOG( "[%d] Waiting to acuire sync.\n" );
258 SDL_SemWait( vg
.sem_allow_exec
);
260 _vg_ensure_engine_running();
262 SDL_GL_MakeCurrent( vg
.window
, vg
.gl_context
);
263 VG_SYNC_LOG( "[%d] granted\n" );
267 vg
.context_ownership_depth
++;
268 VG_SYNC_LOG( "[%d] granted\n" );
269 SDL_AtomicUnlock( &vg
.sl_context
);
275 * Signify that we are done with the OpenGL context in this thread.
276 * Anything after this call will be in an undefined context.
278 VG_STATIC
void vg_release_thread_sync(void)
280 if( vg_thread_purpose() == k_thread_purpose_loader
)
282 VG_SYNC_LOG( "[%d] vg_release_thread_sync()\n" );
284 SDL_AtomicLock( &vg
.sl_context
);
285 vg
.context_ownership_depth
--;
287 if( vg
.context_ownership_depth
== 0 )
289 SDL_AtomicUnlock( &vg
.sl_context
);
290 VG_SYNC_LOG( "[%d] Releasing context.\n" );
291 SDL_GL_MakeCurrent( NULL
, NULL
);
292 SDL_SemPost( vg
.sem_exec_finished
);
295 SDL_AtomicUnlock( &vg
.sl_context
);
299 VG_STATIC
void _vg_run_synced(void)
301 SDL_AtomicLock( &vg
.sl_context
);
303 if( vg
.exec_context
!= 0 )
305 VG_SYNC_LOG( "[%d] _vg_run_synced() (%d).\n", vg
.exec_context
);
307 SDL_AtomicUnlock( &vg
.sl_context
);
309 /* allow operations to go */
310 SDL_GL_MakeCurrent( NULL
, NULL
);
311 SDL_SemPost( vg
.sem_allow_exec
);
313 /* wait for operations to complete */
314 VG_SYNC_LOG( "[%d] Waiting for content.\n" );
315 SDL_SemWait( vg
.sem_exec_finished
);
317 /* check if we killed the engine */
318 _vg_ensure_engine_running();
320 /* re-engage main thread */
321 VG_SYNC_LOG( "[%d] Re-engaging.\n" );
322 SDL_GL_MakeCurrent( vg
.window
, vg
.gl_context
);
326 VG_SYNC_LOG( "[%d] Nothing to do.\n" );
327 SDL_AtomicUnlock( &vg
.sl_context
);
331 VG_STATIC
void _vg_opengl_sync_init(void)
333 vg
.sem_allow_exec
= SDL_CreateSemaphore(0);
334 vg
.sem_exec_finished
= SDL_CreateSemaphore(0);
335 vg
.sem_loader
= SDL_CreateSemaphore(1);
338 VG_STATIC
void vg_checkgl( const char *src_info
);
339 #define VG_STRINGIT( X ) #X
340 #define VG_CHECK_GL_ERR() vg_checkgl( __FILE__ ":L" VG_STRINGIT(__LINE__) )
342 #include "vg_console.h"
343 #include "vg_profiler.h"
344 #include "vg_audio.h"
345 #include "vg_shader.h"
347 #include "vg_input.h"
349 #include "vg_lines.h"
350 #include "vg_loader.h"
354 VG_STATIC
struct vg_profile vg_prof_update
= {.name
="update()"},
355 vg_prof_render
= {.name
="render()"};
357 VG_STATIC
void vg_checkgl( const char *src_info
)
362 while( (err
= glGetError()) != GL_NO_ERROR
)
364 vg_error( "(%s) OpenGL Error: #%d\n", src_info
, err
);
369 vg_fatal_exit_loop( "OpenGL Error" );
372 VG_STATIC
void vg_bake_shaders(void)
374 vg_acquire_thread_sync();
376 vg_function_push( (struct vg_cmd
)
378 .name
= "reload_shaders",
379 .function
= vg_shaders_live_recompile
382 vg_shaders_compile();
383 vg_release_thread_sync();
386 VG_STATIC
void _vg_load_full(void)
391 vg_loader_step( vg_input_init
, vg_input_free
);
392 vg_loader_step( vg_lines_init
, NULL
);
393 vg_loader_step( vg_audio_init
, vg_audio_free
);
394 vg_loader_step( vg_profiler_init
, NULL
);
400 VG_STATIC
void _vg_process_events(void)
403 vg
.time_real_last
= vg
.time_real
;
404 vg
.time_real
= (double)SDL_GetTicks64() / 1000.0;
405 vg
.frame_delta
= vg
.time_real
-vg
.time_real_last
;
407 v2_zero( vg
.mouse_wheel
);
408 v2_zero( vg
.mouse_delta
);
412 while( SDL_PollEvent( &event
) )
414 if( event
.type
== SDL_KEYDOWN
)
416 console_proc_key( event
.key
.keysym
);
418 else if( event
.type
== SDL_MOUSEWHEEL
)
420 vg
.mouse_wheel
[0] += event
.wheel
.preciseX
;
421 vg
.mouse_wheel
[1] += event
.wheel
.preciseY
;
423 else if( event
.type
== SDL_CONTROLLERAXISMOTION
||
424 event
.type
== SDL_CONTROLLERBUTTONDOWN
||
425 event
.type
== SDL_CONTROLLERBUTTONUP
||
426 event
.type
== SDL_CONTROLLERDEVICEADDED
||
427 event
.type
== SDL_CONTROLLERDEVICEREMOVED
430 vg_input_controller_event( &event
);
432 else if( event
.type
== SDL_MOUSEMOTION
)
434 vg
.mouse_delta
[0] += event
.motion
.xrel
;
435 vg
.mouse_delta
[1] += event
.motion
.yrel
;
437 else if( event
.type
== SDL_WINDOWEVENT
)
439 if( event
.window
.event
== SDL_WINDOWEVENT_SIZE_CHANGED
)
442 SDL_GL_GetDrawableSize( vg
.window
, &w
, &h
);
446 vg_warn( "Got a invalid framebuffer size: "
447 "%dx%d... ignoring\n", w
, h
);
454 vg_framebuffer_resize(w
,h
);
457 else if( event
.window
.event
== SDL_WINDOWEVENT_CLOSE
)
459 vg
.window_should_close
= 1;
462 else if( event
.type
== SDL_TEXTINPUT
)
464 console_proc_utf8( event
.text
.text
);
468 vg
.mouse_pos
[0] += vg
.mouse_delta
[0];
469 vg
.mouse_pos
[1] += vg
.mouse_delta
[1];
475 VG_STATIC
void _vg_gameloop_update(void)
477 vg_profile_begin( &vg_prof_update
);
479 vg
.engine_stage
= k_engine_stage_update
;
482 /* Fixed update loop */
483 vg
.engine_stage
= k_engine_stage_update_fixed
;
484 vg
.accumulator
+= vg
.time_delta
;
486 vg
.fixed_iterations
= 0;
487 vg_lines
.allow_input
= 1;
488 while( vg
.accumulator
>= (VG_TIMESTEP_FIXED
-0.00125) )
491 vg_lines
.allow_input
= 0;
493 vg
.accumulator
-= VG_TIMESTEP_FIXED
;
494 vg
.accumulator
= VG_MAX( 0.0, vg
.accumulator
);
496 vg
.fixed_iterations
++;
497 if( vg
.fixed_iterations
== 8 )
502 vg_lines
.allow_input
= 1;
504 vg
.engine_stage
= k_engine_stage_update
;
506 vg_profile_end( &vg_prof_update
);
509 VG_STATIC
void _vg_gameloop_render(void)
511 vg_profile_begin( &vg_prof_render
);
516 vg
.engine_stage
= k_engine_stage_rendering
;
520 vg
.engine_stage
= k_engine_stage_ui
;
522 ui_begin( vg
.window_x
, vg
.window_y
);
525 ui_set_mouse( vg
.mouse_pos
[0], vg
.mouse_pos
[1], 0 );
528 (struct vg_profile
*[]){&vg_prof_update
,&vg_prof_render
}, 2,
529 (1.0f
/(float)vg
.refresh_rate
)*1000.0f
,
530 (ui_rect
){ 4, 4, 250, 0 }, 0
540 "refresh: %.1f (%.1fms)\n"
542 "iterations: %d (acc: %.3fms%%)\n",
543 vg
.window_x
, vg
.window_y
,
544 vg
.refresh_rate
, (1.0f
/vg
.refresh_rate
)*1000.0f
,
547 (vg
.accumulator
/VG_TIMESTEP_FIXED
)*100.0f
);
549 ui_text( (ui_rect
){258, 4+24+12,0,0},perf
, 1,0);
554 audio_debug_ui( vg
.pv
);
564 vg_profile_end( &vg_prof_render
);
567 VG_STATIC
void _vg_gameloop(void)
569 vg
.accumulator
= 0.75f
* (1.0f
/60.0f
);
574 _vg_process_events();
576 if( vg
.window_should_close
)
580 vg
.time_delta
= vg
.frame_delta
* vg
.time_rate
;
581 vg
.time
+= vg
.time_delta
;
596 _vg_gameloop_update();
597 _vg_gameloop_render();
598 audio_push_console_vol();
600 SDL_GL_SwapWindow( vg
.window
);
605 VG_STATIC
void _vg_process_launch_opts_internal( int argc
, char *argv
[] )
608 while( vg_argp( argc
, argv
) )
610 if( (arg
= vg_opt_arg( 'w' )) )
612 vg
.window_x
= atoi( arg
);
615 if( (arg
= vg_opt_arg( 'h' )) )
617 vg
.window_y
= atoi( arg
);
620 if( (arg
= vg_long_opt_arg( "samples" )) )
622 vg
.samples
= VG_MAX( 0, VG_MIN( 8, atoi( arg
) ) );
625 if( vg_long_opt( "use-libc-malloc" ) )
627 vg_mem
.use_libc_malloc
= 1;
630 if( vg_long_opt( "high-performance" ) )
632 vg
.quality_profile
= k_quality_profile_low
;
639 VG_STATIC
void _vg_init_window( const char *window_name
)
641 vg_info( "SDL_INIT\n" );
643 if( SDL_Init( SDL_INIT_VIDEO
) != 0 )
645 vg_error( "SDL_Init failed: %s\n", SDL_GetError() );
649 SDL_InitSubSystem( SDL_INIT_AUDIO
);
650 SDL_InitSubSystem( SDL_INIT_GAMECONTROLLER
);
652 SDL_GL_SetAttribute( SDL_GL_DOUBLEBUFFER
, 1 );
653 SDL_GL_SetAttribute( SDL_GL_CONTEXT_MAJOR_VERSION
, 3 );
654 SDL_GL_SetAttribute( SDL_GL_CONTEXT_MINOR_VERSION
, 3 );
655 SDL_GL_SetAttribute( SDL_GL_CONTEXT_PROFILE_MASK
,
656 SDL_GL_CONTEXT_PROFILE_CORE
);
658 SDL_GL_SetAttribute( SDL_GL_CONTEXT_RELEASE_BEHAVIOR
,
659 SDL_GL_CONTEXT_RELEASE_BEHAVIOR_FLUSH
);
661 SDL_GL_SetAttribute( SDL_GL_RED_SIZE
, 8 );
662 SDL_GL_SetAttribute( SDL_GL_GREEN_SIZE
, 8 );
663 SDL_GL_SetAttribute( SDL_GL_BLUE_SIZE
, 8 );
664 SDL_GL_SetAttribute( SDL_GL_ALPHA_SIZE
, 8 );
665 SDL_GL_SetAttribute( SDL_GL_STENCIL_SIZE
, 0 );
668 * Get monitor information
670 vg_info( "Getting display count\n" );
671 int display_count
= 0, display_index
= 0, mode_index
= 0;
672 if( (display_count
= SDL_GetNumVideoDisplays()) < 1 )
674 vg_error( "SDL_GetNumVideoDisplays returned: %i\n", display_count
);
681 /* TODO: Allow chosing the modes at startup */
682 vg_info( "Getting default display mode\n" );
683 SDL_DisplayMode vm_ideal
= { 0, 0, 0, 0, 0 };
684 if( SDL_GetDisplayMode( display_index
, mode_index
, &vm_ideal
) != 0 )
686 vg_error( "SDL_GetDisplayMode failed: %s", SDL_GetError() );
691 vm_ideal
.w
= vg
.window_x
;
694 vm_ideal
.h
= vg
.window_y
;
697 SDL_DisplayMode vm_best
;
698 if( !SDL_GetClosestDisplayMode( display_index
, &vm_ideal
, &vm_best
) )
700 vg_error( "SDL_GetClosestDisplayMode failed: %s", SDL_GetError() );
704 vg
.refresh_rate
= vm_best
.refresh_rate
;
705 vg
.window_x
= vm_best
.w
;
706 vg
.window_y
= vm_best
.h
;
708 vg_info( "CreateWindow( %d %d @%.2fhz )\n", vg
.window_x
, vg
.window_y
,
711 /* TODO: Allow selecting closest video mode from launch opts */
712 if((vg
.window
= SDL_CreateWindow( window_name
,
713 SDL_WINDOWPOS_UNDEFINED
,
714 SDL_WINDOWPOS_UNDEFINED
,
715 vg
.window_x
, vg
.window_y
,
717 SDL_WINDOW_FULLSCREEN_DESKTOP
|
719 SDL_WINDOW_INPUT_GRABBED
)))
721 if( SDL_SetWindowDisplayMode( vg
.window
, &vm_best
) )
723 vg_error( "SDL_SetWindowDisplayMode failed: %s", SDL_GetError() );
730 vg_error( "SDL_CreateWindow failed: %s", SDL_GetError() );
734 vg_info( "CreateContext\n" );
739 if( (vg
.gl_context
= SDL_GL_CreateContext(vg
.window
) ))
741 SDL_GL_GetDrawableSize( vg
.window
, &vg
.window_x
, &vg
.window_y
);
742 vg_success( "Window created (%dx%d)\n", vg
.window_x
, vg
.window_y
);
746 vg_error( "SDL_GL_CreateContext failed: %s\n", SDL_GetError() );
751 if( !gladLoadGLLoader((GLADloadproc
)SDL_GL_GetProcAddress
) )
753 vg_error( "Glad Failed to initialize\n" );
754 SDL_GL_DeleteContext( vg
.gl_context
);
759 const unsigned char* glver
= glGetString( GL_VERSION
);
760 vg_success( "Load setup complete, OpenGL version: %s\n", glver
);
762 vg_info( "Setting swap interval\n" );
764 if( SDL_GL_SetSwapInterval( -1 ) == -1 )
766 vg_warn( "Adaptive Vsync not supported\n" );
768 if( SDL_GL_SetSwapInterval( 1 ) == -1 )
770 vg_fatal_exit_loop( "Cannot enable Vsync! You might be overriding it"
771 " in your graphics control panel.\n" );
774 vg_success( "Using vsync\n" );
777 vg_success( "Using adaptive Vsync\n" );
779 SDL_DisplayMode dispmode
;
780 if( !SDL_GetWindowDisplayMode( vg
.window
, &dispmode
) )
782 if( dispmode
.refresh_rate
)
784 vg
.refresh_rate
= dispmode
.refresh_rate
;
785 vg_info( "Refresh rate: %d\n", dispmode
.refresh_rate
);
790 VG_STATIC
void vg_enter( int argc
, char *argv
[], const char *window_name
)
792 _vg_process_launch_opts_internal( argc
, argv
);
798 _vg_init_window( window_name
);
800 SDL_SetRelativeMouseMode(1);
801 vg
.thread_id_main
= SDL_GetThreadID(NULL
);
803 /* Opengl-required systems */
807 vg
.engine_status
= k_engine_status_running
;
809 _vg_opengl_sync_init();
810 vg_loader_start( _vg_load_full
);
814 _vg_console_write_persistent();
816 SDL_AtomicLock( &vg
.sl_context
);
817 vg
.engine_status
= k_engine_status_none
;
818 SDL_AtomicUnlock( &vg
.sl_context
);
822 vg_success( "If you see this it means everything went.. \"well\".....\n" );
824 SDL_GL_DeleteContext( vg
.gl_context
);
829 * Immediately transfer away from calling thread into a safe loop, signal for
830 * others to shutdown, then free everything once the user closes the window.
832 * FIXME(bug): glfwWindowShouldClose() never returns 1 in windows via wine, ONLY
833 * when calling the program from outside its normal directory.
835 VG_STATIC
void vg_fatal_exit_loop( const char *error
)
838 * https://www.gnu.org/software/libc/manual/html_node/Backtraces.html
841 * TODO: this on windows?
850 size
= backtrace( array
, 20 );
851 strings
= backtrace_symbols( array
, size
);
853 if( strings
!= NULL
)
855 vg_error( "---------------- gnu backtrace -------------\n" );
857 for( int i
=0; i
<size
; i
++ )
858 vg_info( "%s\n", strings
[i
] );
860 vg_error( "---------------- gnu backtrace -------------\n" );
867 vg_error( "Fatal error: %s\n", error
);
869 SDL_AtomicLock( &vg
.sl_context
);
870 if( vg
.engine_status
== k_engine_status_none
)
872 SDL_AtomicUnlock( &vg
.sl_context
);
874 /* TODO: Correct shutdown before other systems */
879 SDL_AtomicUnlock( &vg
.sl_context
);
881 vg_acquire_thread_sync();
883 SDL_AtomicLock( &vg
.sl_context
);
884 vg
.engine_status
= k_engine_status_crashed
;
885 vg
.str_const_engine_err
= error
;
886 SDL_AtomicUnlock( &vg
.sl_context
);
888 /* Notify other thread for curtosey */
889 if( vg_thread_purpose() == k_thread_purpose_main
)
891 SDL_AtomicLock( &vg
.sl_context
);
893 if( vg
.exec_context
!= 0 )
894 SDL_SemPost( vg
.sem_allow_exec
);
896 SDL_AtomicUnlock( &vg
.sl_context
);
903 _vg_process_events();
904 if( vg
.window_should_close
)
907 if( vg_getkey( SDLK_ESCAPE
) )
910 glBindFramebuffer( GL_FRAMEBUFFER
, 0 );
912 glDisable(GL_DEPTH_TEST
);
913 glBlendFunc(GL_ONE_MINUS_DST_ALPHA
, GL_DST_ALPHA
);
914 glBlendEquation(GL_FUNC_ADD
);
916 glClearColor( 0.15f
+ sinf(vg
.time_real
)*0.1f
, 0.0f
, 0.0f
,1.0f
);
917 glClear( GL_COLOR_BUFFER_BIT
);
918 glViewport( 0,0, vg
.window_x
, vg
.window_y
);
921 SDL_GL_SwapWindow( vg
.window
);
924 /* Can now shutdown and EXIT */
926 SDL_GL_DeleteContext( vg
.gl_context
);
934 VG_STATIC
void vg_fatal_exit_loop( const char *error
)
936 vg_error( "Fatal error: %s\n", error
);
943 * Graphic cards will check these to force it to use the GPU
945 u32 NvOptimusEnablement
= 0x00000001;
946 int AmdPowerXpressRequestHighPerformance
= 1;
948 #endif /* VG_HEADER_H */