X-Git-Url: https://harrygodden.com/git/?p=vg.git;a=blobdiff_plain;f=vg.h;h=eb858a38b33017d7fc20b5e457c91802d8c41b00;hp=b7475ad1afc2577d99e16504c6be82da8a0dcc4e;hb=HEAD;hpb=0aea2ef68a5ed32fc940673402a1b4b67f38d4d3 diff --git a/vg.h b/vg.h index b7475ad..2d06aab 100644 --- a/vg.h +++ b/vg.h @@ -1,948 +1,86 @@ -/* Copyright (C) 2021-2022 Harry Godden (hgn) - All Rights Reserved */ - -/* - - .-. VG Event loop -| 0 | -| | .---------------------------------------------------------. -|API| | vg_enter( int argc, char *argv[], const char *window_name | -| | '---------------------------------------------------------' -| | | -| | v -|IMP| vg_launch_opt(void) <--. -| | | | -| | |'---------------' -| | | .-. -| | |'-----------------------------------| 1 |------. -| | | | | | -| | | | | v -| | | |IMP| vg_preload(void) -| | | | | | -| | .-----+. | | v -| | | | |IMP| vg_load(void) -| | | v '___' | -|IMP| | vg_framebuffer_resize(void) | -| | | | | -|IMP| | |.------------- vg_start(void) ---------------' -| | | | -| | | v -|IMP| | vg_update(void) -| | | | -| | | .-----+. -| | | | | -| | | | v -|IMP| | '- vg_update_fixed(void) -| | | | -| | | .-' -| | | | -| | | v -|IMP| | vg_update_post(void) -| | | | -| | | v -|IMP| | vg_render(void) -| | | | -| | | v -|IMP| | vg_ui(void) -| | | | -| | '----' -'___' - - .-. -| ? | -| | .-------------------------------------. -|API| | vg_fatal_exit_loop( const char *err ) | -| | '-------------------------------------' -| | | -| | .------+. -| | | | -| | | v -|IMP| '- vg_framebuffer_resize(void) -'___' - -*/ - -#ifndef VG_STATIC - #define VG_STATIC -#endif - -/* API */ -VG_STATIC void vg_enter( int argc, char *argv[], const char *window_name ); - -/* Thread 1 */ -VG_STATIC void vg_preload(void); -VG_STATIC void vg_load(void); - -/* Main thread */ -VG_STATIC void vg_launch_opt(void); -VG_STATIC void vg_start(void); - -VG_STATIC void vg_framebuffer_resize(int w, int h); -VG_STATIC void vg_update(void); -VG_STATIC void vg_update_fixed(void); -VG_STATIC void vg_update_post(void); - -VG_STATIC void vg_render(void); -VG_STATIC void vg_ui(void); - -#ifndef VG_HEADER_H - #define VG_HEADER_H - - #include "vg_platform.h" - #include "vg_mem.h" - - #ifndef _WIN32 - #include - #endif - - #ifdef VG_GAME - #include "dep/glad/glad.h" - #include "submodules/SDL/include/SDL.h" - #include "vg_stdint.h" - - void vg_register_exit( void( *funcptr )(void), const char *name ); - - #include "vg_m.h" - #include "vg_io.h" - #include "vg_log.h" - #include "vg_steam.h" - - //#define VG_SYNC_DEBUG - #ifdef VG_SYNC_DEBUG - #define VG_SYNC_LOG(STR,...) \ - vg_info(STR,SDL_GetThreadID(NULL),##__VA_ARGS__) - #else - #define VG_SYNC_LOG(...) - #endif - -struct vg -{ - /* Engine sync */ - SDL_Window *window; - SDL_GLContext gl_context; - - SDL_SpinLock sl_context; - SDL_sem *sem_allow_exec, - *sem_exec_finished, - *sem_loader; - - SDL_threadID thread_id_main, - thread_id_loader, - thread_id_with_opengl_context; - int context_ownership_depth; - - int exec_context; - - enum engine_status - { - k_engine_status_none, - k_engine_status_running, - k_engine_status_crashed - } - engine_status; - const char *str_const_engine_err; - int is_loaded; - - /* Window information */ - int window_x, - window_y, - samples, - window_should_close; - - float refresh_rate; - - double mouse_pos[2]; - v2f mouse_delta, - mouse_wheel; - - /* Runtime */ - double time, - time_delta, - frame_delta, - time_real, - time_real_last, - time_rate, - accumulator; - - int fixed_iterations; - - enum engine_stage - { - k_engine_stage_none, - k_engine_stage_update, - k_engine_stage_update_fixed, - k_engine_stage_rendering, - k_engine_stage_ui - } - engine_stage; - - /* graphics */ -#if 0 - m4x4f pv; -#endif - enum quality_profile - { - k_quality_profile_high = 0, - k_quality_profile_low = 1, - } - quality_profile; -} -VG_STATIC vg = { .time_rate = 1.0 }; - -enum vg_thread_purpose -{ - k_thread_purpose_nothing, - k_thread_purpose_main, - k_thread_purpose_loader -}; - -VG_STATIC void vg_fatal_exit_loop( const char *error ); - -/* - * Checks if the engine is running - */ -VG_STATIC void _vg_ensure_engine_running(void) -{ - /* Check if the engine is no longer running */ - SDL_AtomicLock( &vg.sl_context ); - enum engine_status status = vg.engine_status; - SDL_AtomicUnlock( &vg.sl_context ); - - if( status != k_engine_status_running ) - { - while(1) - { - VG_SYNC_LOG( "[%d] No longer running...\n"); - SDL_Delay(1000); - } - } -} - -VG_STATIC enum vg_thread_purpose vg_thread_purpose(void) -{ - SDL_AtomicLock( &vg.sl_context ); - - if( vg.thread_id_main == SDL_GetThreadID(NULL) ) - { - SDL_AtomicUnlock( &vg.sl_context ); - return k_thread_purpose_main; - } - else - { - SDL_AtomicUnlock( &vg.sl_context ); - return k_thread_purpose_loader; - } -} - -/* - * Sync execution so that the OpenGL context is switched onto this thread. - * Anything after this call will be in a valid context. - */ -VG_STATIC void vg_acquire_thread_sync(void) -{ - /* We dont want to do anything if this is the main thread */ - - if( vg_thread_purpose() == k_thread_purpose_loader ) - { - VG_SYNC_LOG( "[%d] vg_acquire_thread_sync()\n" ); - _vg_ensure_engine_running(); - - SDL_AtomicLock( &vg.sl_context ); - if( vg.context_ownership_depth == 0 ) - { - vg.context_ownership_depth ++; - vg.exec_context = 1; - SDL_AtomicUnlock( &vg.sl_context ); - - /* wait until told we can go */ - VG_SYNC_LOG( "[%d] Waiting to acuire sync.\n" ); - SDL_SemWait( vg.sem_allow_exec ); - - _vg_ensure_engine_running(); - - SDL_GL_MakeCurrent( vg.window, vg.gl_context ); - VG_SYNC_LOG( "[%d] granted\n" ); - } - else - { - vg.context_ownership_depth ++; - VG_SYNC_LOG( "[%d] granted\n" ); - SDL_AtomicUnlock( &vg.sl_context ); - } - } -} - -/* - * Signify that we are done with the OpenGL context in this thread. - * Anything after this call will be in an undefined context. - */ -VG_STATIC void vg_release_thread_sync(void) -{ - if( vg_thread_purpose() == k_thread_purpose_loader ) - { - VG_SYNC_LOG( "[%d] vg_release_thread_sync()\n" ); - - SDL_AtomicLock( &vg.sl_context ); - vg.context_ownership_depth --; - - if( vg.context_ownership_depth == 0 ) - { - SDL_AtomicUnlock( &vg.sl_context ); - VG_SYNC_LOG( "[%d] Releasing context.\n" ); - SDL_GL_MakeCurrent( NULL, NULL ); - SDL_SemPost( vg.sem_exec_finished ); - } - else - SDL_AtomicUnlock( &vg.sl_context ); - } -} - -VG_STATIC void _vg_run_synced(void) -{ - SDL_AtomicLock( &vg.sl_context ); - - if( vg.exec_context != 0 ) - { - VG_SYNC_LOG( "[%d] _vg_run_synced() (%d).\n", vg.exec_context ); - vg.exec_context = 0; - SDL_AtomicUnlock( &vg.sl_context ); - - /* allow operations to go */ - SDL_GL_MakeCurrent( NULL, NULL ); - SDL_SemPost( vg.sem_allow_exec ); - - /* wait for operations to complete */ - VG_SYNC_LOG( "[%d] Waiting for content.\n" ); - SDL_SemWait( vg.sem_exec_finished ); - - /* check if we killed the engine */ - _vg_ensure_engine_running(); - - /* re-engage main thread */ - VG_SYNC_LOG( "[%d] Re-engaging.\n" ); - SDL_GL_MakeCurrent( vg.window, vg.gl_context ); - } - else - { - VG_SYNC_LOG( "[%d] Nothing to do.\n" ); - SDL_AtomicUnlock( &vg.sl_context ); - } -} - -VG_STATIC void _vg_opengl_sync_init(void) -{ - vg.sem_allow_exec = SDL_CreateSemaphore(0); - vg.sem_exec_finished = SDL_CreateSemaphore(0); - vg.sem_loader = SDL_CreateSemaphore(1); -} - -VG_STATIC void vg_checkgl( const char *src_info ); -#define VG_STRINGIT( X ) #X -#define VG_CHECK_GL_ERR() vg_checkgl( __FILE__ ":L" VG_STRINGIT(__LINE__) ) - -#include "vg_console.h" -#include "vg_profiler.h" -#include "vg_audio.h" -#include "vg_shader.h" -#include "vg_tex.h" -#include "vg_input.h" -#include "vg_ui.h" -#include "vg_lines.h" -#include "vg_loader.h" -#include "vg_opt.h" - -/* Diagnostic */ -VG_STATIC struct vg_profile vg_prof_update = {.name="update()"}, - vg_prof_render = {.name="render()"}; - -VG_STATIC void vg_checkgl( const char *src_info ) -{ - int fail = 0; - - GLenum err; - while( (err = glGetError()) != GL_NO_ERROR ) - { - vg_error( "(%s) OpenGL Error: #%d\n", src_info, err ); - fail = 1; - } - - if( fail ) - vg_fatal_exit_loop( "OpenGL Error" ); -} - -VG_STATIC void vg_bake_shaders(void) -{ - vg_acquire_thread_sync(); - - vg_function_push( (struct vg_cmd) - { - .name = "reload_shaders", - .function = vg_shaders_live_recompile - }); - - vg_shaders_compile(); - vg_release_thread_sync(); -} - -VG_STATIC void _vg_load_full(void) -{ - vg_preload(); - - /* internal */ - vg_loader_step( vg_input_init, vg_input_free ); - vg_loader_step( vg_lines_init, NULL ); - vg_loader_step( vg_audio_init, vg_audio_free ); - vg_loader_step( vg_profiler_init, NULL ); - - /* client */ - vg_load(); -} - -VG_STATIC void _vg_process_events(void) -{ - /* Update timers */ - vg.time_real_last = vg.time_real; - vg.time_real = (double)SDL_GetTicks64() / 1000.0; - vg.frame_delta = vg.time_real-vg.time_real_last; - - v2_zero( vg.mouse_wheel ); - v2_zero( vg.mouse_delta ); - - /* SDL event loop */ - SDL_Event event; - while( SDL_PollEvent( &event ) ) - { - if( event.type == SDL_KEYDOWN ) - { - console_proc_key( event.key.keysym ); - } - else if( event.type == SDL_MOUSEWHEEL ) - { - vg.mouse_wheel[0] += event.wheel.preciseX; - vg.mouse_wheel[1] += event.wheel.preciseY; - } - else if( event.type == SDL_CONTROLLERAXISMOTION || - event.type == SDL_CONTROLLERBUTTONDOWN || - event.type == SDL_CONTROLLERBUTTONUP || - event.type == SDL_CONTROLLERDEVICEADDED || - event.type == SDL_CONTROLLERDEVICEREMOVED - ) - { - vg_input_controller_event( &event ); - } - else if( event.type == SDL_MOUSEMOTION ) - { - vg.mouse_delta[0] += event.motion.xrel; - vg.mouse_delta[1] += event.motion.yrel; - } - else if( event.type == SDL_WINDOWEVENT ) - { - if( event.window.event == SDL_WINDOWEVENT_SIZE_CHANGED ) - { - int w, h; - SDL_GL_GetDrawableSize( vg.window, &w, &h ); - - if( !w || !h ) - { - vg_warn( "Got a invalid framebuffer size: " - "%dx%d... ignoring\n", w, h ); - } - else - { - vg.window_x = w; - vg.window_y = h; - - vg_framebuffer_resize(w,h); - } - } - else if( event.window.event == SDL_WINDOWEVENT_CLOSE ) - { - vg.window_should_close = 1; - } - } - else if( event.type == SDL_TEXTINPUT ) - { - console_proc_utf8( event.text.text ); - } - } - - vg.mouse_pos[0] += vg.mouse_delta[0]; - vg.mouse_pos[1] += vg.mouse_delta[1]; - - /* Update input */ - vg_update_inputs(); -} - -VG_STATIC void _vg_gameloop_update(void) -{ - vg_profile_begin( &vg_prof_update ); - - vg.engine_stage = k_engine_stage_update; - vg_update(); - - /* Fixed update loop */ - vg.engine_stage = k_engine_stage_update_fixed; - vg.accumulator += vg.time_delta; - - vg.fixed_iterations = 0; - vg_lines.allow_input = 1; - while( vg.accumulator >= (VG_TIMESTEP_FIXED-0.00125) ) - { - vg_update_fixed(); - vg_lines.allow_input = 0; - - vg.accumulator -= VG_TIMESTEP_FIXED; - vg.accumulator = VG_MAX( 0.0, vg.accumulator ); - - vg.fixed_iterations ++; - if( vg.fixed_iterations == 8 ) - { - break; - } - } - vg_lines.allow_input = 1; - - vg.engine_stage = k_engine_stage_update; - vg_update_post(); - vg_profile_end( &vg_prof_update ); -} - -VG_STATIC void _vg_gameloop_render(void) -{ - vg_profile_begin( &vg_prof_render ); - - if( vg.is_loaded ) - { - /* render */ - vg.engine_stage = k_engine_stage_rendering; - vg_render(); - - /* ui */ - vg.engine_stage = k_engine_stage_ui; - { - ui_begin( vg.window_x, vg.window_y ); - - /* TODO */ - ui_set_mouse( vg.mouse_pos[0], vg.mouse_pos[1], 0 ); - - vg_profile_drawn( - (struct vg_profile *[]){&vg_prof_update,&vg_prof_render}, 2, - (1.0f/(float)vg.refresh_rate)*1000.0f, - (ui_rect){ 4, 4, 250, 0 }, 0 - ); - - if( vg_profiler ) - { - - char perf[128]; - - snprintf( perf, 127, - "x: %d y: %d\n" - "refresh: %.1f (%.1fms)\n" - "samples: %d\n" - "iterations: %d (acc: %.3fms%%)\n", - vg.window_x, vg.window_y, - vg.refresh_rate, (1.0f/vg.refresh_rate)*1000.0f, - vg.samples, - vg.fixed_iterations, - (vg.accumulator/VG_TIMESTEP_FIXED)*100.0f ); - - ui_text( (ui_rect){258, 4+24+12,0,0},perf, 1,0); - } - - /* FIXME */ -#if 0 - audio_debug_ui( vg.pv ); -#endif - vg_ui(); - _vg_console_draw(); - - ui_resolve(); - ui_draw( NULL ); - } - } - - vg_profile_end( &vg_prof_render ); -} - -VG_STATIC void _vg_gameloop(void) -{ - vg.accumulator = 0.75f * (1.0f/60.0f); - - int post_start = 0; - while(1) - { - _vg_process_events(); - - if( vg.window_should_close ) - break; - - /* scaled time */ - vg.time_delta = vg.frame_delta * vg.time_rate; - vg.time += vg.time_delta; - - if( vg.is_loaded ) - { - if( !post_start ) - { - vg_start(); - post_start = 1; - } - } - else - { - _vg_loader_render(); - } - - _vg_gameloop_update(); - _vg_gameloop_render(); - audio_push_console_vol(); - - SDL_GL_SwapWindow( vg.window ); - _vg_run_synced(); - } -} - -VG_STATIC void _vg_process_launch_opts_internal( int argc, char *argv[] ) -{ - char *arg; - while( vg_argp( argc, argv ) ) - { - if( (arg = vg_opt_arg( 'w' )) ) - { - vg.window_x = atoi( arg ); - } - - if( (arg = vg_opt_arg( 'h' )) ) - { - vg.window_y = atoi( arg ); - } - - if( (arg = vg_long_opt_arg( "samples" )) ) - { - vg.samples = VG_MAX( 0, VG_MIN( 8, atoi( arg ) ) ); - } - - if( vg_long_opt( "use-libc-malloc" ) ) - { - vg_mem.use_libc_malloc = 1; - } - - if( vg_long_opt( "high-performance" ) ) - { - vg.quality_profile = k_quality_profile_low; - } - - vg_launch_opt(); - } -} - -VG_STATIC void _vg_init_window( const char *window_name ) -{ - vg_info( "SDL_INIT\n" ); - - if( SDL_Init( SDL_INIT_VIDEO ) != 0 ) - { - vg_error( "SDL_Init failed: %s\n", SDL_GetError() ); - exit(0); - } - - SDL_InitSubSystem( SDL_INIT_AUDIO ); - SDL_InitSubSystem( SDL_INIT_GAMECONTROLLER ); - - SDL_GL_SetAttribute( SDL_GL_DOUBLEBUFFER, 1 ); - SDL_GL_SetAttribute( SDL_GL_CONTEXT_MAJOR_VERSION, 3 ); - SDL_GL_SetAttribute( SDL_GL_CONTEXT_MINOR_VERSION, 3 ); - SDL_GL_SetAttribute( SDL_GL_CONTEXT_PROFILE_MASK, - SDL_GL_CONTEXT_PROFILE_CORE ); - - SDL_GL_SetAttribute( SDL_GL_CONTEXT_RELEASE_BEHAVIOR, - SDL_GL_CONTEXT_RELEASE_BEHAVIOR_FLUSH ); - - SDL_GL_SetAttribute( SDL_GL_RED_SIZE, 8 ); - SDL_GL_SetAttribute( SDL_GL_GREEN_SIZE, 8 ); - SDL_GL_SetAttribute( SDL_GL_BLUE_SIZE, 8 ); - SDL_GL_SetAttribute( SDL_GL_ALPHA_SIZE, 8 ); - SDL_GL_SetAttribute( SDL_GL_STENCIL_SIZE, 0 ); - - /* - * Get monitor information - */ - vg_info( "Getting display count\n" ); - int display_count = 0, display_index = 0, mode_index = 0; - if( (display_count = SDL_GetNumVideoDisplays()) < 1 ) - { - vg_error( "SDL_GetNumVideoDisplays returned: %i\n", display_count ); - exit(0); - } - - - - - /* TODO: Allow chosing the modes at startup */ - vg_info( "Getting default display mode\n" ); - SDL_DisplayMode vm_ideal = { 0, 0, 0, 0, 0 }; - if( SDL_GetDisplayMode( display_index, mode_index, &vm_ideal ) != 0 ) - { - vg_error( "SDL_GetDisplayMode failed: %s", SDL_GetError() ); - exit(0); - } - - if( vg.window_x ) - vm_ideal.w = vg.window_x; - - if( vg.window_y ) - vm_ideal.h = vg.window_y; - - - SDL_DisplayMode vm_best; - if( !SDL_GetClosestDisplayMode( display_index, &vm_ideal, &vm_best ) ) - { - vg_error( "SDL_GetClosestDisplayMode failed: %s", SDL_GetError() ); - exit(0); - } - - vg.refresh_rate = vm_best.refresh_rate; - vg.window_x = vm_best.w; - vg.window_y = vm_best.h; - - vg_info( "CreateWindow( %d %d @%.2fhz )\n", vg.window_x, vg.window_y, - vg.refresh_rate ); - - /* TODO: Allow selecting closest video mode from launch opts */ - if((vg.window = SDL_CreateWindow( window_name, - SDL_WINDOWPOS_UNDEFINED, - SDL_WINDOWPOS_UNDEFINED, - vg.window_x, vg.window_y, - - SDL_WINDOW_FULLSCREEN_DESKTOP | - SDL_WINDOW_OPENGL | - SDL_WINDOW_INPUT_GRABBED ))) - { - if( SDL_SetWindowDisplayMode( vg.window, &vm_best ) ) - { - vg_error( "SDL_SetWindowDisplayMode failed: %s", SDL_GetError() ); - SDL_Quit(); - exit(0); - } - } - else - { - vg_error( "SDL_CreateWindow failed: %s", SDL_GetError() ); - exit(0); - } - - vg_info( "CreateContext\n" ); - - /* - * OpenGL loading - */ - if( (vg.gl_context = SDL_GL_CreateContext(vg.window) )) - { - SDL_GL_GetDrawableSize( vg.window, &vg.window_x, &vg.window_y ); - vg_success( "Window created (%dx%d)\n", vg.window_x, vg.window_y ); - } - else - { - vg_error( "SDL_GL_CreateContext failed: %s\n", SDL_GetError() ); - SDL_Quit(); - exit(0); - } - - if( !gladLoadGLLoader((GLADloadproc)SDL_GL_GetProcAddress) ) - { - vg_error( "Glad Failed to initialize\n" ); - SDL_GL_DeleteContext( vg.gl_context ); - SDL_Quit(); - exit(0); - } - - const unsigned char* glver = glGetString( GL_VERSION ); - vg_success( "Load setup complete, OpenGL version: %s\n", glver ); - - vg_info( "Setting swap interval\n" ); - - if( SDL_GL_SetSwapInterval( -1 ) == -1 ) - { - vg_warn( "Adaptive Vsync not supported\n" ); - - if( SDL_GL_SetSwapInterval( 1 ) == -1 ) - { - vg_fatal_exit_loop( "Cannot enable Vsync! You might be overriding it" - " in your graphics control panel.\n" ); - } - else - vg_success( "Using vsync\n" ); - } - else - vg_success( "Using adaptive Vsync\n" ); - - SDL_DisplayMode dispmode; - if( !SDL_GetWindowDisplayMode( vg.window, &dispmode ) ) - { - if( dispmode.refresh_rate ) - { - vg.refresh_rate = dispmode.refresh_rate; - vg_info( "Refresh rate: %d\n", dispmode.refresh_rate ); - } - } -} - -VG_STATIC void vg_enter( int argc, char *argv[], const char *window_name ) -{ - _vg_process_launch_opts_internal( argc, argv ); - - /* Systems init */ - vg_alloc_quota(); - _vg_log_init(); - _vg_console_init(); - _vg_init_window( window_name ); - - SDL_SetRelativeMouseMode(1); - vg.thread_id_main = SDL_GetThreadID(NULL); - - /* Opengl-required systems */ - _vg_ui_init(); - _vg_loader_init(); - - vg.engine_status = k_engine_status_running; - - _vg_opengl_sync_init(); - vg_loader_start( _vg_load_full ); - _vg_gameloop(); - - /* Shutdown */ - _vg_console_write_persistent(); - - SDL_AtomicLock( &vg.sl_context ); - vg.engine_status = k_engine_status_none; - SDL_AtomicUnlock( &vg.sl_context ); - - _vg_loader_free(); - - vg_success( "If you see this it means everything went.. \"well\".....\n" ); - - SDL_GL_DeleteContext( vg.gl_context ); - SDL_Quit(); -} - -/* - * Immediately transfer away from calling thread into a safe loop, signal for - * others to shutdown, then free everything once the user closes the window. - * - * FIXME(bug): glfwWindowShouldClose() never returns 1 in windows via wine, ONLY - * when calling the program from outside its normal directory. - */ -VG_STATIC void vg_fatal_exit_loop( const char *error ) -{ - /* - * https://www.gnu.org/software/libc/manual/html_node/Backtraces.html - * thanks gnu <3 - * - * TODO: this on windows? - */ - -#ifndef _WIN32 - - void *array[20]; - char **strings; - int size, i; - - size = backtrace( array, 20 ); - strings = backtrace_symbols( array, size ); - - if( strings != NULL ) - { - vg_error( "---------------- gnu backtrace -------------\n" ); - - for( int i=0; i