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