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
,
182 k_quality_profile_high
= 0,
183 k_quality_profile_low
= 1,
187 VG_STATIC vg
= { .time_rate
= 1.0 };
189 enum vg_thread_purpose
191 k_thread_purpose_nothing
,
192 k_thread_purpose_main
,
193 k_thread_purpose_loader
196 VG_STATIC
void vg_fatal_exit_loop( const char *error
);
199 * Checks if the engine is running
201 VG_STATIC
void _vg_ensure_engine_running(void)
203 /* Check if the engine is no longer running */
204 SDL_AtomicLock( &vg
.sl_context
);
205 enum engine_status status
= vg
.engine_status
;
206 SDL_AtomicUnlock( &vg
.sl_context
);
208 if( status
!= k_engine_status_running
)
212 VG_SYNC_LOG( "[%d] No longer running...\n");
218 VG_STATIC
enum vg_thread_purpose
vg_thread_purpose(void)
220 SDL_AtomicLock( &vg
.sl_context
);
222 if( vg
.thread_id_main
== SDL_GetThreadID(NULL
) )
224 SDL_AtomicUnlock( &vg
.sl_context
);
225 return k_thread_purpose_main
;
229 SDL_AtomicUnlock( &vg
.sl_context
);
230 return k_thread_purpose_loader
;
235 * Sync execution so that the OpenGL context is switched onto this thread.
236 * Anything after this call will be in a valid context.
238 VG_STATIC
void vg_acquire_thread_sync(void)
240 /* We dont want to do anything if this is the main thread */
242 if( vg_thread_purpose() == k_thread_purpose_loader
)
244 VG_SYNC_LOG( "[%d] vg_acquire_thread_sync()\n" );
245 _vg_ensure_engine_running();
247 SDL_AtomicLock( &vg
.sl_context
);
248 if( vg
.context_ownership_depth
== 0 )
250 vg
.context_ownership_depth
++;
252 SDL_AtomicUnlock( &vg
.sl_context
);
254 /* wait until told we can go */
255 VG_SYNC_LOG( "[%d] Waiting to acuire sync.\n" );
256 SDL_SemWait( vg
.sem_allow_exec
);
258 _vg_ensure_engine_running();
260 SDL_GL_MakeCurrent( vg
.window
, vg
.gl_context
);
261 VG_SYNC_LOG( "[%d] granted\n" );
265 vg
.context_ownership_depth
++;
266 VG_SYNC_LOG( "[%d] granted\n" );
267 SDL_AtomicUnlock( &vg
.sl_context
);
273 * Signify that we are done with the OpenGL context in this thread.
274 * Anything after this call will be in an undefined context.
276 VG_STATIC
void vg_release_thread_sync(void)
278 if( vg_thread_purpose() == k_thread_purpose_loader
)
280 VG_SYNC_LOG( "[%d] vg_release_thread_sync()\n" );
282 SDL_AtomicLock( &vg
.sl_context
);
283 vg
.context_ownership_depth
--;
285 if( vg
.context_ownership_depth
== 0 )
287 SDL_AtomicUnlock( &vg
.sl_context
);
288 VG_SYNC_LOG( "[%d] Releasing context.\n" );
289 SDL_GL_MakeCurrent( NULL
, NULL
);
290 SDL_SemPost( vg
.sem_exec_finished
);
293 SDL_AtomicUnlock( &vg
.sl_context
);
297 VG_STATIC
void _vg_run_synced(void)
299 SDL_AtomicLock( &vg
.sl_context
);
301 if( vg
.exec_context
!= 0 )
303 VG_SYNC_LOG( "[%d] _vg_run_synced() (%d).\n", vg
.exec_context
);
305 SDL_AtomicUnlock( &vg
.sl_context
);
307 /* allow operations to go */
308 SDL_GL_MakeCurrent( NULL
, NULL
);
309 SDL_SemPost( vg
.sem_allow_exec
);
311 /* wait for operations to complete */
312 VG_SYNC_LOG( "[%d] Waiting for content.\n" );
313 SDL_SemWait( vg
.sem_exec_finished
);
315 /* check if we killed the engine */
316 _vg_ensure_engine_running();
318 /* re-engage main thread */
319 VG_SYNC_LOG( "[%d] Re-engaging.\n" );
320 SDL_GL_MakeCurrent( vg
.window
, vg
.gl_context
);
324 VG_SYNC_LOG( "[%d] Nothing to do.\n" );
325 SDL_AtomicUnlock( &vg
.sl_context
);
329 VG_STATIC
void _vg_opengl_sync_init(void)
331 vg
.sem_allow_exec
= SDL_CreateSemaphore(0);
332 vg
.sem_exec_finished
= SDL_CreateSemaphore(0);
333 vg
.sem_loader
= SDL_CreateSemaphore(1);
336 VG_STATIC
void vg_checkgl( const char *src_info
);
337 #define VG_STRINGIT( X ) #X
338 #define VG_CHECK_GL_ERR() vg_checkgl( __FILE__ ":L" VG_STRINGIT(__LINE__) )
340 #include "vg_console.h"
341 #include "vg_profiler.h"
342 #include "vg_audio.h"
343 #include "vg_shader.h"
345 #include "vg_input.h"
347 #include "vg_lines.h"
348 #include "vg_loader.h"
352 VG_STATIC
struct vg_profile vg_prof_update
= {.name
="update()"},
353 vg_prof_render
= {.name
="render()"};
355 VG_STATIC
void vg_checkgl( const char *src_info
)
360 while( (err
= glGetError()) != GL_NO_ERROR
)
362 vg_error( "(%s) OpenGL Error: #%d\n", src_info
, err
);
367 vg_fatal_exit_loop( "OpenGL Error" );
370 VG_STATIC
void vg_bake_shaders(void)
372 vg_acquire_thread_sync();
374 vg_function_push( (struct vg_cmd
)
376 .name
= "reload_shaders",
377 .function
= vg_shaders_live_recompile
380 vg_shaders_compile();
381 vg_release_thread_sync();
384 VG_STATIC
void _vg_load_full(void)
389 vg_loader_step( vg_input_init
, vg_input_free
);
390 vg_loader_step( vg_lines_init
, NULL
);
391 vg_loader_step( vg_audio_init
, vg_audio_free
);
392 vg_loader_step( vg_profiler_init
, NULL
);
398 VG_STATIC
void _vg_process_events(void)
401 vg
.time_real_last
= vg
.time_real
;
402 vg
.time_real
= (double)SDL_GetTicks64() / 1000.0;
403 vg
.frame_delta
= vg
.time_real
-vg
.time_real_last
;
405 v2_zero( vg
.mouse_wheel
);
406 v2_zero( vg
.mouse_delta
);
410 while( SDL_PollEvent( &event
) )
412 if( event
.type
== SDL_KEYDOWN
)
414 console_proc_key( event
.key
.keysym
);
416 else if( event
.type
== SDL_MOUSEWHEEL
)
418 vg
.mouse_wheel
[0] += event
.wheel
.preciseX
;
419 vg
.mouse_wheel
[1] += event
.wheel
.preciseY
;
421 else if( event
.type
== SDL_CONTROLLERAXISMOTION
||
422 event
.type
== SDL_CONTROLLERBUTTONDOWN
||
423 event
.type
== SDL_CONTROLLERBUTTONUP
||
424 event
.type
== SDL_CONTROLLERDEVICEADDED
||
425 event
.type
== SDL_CONTROLLERDEVICEREMOVED
428 vg_input_controller_event( &event
);
430 else if( event
.type
== SDL_MOUSEMOTION
)
432 vg
.mouse_delta
[0] += event
.motion
.xrel
;
433 vg
.mouse_delta
[1] += event
.motion
.yrel
;
435 else if( event
.type
== SDL_WINDOWEVENT
)
437 if( event
.window
.event
== SDL_WINDOWEVENT_SIZE_CHANGED
)
440 SDL_GL_GetDrawableSize( vg
.window
, &w
, &h
);
444 vg_warn( "Got a invalid framebuffer size: "
445 "%dx%d... ignoring\n", w
, h
);
452 vg_framebuffer_resize(w
,h
);
455 else if( event
.window
.event
== SDL_WINDOWEVENT_CLOSE
)
457 vg
.window_should_close
= 1;
460 else if( event
.type
== SDL_TEXTINPUT
)
462 console_proc_utf8( event
.text
.text
);
466 vg
.mouse_pos
[0] += vg
.mouse_delta
[0];
467 vg
.mouse_pos
[1] += vg
.mouse_delta
[1];
473 VG_STATIC
void _vg_gameloop_update(void)
475 vg_profile_begin( &vg_prof_update
);
477 vg
.engine_stage
= k_engine_stage_update
;
480 /* Fixed update loop */
481 vg
.engine_stage
= k_engine_stage_update_fixed
;
482 vg
.accumulator
+= vg
.time_delta
;
484 vg
.fixed_iterations
= 0;
485 vg_lines
.allow_input
= 1;
486 while( vg
.accumulator
>= (VG_TIMESTEP_FIXED
-0.00125) )
489 vg_lines
.allow_input
= 0;
491 vg
.accumulator
-= VG_TIMESTEP_FIXED
;
492 vg
.accumulator
= VG_MAX( 0.0, vg
.accumulator
);
494 vg
.fixed_iterations
++;
495 if( vg
.fixed_iterations
== 8 )
500 vg_lines
.allow_input
= 1;
502 vg
.engine_stage
= k_engine_stage_update
;
504 vg_profile_end( &vg_prof_update
);
507 VG_STATIC
void _vg_gameloop_render(void)
509 vg_profile_begin( &vg_prof_render
);
514 vg
.engine_stage
= k_engine_stage_rendering
;
518 vg
.engine_stage
= k_engine_stage_ui
;
520 ui_begin( vg
.window_x
, vg
.window_y
);
523 ui_set_mouse( vg
.mouse_pos
[0], vg
.mouse_pos
[1], 0 );
526 (struct vg_profile
*[]){&vg_prof_update
,&vg_prof_render
}, 2,
527 (1.0f
/(float)vg
.refresh_rate
)*1000.0f
,
528 (ui_rect
){ 4, 4, 250, 0 }, 0
538 "refresh: %.1f (%.1fms)\n"
540 "iterations: %d (acc: %.3fms%%)\n",
541 vg
.window_x
, vg
.window_y
,
542 vg
.refresh_rate
, (1.0f
/vg
.refresh_rate
)*1000.0f
,
545 (vg
.accumulator
/VG_TIMESTEP_FIXED
)*100.0f
);
547 ui_text( (ui_rect
){258, 4+24+12,0,0},perf
, 1,0);
551 audio_debug_ui( vg
.pv
);
560 vg_profile_end( &vg_prof_render
);
563 VG_STATIC
void _vg_gameloop(void)
565 vg
.accumulator
= 0.75f
* (1.0f
/60.0f
);
570 _vg_process_events();
572 if( vg
.window_should_close
)
576 vg
.time_delta
= vg
.frame_delta
* vg
.time_rate
;
577 vg
.time
+= vg
.time_delta
;
592 _vg_gameloop_update();
593 _vg_gameloop_render();
595 SDL_GL_SwapWindow( vg
.window
);
600 VG_STATIC
void _vg_process_launch_opts_internal( int argc
, char *argv
[] )
603 while( vg_argp( argc
, argv
) )
605 if( (arg
= vg_opt_arg( 'w' )) )
607 vg
.window_x
= atoi( arg
);
610 if( (arg
= vg_opt_arg( 'h' )) )
612 vg
.window_y
= atoi( arg
);
615 if( (arg
= vg_long_opt_arg( "samples" )) )
617 vg
.samples
= VG_MAX( 0, VG_MIN( 8, atoi( arg
) ) );
620 if( vg_long_opt( "use-libc-malloc" ) )
622 vg_mem
.use_libc_malloc
= 1;
625 if( vg_long_opt( "high-performance" ) )
627 vg
.quality_profile
= k_quality_profile_low
;
634 VG_STATIC
void _vg_init_window( const char *window_name
)
636 vg_info( "SDL_INIT\n" );
638 if( SDL_Init( SDL_INIT_VIDEO
) != 0 )
640 vg_error( "SDL_Init failed: %s\n", SDL_GetError() );
644 SDL_InitSubSystem( SDL_INIT_AUDIO
);
645 SDL_InitSubSystem( SDL_INIT_GAMECONTROLLER
);
647 SDL_GL_SetAttribute( SDL_GL_DOUBLEBUFFER
, 1 );
648 SDL_GL_SetAttribute( SDL_GL_CONTEXT_MAJOR_VERSION
, 3 );
649 SDL_GL_SetAttribute( SDL_GL_CONTEXT_MINOR_VERSION
, 3 );
650 SDL_GL_SetAttribute( SDL_GL_CONTEXT_PROFILE_MASK
,
651 SDL_GL_CONTEXT_PROFILE_CORE
);
653 SDL_GL_SetAttribute( SDL_GL_CONTEXT_RELEASE_BEHAVIOR
,
654 SDL_GL_CONTEXT_RELEASE_BEHAVIOR_FLUSH
);
656 SDL_GL_SetAttribute( SDL_GL_RED_SIZE
, 8 );
657 SDL_GL_SetAttribute( SDL_GL_GREEN_SIZE
, 8 );
658 SDL_GL_SetAttribute( SDL_GL_BLUE_SIZE
, 8 );
659 SDL_GL_SetAttribute( SDL_GL_ALPHA_SIZE
, 8 );
660 SDL_GL_SetAttribute( SDL_GL_STENCIL_SIZE
, 0 );
663 * Get monitor information
665 vg_info( "Getting display count\n" );
666 int display_count
= 0, display_index
= 0, mode_index
= 0;
667 if( (display_count
= SDL_GetNumVideoDisplays()) < 1 )
669 vg_error( "SDL_GetNumVideoDisplays returned: %i\n", display_count
);
676 /* TODO: Allow chosing the modes at startup */
677 vg_info( "Getting default display mode\n" );
678 SDL_DisplayMode vm_ideal
= { 0, 0, 0, 0, 0 };
679 if( SDL_GetDisplayMode( display_index
, mode_index
, &vm_ideal
) != 0 )
681 vg_error( "SDL_GetDisplayMode failed: %s", SDL_GetError() );
686 vm_ideal
.w
= vg
.window_x
;
689 vm_ideal
.h
= vg
.window_y
;
692 SDL_DisplayMode vm_best
;
693 if( !SDL_GetClosestDisplayMode( display_index
, &vm_ideal
, &vm_best
) )
695 vg_error( "SDL_GetClosestDisplayMode failed: %s", SDL_GetError() );
699 vg
.refresh_rate
= vm_best
.refresh_rate
;
700 vg
.window_x
= vm_best
.w
;
701 vg
.window_y
= vm_best
.h
;
703 vg_info( "CreateWindow( %d %d @%.2fhz )\n", vg
.window_x
, vg
.window_y
,
706 /* TODO: Allow selecting closest video mode from launch opts */
707 if((vg
.window
= SDL_CreateWindow( window_name
,
708 SDL_WINDOWPOS_UNDEFINED
,
709 SDL_WINDOWPOS_UNDEFINED
,
710 vg
.window_x
, vg
.window_y
,
712 SDL_WINDOW_FULLSCREEN_DESKTOP
|
714 SDL_WINDOW_INPUT_GRABBED
)))
716 if( SDL_SetWindowDisplayMode( vg
.window
, &vm_best
) )
718 vg_error( "SDL_SetWindowDisplayMode failed: %s", SDL_GetError() );
725 vg_error( "SDL_CreateWindow failed: %s", SDL_GetError() );
729 vg_info( "CreateContext\n" );
734 if( (vg
.gl_context
= SDL_GL_CreateContext(vg
.window
) ))
736 SDL_GL_GetDrawableSize( vg
.window
, &vg
.window_x
, &vg
.window_y
);
737 vg_success( "Window created (%dx%d)\n", vg
.window_x
, vg
.window_y
);
741 vg_error( "SDL_GL_CreateContext failed: %s\n", SDL_GetError() );
746 if( !gladLoadGLLoader((GLADloadproc
)SDL_GL_GetProcAddress
) )
748 vg_error( "Glad Failed to initialize\n" );
749 SDL_GL_DeleteContext( vg
.gl_context
);
754 const unsigned char* glver
= glGetString( GL_VERSION
);
755 vg_success( "Load setup complete, OpenGL version: %s\n", glver
);
757 vg_info( "Setting swap interval\n" );
759 if( SDL_GL_SetSwapInterval( -1 ) == -1 )
761 vg_warn( "Adaptive Vsync not supported\n" );
763 if( SDL_GL_SetSwapInterval( 1 ) == -1 )
765 vg_fatal_exit_loop( "Cannot enable Vsync! You might be overriding it"
766 " in your graphics control panel.\n" );
769 vg_success( "Using vsync\n" );
772 vg_success( "Using adaptive Vsync\n" );
774 SDL_DisplayMode dispmode
;
775 if( !SDL_GetWindowDisplayMode( vg
.window
, &dispmode
) )
777 if( dispmode
.refresh_rate
)
779 vg
.refresh_rate
= dispmode
.refresh_rate
;
780 vg_info( "Refresh rate: %d\n", dispmode
.refresh_rate
);
785 VG_STATIC
void vg_enter( int argc
, char *argv
[], const char *window_name
)
787 _vg_process_launch_opts_internal( argc
, argv
);
793 _vg_init_window( window_name
);
795 SDL_SetRelativeMouseMode(1);
796 vg
.thread_id_main
= SDL_GetThreadID(NULL
);
798 /* Opengl-required systems */
802 vg
.engine_status
= k_engine_status_running
;
804 _vg_opengl_sync_init();
805 vg_loader_start( _vg_load_full
);
809 _vg_console_write_persistent();
811 SDL_AtomicLock( &vg
.sl_context
);
812 vg
.engine_status
= k_engine_status_none
;
813 SDL_AtomicUnlock( &vg
.sl_context
);
817 vg_success( "If you see this it means everything went.. \"well\".....\n" );
819 SDL_GL_DeleteContext( vg
.gl_context
);
824 * Immediately transfer away from calling thread into a safe loop, signal for
825 * others to shutdown, then free everything once the user closes the window.
827 * FIXME(bug): glfwWindowShouldClose() never returns 1 in windows via wine, ONLY
828 * when calling the program from outside its normal directory.
830 VG_STATIC
void vg_fatal_exit_loop( const char *error
)
833 * https://www.gnu.org/software/libc/manual/html_node/Backtraces.html
836 * TODO: this on windows?
845 size
= backtrace( array
, 20 );
846 strings
= backtrace_symbols( array
, size
);
848 if( strings
!= NULL
)
850 vg_error( "---------------- gnu backtrace -------------\n" );
852 for( int i
=0; i
<size
; i
++ )
853 vg_info( "%s\n", strings
[i
] );
855 vg_error( "---------------- gnu backtrace -------------\n" );
862 vg_error( "Fatal error: %s\n", error
);
864 SDL_AtomicLock( &vg
.sl_context
);
865 if( vg
.engine_status
== k_engine_status_none
)
867 SDL_AtomicUnlock( &vg
.sl_context
);
869 /* TODO: Correct shutdown before other systems */
874 SDL_AtomicUnlock( &vg
.sl_context
);
876 vg_acquire_thread_sync();
878 SDL_AtomicLock( &vg
.sl_context
);
879 vg
.engine_status
= k_engine_status_crashed
;
880 vg
.str_const_engine_err
= error
;
881 SDL_AtomicUnlock( &vg
.sl_context
);
883 /* Notify other thread for curtosey */
884 if( vg_thread_purpose() == k_thread_purpose_main
)
886 SDL_AtomicLock( &vg
.sl_context
);
888 if( vg
.exec_context
!= 0 )
889 SDL_SemPost( vg
.sem_allow_exec
);
891 SDL_AtomicUnlock( &vg
.sl_context
);
898 _vg_process_events();
899 if( vg
.window_should_close
)
902 if( vg_getkey( SDLK_ESCAPE
) )
905 glBindFramebuffer( GL_FRAMEBUFFER
, 0 );
907 glDisable(GL_DEPTH_TEST
);
908 glBlendFunc(GL_ONE_MINUS_DST_ALPHA
, GL_DST_ALPHA
);
909 glBlendEquation(GL_FUNC_ADD
);
911 glClearColor( 0.15f
+ sinf(vg
.time_real
)*0.1f
, 0.0f
, 0.0f
,1.0f
);
912 glClear( GL_COLOR_BUFFER_BIT
);
913 glViewport( 0,0, vg
.window_x
, vg
.window_y
);
916 SDL_GL_SwapWindow( vg
.window
);
919 /* Can now shutdown and EXIT */
921 SDL_GL_DeleteContext( vg
.gl_context
);
929 VG_STATIC
void vg_fatal_exit_loop( const char *error
)
931 vg_error( "Fatal error: %s\n", error
);
938 * Graphic cards will check these to force it to use the GPU
940 u32 NvOptimusEnablement
= 0x00000001;
941 int AmdPowerXpressRequestHighPerformance
= 1;
943 #endif /* VG_HEADER_H */