1 /* Copyright (C) 2021-2023 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)
55 #include "vg_platform.h"
62 VG_STATIC
void vg_print_backtrace(void)
70 size
= backtrace( array
, 20 );
71 strings
= backtrace_symbols( array
, size
);
73 if( strings
!= NULL
){
74 vg_error( "---------------- gnu backtrace -------------\n" );
76 for( int i
=0; i
<size
; i
++ )
77 vg_info( "%s\n", strings
[i
] );
79 vg_error( "---------------- gnu backtrace -------------\n" );
88 #include "dep/glad/glad.h"
89 #include "submodules/SDL/include/SDL.h"
90 #include "vg_stdint.h"
92 void vg_register_exit( void( *funcptr
)(void), const char *name
);
100 //#define VG_SYNC_DEBUG
102 #define VG_SYNC_LOG(STR,...) \
103 vg_info(STR,SDL_GetThreadID(NULL),##__VA_ARGS__)
105 #define VG_SYNC_LOG(...)
109 VG_STATIC
void vg_enter( int argc
, char *argv
[], const char *window_name
);
112 VG_STATIC
void vg_preload(void);
113 VG_STATIC
void vg_load(void);
116 VG_STATIC
void vg_launch_opt(void);
117 VG_STATIC
void vg_start(void);
119 VG_STATIC
void vg_framebuffer_resize(int w
, int h
);
120 VG_STATIC
void vg_update(void);
121 VG_STATIC
void vg_update_fixed(void);
122 VG_STATIC
void vg_update_post(void);
124 VG_STATIC
void vg_render(void);
125 VG_STATIC
void vg_ui(void);
131 SDL_GLContext gl_context
;
133 SDL_sem
*sem_loader
; /* allows only one loader at a time */
135 jmp_buf env_loader_exit
;
137 SDL_threadID thread_id_main
,
140 SDL_SpinLock sl_status
;
143 k_engine_status_none
,
144 k_engine_status_load_internal
,
145 k_engine_status_running
,
146 k_engine_status_crashed
150 /* Window information */
156 int display_refresh_rate
,
157 fps_limit
; /* 0: use vsync, >0: cap fps to this, no vsync */
161 k_vsync_feature_disabled
=0,
162 k_vsync_feature_enabled
=1,
163 k_vsync_feature_enabled_adaptive
=2,
164 k_vsync_feature_error
=3
177 time_fixed_accumulator
,
178 time_fixed_extrapolate
,
181 u64 time_hp
, time_hp_last
, time_spinning
;
183 int fixed_iterations
;
188 k_engine_stage_update
,
189 k_engine_stage_update_fixed
,
190 k_engine_stage_rendering
,
199 k_quality_profile_high
= 0,
200 k_quality_profile_low
= 1,
204 VG_STATIC vg
= { .time_rate
= 1.0 };
206 enum vg_thread_purpose
208 k_thread_purpose_nothing
,
209 k_thread_purpose_main
,
210 k_thread_purpose_loader
213 #include "vg_async.h"
215 VG_STATIC
enum engine_status
_vg_engine_status(void)
217 SDL_AtomicLock( &vg
.sl_status
);
218 enum engine_status status
= vg
.engine_status
;
219 SDL_AtomicUnlock( &vg
.sl_status
);
224 VG_STATIC
enum vg_thread_purpose
vg_thread_purpose(void)
226 SDL_AtomicLock( &vg
.sl_status
);
228 if( vg
.thread_id_main
== SDL_GetThreadID(NULL
) ){
229 SDL_AtomicUnlock( &vg
.sl_status
);
230 return k_thread_purpose_main
;
233 SDL_AtomicUnlock( &vg
.sl_status
);
234 return k_thread_purpose_loader
;
238 VG_STATIC
void _vg_opengl_sync_init(void)
240 vg
.sem_loader
= SDL_CreateSemaphore(1);
243 VG_STATIC
void vg_checkgl( const char *src_info
);
244 #define VG_STRINGIT( X ) #X
245 #define VG_CHECK_GL_ERR() vg_checkgl( __FILE__ ":L" VG_STRINGIT(__LINE__) )
247 #include "vg_console.h"
248 #include "vg_profiler.h"
249 #include "vg_audio.h"
250 #include "vg_shader.h"
252 #include "vg_input.h"
254 #include "vg_lines.h"
255 #include "vg_loader.h"
259 VG_STATIC
struct vg_profile vg_prof_update
= {.name
="update()"},
260 vg_prof_render
= {.name
="render()"},
261 vg_prof_swap
= {.name
="swap"};
263 VG_STATIC
void vg_checkgl( const char *src_info
)
268 while( (err
= glGetError()) != GL_NO_ERROR
){
269 vg_error( "(%s) OpenGL Error: #%d\n", src_info
, err
);
274 vg_fatal_error( "OpenGL Error" );
277 VG_STATIC
void async_vg_bake_shaders( void *payload
, u32 size
)
279 vg_shaders_compile();
282 VG_STATIC
void vg_bake_shaders(void)
284 vg_console_reg_cmd( "reload_shaders", vg_shaders_live_recompile
, NULL
);
285 vg_async_call( async_vg_bake_shaders
, NULL
, 0 );
288 void async_internal_complete( void *payload
, u32 size
)
290 vg_success( "Internal async setup complete\n" );
291 SDL_AtomicLock( &vg
.sl_status
);
293 if( vg
.engine_status
== k_engine_status_crashed
){
294 SDL_AtomicUnlock( &vg
.sl_status
);
298 vg
.engine_status
= k_engine_status_running
;
301 SDL_AtomicUnlock( &vg
.sl_status
);
304 VG_STATIC
void _vg_load_full(void)
309 vg_loader_step( vg_input_init
, vg_input_free
);
310 vg_loader_step( vg_lines_init
, NULL
);
311 vg_loader_step( vg_audio_init
, vg_audio_free
);
312 vg_loader_step( vg_profiler_init
, NULL
);
314 vg_async_call( async_internal_complete
, NULL
, 0 );
320 VG_STATIC
void _vg_process_events(void)
322 v2_zero( vg
.mouse_wheel
);
323 v2_zero( vg
.mouse_delta
);
327 while( SDL_PollEvent( &event
) ){
328 if( event
.type
== SDL_KEYDOWN
){
329 console_proc_key( event
.key
.keysym
);
331 else if( event
.type
== SDL_MOUSEWHEEL
){
332 vg
.mouse_wheel
[0] += event
.wheel
.preciseX
;
333 vg
.mouse_wheel
[1] += event
.wheel
.preciseY
;
335 else if( event
.type
== SDL_CONTROLLERAXISMOTION
||
336 event
.type
== SDL_CONTROLLERBUTTONDOWN
||
337 event
.type
== SDL_CONTROLLERBUTTONUP
||
338 event
.type
== SDL_CONTROLLERDEVICEADDED
||
339 event
.type
== SDL_CONTROLLERDEVICEREMOVED
342 vg_input_controller_event( &event
);
344 else if( event
.type
== SDL_MOUSEMOTION
){
345 vg
.mouse_delta
[0] += event
.motion
.xrel
;
346 vg
.mouse_delta
[1] += event
.motion
.yrel
;
348 else if( event
.type
== SDL_WINDOWEVENT
){
349 if( event
.window
.event
== SDL_WINDOWEVENT_SIZE_CHANGED
){
351 SDL_GL_GetDrawableSize( vg
.window
, &w
, &h
);
354 vg_warn( "Got a invalid framebuffer size: "
355 "%dx%d... ignoring\n", w
, h
);
361 vg_framebuffer_resize(w
,h
);
364 else if( event
.window
.event
== SDL_WINDOWEVENT_CLOSE
){
365 vg
.window_should_close
= 1;
368 else if( event
.type
== SDL_TEXTINPUT
){
369 console_proc_utf8( event
.text
.text
);
373 vg
.mouse_pos
[0] += vg
.mouse_delta
[0];
374 vg
.mouse_pos
[1] += vg
.mouse_delta
[1];
380 VG_STATIC
void _vg_gameloop_update(void)
382 vg_profile_begin( &vg_prof_update
);
384 vg
.engine_stage
= k_engine_stage_update
;
387 /* Fixed update loop */
388 vg
.engine_stage
= k_engine_stage_update_fixed
;
390 vg
.fixed_iterations
= 0;
391 vg_lines
.allow_input
= 1;
392 vg
.time_fixed_accumulator
+= vg
.time_delta
;
394 while( vg
.time_fixed_accumulator
>= VG_TIMESTEP_FIXED
){
396 vg_lines
.allow_input
= 0;
398 vg
.time_fixed_accumulator
-= VG_TIMESTEP_FIXED
;
399 //vg.accumulator = VG_MAX( 0.0, vg.accumulator );
401 vg
.fixed_iterations
++;
402 if( vg
.fixed_iterations
== 8 ){
406 vg_lines
.allow_input
= 1;
407 vg
.time_fixed_extrapolate
= vg
.time_fixed_accumulator
/ VG_TIMESTEP_FIXED
;
409 vg
.engine_stage
= k_engine_stage_update
;
411 vg_profile_end( &vg_prof_update
);
414 VG_STATIC
void _vg_gameloop_render(void)
416 vg_profile_begin( &vg_prof_render
);
419 vg
.engine_stage
= k_engine_stage_rendering
;
423 vg
.engine_stage
= k_engine_stage_ui
;
425 ui_begin( vg
.window_x
, vg
.window_y
);
428 ui_set_mouse( vg
.mouse_pos
[0], vg
.mouse_pos
[1], 0 );
430 int frame_target
= vg
.display_refresh_rate
;
432 if( vg
.fps_limit
> 0 ){
433 frame_target
= vg
.fps_limit
;
437 (struct vg_profile
*[]){
438 &vg_prof_update
,&vg_prof_render
,&vg_prof_swap
}, 3,
439 (1.0f
/(float)frame_target
)*1000.0f
,
440 (ui_rect
){ 4, 4, 250, 0 }, 0
448 "refresh: %d (%.1fms)\n"
450 "iterations: %d (acc: %.3fms%%)\n"
451 "time: real(%.2f) delta(%.2f) rate(%.2f)\n"
453 " extrap(%.2f) frame(%.2f) spin( %llu )\n",
455 " extrap(%.2f) frame(%.2f) spin( %lu )\n",
457 vg
.window_x
, vg
.window_y
,
458 frame_target
, (1.0f
/(float)frame_target
)*1000.0f
,
461 (vg
.time_fixed_accumulator
/VG_TIMESTEP_FIXED
)*100.0f
,
462 vg
.time
, vg
.time_delta
, vg
.time_rate
,
463 vg
.time_fixed_extrapolate
, vg
.time_frame_delta
,
466 ui_text( (ui_rect
){258, 4+24+12+12,0,0},perf
, 1,0);
470 audio_debug_ui( vg
.pv
);
478 vg_profile_end( &vg_prof_render
);
481 VG_STATIC
int vg_framefilter( double dt
)
483 if( (vg
.fps_limit
<= 0) && (vg
.vsync_feature
!= k_vsync_feature_error
) ){
484 /* turn on vsync if not enabled */
486 enum vsync_feature requested
= k_vsync_feature_enabled
;
487 if( vg
.fps_limit
< 0 ) requested
= k_vsync_feature_enabled_adaptive
;
489 if( vg
.vsync_feature
!= requested
){
490 vg_info( "Setting swap interval\n" );
492 int swap_interval
= 1;
493 if( requested
== k_vsync_feature_enabled_adaptive
) swap_interval
= -1;
495 if( SDL_GL_SetSwapInterval( swap_interval
) == -1 ){
496 if( requested
== k_vsync_feature_enabled
){
497 vg_error( "Vsync is not supported by your system\n" );
498 vg_warn( "You may be overriding it in your"
499 " graphics control panel.\n" );
502 vg_error( "Adaptive Vsync is not supported by your system\n" );
505 vg
.vsync_feature
= k_vsync_feature_error
;
506 vg
.fps_limit
= vg
.display_refresh_rate
;
508 /* TODO: Make popup to notify user that this happened */
512 vg_success( "Vsync enabled (%d)\n", requested
);
513 vg
.vsync_feature
= requested
;
520 if( vg
.vsync_feature
!= k_vsync_feature_disabled
){
521 SDL_GL_SetSwapInterval( 0 );
522 vg
.vsync_feature
= k_vsync_feature_disabled
;
525 if( vg
.fps_limit
< 25 ) vg
.fps_limit
= 25;
526 if( vg
.fps_limit
> 300 ) vg
.fps_limit
= 300;
528 double min_frametime
= 1.0/(double)vg
.fps_limit
;
529 if( vg
.time_frame_delta
< min_frametime
){
530 /* TODO: we can use high res nanosleep on Linux here */
531 double sleep_ms
= (min_frametime
-vg
.time_frame_delta
) * 1000.0;
532 u32 ms
= (u32
)floor( sleep_ms
);
547 VG_STATIC
int _vg_crashscreen(void)
549 if( vg
.window_should_close
)
552 if( vg_getkey( SDLK_ESCAPE
) )
555 glBindFramebuffer( GL_FRAMEBUFFER
, 0 );
557 glDisable(GL_DEPTH_TEST
);
558 glBlendFunc(GL_ONE_MINUS_DST_ALPHA
, GL_DST_ALPHA
);
559 glBlendEquation(GL_FUNC_ADD
);
561 glClearColor( 0.15f
+ sinf(vg
.time
)*0.1f
, 0.0f
, 0.0f
,1.0f
);
562 glClear( GL_COLOR_BUFFER_BIT
);
563 glViewport( 0,0, vg
.window_x
, vg
.window_y
);
570 VG_STATIC
void _vg_gameloop(void)
572 //vg.time_fixed_accumulator = 0.75f * (1.0f/60.0f);
574 vg
.time_hp
= SDL_GetPerformanceCounter();
575 vg
.time_hp_last
= vg
.time_hp
;
580 vg
.time_hp
= SDL_GetPerformanceCounter();
581 u64 udt
= vg
.time_hp
- vg
.time_hp_last
;
582 vg
.time_hp_last
= vg
.time_hp
;
584 double dt
= (double)udt
/ (double)SDL_GetPerformanceFrequency();
586 vg
.time_frame_delta
+= dt
;
588 if( vg_framefilter( dt
) )
591 vg_profile_begin( &vg_prof_swap
);
592 SDL_GL_SwapWindow( vg
.window
);
593 vg_profile_end( &vg_prof_swap
);
595 enum engine_status status
= _vg_engine_status();
597 if( status
== k_engine_status_crashed
){
598 if( _vg_crashscreen() )
602 vg
.time_delta
= vg
.time_frame_delta
* vg
.time_rate
;
603 vg
.time
+= vg
.time_delta
;
605 vg_run_async_checked();
606 _vg_process_events();
608 if( vg
.window_should_close
)
611 if( status
== k_engine_status_running
){
612 _vg_gameloop_update();
613 _vg_gameloop_render();
620 vg
.time_frame_delta
= 0.0;
621 vg
.time_spinning
= 0;
625 VG_STATIC
void _vg_process_launch_opts_internal( int argc
, char *argv
[] )
628 while( vg_argp( argc
, argv
) ){
629 if( (arg
= vg_opt_arg( 'w' )) ){
630 vg
.window_x
= atoi( arg
);
633 if( (arg
= vg_opt_arg( 'h' )) ){
634 vg
.window_y
= atoi( arg
);
637 if( (arg
= vg_long_opt_arg( "samples" )) ){
638 vg
.samples
= VG_MAX( 0, VG_MIN( 8, atoi( arg
) ) );
641 if( vg_long_opt( "use-libc-malloc" ) ){
642 vg_mem
.use_libc_malloc
= 1;
645 if( vg_long_opt( "high-performance" ) ){
646 vg
.quality_profile
= k_quality_profile_low
;
653 VG_STATIC
void _vg_init_window( const char *window_name
)
655 vg_info( "SDL_INIT\n" );
657 if( SDL_Init( SDL_INIT_VIDEO
) != 0 ){
658 vg_error( "SDL_Init failed: %s\n", SDL_GetError() );
662 SDL_InitSubSystem( SDL_INIT_AUDIO
);
663 SDL_InitSubSystem( SDL_INIT_GAMECONTROLLER
);
665 SDL_GL_SetAttribute( SDL_GL_DOUBLEBUFFER
, 1 );
666 SDL_GL_SetAttribute( SDL_GL_CONTEXT_MAJOR_VERSION
, 3 );
667 SDL_GL_SetAttribute( SDL_GL_CONTEXT_MINOR_VERSION
, 3 );
668 SDL_GL_SetAttribute( SDL_GL_CONTEXT_PROFILE_MASK
,
669 SDL_GL_CONTEXT_PROFILE_CORE
);
671 SDL_GL_SetAttribute( SDL_GL_CONTEXT_RELEASE_BEHAVIOR
,
672 SDL_GL_CONTEXT_RELEASE_BEHAVIOR_FLUSH
);
674 SDL_GL_SetAttribute( SDL_GL_RED_SIZE
, 8 );
675 SDL_GL_SetAttribute( SDL_GL_GREEN_SIZE
, 8 );
676 SDL_GL_SetAttribute( SDL_GL_BLUE_SIZE
, 8 );
677 SDL_GL_SetAttribute( SDL_GL_ALPHA_SIZE
, 8 );
678 SDL_GL_SetAttribute( SDL_GL_STENCIL_SIZE
, 0 );
681 * Get monitor information
683 vg_info( "Getting display count\n" );
684 int display_count
= 0,
693 SDL_DisplayMode video_mode
;
694 if( SDL_GetDesktopDisplayMode( display_index
, &video_mode
) ){
695 vg_error( "SDL_GetDesktopDisplayMode failed: %s\n", SDL_GetError() );
700 vg
.display_refresh_rate
= video_mode
.refresh_rate
;
701 vg
.window_x
= video_mode
.w
;
702 vg
.window_y
= video_mode
.h
;
706 SDL_SetHint( "SDL_VIDEO_X11_XINERAMA", "1" );
707 SDL_SetHint( "SDL_VIDEO_X11_XRANDR", "0" );
708 SDL_SetHint( "SDL_VIDEO_X11_XVIDMODE", "0" );
711 vg_info( "CreateWindow( %d %d @%dhz )\n", vg
.window_x
, vg
.window_y
,
712 vg
.display_refresh_rate
);
714 /* TODO: Allow selecting closest video mode from launch opts */
715 if((vg
.window
= SDL_CreateWindow( window_name
,
718 0, 0, vg
.window_x
, vg
.window_y
,
719 SDL_WINDOW_BORDERLESS
|SDL_WINDOW_OPENGL
|SDL_WINDOW_INPUT_GRABBED
723 vg
.window_x
, vg
.window_y
,
725 SDL_WINDOW_FULLSCREEN_DESKTOP
|
727 SDL_WINDOW_INPUT_GRABBED
730 if( SDL_SetWindowDisplayMode( vg
.window
, &video_mode
) ){
731 vg_error( "SDL_SetWindowDisplayMode failed: %s", SDL_GetError() );
738 vg_error( "SDL_CreateWindow failed: %s", SDL_GetError() );
742 SDL_RaiseWindow( vg
.window
);
744 vg_info( "CreateContext\n" );
749 if( (vg
.gl_context
= SDL_GL_CreateContext(vg
.window
) )){
750 SDL_GL_GetDrawableSize( vg
.window
, &vg
.window_x
, &vg
.window_y
);
751 vg_success( "Window created (%dx%d)\n", vg
.window_x
, vg
.window_y
);
754 vg_error( "SDL_GL_CreateContext failed: %s\n", SDL_GetError() );
759 if( !gladLoadGLLoader((GLADloadproc
)SDL_GL_GetProcAddress
) ) {
760 vg_error( "Glad Failed to initialize\n" );
761 SDL_GL_DeleteContext( vg
.gl_context
);
766 const unsigned char* glver
= glGetString( GL_VERSION
);
767 vg_success( "Load setup complete, OpenGL version: %s\n", glver
);
769 SDL_GL_SetSwapInterval(0); /* disable vsync while loading */
771 SDL_DisplayMode dispmode
;
772 if( !SDL_GetWindowDisplayMode( vg
.window
, &dispmode
) ){
773 if( dispmode
.refresh_rate
){
774 vg
.display_refresh_rate
= dispmode
.refresh_rate
;
778 if( vg
.display_refresh_rate
< 25 || vg
.display_refresh_rate
> 300 ){
779 vg
.display_refresh_rate
= 60;
782 vg_info( "Display refresh rate: %d\n", dispmode
.refresh_rate
);
785 vg
.fps_limit
= vg
.display_refresh_rate
;
787 /* request vsync by default on linux to avoid screen tearing.
788 * this does have its own issues with compositing on X11. */
793 VG_STATIC
void _vg_terminate(void)
796 _vg_console_write_persistent();
798 SDL_AtomicLock( &vg
.sl_status
);
799 vg
.engine_status
= k_engine_status_none
;
800 SDL_AtomicUnlock( &vg
.sl_status
);
804 vg_success( "If you see this it means everything went.. \"well\".....\n" );
806 SDL_GL_DeleteContext( vg
.gl_context
);
811 VG_STATIC
void vg_enter( int argc
, char *argv
[], const char *window_name
)
813 _vg_process_launch_opts_internal( argc
, argv
);
819 vg_console_reg_var( "fps_limit", &vg
.fps_limit
, k_var_dtype_i32
, 0 );
820 _vg_init_window( window_name
);
824 SDL_SetRelativeMouseMode(1);
825 vg
.thread_id_main
= SDL_GetThreadID(NULL
);
827 /* Opengl-required systems */
831 vg
.engine_status
= k_engine_status_load_internal
;
833 _vg_opengl_sync_init();
834 vg_loader_start( _vg_load_full
);
839 VG_STATIC
void vg_fatal_error( const char *fmt
, ... )
842 va_start( args
, fmt
);
843 _vg_log_write( stderr
, KRED
" fatal" KWHT
"| " KRED
, fmt
, args
);
846 vg_print_backtrace();
848 SDL_AtomicLock( &vg
.sl_status
);
849 vg
.engine_status
= k_engine_status_crashed
;
850 SDL_AtomicUnlock( &vg
.sl_status
);
852 if( vg_thread_purpose() == k_thread_purpose_loader
){
853 longjmp( vg
.env_loader_exit
, 1 );
856 vg_error( "There is no jump to the error runner thing yet! bai bai\n" );
864 VG_STATIC
void vg_fatal_error( const char *fmt
, ... )
867 va_start( args
, fmt
);
868 _vg_log_write( stderr
, KRED
" fatal" KWHT
"| " KRED
, fmt
, args
);
876 * Graphic cards will check these to force it to use the GPU
878 u32 NvOptimusEnablement
= 0x00000001;
879 int AmdPowerXpressRequestHighPerformance
= 1;
881 #endif /* VG_HEADER_H */