added back the demo gui for looking up widgets
[laserbrain_demo] / src / app.cc
1 #include <stdio.h>
2 #include <assert.h>
3 #include <goatvr.h>
4 #include "app.h"
5 #include "opengl.h"
6 #include "sdr.h"
7 #include "texture.h"
8 #include "mesh.h"
9 #include "meshgen.h"
10 #include "scene.h"
11 #include "metascene.h"
12 #include "datamap.h"
13 #include "ui.h"
14 #include "opt.h"
15 #include "post.h"
16 #include "renderer.h"
17 #include "avatar.h"
18 #include "vrinput.h"
19 #include "exman.h"
20 #include "blob_exhibit.h"
21 #include "dbg_gui.h"
22
23 #define NEAR_CLIP       5.0
24 #define FAR_CLIP        10000.0
25
26 static void draw_scene();
27 static void toggle_flight();
28 static void calc_framerate();
29
30 long time_msec;
31 int win_width, win_height;
32 float win_aspect;
33 bool fb_srgb;
34 bool opt_gear_wireframe;
35
36 TextureSet texman;
37 SceneSet sceneman;
38
39 unsigned int sdr_ltmap, sdr_ltmap_notex;
40
41 static Avatar avatar;
42
43 static float cam_dist = 0.0;
44 static float floor_y;   // last floor height
45 static float user_eye_height = 165;
46
47 static float walk_speed = 300.0f;
48 static float mouse_speed = 0.5f;
49 static bool show_walk_mesh, noclip = false;
50
51 static bool have_headtracking, have_handtracking, should_swap;
52
53 static int prev_mx, prev_my;
54 static bool bnstate[8];
55 static bool keystate[256];
56 static bool gpad_bnstate[64];
57 static Vec2 joy_move, joy_look;
58 static float joy_deadzone = 0.01;
59
60 static float framerate;
61
62 static Mat4 view_matrix, mouse_view_matrix, proj_matrix;
63 static MetaScene *mscn;
64 static unsigned int sdr_post_gamma;
65
66 static long prev_msec;
67
68 static ExhibitManager *exman;
69 static BlobExhibit *blobs;
70 static bool show_blobs;
71
72 static Renderer *rend;
73
74
75 bool app_init(int argc, char **argv)
76 {
77         if(!init_options(argc, argv, "demo.conf")) {
78                 return false;
79         }
80         app_resize(opt.width, opt.height);
81         app_fullscreen(opt.fullscreen);
82
83         if(opt.vr) {
84                 if(goatvr_init() == -1) {
85                         return false;
86                 }
87                 goatvr_set_origin_mode(GOATVR_HEAD);
88                 goatvr_set_units_scale(100.0f);
89
90                 goatvr_startvr();
91                 should_swap = goatvr_should_swap() != 0;
92                 user_eye_height = goatvr_get_eye_height();
93                 have_headtracking = goatvr_have_headtracking();
94                 have_handtracking = goatvr_have_handtracking();
95
96                 goatvr_recenter();
97         }
98
99         if(fb_srgb) {
100                 int srgb_capable;
101                 glGetIntegerv(GL_FRAMEBUFFER_SRGB_CAPABLE_EXT, &srgb_capable);
102                 printf("Framebuffer %s sRGB-capable\n", srgb_capable ? "is" : "is not");
103                 if(srgb_capable) {
104                         glEnable(GL_FRAMEBUFFER_SRGB);
105                 } else {
106                         fb_srgb = 0;
107                 }
108         }
109
110         glEnable(GL_MULTISAMPLE);
111         glEnable(GL_DEPTH_TEST);
112         glEnable(GL_CULL_FACE);
113         glEnable(GL_LIGHTING);
114         glEnable(GL_NORMALIZE);
115
116         if(!init_debug_gui()) {
117                 return false;
118         }
119
120         Mesh::use_custom_sdr_attr = false;
121
122         float ambient[] = {0.0, 0.0, 0.0, 0.0};
123         glLightModelfv(GL_LIGHT_MODEL_AMBIENT, ambient);
124
125         glClearColor(1, 1, 1, 1);
126
127         init_audio();
128
129         if(!init_vrhands()) {
130                 return false;
131         }
132
133         mscn = new MetaScene;
134         if(!mscn->load(opt.scenefile ? opt.scenefile : "data/museum.scene")) {
135                 return false;
136         }
137
138         avatar.pos = mscn->start_pos;
139         Vec3 dir = rotate(Vec3(0, 0, 1), mscn->start_rot);
140         dir.y = 0;
141         avatar.body_rot = rad_to_deg(acos(dot(dir, Vec3(0, 0, 1))));
142
143         exman = new ExhibitManager;
144         if(!exman->load(mscn, "data/exhibits")) {
145                 //return false;
146         }
147
148         blobs = new BlobExhibit;
149         blobs->node = new SceneNode;
150         blobs->init();
151         blobs->node->set_position(Vec3(-680, 160, -100));
152         blobs->node->set_scaling(Vec3(28, 28, 28));
153         blobs->node->update(0);
154
155         exman->add(blobs);
156
157         if(!(sdr_ltmap_notex = create_program_load("sdr/lightmap.v.glsl", "sdr/lightmap-notex.p.glsl"))) {
158                 return false;
159         }
160         set_uniform_int(sdr_ltmap_notex, "texmap", MTL_TEX_DIFFUSE);
161         set_uniform_int(sdr_ltmap_notex, "lightmap", MTL_TEX_LIGHTMAP);
162
163         if(!(sdr_ltmap = create_program_load("sdr/lightmap.v.glsl", "sdr/lightmap-tex.p.glsl"))) {
164                 return false;
165         }
166         set_uniform_int(sdr_ltmap, "texmap", MTL_TEX_DIFFUSE);
167         set_uniform_int(sdr_ltmap, "lightmap", MTL_TEX_LIGHTMAP);
168
169         if(!fb_srgb) {
170                 sdr_post_gamma = create_program_load("sdr/post_gamma.v.glsl", "sdr/post_gamma.p.glsl");
171         }
172
173         rend = new Renderer;
174         rend->set_scene(mscn);
175
176         glUseProgram(0);
177
178         if(opt.vr || opt.fullscreen) {
179                 app_grab_mouse(true);
180         }
181
182         if(mscn->music && opt.music) {
183                 mscn->music->play(AUDIO_PLAYMODE_LOOP);
184         }
185         return true;
186 }
187
188 void app_cleanup()
189 {
190         if(mscn->music) {
191                 mscn->music->stop();
192         }
193         destroy_audio();
194
195         app_grab_mouse(false);
196         if(opt.vr) {
197                 goatvr_shutdown();
198         }
199         destroy_vrhands();
200
201         delete rend;
202
203         delete exman;
204
205         texman.clear();
206         sceneman.clear();
207
208         cleanup_debug_gui();
209 }
210
211 static bool constrain_walk_mesh(const Vec3 &v, Vec3 *newv)
212 {
213         Mesh *wm = mscn->walk_mesh;
214         if(!wm) {
215                 *newv = v;
216                 return true;
217         }
218
219         Ray downray = Ray(v, Vec3(0, -1, 0));
220         HitPoint hit;
221         if(mscn->walk_mesh->intersect(downray, &hit)) {
222                 *newv = hit.pos;
223                 newv->y += user_eye_height;
224                 return true;
225         }
226         return false;
227 }
228
229 static void update(float dt)
230 {
231         texman.update();
232         sceneman.update();
233
234         mscn->update(dt);
235         exman->update(dt);
236
237         float speed = walk_speed * dt;
238         Vec3 dir;
239
240         // joystick
241         float jdeadsq = joy_deadzone * joy_deadzone;
242         float jmove_lensq = length_sq(joy_move);
243         float jlook_lensq = length_sq(joy_look);
244
245         if(jmove_lensq > jdeadsq) {
246                 float len = sqrt(jmove_lensq);
247                 jmove_lensq -= jdeadsq;
248
249                 float mag = len * len;
250                 dir.x += mag * joy_move.x / len * 2.0 * speed;
251                 dir.z += mag * joy_move.y / len * 2.0 * speed;
252         }
253         if(jlook_lensq > jdeadsq) {
254                 float len = sqrt(jlook_lensq);
255                 jlook_lensq -= jdeadsq;
256
257                 float mag = len * len;
258                 avatar.body_rot += mag * joy_look.x / len * 200.0 * dt;
259                 avatar.head_alt += mag * joy_look.y / len * 100.0 * dt;
260                 if(avatar.head_alt < -90.0f) avatar.head_alt = -90.0f;
261                 if(avatar.head_alt > 90.0f) avatar.head_alt = 90.0f;
262         }
263
264         // keyboard move
265         if(keystate[(int)'w']) {
266                 dir.z -= speed;
267         }
268         if(keystate[(int)'s']) {
269                 dir.z += speed;
270         }
271         if(keystate[(int)'d']) {
272                 dir.x += speed;
273         }
274         if(keystate[(int)'a']) {
275                 dir.x -= speed;
276         }
277         if(keystate[(int)'q'] || gpad_bnstate[GPAD_UP]) {
278                 avatar.pos.y += speed;
279         }
280         if(keystate[(int)'z'] || gpad_bnstate[GPAD_DOWN]) {
281                 avatar.pos.y -= speed;
282         }
283
284         float theta = M_PI * avatar.body_rot / 180.0f;
285         Vec3 newpos;
286         newpos.x = avatar.pos.x + cos(theta) * dir.x - sin(theta) * dir.z;
287         newpos.y = avatar.pos.y;
288         newpos.z = avatar.pos.z + sin(theta) * dir.x + cos(theta) * dir.z;
289
290         if(noclip) {
291                 avatar.pos = newpos;
292         } else {
293                 if(!constrain_walk_mesh(newpos, &avatar.pos)) {
294                         float dtheta = M_PI / 32.0;
295                         float theta = dtheta;
296                         Vec2 dir2d = newpos.xz() - avatar.pos.xz();
297
298                         for(int i=0; i<16; i++) {
299                                 Vec2 dvec = rotate(dir2d, theta);
300                                 Vec3 pos = avatar.pos + Vec3(dvec.x, 0, dvec.y);
301                                 if(constrain_walk_mesh(pos, &avatar.pos)) {
302                                         break;
303                                 }
304                                 dvec = rotate(dir2d, -theta);
305                                 pos = avatar.pos + Vec3(dvec.x, 0, dvec.y);
306                                 if(constrain_walk_mesh(pos, &avatar.pos)) {
307                                         break;
308                                 }
309                                 theta += dtheta;
310                         }
311                 }
312                 floor_y = avatar.pos.y - user_eye_height;
313         }
314
315         // TODO move to avatar
316         // calculate mouselook view matrix
317         mouse_view_matrix = Mat4::identity;
318         mouse_view_matrix.pre_translate(0, 0, -cam_dist);
319         if(!have_headtracking) {
320                 mouse_view_matrix.pre_rotate_x(deg_to_rad(avatar.head_alt));
321         }
322         mouse_view_matrix.pre_rotate_y(deg_to_rad(avatar.body_rot));
323         mouse_view_matrix.pre_translate(-avatar.pos.x, -avatar.pos.y, -avatar.pos.z);
324
325         // update hand-tracking
326         if(have_handtracking) {
327                 update_vrhands(&avatar);
328         }
329 }
330
331 static void set_light(int idx, const Vec3 &pos, const Vec3 &color)
332 {
333         unsigned int lt = GL_LIGHT0 + idx;
334         float posv[] = { pos.x, pos.y, pos.z, 1 };
335         float colv[] = { color.x, color.y, color.z, 1 };
336
337         glEnable(lt);
338         glLightfv(lt, GL_POSITION, posv);
339         glLightfv(lt, GL_DIFFUSE, colv);
340         glLightfv(lt, GL_SPECULAR, colv);
341 }
342
343 void app_display()
344 {
345         float dt = (float)(time_msec - prev_msec) / 1000.0f;
346         prev_msec = time_msec;
347
348         if(debug_gui) {
349                 ImGui::GetIOPtr()->DeltaTime = dt;
350                 ImGui::NewFrame();
351
352                 ImGui::ShowTestWindow();
353         }
354
355         if(opt.vr) {
356                 // VR mode
357                 goatvr_draw_start();
358                 glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
359
360                 update(dt);
361
362                 for(int i=0; i<2; i++) {
363                         // for each eye
364                         goatvr_draw_eye(i);
365
366                         proj_matrix = goatvr_projection_matrix(i, NEAR_CLIP, FAR_CLIP);
367                         glMatrixMode(GL_PROJECTION);
368                         glLoadMatrixf(proj_matrix[0]);
369
370                         view_matrix = mouse_view_matrix * Mat4(goatvr_view_matrix(i));
371                         glMatrixMode(GL_MODELVIEW);
372                         glLoadMatrixf(view_matrix[0]);
373
374                         draw_scene();
375                         if(have_handtracking) {
376                                 draw_vrhands();
377                         }
378
379                         if(debug_gui) {
380                                 ImGui::Render();
381                         }
382                 }
383                 goatvr_draw_done();
384
385                 if(should_swap) {
386                         app_swap_buffers();
387                 }
388
389         } else {
390                 glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
391
392                 update(dt);
393
394                 proj_matrix.perspective(deg_to_rad(50.0), win_aspect, NEAR_CLIP, FAR_CLIP);
395                 glMatrixMode(GL_PROJECTION);
396                 glLoadMatrixf(proj_matrix[0]);
397
398                 view_matrix = mouse_view_matrix;
399                 glMatrixMode(GL_MODELVIEW);
400                 glLoadMatrixf(view_matrix[0]);
401
402                 draw_scene();
403
404                 if(!fb_srgb && sdr_post_gamma) {
405                         slow_post(sdr_post_gamma);
406                         glUseProgram(0);
407                 }
408
409                 if(debug_gui) {
410                         ImGui::Render();
411                 }
412                 app_swap_buffers();
413         }
414         assert(glGetError() == GL_NO_ERROR);
415
416         calc_framerate();
417 }
418
419
420 static void draw_scene()
421 {
422         static const Vec3 lpos[] = { Vec3(-50, 75, 100), Vec3(100, 0, 30), Vec3(-10, -10, 60) };
423         set_light(0, lpos[0], Vec3(1.0, 0.8, 0.7) * 0.8);
424         set_light(1, lpos[1], Vec3(0.6, 0.7, 1.0) * 0.6);
425         set_light(2, lpos[2], Vec3(0.8, 1.0, 0.8) * 0.3);
426
427         rend->draw();
428
429         if(show_blobs) {
430                 blobs->draw();
431         }
432
433         /*
434         if(have_handtracking) {
435                 Mat4 head_xform = inverse(mouse_view_matrix);//goatvr_head_matrix();
436                 Mat4 head_dir_xform = head_xform.upper3x3();
437
438                 glUseProgram(0);
439                 glPushAttrib(GL_ENABLE_BIT);
440                 glDisable(GL_LIGHTING);
441                 glBegin(GL_LINES);
442                 for(int i=0; i<2; i++) {
443                         if(hand[i].valid) {
444                                 glColor3f(i, 1 - i, i);
445                         } else {
446                                 glColor3f(0.5, 0.5, 0.5);
447                         }
448                         Vec3 v = head_xform * hand[i].pos;
449                         Vec3 dir = head_dir_xform * rotate(Vec3(0, 0, -1), hand[i].rot) * 20.0f;
450                         Vec3 up = head_dir_xform * rotate(Vec3(0, 1, 0), hand[i].rot) * 10.0f;
451                         Vec3 right = head_dir_xform * rotate(Vec3(1, 0, 0), hand[i].rot) * 10.0f;
452
453                         glVertex3f(v.x, v.y, v.z);
454                         glVertex3f(v.x + dir.x, v.y + dir.y, v.z + dir.z);
455                         glVertex3f(v.x - right.x, v.y - right.y, v.z - right.z);
456                         glVertex3f(v.x + right.x, v.y + right.y, v.z + right.z);
457                         glVertex3f(v.x - up.x, v.y - up.y, v.z - up.z);
458                         glVertex3f(v.x + up.x, v.y + up.y, v.z + up.z);
459                 }
460                 glEnd();
461                 glPopAttrib();
462         }
463         */
464
465         if(show_walk_mesh && mscn->walk_mesh) {
466                 glPushAttrib(GL_ENABLE_BIT);
467                 glEnable(GL_BLEND);
468                 glBlendFunc(GL_ONE, GL_ONE);
469                 glDisable(GL_LIGHTING);
470                 glEnable(GL_POLYGON_OFFSET_FILL);
471
472                 glUseProgram(0);
473
474                 glPolygonOffset(-1, 1);
475                 glDepthMask(0);
476
477                 glColor3f(0.3, 0.08, 0.01);
478                 mscn->walk_mesh->draw();
479
480                 glDepthMask(1);
481
482                 glPopAttrib();
483         }
484
485         print_text(Vec2(9 * win_width / 10, 20), Vec3(1, 1, 0), "fps: %.1f", framerate);
486         draw_ui();
487 }
488
489
490 void app_reshape(int x, int y)
491 {
492         glViewport(0, 0, x, y);
493         goatvr_set_fb_size(x, y, 1.0f);
494         debug_gui_reshape(x, y);
495 }
496
497 void app_keyboard(int key, bool pressed)
498 {
499         unsigned int mod = app_get_modifiers();
500
501         if(debug_gui && !(pressed && (key == '`' || key == 27))) {
502                 debug_gui_key(key, pressed, mod);
503                 return; // ignore all keystrokes when GUI is visible
504         }
505
506         if(pressed) {
507                 switch(key) {
508                 case 27:
509                         app_quit();
510                         break;
511
512                 case '\n':
513                 case '\r':
514                         if(mod & MOD_ALT) {
515                                 app_toggle_fullscreen();
516                         }
517                         break;
518
519                 case '`':
520                         debug_gui = !debug_gui;
521                         show_message("debug gui %s", debug_gui ? "enabled" : "disabled");
522                         break;
523
524                 case 'm':
525                         app_toggle_grab_mouse();
526                         show_message("mouse %s", app_is_mouse_grabbed() ? "grabbed" : "released");
527                         break;
528
529                 case 'w':
530                         if(mod & MOD_CTRL) {
531                                 show_walk_mesh = !show_walk_mesh;
532                                 show_message("walk mesh: %s", show_walk_mesh ? "on" : "off");
533                         }
534                         break;
535
536                 case 'c':
537                         if(mod & MOD_CTRL) {
538                                 noclip = !noclip;
539                                 show_message(noclip ? "no clip" : "clip");
540                         }
541                         break;
542
543                 case 'f':
544                         toggle_flight();
545                         break;
546
547                 case 'p':
548                         if(mod & MOD_CTRL) {
549                                 fb_srgb = !fb_srgb;
550                                 show_message("gamma correction for non-sRGB framebuffers: %s\n", fb_srgb ? "off" : "on");
551                         }
552                         break;
553
554                 case '=':
555                         walk_speed *= 1.25;
556                         show_message("walk speed: %g", walk_speed);
557                         break;
558
559                 case '-':
560                         walk_speed *= 0.75;
561                         show_message("walk speed: %g", walk_speed);
562                         break;
563
564                 case ']':
565                         mouse_speed *= 1.2;
566                         show_message("mouse speed: %g", mouse_speed);
567                         break;
568
569                 case '[':
570                         mouse_speed *= 0.8;
571                         show_message("mouse speed: %g", mouse_speed);
572                         break;
573
574                 case 'b':
575                         show_blobs = !show_blobs;
576                         show_message("blobs: %s\n", show_blobs ? "on" : "off");
577                         break;
578
579                 case ' ':
580                         goatvr_recenter();
581                         show_message("VR recenter\n");
582                         break;
583                 }
584         }
585
586         if(key < 256 && !(mod & (MOD_CTRL | MOD_ALT))) {
587                 keystate[key] = pressed;
588         }
589 }
590
591 void app_mouse_button(int bn, bool pressed, int x, int y)
592 {
593         if(debug_gui) {
594                 debug_gui_mbutton(bn, pressed, x, y);
595                 return; // ignore mouse events while GUI is visible
596         }
597
598         prev_mx = x;
599         prev_my = y;
600         bnstate[bn] = pressed;
601 }
602
603 static inline void mouse_look(float dx, float dy)
604 {
605         float scrsz = (float)win_height;
606         avatar.body_rot += dx * 512.0 / scrsz;
607         avatar.head_alt += dy * 512.0 / scrsz;
608
609         if(avatar.head_alt < -90) avatar.head_alt = -90;
610         if(avatar.head_alt > 90) avatar.head_alt = 90;
611 }
612
613 static void mouse_zoom(float dx, float dy)
614 {
615         cam_dist += dy * 0.1;
616         if(cam_dist < 0.0) cam_dist = 0.0;
617 }
618
619 void app_mouse_motion(int x, int y)
620 {
621         if(debug_gui) {
622                 debug_gui_mmotion(x, y);
623                 return; // ignore mouse events while GUI is visible
624         }
625
626         int dx = x - prev_mx;
627         int dy = y - prev_my;
628         prev_mx = x;
629         prev_my = y;
630
631         if(!dx && !dy) return;
632
633         if(bnstate[0]) {
634                 mouse_look(dx, dy);
635         }
636         if(bnstate[2]) {
637                 mouse_zoom(dx, dy);
638         }
639 }
640
641 void app_mouse_delta(int dx, int dy)
642 {
643         if(bnstate[2]) {
644                 mouse_zoom(dx * mouse_speed, dy * mouse_speed);
645         } else {
646                 mouse_look(dx * mouse_speed, dy * mouse_speed);
647         }
648 }
649
650 void app_mouse_wheel(int dir)
651 {
652         if(debug_gui) {
653                 debug_gui_wheel(dir);
654         }
655 }
656
657 void app_gamepad_axis(int axis, float val)
658 {
659         switch(axis) {
660         case 0:
661                 joy_move.x = val;
662                 break;
663         case 1:
664                 joy_move.y = val;
665                 break;
666
667         case 2:
668                 joy_look.x = val;
669                 break;
670         case 3:
671                 joy_look.y = val;
672                 break;
673         }
674 }
675
676 void app_gamepad_button(int bn, bool pressed)
677 {
678         gpad_bnstate[bn] = pressed;
679
680         if(pressed) {
681                 switch(bn) {
682                 case GPAD_LSTICK:
683                         toggle_flight();
684                         break;
685
686                 case GPAD_X:
687                         show_blobs = !show_blobs;
688                         show_message("blobs: %s\n", show_blobs ? "on" : "off");
689                         break;
690
691                 case GPAD_START:
692                         goatvr_recenter();
693                         show_message("VR recenter\n");
694                         break;
695
696                 default:
697                         break;
698                 }
699         }
700 }
701
702 static void toggle_flight()
703 {
704         static float prev_walk_speed = -1.0;
705         if(prev_walk_speed < 0.0) {
706                 noclip = true;
707                 prev_walk_speed = walk_speed;
708                 walk_speed = 1000.0;
709                 show_message("fly mode\n");
710         } else {
711                 noclip = false;
712                 walk_speed = prev_walk_speed;
713                 prev_walk_speed = -1.0;
714                 show_message("walk mode\n");
715         }
716 }
717
718 static void calc_framerate()
719 {
720         static int ncalc;
721         static int nframes;
722         static long prev_upd;
723
724         long elapsed = time_msec - prev_upd;
725         if(elapsed >= 1000) {
726                 framerate = (float)nframes / (float)(elapsed * 0.001);
727                 nframes = 1;
728                 prev_upd = time_msec;
729
730                 /*if(++ncalc >= 5) {
731                         printf("fps: %f\n", framerate);
732                         ncalc = 0;
733                 }*/
734         } else {
735                 ++nframes;
736         }
737 }