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();
375 vg_function_push( (struct vg_cmd
)
378 .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);
552 audio_debug_ui( vg
.pv
);
561 vg_profile_end( &vg_prof_render
);
564 VG_STATIC
void _vg_gameloop(void)
566 vg
.accumulator
= 0.75f
* (1.0f
/60.0f
);
571 _vg_process_events();
573 if( vg
.window_should_close
)
577 vg
.time_delta
= vg
.frame_delta
* vg
.time_rate
;
578 vg
.time
+= vg
.time_delta
;
593 _vg_gameloop_update();
594 _vg_gameloop_render();
596 SDL_GL_SwapWindow( vg
.window
);
601 VG_STATIC
void _vg_process_launch_opts_internal( int argc
, char *argv
[] )
604 while( vg_argp( argc
, argv
) )
606 if( (arg
= vg_opt_arg( 'w' )) )
608 vg
.window_x
= atoi( arg
);
611 if( (arg
= vg_opt_arg( 'h' )) )
613 vg
.window_y
= atoi( arg
);
616 if( (arg
= vg_long_opt_arg( "samples" )) )
618 vg
.samples
= VG_MAX( 0, VG_MIN( 8, atoi( arg
) ) );
621 if( vg_long_opt( "use-libc-malloc" ) )
623 vg_mem
.use_libc_malloc
= atoi( arg
);
626 if( vg_long_opt( "high-performance" ) )
628 vg
.quality_profile
= k_quality_profile_low
;
635 VG_STATIC
void _vg_init_window( const char *window_name
)
637 if( SDL_Init(SDL_INIT_VIDEO
|SDL_INIT_AUDIO
|SDL_INIT_GAMECONTROLLER
) != 0 )
639 vg_error( "SDL_Init failed: %s\n", SDL_GetError() );
643 SDL_GL_SetSwapInterval( 1 );
644 SDL_GL_SetAttribute( SDL_GL_DOUBLEBUFFER
, 1 );
645 SDL_GL_SetAttribute( SDL_GL_CONTEXT_MAJOR_VERSION
, 3 );
646 SDL_GL_SetAttribute( SDL_GL_CONTEXT_MINOR_VERSION
, 3 );
647 SDL_GL_SetAttribute( SDL_GL_CONTEXT_PROFILE_MASK
,
648 SDL_GL_CONTEXT_PROFILE_CORE
);
650 SDL_GL_SetAttribute( SDL_GL_STENCIL_SIZE
, 1 );
651 SDL_GL_SetAttribute( SDL_GL_RED_SIZE
, 8 );
652 SDL_GL_SetAttribute( SDL_GL_GREEN_SIZE
, 8 );
653 SDL_GL_SetAttribute( SDL_GL_BLUE_SIZE
, 8 );
654 SDL_GL_SetAttribute( SDL_GL_ALPHA_SIZE
, 8 );
658 SDL_GL_SetAttribute( SDL_GL_MULTISAMPLEBUFFERS
, 1 );
659 SDL_GL_SetAttribute( SDL_GL_MULTISAMPLESAMPLES
, vg
.samples
);
662 SDL_GL_SetAttribute( SDL_GL_CONTEXT_RELEASE_BEHAVIOR
,
663 SDL_GL_CONTEXT_RELEASE_BEHAVIOR_FLUSH
);
666 * Get monitor information
668 int display_count
= 0, display_index
= 0, mode_index
= 0;
669 if( (display_count
= SDL_GetNumVideoDisplays()) < 1 )
671 vg_error( "SDL_GetNumVideoDisplays returned: %i\n", display_count
);
675 /* TODO: Allow chosing the modes at startup */
676 SDL_DisplayMode mode
= { SDL_PIXELFORMAT_UNKNOWN
, 0, 0, 0, 0 };
677 if( SDL_GetDisplayMode( display_index
, mode_index
, &mode
) != 0 )
679 vg_error( "SDL_GetDisplayMode failed: %s", SDL_GetError() );
683 vg
.refresh_rate
= mode
.refresh_rate
;
685 /* TODO: Allow selecting closest video mode from launch opts */
686 if((vg
.window
= SDL_CreateWindow( window_name
,
687 SDL_WINDOWPOS_UNDEFINED
,
688 SDL_WINDOWPOS_UNDEFINED
,
691 SDL_WINDOW_FULLSCREEN_DESKTOP
|
693 SDL_WINDOW_INPUT_GRABBED
)))
698 vg_error( "SDL_CreateWindow failed: %s", SDL_GetError() );
705 if( (vg
.gl_context
= SDL_GL_CreateContext(vg
.window
) ))
707 SDL_GL_GetDrawableSize( vg
.window
, &vg
.window_x
, &vg
.window_y
);
708 vg_success( "Window created (%dx%d)\n", vg
.window_x
, vg
.window_y
);
712 vg_error( "SDL_GL_CreateContext failed: %s\n", SDL_GetError() );
717 if( !gladLoadGLLoader((GLADloadproc
)SDL_GL_GetProcAddress
) )
719 vg_error( "Glad Failed to initialize\n" );
720 SDL_GL_DeleteContext( vg
.gl_context
);
725 const unsigned char* glver
= glGetString( GL_VERSION
);
726 vg_success( "Load setup complete, OpenGL version: %s\n", glver
);
729 VG_STATIC
void vg_enter( int argc
, char *argv
[], const char *window_name
)
731 _vg_process_launch_opts_internal( argc
, argv
);
737 _vg_init_window( window_name
);
739 SDL_SetRelativeMouseMode(1);
740 vg
.thread_id_main
= SDL_GetThreadID(NULL
);
742 /* Opengl-required systems */
746 vg
.engine_status
= k_engine_status_running
;
748 _vg_opengl_sync_init();
749 vg_loader_start( _vg_load_full
);
753 _vg_console_write_persistent();
755 SDL_AtomicLock( &vg
.sl_context
);
756 vg
.engine_status
= k_engine_status_none
;
757 SDL_AtomicUnlock( &vg
.sl_context
);
761 vg_success( "If you see this it means everything went.. \"well\".....\n" );
763 SDL_GL_DeleteContext( vg
.gl_context
);
768 * Immediately transfer away from calling thread into a safe loop, signal for
769 * others to shutdown, then free everything once the user closes the window.
771 * FIXME(bug): glfwWindowShouldClose() never returns 1 in windows via wine, ONLY
772 * when calling the program from outside its normal directory.
774 VG_STATIC
void vg_fatal_exit_loop( const char *error
)
777 * https://www.gnu.org/software/libc/manual/html_node/Backtraces.html
780 * TODO: this on windows?
789 size
= backtrace( array
, 20 );
790 strings
= backtrace_symbols( array
, size
);
792 if( strings
!= NULL
)
794 vg_error( "---------------- gnu backtrace -------------\n" );
796 for( int i
=0; i
<size
; i
++ )
797 vg_info( "%s\n", strings
[i
] );
799 vg_error( "---------------- gnu backtrace -------------\n" );
806 vg_error( "Fatal error: %s\n", error
);
808 SDL_AtomicLock( &vg
.sl_context
);
809 if( vg
.engine_status
== k_engine_status_none
)
811 SDL_AtomicUnlock( &vg
.sl_context
);
813 /* TODO: Correct shutdown before other systems */
818 SDL_AtomicUnlock( &vg
.sl_context
);
820 vg_acquire_thread_sync();
822 SDL_AtomicLock( &vg
.sl_context
);
823 vg
.engine_status
= k_engine_status_crashed
;
824 vg
.str_const_engine_err
= error
;
825 SDL_AtomicUnlock( &vg
.sl_context
);
827 /* Notify other thread for curtosey */
828 if( vg_thread_purpose() == k_thread_purpose_main
)
830 SDL_AtomicLock( &vg
.sl_context
);
832 if( vg
.exec_context
!= 0 )
833 SDL_SemPost( vg
.sem_allow_exec
);
835 SDL_AtomicUnlock( &vg
.sl_context
);
842 _vg_process_events();
843 if( vg
.window_should_close
)
846 if( vg_getkey( SDLK_ESCAPE
) )
849 glBindFramebuffer( GL_FRAMEBUFFER
, 0 );
851 glDisable(GL_DEPTH_TEST
);
852 glBlendFunc(GL_ONE_MINUS_DST_ALPHA
, GL_DST_ALPHA
);
853 glBlendEquation(GL_FUNC_ADD
);
855 glClearColor( 0.15f
+ sinf(vg
.time_real
)*0.1f
, 0.0f
, 0.0f
,1.0f
);
856 glClear( GL_COLOR_BUFFER_BIT
|GL_DEPTH_BUFFER_BIT
);
857 glViewport( 0,0, vg
.window_x
, vg
.window_y
);
860 SDL_GL_SwapWindow( vg
.window
);
863 /* Can now shutdown and EXIT */
865 SDL_GL_DeleteContext( vg
.gl_context
);
873 VG_STATIC
void vg_fatal_exit_loop( const char *error
)
875 vg_error( "Fatal error: %s\n", error
);
882 * Graphic cards will check these to force it to use the GPU
884 u32 NvOptimusEnablement
= 0x00000001;
885 int AmdPowerXpressRequestHighPerformance
= 1;
887 #endif /* VG_HEADER_H */