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