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