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_gui(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,
206 VG_STATIC vg
= { .time_rate
= 1.0 };
208 enum vg_thread_purpose
210 k_thread_purpose_nothing
,
211 k_thread_purpose_main
,
212 k_thread_purpose_loader
215 #include "vg_async.h"
217 VG_STATIC
enum engine_status
_vg_engine_status(void)
219 SDL_AtomicLock( &vg
.sl_status
);
220 enum engine_status status
= vg
.engine_status
;
221 SDL_AtomicUnlock( &vg
.sl_status
);
226 VG_STATIC
enum vg_thread_purpose
vg_thread_purpose(void)
228 SDL_AtomicLock( &vg
.sl_status
);
230 if( vg
.thread_id_main
== SDL_GetThreadID(NULL
) ){
231 SDL_AtomicUnlock( &vg
.sl_status
);
232 return k_thread_purpose_main
;
235 SDL_AtomicUnlock( &vg
.sl_status
);
236 return k_thread_purpose_loader
;
240 VG_STATIC
void _vg_opengl_sync_init(void)
242 vg
.sem_loader
= SDL_CreateSemaphore(1);
245 VG_STATIC
void vg_checkgl( const char *src_info
);
246 #define VG_STRINGIT( X ) #X
247 #define VG_CHECK_GL_ERR() vg_checkgl( __FILE__ ":L" VG_STRINGIT(__LINE__) )
249 #include "vg_console.h"
250 #include "vg_profiler.h"
251 #include "vg_audio.h"
252 #include "vg_shader.h"
254 #include "vg_input.h"
256 #include "vg_imgui.h"
257 #include "vg_lines.h"
258 #include "vg_loader.h"
262 VG_STATIC
struct vg_profile vg_prof_update
= {.name
="update()"},
263 vg_prof_render
= {.name
="render()"},
264 vg_prof_swap
= {.name
="swap"};
266 VG_STATIC
void vg_checkgl( const char *src_info
)
271 while( (err
= glGetError()) != GL_NO_ERROR
){
272 vg_error( "(%s) OpenGL Error: #%d\n", src_info
, err
);
277 vg_fatal_error( "OpenGL Error" );
280 VG_STATIC
void async_vg_bake_shaders( void *payload
, u32 size
)
282 vg_shaders_compile();
285 VG_STATIC
void vg_bake_shaders(void)
287 vg_console_reg_cmd( "reload_shaders", vg_shaders_live_recompile
, NULL
);
288 vg_async_call( async_vg_bake_shaders
, NULL
, 0 );
291 void async_internal_complete( void *payload
, u32 size
)
293 vg_success( "Internal async setup complete\n" );
294 SDL_AtomicLock( &vg
.sl_status
);
296 if( vg
.engine_status
== k_engine_status_crashed
){
297 SDL_AtomicUnlock( &vg
.sl_status
);
301 vg
.engine_status
= k_engine_status_running
;
304 SDL_AtomicUnlock( &vg
.sl_status
);
307 VG_STATIC
void _vg_load_full(void)
312 vg_loader_step( vg_input_init
, vg_input_free
);
313 vg_loader_step( vg_lines_init
, NULL
);
314 vg_loader_step( vg_audio_init
, vg_audio_free
);
315 vg_loader_step( vg_profiler_init
, NULL
);
317 vg_async_call( async_internal_complete
, NULL
, 0 );
323 VG_STATIC
void _vg_process_events(void)
325 v2_zero( vg
.mouse_wheel
);
326 v2_zero( vg
.mouse_delta
);
333 while( SDL_PollEvent( &event
) ){
334 if( event
.type
== SDL_KEYDOWN
){
335 //console_proc_key( event.key.keysym );
336 _ui_proc_key( event
.key
.keysym
);
338 else if( event
.type
== SDL_MOUSEWHEEL
){
339 vg
.mouse_wheel
[0] += event
.wheel
.preciseX
;
340 vg
.mouse_wheel
[1] += event
.wheel
.preciseY
;
342 else if( event
.type
== SDL_CONTROLLERDEVICEADDED
||
343 event
.type
== SDL_CONTROLLERDEVICEREMOVED
)
345 vg_input_device_event( &event
);
347 else if( event
.type
== SDL_CONTROLLERAXISMOTION
||
348 event
.type
== SDL_CONTROLLERBUTTONDOWN
||
349 event
.type
== SDL_CONTROLLERBUTTONUP
)
351 vg_input_controller_event( &event
);
353 else if( event
.type
== SDL_MOUSEMOTION
){
354 vg
.mouse_delta
[0] += event
.motion
.xrel
;
355 vg
.mouse_delta
[1] += event
.motion
.yrel
;
357 else if( event
.type
== SDL_WINDOWEVENT
){
358 if( event
.window
.event
== SDL_WINDOWEVENT_SIZE_CHANGED
){
360 SDL_GL_GetDrawableSize( vg
.window
, &w
, &h
);
363 vg_warn( "Got a invalid framebuffer size: "
364 "%dx%d... ignoring\n", w
, h
);
370 vg_framebuffer_resize(w
,h
);
373 else if( event
.window
.event
== SDL_WINDOWEVENT_CLOSE
){
374 vg
.window_should_close
= 1;
377 else if( event
.type
== SDL_TEXTINPUT
){
378 //console_proc_utf8( event.text.text );
379 ui_proc_utf8( event
.text
.text
);
383 vg
.mouse_pos
[0] += vg
.mouse_delta
[0];
384 vg
.mouse_pos
[1] += vg
.mouse_delta
[1];
387 VG_STATIC
void _vg_gameloop_update(void)
389 vg_profile_begin( &vg_prof_update
);
391 vg
.engine_stage
= k_engine_stage_update
;
394 /* Fixed update loop */
395 vg
.engine_stage
= k_engine_stage_update_fixed
;
397 vg
.fixed_iterations
= 0;
398 vg_lines
.allow_input
= 1;
399 vg
.time_fixed_accumulator
+= vg
.time_delta
;
401 while( vg
.time_fixed_accumulator
>= VG_TIMESTEP_FIXED
){
403 vg_lines
.allow_input
= 0;
405 vg
.time_fixed_accumulator
-= VG_TIMESTEP_FIXED
;
406 //vg.accumulator = VG_MAX( 0.0, vg.accumulator );
408 vg
.fixed_iterations
++;
409 if( vg
.fixed_iterations
== 8 ){
413 vg_lines
.allow_input
= 1;
414 vg
.time_fixed_extrapolate
= vg
.time_fixed_accumulator
/ VG_TIMESTEP_FIXED
;
416 vg
.engine_stage
= k_engine_stage_update
;
418 vg_profile_end( &vg_prof_update
);
421 VG_STATIC
void _vg_gameloop_render(void)
423 vg_profile_begin( &vg_prof_render
);
426 vg
.engine_stage
= k_engine_stage_rendering
;
430 vg
.engine_stage
= k_engine_stage_ui
;
436 ui_begin( vg
.window_x
, vg
.window_y
);
439 ui_set_mouse( vg
.mouse_pos
[0], vg
.mouse_pos
[1], 0 );
441 int frame_target
= vg
.display_refresh_rate
;
443 if( vg
.fps_limit
> 0 ){
444 frame_target
= vg
.fps_limit
;
448 (struct vg_profile
*[]){
449 &vg_prof_update
,&vg_prof_render
,&vg_prof_swap
}, 3,
450 (1.0f
/(float)frame_target
)*1000.0f
,
451 (ui_rect
){ 4, 4, 250, 0 }, 0
459 "refresh: %d (%.1fms)\n"
461 "iterations: %d (acc: %.3fms%%)\n"
462 "time: real(%.2f) delta(%.2f) rate(%.2f)\n"
464 " extrap(%.2f) frame(%.2f) spin( %llu )\n",
466 " extrap(%.2f) frame(%.2f) spin( %lu )\n",
468 vg
.window_x
, vg
.window_y
,
469 frame_target
, (1.0f
/(float)frame_target
)*1000.0f
,
472 (vg
.time_fixed_accumulator
/VG_TIMESTEP_FIXED
)*100.0f
,
473 vg
.time
, vg
.time_delta
, vg
.time_rate
,
474 vg
.time_fixed_extrapolate
, vg
.time_frame_delta
,
477 ui_text( (ui_rect
){258, 4+24+12+12,0,0},perf
, 1,0);
481 audio_debug_ui( vg
.pv
);
490 vg_profile_end( &vg_prof_render
);
493 VG_STATIC
int vg_framefilter( double dt
)
495 if( (vg
.fps_limit
<= 0) && (vg
.vsync_feature
!= k_vsync_feature_error
) ){
496 /* turn on vsync if not enabled */
498 enum vsync_feature requested
= k_vsync_feature_enabled
;
499 if( vg
.fps_limit
< 0 ) requested
= k_vsync_feature_enabled_adaptive
;
501 if( vg
.vsync_feature
!= requested
){
502 vg_info( "Setting swap interval\n" );
504 int swap_interval
= 1;
505 if( requested
== k_vsync_feature_enabled_adaptive
) swap_interval
= -1;
507 if( SDL_GL_SetSwapInterval( swap_interval
) == -1 ){
508 if( requested
== k_vsync_feature_enabled
){
509 vg_error( "Vsync is not supported by your system\n" );
510 vg_warn( "You may be overriding it in your"
511 " graphics control panel.\n" );
514 vg_error( "Adaptive Vsync is not supported by your system\n" );
517 vg
.vsync_feature
= k_vsync_feature_error
;
518 vg
.fps_limit
= vg
.display_refresh_rate
;
520 /* TODO: Make popup to notify user that this happened */
524 vg_success( "Vsync enabled (%d)\n", requested
);
525 vg
.vsync_feature
= requested
;
532 if( vg
.vsync_feature
!= k_vsync_feature_disabled
){
533 SDL_GL_SetSwapInterval( 0 );
534 vg
.vsync_feature
= k_vsync_feature_disabled
;
537 if( vg
.fps_limit
< 25 ) vg
.fps_limit
= 25;
538 if( vg
.fps_limit
> 300 ) vg
.fps_limit
= 300;
540 double min_frametime
= 1.0/(double)vg
.fps_limit
;
541 if( vg
.time_frame_delta
< min_frametime
){
542 /* TODO: we can use high res nanosleep on Linux here */
543 double sleep_ms
= (min_frametime
-vg
.time_frame_delta
) * 1000.0;
544 u32 ms
= (u32
)floor( sleep_ms
);
559 VG_STATIC
int _vg_crashscreen(void)
562 if( vg_getkey( SDLK_ESCAPE
) )
566 glBindFramebuffer( GL_FRAMEBUFFER
, 0 );
568 glDisable(GL_DEPTH_TEST
);
569 glBlendFunc(GL_ONE_MINUS_DST_ALPHA
, GL_DST_ALPHA
);
570 glBlendEquation(GL_FUNC_ADD
);
572 glClearColor( 0.15f
+ sinf(vg
.time
)*0.1f
, 0.0f
, 0.0f
,1.0f
);
573 glClear( GL_COLOR_BUFFER_BIT
);
574 glViewport( 0,0, vg
.window_x
, vg
.window_y
);
581 VG_STATIC
void _vg_gameloop(void)
583 //vg.time_fixed_accumulator = 0.75f * (1.0f/60.0f);
585 vg
.time_hp
= SDL_GetPerformanceCounter();
586 vg
.time_hp_last
= vg
.time_hp
;
591 vg
.time_hp
= SDL_GetPerformanceCounter();
592 u64 udt
= vg
.time_hp
- vg
.time_hp_last
;
593 vg
.time_hp_last
= vg
.time_hp
;
595 double dt
= (double)udt
/ (double)SDL_GetPerformanceFrequency();
597 vg
.time_frame_delta
+= dt
;
599 if( vg_framefilter( dt
) )
602 vg_profile_begin( &vg_prof_swap
);
603 SDL_GL_SwapWindow( vg
.window
);
604 vg_profile_end( &vg_prof_swap
);
606 enum engine_status status
= _vg_engine_status();
608 vg
.time_delta
= vg
.time_frame_delta
* vg
.time_rate
;
609 vg
.time
+= vg
.time_delta
;
611 vg_run_async_checked();
612 _vg_process_events();
614 if( vg
.window_should_close
)
617 if( status
== k_engine_status_crashed
){
618 if( _vg_crashscreen() )
622 if( status
== k_engine_status_running
){
623 _vg_gameloop_update();
624 _vg_gameloop_render();
631 if( vg
.loader_ring
> 0.01f
){
632 vg
.loader_ring
-= vg
.time_frame_delta
* 0.5f
;
633 _vg_loader_render_ring( vg
.loader_ring
);
636 vg
.time_frame_delta
= 0.0;
637 vg
.time_spinning
= 0;
641 VG_STATIC
void _vg_process_launch_opts_internal( int argc
, char *argv
[] )
644 while( vg_argp( argc
, argv
) ){
645 if( (arg
= vg_opt_arg( 'w' )) ){
646 vg
.window_x
= atoi( arg
);
649 if( (arg
= vg_opt_arg( 'h' )) ){
650 vg
.window_y
= atoi( arg
);
653 if( (arg
= vg_long_opt_arg( "samples" )) ){
654 vg
.samples
= VG_MAX( 0, VG_MIN( 8, atoi( arg
) ) );
657 if( vg_long_opt( "use-libc-malloc" ) ){
658 vg_mem
.use_libc_malloc
= 1;
661 if( vg_long_opt( "high-performance" ) ){
662 vg
.quality_profile
= k_quality_profile_low
;
669 VG_STATIC
void _vg_init_window( const char *window_name
)
671 vg_info( "SDL_INIT\n" );
673 if( SDL_Init( SDL_INIT_VIDEO
) != 0 ){
674 vg_error( "SDL_Init failed: %s\n", SDL_GetError() );
678 SDL_InitSubSystem( SDL_INIT_AUDIO
);
679 SDL_InitSubSystem( SDL_INIT_GAMECONTROLLER
);
681 SDL_GL_SetAttribute( SDL_GL_DOUBLEBUFFER
, 1 );
682 SDL_GL_SetAttribute( SDL_GL_CONTEXT_MAJOR_VERSION
, 3 );
683 SDL_GL_SetAttribute( SDL_GL_CONTEXT_MINOR_VERSION
, 3 );
684 SDL_GL_SetAttribute( SDL_GL_CONTEXT_PROFILE_MASK
,
685 SDL_GL_CONTEXT_PROFILE_CORE
);
687 SDL_GL_SetAttribute( SDL_GL_CONTEXT_RELEASE_BEHAVIOR
,
688 SDL_GL_CONTEXT_RELEASE_BEHAVIOR_FLUSH
);
690 SDL_GL_SetAttribute( SDL_GL_RED_SIZE
, 8 );
691 SDL_GL_SetAttribute( SDL_GL_GREEN_SIZE
, 8 );
692 SDL_GL_SetAttribute( SDL_GL_BLUE_SIZE
, 8 );
693 SDL_GL_SetAttribute( SDL_GL_ALPHA_SIZE
, 8 );
694 SDL_GL_SetAttribute( SDL_GL_STENCIL_SIZE
, 0 );
697 * Get monitor information
699 vg_info( "Getting display count\n" );
700 int display_count
= 0,
709 SDL_DisplayMode video_mode
;
710 if( SDL_GetDesktopDisplayMode( display_index
, &video_mode
) ){
711 vg_error( "SDL_GetDesktopDisplayMode failed: %s\n", SDL_GetError() );
716 vg
.display_refresh_rate
= video_mode
.refresh_rate
;
717 vg
.window_x
= video_mode
.w
;
718 vg
.window_y
= video_mode
.h
;
722 SDL_SetHint( "SDL_VIDEO_X11_XINERAMA", "1" );
723 SDL_SetHint( "SDL_VIDEO_X11_XRANDR", "0" );
724 SDL_SetHint( "SDL_VIDEO_X11_XVIDMODE", "0" );
727 vg_info( "CreateWindow( %d %d @%dhz )\n", vg
.window_x
, vg
.window_y
,
728 vg
.display_refresh_rate
);
730 /* TODO: Allow selecting closest video mode from launch opts */
731 if((vg
.window
= SDL_CreateWindow( window_name
,
734 0, 0, vg
.window_x
, vg
.window_y
,
735 SDL_WINDOW_BORDERLESS
|SDL_WINDOW_OPENGL
739 vg
.window_x
, vg
.window_y
,
741 SDL_WINDOW_FULLSCREEN_DESKTOP
|
743 SDL_WINDOW_INPUT_GRABBED
746 if( SDL_SetWindowDisplayMode( vg
.window
, &video_mode
) ){
747 vg_error( "SDL_SetWindowDisplayMode failed: %s", SDL_GetError() );
754 vg_error( "SDL_CreateWindow failed: %s", SDL_GetError() );
758 SDL_RaiseWindow( vg
.window
);
760 vg_info( "CreateContext\n" );
763 if( SDL_IsTextInputActive() ) SDL_StopTextInput();
768 if( (vg
.gl_context
= SDL_GL_CreateContext(vg
.window
) )){
769 SDL_GL_GetDrawableSize( vg
.window
, &vg
.window_x
, &vg
.window_y
);
770 vg_success( "Window created (%dx%d)\n", vg
.window_x
, vg
.window_y
);
773 vg_error( "SDL_GL_CreateContext failed: %s\n", SDL_GetError() );
778 if( !gladLoadGLLoader((GLADloadproc
)SDL_GL_GetProcAddress
) ) {
779 vg_error( "Glad Failed to initialize\n" );
780 SDL_GL_DeleteContext( vg
.gl_context
);
785 const unsigned char* glver
= glGetString( GL_VERSION
);
786 vg_success( "Load setup complete, OpenGL version: %s\n", glver
);
788 SDL_GL_SetSwapInterval(0); /* disable vsync while loading */
790 SDL_DisplayMode dispmode
;
791 if( !SDL_GetWindowDisplayMode( vg
.window
, &dispmode
) ){
792 if( dispmode
.refresh_rate
){
793 vg
.display_refresh_rate
= dispmode
.refresh_rate
;
797 if( vg
.display_refresh_rate
< 25 || vg
.display_refresh_rate
> 300 ){
798 vg
.display_refresh_rate
= 60;
801 vg_info( "Display refresh rate: %d\n", dispmode
.refresh_rate
);
804 vg
.fps_limit
= vg
.display_refresh_rate
;
806 /* request vsync by default on linux to avoid screen tearing.
807 * this does have its own issues with compositing on X11. */
812 VG_STATIC
void _vg_terminate(void)
815 _vg_console_write_persistent();
817 SDL_AtomicLock( &vg
.sl_status
);
818 vg
.engine_status
= k_engine_status_none
;
819 SDL_AtomicUnlock( &vg
.sl_status
);
823 vg_success( "If you see this it means everything went.. \"well\".....\n" );
825 SDL_GL_DeleteContext( vg
.gl_context
);
830 VG_STATIC
void vg_enter( int argc
, char *argv
[], const char *window_name
)
832 _vg_process_launch_opts_internal( argc
, argv
);
838 vg_console_reg_var( "fps_limit", &vg
.fps_limit
, k_var_dtype_i32
, 0 );
839 _vg_init_window( window_name
);
844 SDL_SetRelativeMouseMode(1);
847 vg
.thread_id_main
= SDL_GetThreadID(NULL
);
849 /* Opengl-required systems */
853 vg
.engine_status
= k_engine_status_load_internal
;
855 _vg_opengl_sync_init();
856 vg_loader_start( _vg_load_full
);
861 VG_STATIC
void vg_fatal_error( const char *fmt
, ... )
864 va_start( args
, fmt
);
865 _vg_log_write( stderr
, KRED
" fatal" KWHT
"| " KRED
, fmt
, args
);
868 vg_print_backtrace();
870 SDL_AtomicLock( &vg
.sl_status
);
871 vg
.engine_status
= k_engine_status_crashed
;
872 SDL_AtomicUnlock( &vg
.sl_status
);
874 if( vg_thread_purpose() == k_thread_purpose_loader
){
875 longjmp( vg
.env_loader_exit
, 1 );
878 vg_error( "There is no jump to the error runner thing yet! bai bai\n" );
886 VG_STATIC
void vg_fatal_error( const char *fmt
, ... )
889 va_start( args
, fmt
);
890 _vg_log_write( stderr
, KRED
" fatal" KWHT
"| " KRED
, fmt
, args
);
898 * Graphic cards will check these to force it to use the GPU
900 u32 NvOptimusEnablement
= 0x00000001;
901 int AmdPowerXpressRequestHighPerformance
= 1;
903 #endif /* VG_HEADER_H */