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