1 /* Copyright (C) 2021-2022 Harry Godden (hgn) - All Rights Reserved */
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( int loaded )
34 |IMP| | '- vg_update_fixed( int loaded )
39 |IMP| | vg_update_post(void)
42 |IMP| | vg_render(void)
57 VG_STATIC
void vg_enter( int argc
, char *argv
[], const char *window_name
);
60 VG_STATIC
void vg_preload(void);
61 VG_STATIC
void vg_load(void);
64 VG_STATIC
void vg_launch_opt(void);
65 VG_STATIC
void vg_start(void);
67 VG_STATIC
void vg_framebuffer_resize(int w
, int h
);
68 VG_STATIC
void vg_update(int loaded
);
69 VG_STATIC
void vg_update_fixed(int loaded
);
70 VG_STATIC
void vg_update_post(int loaded
);
72 VG_STATIC
void vg_render(void);
73 VG_STATIC
void vg_ui(void);
78 #include "vg_platform.h"
86 #include "dep/glad/glad.h"
87 #include "submodules/SDL/include/SDL.h"
88 #include "vg_stdint.h"
90 void vg_register_exit( void( *funcptr
)(void), const char *name
);
97 //#define VG_SYNC_DEBUG
99 #define VG_SYNC_LOG(STR,...) \
100 vg_info(STR,SDL_GetThreadID(NULL),##__VA_ARGS__)
102 #define VG_SYNC_LOG(...)
109 SDL_GLContext gl_context
;
111 SDL_SpinLock sl_context
;
112 SDL_sem
*sem_allow_exec
,
116 SDL_threadID thread_id_main
,
118 thread_id_with_opengl_context
;
119 int context_ownership_refcount
;
125 k_engine_status_none
,
126 k_engine_status_running
,
127 k_engine_status_crashed
130 const char *str_const_engine_err
;
133 /* Window information */
154 int fixed_iterations
;
159 k_engine_stage_update
,
160 k_engine_stage_update_fixed
,
161 k_engine_stage_rendering
,
170 k_quality_profile_high
= 0,
171 k_quality_profile_low
= 1,
175 VG_STATIC vg
= { .time_rate
= 1.0 };
177 struct vg_thread_info
179 enum vg_thread_purpose
181 k_thread_purpose_nothing
,
182 k_thread_purpose_main
,
183 k_thread_purpose_loader
187 int gl_context_level
;
190 VG_STATIC
void vg_fatal_exit_loop( const char *error
);
191 VG_STATIC
void vg_required( void *ptr
, const char *path
)
195 vg_fatal_exit_loop( path
);
199 VG_STATIC
void vg_ensure_engine_running(void)
201 VG_SYNC_LOG( "[%d] Checks if engine is running\n" );
203 /* Check if the engine is no longer running */
204 SDL_AtomicLock( &vg
.sl_context
);
206 if( vg
.engine_status
!= k_engine_status_running
)
208 VG_SYNC_LOG( "[%d] Engine is no longer running\n");
210 /* Safe to disregard loader thread from this point on, elswhere */
211 if( vg
.thread_id_loader
== SDL_GetThreadID(NULL
) )
213 SDL_SemPost( vg
.sem_loader
);
216 SDL_AtomicUnlock( &vg
.sl_context
);
218 VG_SYNC_LOG( "[%d] is just going to hang around and wait to die\n");
219 while(1) SDL_Delay(1000);
222 SDL_AtomicUnlock( &vg
.sl_context
);
226 * Sync execution so that the OpenGL context is switched onto this thread.
227 * Anything after this call will be in a valid context.
229 VG_STATIC
void vg_acquire_thread_sync(void)
231 VG_SYNC_LOG( "[%d] Starts acquiring sync\n" );
233 /* We dont want to do anything if this is the main thread */
234 SDL_AtomicLock( &vg
.sl_context
);
235 if( vg
.thread_id_main
== SDL_GetThreadID(NULL
) )
237 SDL_AtomicUnlock( &vg
.sl_context
);
240 SDL_AtomicUnlock( &vg
.sl_context
);
242 vg_ensure_engine_running();
244 /* Check if thread already has the context */
245 SDL_AtomicLock( &vg
.sl_context
);
246 if( vg
.thread_id_with_opengl_context
== SDL_GetThreadID(NULL
) )
248 vg
.context_ownership_refcount
++;
249 SDL_AtomicUnlock( &vg
.sl_context
);
251 VG_SYNC_LOG( "[%d] We already have sync here\n" );
255 VG_SYNC_LOG( "[%d] Signal to sync.\n" );
257 SDL_AtomicUnlock( &vg
.sl_context
);
259 /* wait until told we can go */
260 VG_SYNC_LOG( "[%d] Waiting to acuire sync.\n" );
262 SDL_SemWait( vg
.sem_allow_exec
);
263 SDL_GL_MakeCurrent( vg
.window
, vg
.gl_context
);
265 VG_SYNC_LOG( "[%d] Allow exec passed\n" );
267 /* context now valid to work in while we hold up main thread */
268 SDL_AtomicLock( &vg
.sl_context
);
269 vg
.context_ownership_refcount
++;
270 SDL_AtomicUnlock( &vg
.sl_context
);
272 VG_SYNC_LOG( "[%d] Context acquired.\n" );
276 * Signify that we are done with the OpenGL context in this thread.
277 * Anything after this call will be in an undefined context.
279 VG_STATIC
void vg_release_thread_sync(void)
281 VG_SYNC_LOG( "[%d] Releases sync\n" );
283 SDL_AtomicLock( &vg
.sl_context
);
284 if( vg
.thread_id_main
== SDL_GetThreadID(NULL
) )
286 SDL_AtomicUnlock( &vg
.sl_context
);
290 /* signal that we are done */
291 vg
.context_ownership_refcount
--;
292 if( !vg
.context_ownership_refcount
)
294 SDL_AtomicUnlock( &vg
.sl_context
);
296 VG_SYNC_LOG( "[%d] Releasing context.\n" );
298 SDL_GL_MakeCurrent( NULL
, NULL
);
299 SDL_SemPost( vg
.sem_exec_finished
);
302 SDL_AtomicUnlock( &vg
.sl_context
);
305 VG_STATIC
void vg_run_synced_content(void)
307 SDL_AtomicLock( &vg
.sl_context
);
309 if( vg
.exec_context
!= 0 )
311 VG_SYNC_LOG( "[%d] Allowing content (%d).\n", vg
.exec_context
);
313 SDL_AtomicUnlock( &vg
.sl_context
);
315 /* allow operations to go */
316 SDL_GL_MakeCurrent( NULL
, NULL
);
317 SDL_SemPost( vg
.sem_allow_exec
);
319 /* wait for operations to complete */
320 VG_SYNC_LOG( "[%d] Waiting for content.\n" );
321 SDL_SemWait( vg
.sem_exec_finished
);
323 /* check if we killed the engine */
324 vg_ensure_engine_running();
326 /* re-engage main thread */
327 VG_SYNC_LOG( "[%d] Re-engaging.\n" );
328 SDL_GL_MakeCurrent( vg
.window
, vg
.gl_context
);
331 SDL_AtomicUnlock( &vg
.sl_context
);
334 VG_STATIC
void vg_opengl_sync_init(void)
336 vg
.sem_allow_exec
= SDL_CreateSemaphore(0);
337 vg
.sem_exec_finished
= SDL_CreateSemaphore(0);
338 vg
.sem_loader
= SDL_CreateSemaphore(1);
341 VG_STATIC
void vg_checkgl( const char *src_info
);
342 #define VG_STRINGIT( X ) #X
343 #define VG_CHECK_GL_ERR() vg_checkgl( __FILE__ ":L" VG_STRINGIT(__LINE__) )
345 #include "vg_console.h"
346 #include "vg_profiler.h"
347 #include "vg_audio.h"
348 #include "vg_shader.h"
350 #include "vg_input.h"
352 #include "vg_lines.h"
353 #include "vg_loader.h"
357 VG_STATIC
struct vg_profile vg_prof_update
= {.name
="update()"},
358 vg_prof_render
= {.name
="render()"};
360 VG_STATIC
void vg_checkgl( const char *src_info
)
365 while( (err
= glGetError()) != GL_NO_ERROR
)
367 vg_error( "(%s) OpenGL Error: #%d\n", src_info
, err
);
372 vg_fatal_exit_loop( "OpenGL Error" );
375 VG_STATIC
void vg_bake_shaders(void)
377 vg_acquire_thread_sync();
380 vg_function_push( (struct vg_cmd
)
383 .function
= vg_shaders_live_recompile
387 vg_shaders_compile();
388 vg_release_thread_sync();
391 VG_STATIC
void vg_load_full(void)
396 vg_loader_highwater( vg_input_init
, vg_input_free
, NULL
);
397 vg_loader_highwater( vg_lines_init
, NULL
, NULL
);
398 vg_loader_highwater( vg_audio_init
, vg_audio_free
, NULL
);
399 vg_loader_highwater( vg_profiler_init
, NULL
, NULL
);
404 vg_acquire_thread_sync();
406 vg_release_thread_sync();
409 VG_STATIC
void vg_process_events(void)
412 vg
.time_real_last
= vg
.time_real
;
413 vg
.time_real
= (double)SDL_GetTicks64() / 1000.0;
414 vg
.frame_delta
= vg
.time_real
-vg
.time_real_last
;
416 v2_zero( vg
.mouse_wheel
);
417 v2_zero( vg
.mouse_delta
);
421 while( SDL_PollEvent( &event
) )
423 if( event
.type
== SDL_KEYDOWN
)
425 console_proc_key( event
.key
.keysym
);
427 else if( event
.type
== SDL_MOUSEWHEEL
)
429 vg
.mouse_wheel
[0] += event
.wheel
.preciseX
;
430 vg
.mouse_wheel
[1] += event
.wheel
.preciseY
;
432 else if( event
.type
== SDL_CONTROLLERAXISMOTION
||
433 event
.type
== SDL_CONTROLLERBUTTONDOWN
||
434 event
.type
== SDL_CONTROLLERBUTTONUP
||
435 event
.type
== SDL_CONTROLLERDEVICEADDED
||
436 event
.type
== SDL_CONTROLLERDEVICEREMOVED
439 vg_input_controller_event( &event
);
441 else if( event
.type
== SDL_MOUSEMOTION
)
443 vg
.mouse_delta
[0] += event
.motion
.xrel
;
444 vg
.mouse_delta
[1] += event
.motion
.yrel
;
446 else if( event
.type
== SDL_WINDOWEVENT
)
448 if( event
.window
.event
== SDL_WINDOWEVENT_SIZE_CHANGED
)
451 SDL_GL_GetDrawableSize( vg
.window
, &w
, &h
);
455 vg_warn( "Got a invalid framebuffer size: "
456 "%dx%d... ignoring\n", w
, h
);
463 vg_framebuffer_resize(w
,h
);
466 else if( event
.window
.event
== SDL_WINDOWEVENT_CLOSE
)
468 vg
.window_should_close
= 1;
471 else if( event
.type
== SDL_TEXTINPUT
)
473 console_proc_utf8( event
.text
.text
);
477 vg
.mouse_pos
[0] += vg
.mouse_delta
[0];
478 vg
.mouse_pos
[1] += vg
.mouse_delta
[1];
484 VG_STATIC
void vg_gameloop_update( int post_start
)
486 vg_profile_begin( &vg_prof_update
);
488 vg
.engine_stage
= k_engine_stage_update
;
489 vg_update( post_start
);
491 /* Fixed update loop */
492 vg
.engine_stage
= k_engine_stage_update_fixed
;
493 vg
.accumulator
+= vg
.time_delta
;
495 vg
.fixed_iterations
= 0;
496 vg_lines
.allow_input
= 1;
497 while( vg
.accumulator
>= (VG_TIMESTEP_FIXED
-0.00125) )
499 vg_update_fixed( post_start
);
500 vg_lines
.allow_input
= 0;
502 vg
.accumulator
-= VG_TIMESTEP_FIXED
;
503 vg
.accumulator
= VG_MAX( 0.0, vg
.accumulator
);
505 vg
.fixed_iterations
++;
506 if( vg
.fixed_iterations
== 8 )
511 vg_lines
.allow_input
= 1;
513 vg
.engine_stage
= k_engine_stage_update
;
514 vg_update_post( post_start
);
515 vg_profile_end( &vg_prof_update
);
518 VG_STATIC
void vg_gameloop_render( int post_start
)
520 vg_profile_begin( &vg_prof_render
);
525 vg
.engine_stage
= k_engine_stage_rendering
;
529 vg
.engine_stage
= k_engine_stage_ui
;
531 ui_begin( vg
.window_x
, vg
.window_y
);
534 ui_set_mouse( vg
.mouse_pos
[0], vg
.mouse_pos
[1], 0 );
537 (struct vg_profile
*[]){&vg_prof_update
,&vg_prof_render
}, 2,
538 (1.0f
/(float)vg
.refresh_rate
)*1000.0f
,
539 (ui_rect
){ 4, 4, 250, 0 }, 0
549 "refresh: %.1f (%.1fms)\n"
551 "iterations: %d (acc: %.3fms%%)\n",
552 vg
.window_x
, vg
.window_y
,
553 vg
.refresh_rate
, (1.0f
/vg
.refresh_rate
)*1000.0f
,
556 (vg
.accumulator
/VG_TIMESTEP_FIXED
)*100.0f
);
558 ui_text( (ui_rect
){258, 4+24+12,0,0},perf
, 1,0);
561 audio_debug_ui( vg
.pv
);
570 vg_profile_end( &vg_prof_render
);
573 VG_STATIC
void vg_gameloop(void)
575 vg
.accumulator
= 0.75f
* (1.0f
/60.0f
);
582 if( vg
.window_should_close
)
586 vg
.time_delta
= vg
.frame_delta
* vg
.time_rate
;
587 vg
.time
+= vg
.time_delta
;
602 vg_gameloop_update( post_start
);
603 vg_gameloop_render( post_start
);
605 SDL_GL_SwapWindow( vg
.window
);
606 vg_run_synced_content();
610 VG_STATIC
void vg_process_launch_opts_internal(void)
613 while( vg_argp( argc
, argv
) )
615 if( (arg
= vg_opt_arg( 'w' )) )
617 vg
.window_x
= atoi( arg
);
620 if( (arg
= vg_opt_arg( 'h' )) )
622 vg
.window_y
= atoi( arg
);
625 if( (arg
= vg_long_opt_arg( "samples" )) )
627 vg
.samples
= VG_MAX( 0, VG_MIN( 8, atoi( arg
) ) );
630 if( vg_long_opt( "use-libc-malloc" ) )
632 vg_mem
.use_libc_malloc
= atoi( arg
);
635 if( vg_long_opt( "high-performance" ) )
637 vg
.quality_profile
= k_quality_profile_low
;
644 VG_STATIC
void vg_init_window(void)
646 if( SDL_Init(SDL_INIT_VIDEO
|SDL_INIT_AUDIO
|SDL_INIT_GAMECONTROLLER
) != 0 )
648 vg_error( "SDL_Init failed: %s\n", SDL_GetError() );
652 SDL_GL_SetSwapInterval( 1 );
653 SDL_GL_SetAttribute( SDL_GL_DOUBLEBUFFER
, 1 );
654 SDL_GL_SetAttribute( SDL_GL_CONTEXT_MAJOR_VERSION
, 3 );
655 SDL_GL_SetAttribute( SDL_GL_CONTEXT_MINOR_VERSION
, 3 );
656 SDL_GL_SetAttribute( SDL_GL_CONTEXT_PROFILE_MASK
,
657 SDL_GL_CONTEXT_PROFILE_CORE
);
659 SDL_GL_SetAttribute( SDL_GL_STENCIL_SIZE
, 1 );
660 SDL_GL_SetAttribute( SDL_GL_RED_SIZE
, 8 );
661 SDL_GL_SetAttribute( SDL_GL_GREEN_SIZE
, 8 );
662 SDL_GL_SetAttribute( SDL_GL_BLUE_SIZE
, 8 );
663 SDL_GL_SetAttribute( SDL_GL_ALPHA_SIZE
, 8 );
667 SDL_GL_SetAttribute( SDL_GL_MULTISAMPLEBUFFERS
, 1 );
668 SDL_GL_SetAttribute( SDL_GL_MULTISAMPLESAMPLES
, vg
.samples
);
671 SDL_GL_SetAttribute( SDL_GL_CONTEXT_RELEASE_BEHAVIOR
,
672 SDL_GL_CONTEXT_RELEASE_BEHAVIOR_FLUSH
);
675 * Get monitor information
677 int display_count
= 0, display_index
= 0, mode_index
= 0;
678 if( (display_count
= SDL_GetNumVideoDisplays()) < 1 )
680 vg_error( "SDL_GetNumVideoDisplays returned: %i\n", display_count
);
684 /* TODO: Allow chosing the modes at startup */
685 SDL_DisplayMode mode
= { SDL_PIXELFORMAT_UNKNOWN
, 0, 0, 0, 0 };
686 if( SDL_GetDisplayMode( display_index
, mode_index
, &mode
) != 0 )
688 vg_error( "SDL_GetDisplayMode failed: %s", SDL_GetError() );
692 vg
.refresh_rate
= mode
.refresh_rate
;
694 /* TODO: Allow selecting closest video mode from launch opts */
695 if((vg
.window
= SDL_CreateWindow( window_name
,
696 SDL_WINDOWPOS_UNDEFINED
,
697 SDL_WINDOWPOS_UNDEFINED
,
700 SDL_WINDOW_FULLSCREEN
|
702 SDL_WINDOW_INPUT_GRABBED
)))
707 vg_error( "SDL_CreateWindow failed: %s", SDL_GetError() );
714 if( (vg
.gl_context
= SDL_GL_CreateContext(vg
.window
) ))
716 SDL_GL_GetDrawableSize( vg
.window
, &vg
.window_x
, &vg
.window_y
);
717 vg_success( "Window created (%dx%d)\n", vg
.window_x
, vg
.window_y
);
721 vg_error( "SDL_GL_CreateContext failed: %s\n", SDL_GetError() );
726 if( !gladLoadGLLoader((GLADloadproc
)SDL_GL_GetProcAddress
) )
728 vg_error( "Glad Failed to initialize\n" );
729 SDL_GL_DeleteContext( vg
.gl_context
);
734 const unsigned char* glver
= glGetString( GL_VERSION
);
735 vg_success( "Load setup complete, OpenGL version: %s\n", glver
);
738 VG_STATIC
void vg_enter( int argc
, char *argv
[], const char *window_name
)
740 vg_process_launch_opts_internal();
748 SDL_SetRelativeMouseMode(1);
749 vg
.thread_id_main
= SDL_GetThreadID(NULL
);
751 /* Opengl-required systems */
755 vg
.engine_status
= k_engine_status_running
;
757 vg_opengl_sync_init();
764 vg_console_write_persistent();
766 SDL_AtomicLock( &vg
.sl_context
);
767 vg
.engine_status
= k_engine_status_none
;
768 SDL_AtomicUnlock( &vg
.sl_context
);
772 vg_success( "If you see this it means everything went.. \"well\".....\n" );
774 SDL_GL_DeleteContext( vg
.gl_context
);
779 * Immediately transfer away from calling thread into a safe loop, signal for
780 * others to shutdown, then free everything once the user closes the window.
782 * FIXME(bug): glfwWindowShouldClose() never returns 1 in windows via wine, ONLY
783 * when calling the program from outside its normal directory.
785 VG_STATIC
void vg_fatal_exit_loop( const char *error
)
788 * https://www.gnu.org/software/libc/manual/html_node/Backtraces.html
791 * TODO: this on windows?
800 size
= backtrace( array
, 20 );
801 strings
= backtrace_symbols( array
, size
);
803 if( strings
!= NULL
)
805 vg_error( "---------------- gnu backtrace -------------\n" );
807 for( int i
=0; i
<size
; i
++ )
808 vg_info( "%s\n", strings
[i
] );
810 vg_error( "---------------- gnu backtrace -------------\n" );
817 vg_error( "Fatal error: %s\n", error
);
819 SDL_AtomicLock( &vg
.sl_context
);
820 if( vg
.engine_status
== k_engine_status_none
)
822 SDL_AtomicUnlock( &vg
.sl_context
);
824 /* TODO: Correct shutdown before other systems */
829 SDL_AtomicUnlock( &vg
.sl_context
);
834 * wait until loader checks in, it will die
841 * wait for main to get to us, it will never be used again
843 * undefined behaviour:
844 * fatal_exit_loop is called in both threads, preventing an appropriate
845 * reaction to the crash. This *should* be made
846 * obvious by the assertion
848 vg_acquire_thread_sync();
850 SDL_AtomicUnlock( &vg
.sl_context
);
851 vg
.engine_status
= k_engine_status_crashed
;
852 vg
.str_const_engine_err
= error
;
855 * Wait for loader to finish what it was doing, if it was running.
856 * Then we can continue in our nice error screen
858 if( vg
.thread_id_main
== SDL_GetThreadID(NULL
) )
860 SDL_AtomicUnlock( &vg
.sl_context
);
861 SDL_SemWait( vg
.sem_loader
);
864 SDL_AtomicUnlock( &vg
.sl_context
);
871 if( vg
.window_should_close
)
874 if( vg_getkey( SDLK_ESCAPE
) )
877 glBindFramebuffer( GL_FRAMEBUFFER
, 0 );
879 glDisable(GL_DEPTH_TEST
);
880 glBlendFunc(GL_ONE_MINUS_DST_ALPHA
, GL_DST_ALPHA
);
881 glBlendEquation(GL_FUNC_ADD
);
883 glClearColor( 0.15f
+ sinf(vg
.time_real
)*0.1f
, 0.0f
, 0.0f
,1.0f
);
884 glClear( GL_COLOR_BUFFER_BIT
|GL_DEPTH_BUFFER_BIT
);
885 glViewport( 0,0, vg
.window_x
, vg
.window_y
);
888 SDL_GL_SwapWindow( vg
.window
);
891 /* Can now shutdown and EXIT */
893 SDL_GL_DeleteContext( vg
.gl_context
);
901 VG_STATIC
void vg_fatal_exit_loop( const char *error
)
903 vg_error( "Fatal error: %s\n", error
);
910 * Graphic cards will check these to force it to use the GPU
912 u32 NvOptimusEnablement
= 0x00000001;
913 int AmdPowerXpressRequestHighPerformance
= 1;
915 #endif /* VG_HEADER_H */