268594f915f7df4b6b51b038a61ac5ae8e8435ce
[vg.git] / vg_engine.c
1 #include "vg_engine.h"
2 #include "vg_async.h"
3
4 struct vg_engine vg = {
5 .time_rate = 1.0,
6 .time_fixed_delta = VG_TIMESTEP_FIXED
7 };
8
9 #include <string.h>
10
11 enum engine_status _vg_engine_status(void)
12 {
13 SDL_AtomicLock( &vg.sl_status );
14 enum engine_status status = vg.engine_status;
15 SDL_AtomicUnlock( &vg.sl_status );
16
17 return status;
18 }
19
20 enum vg_thread_purpose vg_thread_purpose(void)
21 {
22 SDL_AtomicLock( &vg.sl_status );
23
24 if( vg.thread_id_main == SDL_GetThreadID(NULL) ){
25 SDL_AtomicUnlock( &vg.sl_status );
26 return k_thread_purpose_main;
27 }
28 else{
29 SDL_AtomicUnlock( &vg.sl_status );
30 return k_thread_purpose_loader;
31 }
32 }
33
34 static void vg_assert_thread( enum vg_thread_purpose required )
35 {
36 enum vg_thread_purpose purpose = vg_thread_purpose();
37
38 if( purpose != required ){
39 vg_fatal_error( "thread_purpose must be %u not %u\n", required, purpose );
40 }
41 }
42
43 static void _vg_opengl_sync_init(void)
44 {
45 vg.sem_loader = SDL_CreateSemaphore(1);
46 }
47
48 #include "vg_console.h"
49 #include "vg_profiler.h"
50 #ifndef VG_NO_AUDIO
51 #include "vg_audio.h"
52 #endif
53 #include "vg_shader.h"
54 #include "vg_tex.h"
55 #include "vg_input.h"
56 #include "vg_imgui.h"
57 #include "vg_lines.h"
58 #include "vg_rigidbody_view.h"
59 #include "vg_loader.h"
60 #include "vg_opt.h"
61
62 /* Diagnostic */
63 static struct vg_profile vg_prof_update = {.name="update()"},
64 vg_prof_render = {.name="render()"},
65 vg_prof_swap = {.name="swap"};
66
67 void vg_checkgl( const char *src_info )
68 {
69 int fail = 0;
70
71 GLenum err;
72 while( (err = glGetError()) != GL_NO_ERROR ){
73 vg_error( "(%s) OpenGL Error: #%d\n", src_info, err );
74 fail = 1;
75 }
76
77 if( fail )
78 vg_fatal_error( "OpenGL Error" );
79 }
80
81 static void async_vg_bake_shaders( void *payload, u32 size )
82 {
83 vg_shaders_compile();
84 }
85
86 void vg_bake_shaders(void)
87 {
88 vg_console_reg_cmd( "reload_shaders", vg_shaders_live_recompile, NULL );
89 vg_async_call( async_vg_bake_shaders, NULL, 0 );
90 }
91
92 void async_internal_complete( void *payload, u32 size )
93 {
94 vg_success( "Internal async setup complete\n" );
95 SDL_AtomicLock( &vg.sl_status );
96
97 if( vg.engine_status == k_engine_status_crashed ){
98 SDL_AtomicUnlock( &vg.sl_status );
99 return;
100 }
101 else{
102 vg.engine_status = k_engine_status_running;
103 }
104
105 SDL_AtomicUnlock( &vg.sl_status );
106 }
107
108 #ifdef VG_CUSTOM_SHADERS
109 void vg_auto_shader_register(void); /* created from codegen */
110 #endif
111
112 static void _vg_load_full( void *data )
113 {
114 vg_preload();
115 vg_tex2d_replace_with_error_async( &vg.tex_missing );
116 vg_ui.tex_bg = vg.tex_missing;
117
118 /* internal */
119 vg_loader_step( vg_input_init, vg_input_free );
120 vg_loader_step( vg_lines_init, NULL );
121 vg_loader_step( vg_rb_view_init, NULL );
122 #ifndef VG_NO_AUDIO
123 vg_loader_step( vg_audio_init, vg_audio_free );
124 #endif
125 vg_loader_step( vg_profiler_init, NULL );
126
127 /* client */
128 #ifdef VG_CUSTOM_SHADERS
129 vg_auto_shader_register();
130 #endif
131 vg_load();
132
133 vg_async_call( async_internal_complete, NULL, 0 );
134
135 vg_success( "Client loaded in %fs\n", vg.time_real );
136 }
137
138 static void _vg_process_events(void)
139 {
140 v2_zero( vg.mouse_wheel );
141 v2_zero( vg.mouse_delta );
142
143 /* Update input */
144 vg_process_inputs();
145
146 /* SDL event loop */
147 SDL_Event event;
148 while( SDL_PollEvent( &event ) ){
149 if( event.type == SDL_KEYDOWN ){
150 if( vg_console.enabled &&
151 (vg_ui.focused_control_type != k_ui_control_modal) ){
152 if( event.key.keysym.sym == SDLK_ESCAPE ||
153 event.key.keysym.scancode == SDL_SCANCODE_GRAVE ){
154 vg_console.enabled = 0;
155 ui_defocus_all();
156 }
157 else if( (event.key.keysym.mod & KMOD_CTRL) &&
158 event.key.keysym.sym == SDLK_n ){
159 console_suggest_next();
160 }
161 else if( (event.key.keysym.mod & KMOD_CTRL ) &&
162 event.key.keysym.sym == SDLK_p ){
163 console_suggest_prev();
164 }
165 else{
166 ui_proc_key( event.key.keysym );
167 }
168 }
169 else{
170 if( event.key.keysym.scancode == SDL_SCANCODE_GRAVE ){
171 vg_console.enabled = 1;
172 }
173 else {
174 ui_proc_key( event.key.keysym );
175 }
176 }
177 }
178 else if( event.type == SDL_MOUSEWHEEL ){
179 vg.mouse_wheel[0] += event.wheel.preciseX;
180 vg.mouse_wheel[1] += event.wheel.preciseY;
181 }
182 else if( event.type == SDL_CONTROLLERDEVICEADDED ||
183 event.type == SDL_CONTROLLERDEVICEREMOVED )
184 {
185 vg_input_device_event( &event );
186 }
187 else if( event.type == SDL_CONTROLLERAXISMOTION ||
188 event.type == SDL_CONTROLLERBUTTONDOWN ||
189 event.type == SDL_CONTROLLERBUTTONUP )
190 {
191 vg_input_controller_event( &event );
192 }
193 else if( event.type == SDL_MOUSEMOTION ){
194 vg.mouse_delta[0] += event.motion.xrel;
195 vg.mouse_delta[1] += event.motion.yrel;
196 }
197 else if( event.type == SDL_WINDOWEVENT ){
198 if( event.window.event == SDL_WINDOWEVENT_SIZE_CHANGED ){
199 int w, h;
200 SDL_GL_GetDrawableSize( vg.window, &w, &h );
201
202 if( !w || !h ){
203 vg_warn( "Got a invalid framebuffer size: "
204 "%dx%d... ignoring\n", w, h );
205 }
206 else{
207 vg.window_x = w;
208 vg.window_y = h;
209
210 vg_framebuffer_resize(w,h);
211 }
212 }
213 else if( event.window.event == SDL_WINDOWEVENT_CLOSE ){
214 vg.window_should_close = 1;
215 }
216 }
217 else if( event.type == SDL_TEXTINPUT ){
218 ui_proc_utf8( event.text.text );
219 }
220 }
221
222 SDL_GetMouseState( &vg.mouse_pos[0], &vg.mouse_pos[1] );
223 }
224
225 static void _vg_gameloop_update(void)
226 {
227 vg_profile_begin( &vg_prof_update );
228
229 vg.engine_stage = k_engine_stage_update;
230 vg_pre_update();
231
232 /* Fixed update loop */
233 vg.engine_stage = k_engine_stage_update_fixed;
234
235 vg.fixed_iterations = 0;
236 vg_lines.enabled = vg_lines.render;
237 vg.time_fixed_accumulator += vg.time_delta;
238
239 while( vg.time_fixed_accumulator >= vg.time_fixed_delta ){
240 vg_fixed_update();
241 vg_lines.enabled = 0;
242 vg.time_fixed_accumulator -= vg.time_fixed_delta;
243
244 vg.fixed_iterations ++;
245 if( vg.fixed_iterations == 8 ){
246 break;
247 }
248 }
249 vg_lines.enabled = vg_lines.render;
250 vg.time_fixed_extrapolate = vg.time_fixed_accumulator / vg.time_fixed_delta;
251
252 vg.engine_stage = k_engine_stage_update;
253 vg_post_update();
254 vg_profile_end( &vg_prof_update );
255 }
256
257 static void vg_settings_gui(void);
258 static void _vg_gameloop_render(void)
259 {
260 vg_profile_begin( &vg_prof_render );
261
262 /* render */
263 vg.engine_stage = k_engine_stage_rendering;
264 vg_render();
265
266 vg_profile_end( &vg_prof_render );
267
268 /* ui */
269 vg.engine_stage = k_engine_stage_ui;
270 {
271 ui_prerender();
272 if( vg_console.enabled ){
273 vg_ui.ignore_input_frames = 10;
274 vg_gui();
275 vg_ui.ignore_input_frames = 0;
276 vg_ui.wants_mouse = 1;
277 vg_console_draw();
278 }
279 else vg_gui();
280
281 if( vg.settings_open )
282 vg_settings_gui();
283
284 /* vg tools */
285 #ifndef VG_NO_AUDIO
286 audio_debug_ui( vg.pv );
287 #endif
288
289 /* profiling */
290 if( vg_profiler ){
291 int frame_target = vg.display_refresh_rate;
292 if( vg.fps_limit > 0 ) frame_target = vg.fps_limit;
293 vg_profile_drawn(
294 (struct vg_profile *[]){
295 &vg_prof_update,&vg_prof_render,&vg_prof_swap}, 3,
296 (1.0f/(float)frame_target)*1000.0f,
297 (ui_rect){ 4, 4, 250, 0 }, 0, 0
298 );
299 char perf[256];
300
301 snprintf( perf, 255,
302 "x: %d y: %d\n"
303 "refresh: %d (%.1fms)\n"
304 "samples: %d\n"
305 "iterations: %d (acc: %.3fms%%)\n"
306 "time: real(%.2f) delta(%.2f) rate(%.2f)\n"
307 " extrap(%.2f) frame(%.2f) spin( "PRINTF_U64" )\n",
308 vg.window_x, vg.window_y,
309 frame_target, (1.0f/(float)frame_target)*1000.0f,
310 vg.samples,
311 vg.fixed_iterations,
312 (vg.time_fixed_accumulator/VG_TIMESTEP_FIXED)*100.0f,
313 vg.time_real, vg.time_delta, vg.time_rate,
314 vg.time_fixed_extrapolate, vg.time_frame_delta,
315 vg.time_spinning );
316
317 ui_text( (ui_rect){258,4,900,900},perf,1,0,k_ui_align_left);
318 }
319 ui_postrender();
320 }
321 }
322
323 static void vg_changevsync(void){
324 if( vg.vsync && (vg.vsync_feature != k_vsync_feature_error) ){
325 /* turn on vsync if not enabled */
326
327 enum vsync_feature requested = k_vsync_feature_enabled;
328 if( vg.vsync < 0 ) requested = k_vsync_feature_enabled_adaptive;
329
330 if( vg.vsync_feature != requested ){
331 vg_info( "Setting swap interval\n" );
332
333 int swap_interval = 1;
334 if( requested == k_vsync_feature_enabled_adaptive )
335 swap_interval = -1;
336
337 if( SDL_GL_SetSwapInterval( swap_interval ) == -1 ){
338 if( requested == k_vsync_feature_enabled ){
339 vg_error( "Vsync is not supported by your system\n" );
340 vg_warn( "You may be overriding it in your"
341 " graphics control panel.\n" );
342 }
343 else{
344 vg_error( "Adaptive Vsync is not supported by your system\n" );
345 }
346
347 vg.vsync_feature = k_vsync_feature_error;
348 vg.vsync = 0;
349 /* TODO: Make popup to notify user that this happened */
350 }
351 else{
352 vg_success( "Vsync enabled (%d)\n", requested );
353 vg.vsync_feature = requested;
354 }
355 }
356 }
357 else {
358 if( vg.vsync_feature != k_vsync_feature_disabled ){
359 SDL_GL_SetSwapInterval( 0 );
360 vg.vsync_feature = k_vsync_feature_disabled;
361 }
362 }
363 }
364
365 static int vg_framefilter( double dt ){
366 if( vg.fps_limit < 24 ) vg.fps_limit = 24;
367 if( vg.fps_limit > 300 ) vg.fps_limit = 300;
368
369 double min_frametime = 1.0/(double)vg.fps_limit;
370 if( vg.time_frame_delta < min_frametime ){
371 /* TODO: we can use high res nanosleep on Linux here */
372 double sleep_ms = (min_frametime-vg.time_frame_delta) * 1000.0;
373 u32 ms = (u32)floor( sleep_ms );
374
375 if( ms ){
376 if( !vg_loader_availible() )
377 SDL_Delay(1);
378 else
379 SDL_Delay(ms);
380 }
381 else{
382 vg.time_spinning ++;
383 }
384
385 return 1;
386 }
387
388 return 0;
389 }
390
391 static int _vg_crashscreen(void)
392 {
393 #if 0
394 if( vg_getkey( SDLK_ESCAPE ) )
395 return 1;
396 #endif
397
398 glBindFramebuffer( GL_FRAMEBUFFER, 0 );
399 glEnable(GL_BLEND);
400 glDisable(GL_DEPTH_TEST);
401 glBlendFunc(GL_ONE_MINUS_DST_ALPHA, GL_DST_ALPHA);
402 glBlendEquation(GL_FUNC_ADD);
403
404 glClearColor( 0.15f + sinf(vg.time_real)*0.1f, 0.0f, 0.0f,1.0f );
405 glClear( GL_COLOR_BUFFER_BIT );
406 glViewport( 0,0, vg.window_x, vg.window_y );
407
408 #if 0
409 _vg_render_log();
410 #endif
411
412 return 0;
413 }
414
415 static void _vg_gameloop(void){
416 //vg.time_fixed_accumulator = 0.75f * (1.0f/60.0f);
417
418 vg.time_hp = SDL_GetPerformanceCounter();
419 vg.time_hp_last = vg.time_hp;
420
421 int post_start = 0;
422 while(1){
423 vg.time_hp = SDL_GetPerformanceCounter();
424 u64 udt = vg.time_hp - vg.time_hp_last;
425 vg.time_hp_last = vg.time_hp;
426
427 double dt = (double)udt / (double)SDL_GetPerformanceFrequency();
428
429 vg.time_frame_delta += dt;
430 vg_run_async_checked();
431
432 if( vg_framefilter( dt ) )
433 continue;
434
435 vg_changevsync();
436
437 enum engine_status status = _vg_engine_status();
438 if( status == k_engine_status_running )
439 vg_profile_begin( &vg_prof_swap );
440
441 SDL_GL_SwapWindow( vg.window );
442
443 if( status == k_engine_status_running )
444 vg_profile_end( &vg_prof_swap );
445
446 vg.time_real += vg.time_frame_delta;
447 vg.time_delta = vg.time_frame_delta * vg.time_rate;
448 vg.time += vg.time_delta;
449
450 _vg_process_events();
451
452 if( vg.window_should_close )
453 break;
454
455 if( status == k_engine_status_crashed ){
456 if( _vg_crashscreen() )
457 break;
458 }
459 else{
460 if( status == k_engine_status_running ){
461 _vg_gameloop_update();
462 _vg_gameloop_render();
463 }
464 else{
465 vg_loader_render();
466 }
467 }
468
469 if( vg.loader_ring > 0.01f ){
470 vg_loader_render_ring( vg.loader_ring );
471 vg.loader_ring -= vg.time_frame_delta * 0.5f;
472 }
473
474 vg.time_frame_delta = 0.0;
475 vg.time_spinning = 0;
476 }
477 }
478
479 static void _vg_process_launch_opts_internal( int argc, char *argv[] )
480 {
481 char *arg;
482 while( vg_argp( argc, argv ) ){
483 if( (arg = vg_opt_arg( 'w' )) ){
484 vg.window_x = atoi( arg );
485 }
486
487 if( (arg = vg_opt_arg( 'h' )) ){
488 vg.window_y = atoi( arg );
489 }
490
491 if( (arg = vg_long_opt_arg( "samples" )) ){
492 vg.samples = VG_MAX( 0, VG_MIN( 8, atoi( arg ) ) );
493 }
494
495 if( vg_long_opt( "use-libc-malloc" ) ){
496 vg_mem.use_libc_malloc = 1;
497 }
498
499 if( vg_long_opt( "high-performance" ) ){
500 vg.quality_profile = k_quality_profile_low;
501 }
502
503 vg_launch_opt();
504 }
505 }
506
507 static void _vg_init_window( const char *window_name )
508 {
509 vg_info( "SDL_INIT\n" );
510
511 if( SDL_Init( SDL_INIT_VIDEO ) != 0 ){
512 vg_error( "SDL_Init failed: %s\n", SDL_GetError() );
513 exit(0);
514 }
515
516 #ifndef VG_NO_AUDIO
517 SDL_InitSubSystem( SDL_INIT_AUDIO );
518 #endif
519 SDL_InitSubSystem( SDL_INIT_GAMECONTROLLER );
520
521 char *exe_basepath = SDL_GetBasePath();
522 u32 len = vg_align8( strlen(exe_basepath)+1 );
523 char *dest = vg_linear_alloc( vg_mem.rtmemory, len );
524 strcpy( dest, exe_basepath );
525 SDL_free( exe_basepath );
526 vg.base_path = dest;
527
528 vg_info( "Basepath: %s\n", vg.base_path );
529
530 SDL_GL_SetAttribute( SDL_GL_DOUBLEBUFFER, 1 );
531 SDL_GL_SetAttribute( SDL_GL_CONTEXT_MAJOR_VERSION, 3 );
532 SDL_GL_SetAttribute( SDL_GL_CONTEXT_MINOR_VERSION, 3 );
533 SDL_GL_SetAttribute( SDL_GL_CONTEXT_PROFILE_MASK,
534 SDL_GL_CONTEXT_PROFILE_CORE );
535
536 SDL_GL_SetAttribute( SDL_GL_CONTEXT_RELEASE_BEHAVIOR,
537 SDL_GL_CONTEXT_RELEASE_BEHAVIOR_FLUSH );
538
539 SDL_GL_SetAttribute( SDL_GL_RED_SIZE, 8 );
540 SDL_GL_SetAttribute( SDL_GL_GREEN_SIZE, 8 );
541 SDL_GL_SetAttribute( SDL_GL_BLUE_SIZE, 8 );
542 SDL_GL_SetAttribute( SDL_GL_ALPHA_SIZE, 8 );
543 SDL_GL_SetAttribute( SDL_GL_STENCIL_SIZE, 0 );
544
545 /*
546 * Get monitor information
547 */
548 vg_info( "Getting display count\n" );
549 int display_count = 0,
550 display_index = 0,
551 mode_index = 0;
552
553 SDL_DisplayMode video_mode;
554 if( SDL_GetDesktopDisplayMode( display_index, &video_mode ) ){
555 vg_error( "SDL_GetDesktopDisplayMode failed: %s\n", SDL_GetError() );
556 SDL_Quit();
557 exit(0);
558 }
559
560 vg.display_refresh_rate = video_mode.refresh_rate;
561 vg.window_x = video_mode.w;
562 vg.window_y = video_mode.h;
563
564 if( vg.screen_mode == 2 ){
565 vg.window_x = 1280;
566 vg.window_y = 720;
567 }
568
569 #ifndef _WIN32
570 SDL_SetHint( "SDL_VIDEO_X11_XINERAMA", "1" );
571 SDL_SetHint( "SDL_VIDEO_X11_XRANDR", "0" );
572 SDL_SetHint( "SDL_VIDEO_X11_XVIDMODE", "0" );
573 #endif
574
575 u32 flags = SDL_WINDOW_OPENGL | SDL_WINDOW_INPUT_GRABBED |
576 SDL_WINDOW_RESIZABLE;
577
578 if( vg.screen_mode == 1 )
579 flags |= SDL_WINDOW_FULLSCREEN;
580 else if( vg.screen_mode == 0 )
581 flags |= SDL_WINDOW_FULLSCREEN_DESKTOP;
582
583 vg_info( "CreateWindow( %d %d %u )\n", vg.window_x, vg.window_y, flags );
584
585 if((vg.window = SDL_CreateWindow( window_name, 0, 0,
586 vg.window_x, vg.window_y, flags ))){
587 if( vg.screen_mode == 2 )
588 SDL_SetWindowPosition( vg.window, video_mode.w-vg.window_x, 0 );
589 }
590 else{
591 vg_error( "SDL_CreateWindow failed: %s", SDL_GetError() );
592 exit(0);
593 }
594
595 SDL_RaiseWindow( vg.window );
596 SDL_SetWindowMinimumSize( vg.window, 1280, 720 );
597 SDL_SetWindowMaximumSize( vg.window, 4096, 4096 );
598
599 vg_info( "CreateContext\n" );
600
601 /* ????? */
602 if( SDL_IsTextInputActive() ) SDL_StopTextInput();
603
604 /*
605 * OpenGL loading
606 */
607 if( (vg.gl_context = SDL_GL_CreateContext(vg.window) )){
608 SDL_GL_GetDrawableSize( vg.window, &vg.window_x, &vg.window_y );
609 vg_success( "Window created (%dx%d)\n", vg.window_x, vg.window_y );
610 }
611 else{
612 vg_error( "SDL_GL_CreateContext failed: %s\n", SDL_GetError() );
613 SDL_Quit();
614 exit(0);
615 }
616
617 if( !gladLoadGLLoader((GLADloadproc)SDL_GL_GetProcAddress) ) {
618 vg_error( "Glad Failed to initialize\n" );
619 SDL_GL_DeleteContext( vg.gl_context );
620 SDL_Quit();
621 exit(0);
622 }
623
624 const unsigned char* glver = glGetString( GL_VERSION );
625 vg_success( "Load setup complete, OpenGL version: %s\n", glver );
626
627 SDL_GL_SetSwapInterval(0); /* disable vsync while loading */
628
629 SDL_DisplayMode dispmode;
630 if( !SDL_GetWindowDisplayMode( vg.window, &dispmode ) ){
631 if( dispmode.refresh_rate ){
632 vg.display_refresh_rate = dispmode.refresh_rate;
633 }
634 }
635
636 if( vg.display_refresh_rate < 25 || vg.display_refresh_rate > 300 ){
637 vg.display_refresh_rate = 60;
638 }
639
640 vg_info( "Display refresh rate: %d\n", dispmode.refresh_rate );
641 if( !vg.fps_limit) vg.fps_limit = vg.display_refresh_rate;
642 }
643
644 static void _vg_terminate(void)
645 {
646 /* Shutdown */
647 vg_console_write_persistent();
648
649 SDL_AtomicLock( &vg.sl_status );
650 vg.engine_status = k_engine_status_none;
651 SDL_AtomicUnlock( &vg.sl_status );
652
653 vg_loader_free();
654
655 vg_success( "If you see this it means everything went.. \"well\".....\n" );
656
657 SDL_GL_DeleteContext( vg.gl_context );
658 SDL_Quit();
659 exit(0);
660 }
661
662 static int cmd_vg_settings_toggle( int argc, const char *argv[] );
663 void vg_enter( int argc, char *argv[], const char *window_name )
664 {
665 vg_rand_seed( &vg.rand, 461 );
666 _vg_process_launch_opts_internal( argc, argv );
667
668 /* Systems init */
669 vg_alloc_quota();
670 vg_console_init();
671
672 vg_console_reg_var( "vg_fps_limit", &vg.fps_limit,
673 k_var_dtype_i32, VG_VAR_PERSISTENT );
674 vg_console_reg_var( "vg_vsync", &vg.vsync,
675 k_var_dtype_i32, VG_VAR_PERSISTENT );
676 vg_console_reg_var( "vg_quality", &vg.quality_profile,
677 k_var_dtype_i32, VG_VAR_PERSISTENT );
678 vg_console_reg_var( "vg_screen_mode", &vg.screen_mode,
679 k_var_dtype_i32, VG_VAR_PERSISTENT );
680 vg_audio_register();
681 vg_console_load_autos();
682
683 vg_console_reg_cmd( "vg_settings", cmd_vg_settings_toggle, NULL );
684 _vg_init_window( window_name );
685
686 vg_async_init();
687 SDL_SetRelativeMouseMode(1);
688
689 vg.thread_id_main = SDL_GetThreadID(NULL);
690
691 /* Opengl-required systems */
692 vg_ui_init();
693 vg_loader_init();
694
695 vg.engine_status = k_engine_status_load_internal;
696
697 _vg_opengl_sync_init();
698 vg_loader_start( _vg_load_full, NULL );
699 _vg_gameloop();
700 _vg_terminate();
701 }
702
703 void vg_fatal_error( const char *fmt, ... )
704 {
705 va_list args;
706 va_start( args, fmt );
707 _vg_logx_va( stderr, NULL, "fatal", KRED, fmt, args );
708 va_end( args );
709
710 vg_print_backtrace();
711
712 SDL_AtomicLock( &vg.sl_status );
713 vg.engine_status = k_engine_status_crashed;
714 SDL_AtomicUnlock( &vg.sl_status );
715
716 if( vg_thread_purpose() == k_thread_purpose_loader )
717 {
718 longjmp( vg.env_loader_exit, 1 );
719 }
720 else
721 {
722 vg_error( "There is no jump to the error runner thing yet! bai bai\n" );
723 _vg_terminate();
724 }
725 }
726
727 /*
728 * settings menu
729 * ---------------------------------------------------------------------------
730 */
731
732 #ifdef VG_GAME_SETTINGS
733 extern void vg_game_settings_gui( ui_rect panel ) ;
734 extern void vg_game_settings_init(void);
735 #endif
736
737 struct ui_enum_opt vg_settings_vsync_enum[] = {
738 { 0, "None" },
739 { 1, "On" },
740 {-1, "Adaptive" },
741 };
742
743 struct ui_enum_opt vg_settings_quality_enum[] = {
744 { 0, "High Quality" },
745 { 1, "Faster" },
746 { 2, "Absolute Minimum" },
747 };
748
749 struct ui_enum_opt vg_settings_screen_mode_enum[] = {
750 { 0, "Fullscreen (desktop)" },
751 { 1, "Fullscreen (native)" },
752 { 2, "Floating Window" }
753 };
754
755 struct ui_enum_opt vg_settings_dsp_enum[] = {
756 { 1, "Enabled" },
757 { 0, "Disabled" },
758 };
759
760 struct {
761 struct vg_setting_ranged_i32 fps_limit;
762 struct vg_setting_enum vsync, quality, screenmode, audio_devices, dsp;
763 i32 temp_audio_choice;
764 }
765 static vg_settings = {
766 .fps_limit = { .label = "Fps Limit",
767 .min=24, .max=300, .actual_value = &vg.fps_limit },
768 .vsync = { .label = "Vsync",
769 .actual_value = &vg.vsync,
770 .options = vg_settings_vsync_enum, .option_count = 3 },
771 .quality = { .label = "Graphic Quality",
772 .actual_value = &vg.quality_profile,
773 .options = vg_settings_quality_enum, .option_count = 3 },
774 .screenmode = { .label = "Type",
775 .actual_value = &vg.screen_mode,
776 .options = vg_settings_screen_mode_enum, .option_count=3 },
777 .audio_devices = { .label = "Audio Device",
778 .actual_value = &vg_settings.temp_audio_choice,
779 .options = NULL, .option_count = 0 },
780 .dsp = { .label = "Audio effects (reverb etc.)",
781 .actual_value = &vg_audio.dsp_enabled,
782 .options = vg_settings_dsp_enum, .option_count=2 },
783 };
784
785 static void vg_settings_ui_draw_diff( ui_rect orig ){
786 ui_rect l,r;
787 ui_split( orig, k_ui_axis_v, -32, 0, l, r );
788 ui_text( r, "*", 1, k_ui_align_middle_center, ui_colour(k_ui_blue) );
789 }
790
791 /* i32 settings
792 * ------------------------------------------------------------------------- */
793
794 static void vg_settings_ui_int( char *buf, u32 len ){
795 for( u32 i=0, j=0; i<len; i ++ ){
796 if( ((buf[i] >= '0') && (buf[i] <= '9')) || (buf[i] == '\0') )
797 buf[j ++] = buf[i];
798 }
799 }
800
801 struct ui_textbox_callbacks static vg_settings_ui_int_callbacks = {
802 .change = vg_settings_ui_int
803 };
804
805 static bool vg_settings_ranged_i32_valid( struct vg_setting_ranged_i32 *prop ){
806 if( prop->new_value < prop->min ) return 0;
807 if( prop->new_value > prop->max ) return 0;
808 return 1;
809 }
810
811 static bool vg_settings_ranged_i32_diff( struct vg_setting_ranged_i32 *prop ){
812 if( prop->new_value != *prop->actual_value ) return 1;
813 else return 0;
814 }
815
816 static bool vg_settings_ui_ranged_i32( struct vg_setting_ranged_i32 *prop,
817 ui_rect rect ){
818 ui_rect orig;
819 rect_copy( rect, orig );
820
821 ui_textbox( rect, prop->label, prop->buf, sizeof(prop->buf),
822 1, 0, &vg_settings_ui_int_callbacks );
823 prop->new_value = atoi( prop->buf );
824
825 if( vg_settings_ranged_i32_diff( prop ) )
826 vg_settings_ui_draw_diff( orig );
827
828 bool valid = vg_settings_ranged_i32_valid( prop );
829 if( !valid ){
830 ui_rect _null, line;
831 ui_split( orig, k_ui_axis_h, -1, 0, _null, line );
832 line[1] += 3;
833
834 ui_fill( line, ui_colour( k_ui_red ) );
835 }
836
837 return valid;
838 }
839
840 void ui_settings_ranged_i32_init( struct vg_setting_ranged_i32 *prop )
841 {
842 vg_str tmp;
843 vg_strnull( &tmp, prop->buf, sizeof(prop->buf) );
844 vg_strcati32( &tmp, *prop->actual_value );
845 prop->new_value = *prop->actual_value;
846 }
847
848 /* enum settings
849 * ------------------------------------------------------------------------- */
850
851 bool vg_settings_enum_diff( struct vg_setting_enum *prop )
852 {
853 if( prop->new_value != *prop->actual_value ) return 1;
854 else return 0;
855 }
856
857 bool vg_settings_enum( struct vg_setting_enum *prop, ui_rect rect )
858 {
859 ui_rect orig;
860 rect_copy( rect, orig );
861
862 ui_enum( rect, prop->label,
863 prop->options, prop->option_count, &prop->new_value );
864
865 if( vg_settings_enum_diff( prop ) )
866 vg_settings_ui_draw_diff( orig );
867
868 return 1;
869 }
870
871 void ui_settings_enum_init( struct vg_setting_enum *prop )
872 {
873 prop->new_value = *prop->actual_value;
874 }
875
876 /* .. */
877
878 void vg_settings_ui_header( ui_rect inout_panel, const char *name )
879 {
880 ui_rect rect;
881 ui_standard_widget( inout_panel, rect, 2 );
882 ui_text( rect, name, 1, k_ui_align_middle_center, ui_colour(k_ui_fg+3) );
883 }
884
885
886 bool vg_settings_apply_button( ui_rect inout_panel, bool validated )
887 {
888 ui_rect last_row;
889 ui_px height = (vg_ui.font->glyph_height + 18) * k_ui_scale;
890 ui_split( inout_panel, k_ui_axis_h, -height, k_ui_padding,
891 inout_panel, last_row );
892
893 const char *string = "Apply";
894 if( validated ){
895 if( ui_button( last_row, string ) == 1 )
896 return 1;
897 }
898 else{
899 ui_rect rect;
900 ui_standard_widget( last_row, rect, 1 );
901 ui_fill( rect, ui_colour( k_ui_bg+1 ) );
902 ui_outline( rect, -1, ui_colour( k_ui_red ), 0 );
903
904 ui_rect t = { 0,0, ui_text_line_width( string ), 14 };
905 ui_rect_center( rect, t );
906 ui_text( t, string, 1, k_ui_align_left, ui_colour(k_ui_fg+3) );
907 }
908
909 return 0;
910 }
911
912 static void vg_settings_video_apply(void){
913 if( vg_settings_enum_diff( &vg_settings.screenmode ) ){
914 vg.screen_mode = vg_settings.screenmode.new_value;
915
916 if( (vg.screen_mode == 0) || (vg.screen_mode == 1) ){
917 SDL_DisplayMode video_mode;
918 if( SDL_GetDesktopDisplayMode( 0, &video_mode ) ){
919 vg_error("SDL_GetDesktopDisplayMode failed: %s\n", SDL_GetError());
920 }
921 else {
922 //vg.display_refresh_rate = video_mode.refresh_rate;
923 vg.window_x = video_mode.w;
924 vg.window_y = video_mode.h;
925 }
926 SDL_SetWindowSize( vg.window, vg.window_x, vg.window_y );
927 }
928
929 if( vg.screen_mode == 0 )
930 SDL_SetWindowFullscreen( vg.window, SDL_WINDOW_FULLSCREEN_DESKTOP );
931 if( vg.screen_mode == 1 )
932 SDL_SetWindowFullscreen( vg.window, SDL_WINDOW_FULLSCREEN );
933 if( vg.screen_mode == 2 ){
934 SDL_SetWindowFullscreen( vg.window, 0 );
935 SDL_SetWindowSize( vg.window, 1280, 720 );
936 SDL_SetWindowPosition( vg.window, 16, 16 );
937 SDL_SetWindowMinimumSize( vg.window, 1280, 720 );
938 SDL_SetWindowMaximumSize( vg.window, 4096, 4096 );
939 }
940 }
941
942 vg.fps_limit = vg_settings.fps_limit.new_value;
943 vg.quality_profile = vg_settings.quality.new_value;
944 vg.vsync = vg_settings.vsync.new_value;
945 }
946
947 static void vg_settings_video_gui( ui_rect panel ){
948 bool validated = 1;
949 ui_rect rq;
950 ui_standard_widget( panel, rq, 1 );
951 vg_settings_enum( &vg_settings.quality, rq );
952
953 /* FIXME */
954 #if 0
955 if( vg.vsync_feature == k_vsync_feature_error ){
956 ui_info( panel, "There was an error activating vsync feature." );
957 }
958 #endif
959
960 /* frame timing */
961 vg_settings_ui_header( panel, "Frame Timing" );
962 ui_rect duo, d0,d1;
963 ui_standard_widget( panel, duo, 1 );
964 ui_split_ratio( duo, k_ui_axis_v, 0.5f, 16, d0, d1 );
965
966 vg_settings_enum( &vg_settings.vsync, d0 );
967 validated &= vg_settings_ui_ranged_i32( &vg_settings.fps_limit, d1 );
968
969 /* profiler */
970 ui_standard_widget( panel, duo, 10 );
971 int frame_target = vg.display_refresh_rate;
972 if( !vg.vsync ) frame_target = vg.fps_limit;
973 vg_profile_drawn(
974 (struct vg_profile *[]){
975 &vg_prof_update,&vg_prof_render,&vg_prof_swap}, 3,
976 (1.0f/(f32)frame_target)*1500.0f,
977 duo, 1, 0
978 );
979
980 ui_fill( (ui_rect){ duo[0], duo[1]+(duo[3]*2)/3, duo[2], 1 },
981 ui_colour(k_ui_fg) );
982
983 /* window spec */
984 vg_settings_ui_header( panel, "Window Specification" );
985
986 ui_standard_widget( panel, duo, 1 );
987 vg_settings_enum( &vg_settings.screenmode, duo );
988
989 if( vg_settings_apply_button( panel, validated ) )
990 vg_settings_video_apply();
991 }
992
993 static void vg_settings_audio_apply(void){
994 if( vg_settings_enum_diff( &vg_settings.audio_devices ) ){
995 if( vg_audio.sdl_output_device ){
996 vg_info( "Closing audio device %d\n", vg_audio.sdl_output_device );
997 SDL_CloseAudioDevice( vg_audio.sdl_output_device );
998 }
999
1000 vg_strfree( &vg_audio.device_choice );
1001
1002 if( vg_settings.audio_devices.new_value == -1 ){ }
1003 else if( vg_settings.audio_devices.new_value == -2 ){
1004 vg_fatal_error( "Programming error\n" );
1005 }
1006 else {
1007 struct ui_enum_opt *selected = NULL, *oi;
1008
1009 for( int i=0; i<vg_settings.audio_devices.option_count; i ++ ){
1010 oi = &vg_settings.audio_devices.options[i];
1011
1012 if( oi->value == vg_settings.audio_devices.new_value ){
1013 selected = oi;
1014 break;
1015 }
1016 }
1017
1018 vg_strnull( &vg_audio.device_choice, NULL, -1 );
1019 vg_strcat( &vg_audio.device_choice, oi->alias );
1020 }
1021
1022 vg_audio_device_init();
1023 *vg_settings.audio_devices.actual_value =
1024 vg_settings.audio_devices.new_value;
1025 }
1026
1027 audio_lock();
1028 if( vg_settings_enum_diff( &vg_settings.dsp ) ){
1029 *vg_settings.dsp.actual_value =
1030 vg_settings.dsp.new_value;
1031 }
1032
1033 audio_unlock();
1034 }
1035
1036 static void vg_settings_audio_gui( ui_rect panel ){
1037 ui_rect rq;
1038 ui_standard_widget( panel, rq, 1 );
1039 vg_settings_enum( &vg_settings.audio_devices, rq );
1040
1041 ui_standard_widget( panel, rq, 1 );
1042 vg_settings_enum( &vg_settings.dsp, rq );
1043
1044 if( vg_settings_apply_button( panel, 1 ) )
1045 vg_settings_audio_apply();
1046 }
1047
1048 void vg_settings_open(void)
1049 {
1050 vg.settings_open = 1;
1051
1052 ui_settings_ranged_i32_init( &vg_settings.fps_limit );
1053 ui_settings_enum_init( &vg_settings.vsync );
1054 ui_settings_enum_init( &vg_settings.quality );
1055 ui_settings_enum_init( &vg_settings.screenmode );
1056
1057 /* Create audio options */
1058 int count = SDL_GetNumAudioDevices( 0 );
1059
1060 struct ui_enum_opt *options = malloc( sizeof(struct ui_enum_opt)*(count+1) );
1061 vg_settings.audio_devices.options = options;
1062 vg_settings.audio_devices.option_count = count+1;
1063
1064 struct ui_enum_opt *o0 = &options[0];
1065 o0->alias = "OS Default";
1066 o0->value = -1;
1067
1068 for( int i=0; i<count; i ++ ){
1069 struct ui_enum_opt *oi = &options[i+1];
1070
1071 const char *device_name = SDL_GetAudioDeviceName( i, 0 );
1072 int len = strlen(device_name);
1073
1074 oi->alias = malloc( len+1 );
1075 memcpy( (void *)oi->alias, device_name, len+1 );
1076 oi->value = i;
1077 }
1078
1079 if( vg_audio.device_choice.buffer ){
1080 vg_settings.temp_audio_choice = -2;
1081
1082 for( int i=0; i<count; i ++ ){
1083 struct ui_enum_opt *oi = &options[i+1];
1084 if( !strcmp( oi->alias, vg_audio.device_choice.buffer ) ){
1085 vg_settings.temp_audio_choice = oi->value;
1086 break;
1087 }
1088 }
1089 }
1090 else {
1091 vg_settings.temp_audio_choice = -1;
1092 }
1093
1094 ui_settings_enum_init( &vg_settings.audio_devices );
1095 ui_settings_enum_init( &vg_settings.dsp );
1096
1097 #ifdef VG_GAME_SETTINGS
1098 vg_game_settings_init();
1099 #endif
1100 }
1101
1102 void vg_settings_close(void)
1103 {
1104 vg.settings_open = 0;
1105
1106 struct ui_enum_opt *options = vg_settings.audio_devices.options;
1107 for( int i=1; i < vg_settings.audio_devices.option_count; i ++ )
1108 free( (void *)options[i].alias );
1109 free( vg_settings.audio_devices.options );
1110 }
1111
1112 static void vg_settings_gui(void)
1113 {
1114 ui_rect null;
1115 ui_rect screen = { 0, 0, vg.window_x, vg.window_y };
1116 ui_rect window = { 0, 0, 1000, 700 };
1117 ui_rect_center( screen, window );
1118 vg_ui.wants_mouse = 1;
1119
1120 ui_fill( window, ui_colour( k_ui_bg+1 ) );
1121 ui_outline( window, 1, ui_colour( k_ui_bg+7 ), 0 );
1122
1123 ui_rect title, panel;
1124 ui_split( window, k_ui_axis_h, 28, 0, title, panel );
1125 ui_fill( title, ui_colour( k_ui_bg+7 ) );
1126 ui_text( title, "Settings", 1, k_ui_align_middle_center,
1127 ui_colourcont(k_ui_bg+7) );
1128
1129 ui_rect quit_button;
1130 ui_split( title, k_ui_axis_v, title[2]-title[3], 2, title, quit_button );
1131
1132 if( ui_button_text( quit_button, "X", 1 ) == 1 ){
1133 vg_settings_close();
1134 return;
1135 }
1136
1137 ui_rect_pad( panel, (ui_px[2]){ 8, 8 } );
1138
1139 const char *opts[] = { "video", "audio",
1140 #ifdef VG_GAME_SETTINGS
1141 "game"
1142 #endif
1143 };
1144
1145 static i32 page = 0;
1146 ui_tabs( panel, panel, opts, vg_list_size(opts), &page );
1147
1148 if( page == 0 ){
1149 vg_settings_video_gui( panel );
1150 }
1151 else if( page == 1 )
1152 vg_settings_audio_gui( panel );
1153
1154 #ifdef VG_GAME_SETTINGS
1155 else if( page == 2 )
1156 vg_game_settings_gui( panel );
1157 #endif
1158 }
1159
1160 static int cmd_vg_settings_toggle( int argc, const char *argv[] ){
1161 vg_settings_open();
1162 return 0;
1163 }
1164
1165 /*
1166 * Graphic cards will check these to force it to use the GPU.
1167 * TODO: explicit declexport. since -flto strips these symbols in release.
1168 */
1169 u32 NvOptimusEnablement = 0x00000001;
1170 int AmdPowerXpressRequestHighPerformance = 1;
1171
1172 #include "vg_async.c"
1173 #include "vg_audio.c"
1174 #include "vg_audio_dsp.c"
1175 #include "vg_audio_synth_bird.c"
1176 #include "vg_binstr.c"
1177 #include "vg_bvh.c"
1178 #include "vg_camera.c"
1179 #include "vg_lines.c"
1180 #include "vg_console.c"
1181 #include "vg_imgui.c"
1182 #include "vg_input.c"
1183 #include "vg_io.c"
1184 #include "vg_loader.c"
1185 #include "vg_log.c"
1186 #include "vg_tex.c"
1187 #include "vg_mem.c"
1188 #include "vg_mem_pool.c"
1189 #include "vg_mem_queue.c"
1190 #include "vg_msg.c"
1191 #include "vg_opt.c"
1192 #include "vg_perlin.c"
1193 #include "vg_string.c"
1194 #include "vg_profiler.c"
1195 #include "vg_rigidbody_collision.c"
1196 #include "vg_rigidbody_constraints.c"
1197 #include "vg_rigidbody.c"
1198 #include "vg_rigidbody_view.c"
1199 #include "vg_shader.c"
1200
1201 #ifdef VG_CUSTOM_SHADERS
1202 #include "shaders/impl.c"
1203 #endif