pick ray calculation (moved to gph-math and used here)
[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 static Ray calc_pick_ray(int x, int y);
30
31 long time_msec;
32 int win_width, win_height;
33 float win_aspect;
34 bool fb_srgb;
35 bool opt_gear_wireframe;
36
37 TextureSet texman;
38 SceneSet sceneman;
39
40 unsigned int sdr_ltmap, sdr_ltmap_notex;
41
42 int fpexcept_enabled;
43
44 static Avatar avatar;
45
46 static float cam_dist = 0.0;
47 static float floor_y;   // last floor height
48 static float user_eye_height = 165;
49
50 static float walk_speed = 300.0f;
51 static float mouse_speed = 0.5f;
52 static bool show_walk_mesh, noclip = false;
53
54 static bool have_headtracking, have_handtracking, should_swap;
55
56 static int prev_mx, prev_my;
57 static bool bnstate[8];
58 static bool keystate[256];
59 static bool gpad_bnstate[64];
60 static Vec2 joy_move, joy_look;
61 static float joy_deadzone = 0.01;
62
63 static float framerate;
64
65 static Mat4 view_matrix, mouse_view_matrix, proj_matrix;
66 static MetaScene *mscn;
67 static unsigned int sdr_post_gamma;
68
69 static long prev_msec;
70
71 static ExhibitManager *exman;
72 static BlobExhibit *blobs;
73 static bool show_blobs;
74
75 static ExSelection ex_sel;
76
77 static Renderer *rend;
78
79 static Ray last_pick_ray;
80
81
82 bool app_init(int argc, char **argv)
83 {
84         set_log_file("demo.log");
85
86         char *env = getenv("FPEXCEPT");
87         if(env && atoi(env)) {
88                 info_log("enabling floating point exceptions\n");
89                 fpexcept_enabled = 1;
90                 enable_fpexcept();
91         }
92
93         if(init_opengl() == -1) {
94                 return false;
95         }
96
97         if(!init_options(argc, argv, "demo.conf")) {
98                 return false;
99         }
100         app_resize(opt.width, opt.height);
101         app_fullscreen(opt.fullscreen);
102
103         if(opt.vr) {
104                 if(goatvr_init() == -1) {
105                         return false;
106                 }
107                 goatvr_set_origin_mode(GOATVR_HEAD);
108                 goatvr_set_units_scale(100.0f);
109
110                 goatvr_startvr();
111                 should_swap = goatvr_should_swap() != 0;
112                 user_eye_height = goatvr_get_eye_height();
113                 have_headtracking = goatvr_have_headtracking();
114                 have_handtracking = goatvr_have_handtracking();
115
116                 goatvr_recenter();
117         }
118
119         if(fb_srgb) {
120                 int srgb_capable;
121                 glGetIntegerv(GL_FRAMEBUFFER_SRGB_CAPABLE_EXT, &srgb_capable);
122                 printf("Framebuffer %s sRGB-capable\n", srgb_capable ? "is" : "is not");
123                 if(srgb_capable) {
124                         glEnable(GL_FRAMEBUFFER_SRGB);
125                 } else {
126                         fb_srgb = 0;
127                 }
128         }
129
130         glEnable(GL_MULTISAMPLE);
131         glEnable(GL_DEPTH_TEST);
132         glEnable(GL_CULL_FACE);
133         glEnable(GL_NORMALIZE);
134
135         if(!init_debug_gui()) {
136                 return false;
137         }
138
139         Mesh::use_custom_sdr_attr = false;
140
141         float ambient[] = {0.0, 0.0, 0.0, 0.0};
142         glLightModelfv(GL_LIGHT_MODEL_AMBIENT, ambient);
143
144         glClearColor(1, 1, 1, 1);
145
146         init_audio();
147
148         if(!init_vrhands()) {
149                 return false;
150         }
151
152         mscn = new MetaScene;
153         if(!mscn->load(opt.scenefile ? opt.scenefile : "data/museum.scene")) {
154                 return false;
155         }
156
157         avatar.pos = mscn->start_pos;
158         Vec3 dir = rotate(Vec3(0, 0, 1), mscn->start_rot);
159         dir.y = 0;
160         avatar.body_rot = rad_to_deg(acos(dot(dir, Vec3(0, 0, 1))));
161
162         exman = new ExhibitManager;
163         /*
164         if(!exman->load(mscn, "data/exhibits")) {
165                 //return false;
166         }
167         */
168
169         blobs = new BlobExhibit;
170         blobs->node = new SceneNode;
171         blobs->init();
172         blobs->node->set_position(Vec3(-680, 160, -100));
173         blobs->node->set_scaling(Vec3(28, 28, 28));
174         blobs->node->update(0);
175
176         exman->add(blobs);
177
178         if(!(sdr_ltmap_notex = create_program_load("sdr/lightmap.v.glsl", "sdr/lightmap-notex.p.glsl"))) {
179                 return false;
180         }
181         set_uniform_int(sdr_ltmap_notex, "texmap", MTL_TEX_DIFFUSE);
182         set_uniform_int(sdr_ltmap_notex, "lightmap", MTL_TEX_LIGHTMAP);
183
184         if(!(sdr_ltmap = create_program_load("sdr/lightmap.v.glsl", "sdr/lightmap-tex.p.glsl"))) {
185                 return false;
186         }
187         set_uniform_int(sdr_ltmap, "texmap", MTL_TEX_DIFFUSE);
188         set_uniform_int(sdr_ltmap, "lightmap", MTL_TEX_LIGHTMAP);
189
190         if(!fb_srgb) {
191                 sdr_post_gamma = create_program_load("sdr/post_gamma.v.glsl", "sdr/post_gamma.p.glsl");
192         }
193
194         rend = new Renderer;
195         rend->set_scene(mscn);
196
197         glUseProgram(0);
198
199         if(opt.vr || opt.fullscreen) {
200                 app_grab_mouse(true);
201         }
202
203         if(mscn->music && opt.music) {
204                 mscn->music->play(AUDIO_PLAYMODE_LOOP);
205         }
206         return true;
207 }
208
209 void app_cleanup()
210 {
211         if(mscn->music) {
212                 mscn->music->stop();
213         }
214         destroy_audio();
215
216         app_grab_mouse(false);
217         if(opt.vr) {
218                 goatvr_shutdown();
219         }
220         destroy_vrhands();
221
222         delete rend;
223
224         delete exman;
225
226         texman.clear();
227         sceneman.clear();
228
229         cleanup_debug_gui();
230 }
231
232 static bool constrain_walk_mesh(const Vec3 &v, Vec3 *newv)
233 {
234         Mesh *wm = mscn->walk_mesh;
235         if(!wm) {
236                 *newv = v;
237                 return true;
238         }
239
240         Ray downray = Ray(v, Vec3(0, -1, 0));
241         HitPoint hit;
242         if(mscn->walk_mesh->intersect(downray, &hit)) {
243                 *newv = hit.pos;
244                 newv->y += user_eye_height;
245                 return true;
246         }
247         return false;
248 }
249
250 static void update(float dt)
251 {
252         texman.update();
253         sceneman.update();
254
255         mscn->update(dt);
256         exman->update(dt);
257
258         float speed = walk_speed * dt;
259         Vec3 dir;
260
261         // joystick
262         float jdeadsq = joy_deadzone * joy_deadzone;
263         float jmove_lensq = length_sq(joy_move);
264         float jlook_lensq = length_sq(joy_look);
265
266         if(jmove_lensq > jdeadsq) {
267                 float len = sqrt(jmove_lensq);
268                 jmove_lensq -= jdeadsq;
269
270                 float mag = len * len;
271                 dir.x += mag * joy_move.x / len * 2.0 * speed;
272                 dir.z += mag * joy_move.y / len * 2.0 * speed;
273         }
274         if(jlook_lensq > jdeadsq) {
275                 float len = sqrt(jlook_lensq);
276                 jlook_lensq -= jdeadsq;
277
278                 float mag = len * len;
279                 avatar.body_rot += mag * joy_look.x / len * 200.0 * dt;
280                 avatar.head_alt += mag * joy_look.y / len * 100.0 * dt;
281                 if(avatar.head_alt < -90.0f) avatar.head_alt = -90.0f;
282                 if(avatar.head_alt > 90.0f) avatar.head_alt = 90.0f;
283         }
284
285         // keyboard move
286         if(keystate[(int)'w']) {
287                 dir.z -= speed;
288         }
289         if(keystate[(int)'s']) {
290                 dir.z += speed;
291         }
292         if(keystate[(int)'d']) {
293                 dir.x += speed;
294         }
295         if(keystate[(int)'a']) {
296                 dir.x -= speed;
297         }
298         if(keystate[(int)'q'] || gpad_bnstate[GPAD_UP]) {
299                 avatar.pos.y += speed;
300         }
301         if(keystate[(int)'z'] || gpad_bnstate[GPAD_DOWN]) {
302                 avatar.pos.y -= speed;
303         }
304
305         float theta = M_PI * avatar.body_rot / 180.0f;
306         Vec3 newpos;
307         newpos.x = avatar.pos.x + cos(theta) * dir.x - sin(theta) * dir.z;
308         newpos.y = avatar.pos.y;
309         newpos.z = avatar.pos.z + sin(theta) * dir.x + cos(theta) * dir.z;
310
311         if(noclip) {
312                 avatar.pos = newpos;
313         } else {
314                 if(!constrain_walk_mesh(newpos, &avatar.pos)) {
315                         float dtheta = M_PI / 32.0;
316                         float theta = dtheta;
317                         Vec2 dir2d = newpos.xz() - avatar.pos.xz();
318
319                         for(int i=0; i<16; i++) {
320                                 Vec2 dvec = rotate(dir2d, theta);
321                                 Vec3 pos = avatar.pos + Vec3(dvec.x, 0, dvec.y);
322                                 if(constrain_walk_mesh(pos, &avatar.pos)) {
323                                         break;
324                                 }
325                                 dvec = rotate(dir2d, -theta);
326                                 pos = avatar.pos + Vec3(dvec.x, 0, dvec.y);
327                                 if(constrain_walk_mesh(pos, &avatar.pos)) {
328                                         break;
329                                 }
330                                 theta += dtheta;
331                         }
332                 }
333                 floor_y = avatar.pos.y - user_eye_height;
334         }
335
336         // TODO move to avatar
337         // calculate mouselook view matrix
338         mouse_view_matrix = Mat4::identity;
339         mouse_view_matrix.pre_translate(0, 0, -cam_dist);
340         if(!have_headtracking) {
341                 mouse_view_matrix.pre_rotate_x(deg_to_rad(avatar.head_alt));
342         }
343         mouse_view_matrix.pre_rotate_y(deg_to_rad(avatar.body_rot));
344         mouse_view_matrix.pre_translate(-avatar.pos.x, -avatar.pos.y, -avatar.pos.z);
345
346         // update hand-tracking
347         if(have_handtracking) {
348                 update_vrhands(&avatar);
349         }
350 }
351
352 void app_display()
353 {
354         float dt = (float)(time_msec - prev_msec) / 1000.0f;
355         prev_msec = time_msec;
356
357         if(debug_gui) {
358                 ImGui::GetIOPtr()->DeltaTime = dt;
359                 ImGui::NewFrame();
360
361                 ImGui::ShowTestWindow();
362         }
363
364         if(opt.vr) {
365                 // VR mode
366                 goatvr_draw_start();
367                 glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
368
369                 update(dt);
370
371                 for(int i=0; i<2; i++) {
372                         // for each eye
373                         goatvr_draw_eye(i);
374
375                         proj_matrix = goatvr_projection_matrix(i, NEAR_CLIP, FAR_CLIP);
376                         glMatrixMode(GL_PROJECTION);
377                         glLoadMatrixf(proj_matrix[0]);
378
379                         view_matrix = mouse_view_matrix * Mat4(goatvr_view_matrix(i));
380                         glMatrixMode(GL_MODELVIEW);
381                         glLoadMatrixf(view_matrix[0]);
382
383                         draw_scene();
384                         if(have_handtracking) {
385                                 draw_vrhands();
386                         }
387
388                         if(debug_gui) {
389                                 ImGui::Render();
390                         }
391                 }
392                 goatvr_draw_done();
393
394                 if(should_swap) {
395                         app_swap_buffers();
396                 }
397
398         } else {
399                 glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
400
401                 update(dt);
402
403                 proj_matrix.perspective(deg_to_rad(50.0), win_aspect, NEAR_CLIP, FAR_CLIP);
404                 glMatrixMode(GL_PROJECTION);
405                 glLoadMatrixf(proj_matrix[0]);
406
407                 view_matrix = mouse_view_matrix;
408                 glMatrixMode(GL_MODELVIEW);
409                 glLoadMatrixf(view_matrix[0]);
410
411                 draw_scene();
412
413                 if(!fb_srgb && sdr_post_gamma) {
414                         slow_post(sdr_post_gamma);
415                         glUseProgram(0);
416                 }
417
418                 if(debug_gui) {
419                         ImGui::Render();
420                 }
421                 app_swap_buffers();
422         }
423         assert(glGetError() == GL_NO_ERROR);
424
425         calc_framerate();
426 }
427
428
429 static void draw_scene()
430 {
431         rend->draw();
432         exman->draw();
433
434         /*
435         if(have_handtracking) {
436                 Mat4 head_xform = inverse(mouse_view_matrix);//goatvr_head_matrix();
437                 Mat4 head_dir_xform = head_xform.upper3x3();
438
439                 glUseProgram(0);
440                 glPushAttrib(GL_ENABLE_BIT);
441                 glDisable(GL_LIGHTING);
442                 glBegin(GL_LINES);
443                 for(int i=0; i<2; i++) {
444                         if(hand[i].valid) {
445                                 glColor3f(i, 1 - i, i);
446                         } else {
447                                 glColor3f(0.5, 0.5, 0.5);
448                         }
449                         Vec3 v = head_xform * hand[i].pos;
450                         Vec3 dir = head_dir_xform * rotate(Vec3(0, 0, -1), hand[i].rot) * 20.0f;
451                         Vec3 up = head_dir_xform * rotate(Vec3(0, 1, 0), hand[i].rot) * 10.0f;
452                         Vec3 right = head_dir_xform * rotate(Vec3(1, 0, 0), hand[i].rot) * 10.0f;
453
454                         glVertex3f(v.x, v.y, v.z);
455                         glVertex3f(v.x + dir.x, v.y + dir.y, v.z + dir.z);
456                         glVertex3f(v.x - right.x, v.y - right.y, v.z - right.z);
457                         glVertex3f(v.x + right.x, v.y + right.y, v.z + right.z);
458                         glVertex3f(v.x - up.x, v.y - up.y, v.z - up.z);
459                         glVertex3f(v.x + up.x, v.y + up.y, v.z + up.z);
460                 }
461                 glEnd();
462                 glPopAttrib();
463         }
464         */
465
466         if(show_walk_mesh && mscn->walk_mesh) {
467                 glPushAttrib(GL_ENABLE_BIT);
468                 glEnable(GL_BLEND);
469                 glBlendFunc(GL_ONE, GL_ONE);
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                 case 'x':
585                         exman->load(mscn, "data/exhibits");
586                         break;
587                 }
588         }
589
590         if(key < 256 && !(mod & (MOD_CTRL | MOD_ALT))) {
591                 keystate[key] = pressed;
592         }
593 }
594
595 void app_mouse_button(int bn, bool pressed, int x, int y)
596 {
597         if(debug_gui) {
598                 debug_gui_mbutton(bn, pressed, x, y);
599                 return; // ignore mouse events while GUI is visible
600         }
601
602         prev_mx = x;
603         prev_my = y;
604         bnstate[bn] = pressed;
605
606         if(bn == 0) {
607                 if(!pressed) {
608                         if(ex_sel.ex) {
609                                 ex_sel.ex = 0;
610                         } else {
611                                 Ray ray = calc_pick_ray(x, y);
612                                 ex_sel = exman->select(ray);
613                         }
614                 }
615         }
616 }
617
618 static inline void mouse_look(float dx, float dy)
619 {
620         float scrsz = (float)win_height;
621         avatar.body_rot += dx * 512.0 / scrsz;
622         avatar.head_alt += dy * 512.0 / scrsz;
623
624         if(avatar.head_alt < -90) avatar.head_alt = -90;
625         if(avatar.head_alt > 90) avatar.head_alt = 90;
626 }
627
628 static void mouse_zoom(float dx, float dy)
629 {
630         cam_dist += dy * 0.1;
631         if(cam_dist < 0.0) cam_dist = 0.0;
632 }
633
634 void app_mouse_motion(int x, int y)
635 {
636         if(debug_gui) {
637                 debug_gui_mmotion(x, y);
638                 return; // ignore mouse events while GUI is visible
639         }
640
641         int dx = x - prev_mx;
642         int dy = y - prev_my;
643         prev_mx = x;
644         prev_my = y;
645
646         if(!dx && !dy) return;
647
648         if(ex_sel.ex) {
649                 Vec3 pos = ex_sel.ex->node->get_node_position();
650                 Vec3 dir = transpose(view_matrix.upper3x3()) * Vec3(dx * 1.0, dy * -1.0, 0);
651
652                 ex_sel.ex->node->set_position(pos + dir);
653         }
654
655         if(bnstate[2]) {
656                 mouse_look(dx, dy);
657         }
658 }
659
660 void app_mouse_delta(int dx, int dy)
661 {
662         if(bnstate[2]) {
663                 mouse_zoom(dx * mouse_speed, dy * mouse_speed);
664         } else {
665                 mouse_look(dx * mouse_speed, dy * mouse_speed);
666         }
667 }
668
669 void app_mouse_wheel(int dir)
670 {
671         if(debug_gui) {
672                 debug_gui_wheel(dir);
673         }
674 }
675
676 void app_gamepad_axis(int axis, float val)
677 {
678         switch(axis) {
679         case 0:
680                 joy_move.x = val;
681                 break;
682         case 1:
683                 joy_move.y = val;
684                 break;
685
686         case 2:
687                 joy_look.x = val;
688                 break;
689         case 3:
690                 joy_look.y = val;
691                 break;
692         }
693 }
694
695 void app_gamepad_button(int bn, bool pressed)
696 {
697         gpad_bnstate[bn] = pressed;
698
699         if(pressed) {
700                 switch(bn) {
701                 case GPAD_LSTICK:
702                         toggle_flight();
703                         break;
704
705                 case GPAD_X:
706                         show_blobs = !show_blobs;
707                         show_message("blobs: %s\n", show_blobs ? "on" : "off");
708                         break;
709
710                 case GPAD_START:
711                         goatvr_recenter();
712                         show_message("VR recenter\n");
713                         break;
714
715                 default:
716                         break;
717                 }
718         }
719 }
720
721 static void toggle_flight()
722 {
723         static float prev_walk_speed = -1.0;
724         if(prev_walk_speed < 0.0) {
725                 noclip = true;
726                 prev_walk_speed = walk_speed;
727                 walk_speed = 1000.0;
728                 show_message("fly mode\n");
729         } else {
730                 noclip = false;
731                 walk_speed = prev_walk_speed;
732                 prev_walk_speed = -1.0;
733                 show_message("walk mode\n");
734         }
735 }
736
737 static void calc_framerate()
738 {
739         //static int ncalc;
740         static int nframes;
741         static long prev_upd;
742
743         long elapsed = time_msec - prev_upd;
744         if(elapsed >= 1000) {
745                 framerate = (float)nframes / (float)(elapsed * 0.001);
746                 nframes = 1;
747                 prev_upd = time_msec;
748
749                 /*if(++ncalc >= 5) {
750                         printf("fps: %f\n", framerate);
751                         ncalc = 0;
752                 }*/
753         } else {
754                 ++nframes;
755         }
756 }
757
758 static Ray calc_pick_ray(int x, int y)
759 {
760         float nx = (float)x / (float)win_width;
761         float ny = (float)(win_height - y) / (float)win_height;
762
763         last_pick_ray = mouse_pick_ray(nx, ny, view_matrix, proj_matrix);
764         return last_pick_ray;
765 }