ee9b5e64a4286054255c0b3618b3c1eef58b521a
[laserbrain_demo] / src / app.cc
1 #include <stdio.h>
2 #include <limits.h>
3 #include <assert.h>
4 #include <goatvr.h>
5 #include "app.h"
6 #include "opengl.h"
7 #include "sdr.h"
8 #include "texture.h"
9 #include "mesh.h"
10 #include "meshgen.h"
11 #include "scene.h"
12 #include "metascene.h"
13 #include "datamap.h"
14 #include "ui.h"
15 #include "opt.h"
16 #include "post.h"
17 #include "renderer.h"
18 #include "avatar.h"
19 #include "vrinput.h"
20 #include "exman.h"
21 #include "blob_exhibit.h"
22 #include "dbg_gui.h"
23 #include "geomdraw.h"
24 #include "ui_exhibit.h"
25
26 #define NEAR_CLIP       5.0
27 #define FAR_CLIP        10000.0
28
29 static void draw_scene();
30 static void toggle_flight();
31 static void calc_framerate();
32 static Ray calc_pick_ray(int x, int y);
33
34 long time_msec;
35 int win_width, win_height;
36 int vp_width, vp_height;
37 float win_aspect;
38 bool fb_srgb;
39 bool opt_gear_wireframe;
40
41 TextureSet texman;
42 SceneSet sceneman;
43
44 int fpexcept_enabled;
45
46 unsigned int dbg_key_pending;
47
48 static Avatar avatar;
49
50 static float cam_dist = 0.0;
51 static float floor_y;   // last floor height
52 static float user_eye_height = 165;
53
54 static float walk_speed = 300.0f;
55 static float mouse_speed = 0.5f;
56 static bool show_walk_mesh, noclip = false;
57
58 static bool have_headtracking, have_handtracking, should_swap;
59
60 static int prev_mx, prev_my;
61 static bool bnstate[8];
62 static bool keystate[256];
63 static bool gpad_bnstate[64];
64 static Vec2 joy_move, joy_look;
65 static float joy_deadzone = 0.01;
66
67 static float framerate;
68
69 static Mat4 view_matrix, mouse_view_matrix, proj_matrix;
70 static MetaScene *mscn;
71 static unsigned int sdr_post_gamma;
72
73 static long prev_msec;
74
75 static ExhibitManager *exman;
76 static bool show_blobs;
77
78 ExSelection exsel_active, exsel_hover;
79 ExSelection exsel_grab_left, exsel_grab_right;
80 #define exsel_grab_mouse exsel_grab_right
81 static ExhibitSlot exslot_left, exslot_right;
82 #define exslot_mouse exslot_right
83
84 static Renderer *rend;
85
86 static Ray last_pick_ray;
87
88 static bool post_scene_init_pending = true;
89
90
91 bool app_init(int argc, char **argv)
92 {
93         set_log_file("demo.log");
94
95         char *env = getenv("FPEXCEPT");
96         if(env && atoi(env)) {
97                 info_log("enabling floating point exceptions\n");
98                 fpexcept_enabled = 1;
99                 enable_fpexcept();
100         }
101
102         if(init_opengl() == -1) {
103                 return false;
104         }
105
106         if(!init_options(argc, argv, "demo.conf")) {
107                 return false;
108         }
109         app_resize(opt.width, opt.height);
110         app_fullscreen(opt.fullscreen);
111
112         if(opt.vr) {
113                 if(goatvr_init() == -1) {
114                         return false;
115                 }
116                 goatvr_set_origin_mode(GOATVR_HEAD);
117                 goatvr_set_units_scale(100.0f);
118
119                 goatvr_startvr();
120                 should_swap = goatvr_should_swap() != 0;
121                 user_eye_height = goatvr_get_eye_height();
122                 have_headtracking = goatvr_have_headtracking();
123                 have_handtracking = goatvr_have_handtracking();
124
125                 goatvr_recenter();
126         }
127
128         if(fb_srgb) {
129                 int srgb_capable;
130                 glGetIntegerv(GL_FRAMEBUFFER_SRGB_CAPABLE_EXT, &srgb_capable);
131                 printf("Framebuffer %s sRGB-capable\n", srgb_capable ? "is" : "is not");
132                 if(srgb_capable) {
133                         glEnable(GL_FRAMEBUFFER_SRGB);
134                 } else {
135                         fb_srgb = 0;
136                 }
137         }
138
139         glEnable(GL_MULTISAMPLE);
140         glEnable(GL_DEPTH_TEST);
141         glEnable(GL_CULL_FACE);
142         glEnable(GL_NORMALIZE);
143
144         if(!init_debug_gui()) {
145                 return false;
146         }
147
148         Mesh::use_custom_sdr_attr = false;
149
150         float ambient[] = {0.0, 0.0, 0.0, 0.0};
151         glLightModelfv(GL_LIGHT_MODEL_AMBIENT, ambient);
152
153         init_audio();
154
155         if(!init_vrhands()) {
156                 return false;
157         }
158
159         mscn = new MetaScene;
160         if(!mscn->load(opt.scenefile ? opt.scenefile : "data/museum.scene")) {
161                 return false;
162         }
163
164         avatar.pos = mscn->start_pos;
165         Vec3 dir = rotate(Vec3(0, 0, 1), mscn->start_rot);
166         dir.y = 0;
167         avatar.body_rot = rad_to_deg(acos(dot(dir, Vec3(0, 0, 1))));
168
169         exman = new ExhibitManager;
170         // exhibits are loaded in post_scene_init, because they need access to the scene graph
171
172         if(!exui_init()) {
173                 error_log("failed to initialize exhibit ui system\n");
174                 return false;
175         }
176         exui_setnode(&exslot_left.node);
177
178         if(!fb_srgb) {
179                 sdr_post_gamma = create_program_load("sdr/post_gamma.v.glsl", "sdr/post_gamma.p.glsl");
180         }
181
182         rend = new Renderer;
183         if(!rend->init()) {
184                 return false;
185         }
186         rend->set_scene(mscn);
187
188         glUseProgram(0);
189
190         if(opt.vr || opt.fullscreen) {
191                 app_grab_mouse(true);
192         }
193
194         if(mscn->music && opt.music) {
195                 mscn->music->play(AUDIO_PLAYMODE_LOOP);
196         }
197         return true;
198 }
199
200 // post_scene_init is called after the scene has completed loading
201 static void post_scene_init()
202 {
203         mscn->update(0);        // update once to calculate node matrices
204
205         int num_mir = mscn->calc_mirror_planes();
206         info_log("found %d mirror planes\n", num_mir);
207
208         exman->load(mscn, "data/exhibits");
209 }
210
211 void app_cleanup()
212 {
213         if(mscn->music) {
214                 mscn->music->stop();
215         }
216         destroy_audio();
217
218         app_grab_mouse(false);
219         if(opt.vr) {
220                 goatvr_shutdown();
221         }
222         destroy_vrhands();
223
224         delete rend;
225
226         exui_shutdown();
227
228         /* this must be destroyed before the scene graph to detach exhibit nodes
229          * before the scene tries to delete them recursively
230          */
231         delete exman;
232
233         texman.clear();
234         sceneman.clear();
235
236         cleanup_debug_gui();
237 }
238
239 static bool constrain_walk_mesh(const Vec3 &v, Vec3 *newv)
240 {
241         Mesh *wm = mscn->walk_mesh;
242         if(!wm) {
243                 *newv = v;
244                 return true;
245         }
246
247         Ray downray = Ray(v, Vec3(0, -1, 0));
248         HitPoint hit;
249         if(mscn->walk_mesh->intersect(downray, &hit)) {
250                 *newv = hit.pos;
251                 newv->y += user_eye_height;
252                 return true;
253         }
254         return false;
255 }
256
257 static void update(float dt)
258 {
259         texman.update();
260         sceneman.update();
261
262         if(post_scene_init_pending && !sceneman.pending()) {
263                 post_scene_init_pending = false;
264                 post_scene_init();
265         }
266
267         mscn->update(dt);
268         exman->update(dt);
269         exui_update(dt);
270
271         float speed = walk_speed * dt;
272         Vec3 dir;
273
274         // joystick
275         float jdeadsq = joy_deadzone * joy_deadzone;
276         float jmove_lensq = length_sq(joy_move);
277         float jlook_lensq = length_sq(joy_look);
278
279         if(jmove_lensq > jdeadsq) {
280                 float len = sqrt(jmove_lensq);
281                 jmove_lensq -= jdeadsq;
282
283                 float mag = len * len;
284                 dir.x += mag * joy_move.x / len * 2.0 * speed;
285                 dir.z += mag * joy_move.y / len * 2.0 * speed;
286         }
287         if(jlook_lensq > jdeadsq) {
288                 float len = sqrt(jlook_lensq);
289                 jlook_lensq -= jdeadsq;
290
291                 float mag = len * len;
292                 avatar.body_rot += mag * joy_look.x / len * 200.0 * dt;
293                 avatar.head_alt += mag * joy_look.y / len * 100.0 * dt;
294                 if(avatar.head_alt < -90.0f) avatar.head_alt = -90.0f;
295                 if(avatar.head_alt > 90.0f) avatar.head_alt = 90.0f;
296         }
297
298         // keyboard move
299         if(keystate[(int)'w']) {
300                 dir.z -= speed;
301         }
302         if(keystate[(int)'s']) {
303                 dir.z += speed;
304         }
305         if(keystate[(int)'d']) {
306                 dir.x += speed;
307         }
308         if(keystate[(int)'a']) {
309                 dir.x -= speed;
310         }
311         if(keystate[(int)'q'] || gpad_bnstate[GPAD_UP]) {
312                 avatar.pos.y += speed;
313         }
314         if(keystate[(int)'z'] || gpad_bnstate[GPAD_DOWN]) {
315                 avatar.pos.y -= speed;
316         }
317
318         float theta = M_PI * avatar.body_rot / 180.0f;
319         Vec3 newpos;
320         newpos.x = avatar.pos.x + cos(theta) * dir.x - sin(theta) * dir.z;
321         newpos.y = avatar.pos.y;
322         newpos.z = avatar.pos.z + sin(theta) * dir.x + cos(theta) * dir.z;
323
324         if(noclip) {
325                 avatar.pos = newpos;
326         } else {
327                 if(!constrain_walk_mesh(newpos, &avatar.pos)) {
328                         float dtheta = M_PI / 32.0;
329                         float theta = dtheta;
330                         Vec2 dir2d = newpos.xz() - avatar.pos.xz();
331
332                         for(int i=0; i<16; i++) {
333                                 Vec2 dvec = rotate(dir2d, theta);
334                                 Vec3 pos = avatar.pos + Vec3(dvec.x, 0, dvec.y);
335                                 if(constrain_walk_mesh(pos, &avatar.pos)) {
336                                         break;
337                                 }
338                                 dvec = rotate(dir2d, -theta);
339                                 pos = avatar.pos + Vec3(dvec.x, 0, dvec.y);
340                                 if(constrain_walk_mesh(pos, &avatar.pos)) {
341                                         break;
342                                 }
343                                 theta += dtheta;
344                         }
345                 }
346                 floor_y = avatar.pos.y - user_eye_height;
347         }
348
349         // TODO move to the avatar system
350         // calculate mouselook view matrix
351         mouse_view_matrix = Mat4::identity;
352         mouse_view_matrix.pre_translate(0, 0, -cam_dist);
353         if(!have_headtracking) {
354                 mouse_view_matrix.pre_rotate_x(deg_to_rad(avatar.head_alt));
355         }
356         mouse_view_matrix.pre_rotate_y(deg_to_rad(avatar.body_rot));
357         mouse_view_matrix.pre_translate(-avatar.pos.x, -avatar.pos.y, -avatar.pos.z);
358
359
360         // update hand-tracking
361         if(have_handtracking) {
362                 update_vrhands(&avatar);
363
364                 if(vrhand[0].valid) {
365                         exslot_left.node.set_position(vrhand[0].pos);
366                         exslot_left.node.set_rotation(vrhand[0].rot);
367
368                         // right hand takes precedence for hover
369                         if(!exsel_grab_left && !exsel_hover) {
370                                 exsel_hover = exman->select(Sphere(vrhand[0].pos, 5));
371                         }
372                 }
373                 if(vrhand[1].valid) {
374                         exslot_right.node.set_position(vrhand[1].pos);
375                         exslot_right.node.set_rotation(vrhand[1].rot);
376
377                         if(!exsel_grab_right) {
378                                 exsel_hover = exman->select(Sphere(vrhand[1].pos, 5));
379                         }
380                 }
381
382         } else {
383                 // check if an exhibit is hovered-over by mouse (only if we don't have one grabbed)
384                 if(!exsel_grab_mouse) {
385                         Ray ray = calc_pick_ray(prev_mx, prev_my);
386                         exsel_hover = exman->select(ray);
387                 }
388
389                 // TODO do this properly
390                 // set the position of the left hand at a suitable position for the exhibit UI
391                 dir = rotate(Vec3(-0.46, -0.1, -1), Vec3(0, 1, 0), deg_to_rad(-avatar.body_rot));
392                 exslot_left.node.set_position(avatar.pos + dir * 30); // magic: distance in front
393         }
394
395         if(!exslot_right.empty()) exslot_right.node.update(dt);
396         // always update the left slot, because it's the anchor point of the exhibit ui
397         exslot_left.node.update(dt);
398 }
399
400 void app_display()
401 {
402         float dt = (float)(time_msec - prev_msec) / 1000.0f;
403         prev_msec = time_msec;
404
405         if(debug_gui) {
406                 ImGui::GetIOPtr()->DeltaTime = dt;
407                 ImGui::NewFrame();
408
409                 //ImGui::ShowTestWindow();
410         }
411
412         glClearColor(1, 1, 1, 1);
413
414         if(opt.vr) {
415                 // VR mode
416                 goatvr_draw_start();
417                 glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
418
419                 update(dt);
420
421                 for(int i=0; i<2; i++) {
422                         // for each eye
423                         goatvr_draw_eye(i);
424                         vp_width = goatvr_get_fb_eye_width(i);
425                         vp_height = goatvr_get_fb_eye_height(i);
426
427                         proj_matrix = goatvr_projection_matrix(i, NEAR_CLIP, FAR_CLIP);
428                         glMatrixMode(GL_PROJECTION);
429                         glLoadMatrixf(proj_matrix[0]);
430
431                         view_matrix = mouse_view_matrix * Mat4(goatvr_view_matrix(i));
432                         glMatrixMode(GL_MODELVIEW);
433                         glLoadMatrixf(view_matrix[0]);
434
435                         draw_scene();
436                         if(have_handtracking) {
437                                 draw_vrhands();
438                         }
439
440                         if(debug_gui) {
441                                 ImGui::Render();
442                         }
443                 }
444                 goatvr_draw_done();
445
446                 vp_width = win_width;
447                 vp_height = win_height;
448
449                 if(should_swap) {
450                         app_swap_buffers();
451                 }
452
453         } else {
454                 glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
455
456                 update(dt);
457
458                 proj_matrix.perspective(deg_to_rad(50.0), win_aspect, NEAR_CLIP, FAR_CLIP);
459                 glMatrixMode(GL_PROJECTION);
460                 glLoadMatrixf(proj_matrix[0]);
461
462                 view_matrix = mouse_view_matrix;
463                 glMatrixMode(GL_MODELVIEW);
464                 glLoadMatrixf(view_matrix[0]);
465
466                 draw_scene();
467
468                 if(!fb_srgb && sdr_post_gamma) {
469                         slow_post(sdr_post_gamma);
470                         glUseProgram(0);
471                 }
472
473                 if(debug_gui) {
474                         ImGui::Render();
475                 }
476                 app_swap_buffers();
477         }
478         assert(glGetError() == GL_NO_ERROR);
479
480         calc_framerate();
481 }
482
483
484 static void draw_scene()
485 {
486         rend->draw();
487         exman->draw();
488
489         if(have_handtracking) {
490                 Mat4 head_xform = inverse(mouse_view_matrix);//goatvr_head_matrix();
491                 Mat4 head_dir_xform = head_xform.upper3x3();
492
493                 glUseProgram(0);
494                 glPushAttrib(GL_ENABLE_BIT);
495                 glDisable(GL_LIGHTING);
496                 glBegin(GL_LINES);
497                 for(int i=0; i<2; i++) {
498                         if(vrhand[i].valid) {
499                                 glColor3f(i, 1 - i, i);
500                         } else {
501                                 glColor3f(0.5, 0.5, 0.5);
502                         }
503                         Vec3 v = head_xform * vrhand[i].pos;
504                         Vec3 dir = head_dir_xform * rotate(Vec3(0, 0, -1), vrhand[i].rot) * 20.0f;
505                         Vec3 up = head_dir_xform * rotate(Vec3(0, 1, 0), vrhand[i].rot) * 10.0f;
506                         Vec3 right = head_dir_xform * rotate(Vec3(1, 0, 0), vrhand[i].rot) * 10.0f;
507
508                         glVertex3f(v.x, v.y, v.z);
509                         glVertex3f(v.x + dir.x, v.y + dir.y, v.z + dir.z);
510                         glVertex3f(v.x - right.x, v.y - right.y, v.z - right.z);
511                         glVertex3f(v.x + right.x, v.y + right.y, v.z + right.z);
512                         glVertex3f(v.x - up.x, v.y - up.y, v.z - up.z);
513                         glVertex3f(v.x + up.x, v.y + up.y, v.z + up.z);
514                 }
515                 glEnd();
516                 glPopAttrib();
517         }
518
519         if(debug_gui && dbg_sel_node) {
520                 AABox bvol = dbg_sel_node->get_bounds();
521                 draw_geom_object(&bvol);
522         }
523
524         if(show_walk_mesh && mscn->walk_mesh) {
525                 glPushAttrib(GL_ENABLE_BIT);
526                 glEnable(GL_BLEND);
527                 glBlendFunc(GL_ONE, GL_ONE);
528                 glEnable(GL_POLYGON_OFFSET_FILL);
529
530                 glUseProgram(0);
531
532                 glPolygonOffset(-1, 1);
533                 glDepthMask(0);
534
535                 glColor3f(0.3, 0.08, 0.01);
536                 mscn->walk_mesh->draw();
537
538                 glDepthMask(1);
539
540                 glPopAttrib();
541         }
542
543         exui_draw();
544
545         print_text(Vec2(9 * win_width / 10, 20), Vec3(1, 1, 0), "fps: %.1f", framerate);
546         draw_ui();
547 }
548
549
550 void app_reshape(int x, int y)
551 {
552         glViewport(0, 0, x, y);
553         goatvr_set_fb_size(x, y, 1.0f);
554         debug_gui_reshape(x, y);
555
556         vp_width = x;
557         vp_height = y;
558 }
559
560 void app_keyboard(int key, bool pressed)
561 {
562         unsigned int mod = app_get_modifiers();
563
564         if(debug_gui && !(pressed && (key == '`' || key == 27))) {
565                 debug_gui_key(key, pressed, mod);
566                 return; // ignore all keystrokes when GUI is visible
567         }
568
569         if(pressed) {
570                 switch(key) {
571                 case 27:
572                         app_quit();
573                         break;
574
575                 case '\n':
576                 case '\r':
577                         if(mod & MOD_ALT) {
578                                 app_toggle_fullscreen();
579                         }
580                         break;
581
582                 case '`':
583                         debug_gui = !debug_gui;
584                         show_message("debug gui %s", debug_gui ? "enabled" : "disabled");
585                         break;
586
587                 case 'm':
588                         app_toggle_grab_mouse();
589                         show_message("mouse %s", app_is_mouse_grabbed() ? "grabbed" : "released");
590                         break;
591
592                 case 'w':
593                         if(mod & MOD_CTRL) {
594                                 show_walk_mesh = !show_walk_mesh;
595                                 show_message("walk mesh: %s", show_walk_mesh ? "on" : "off");
596                         }
597                         break;
598
599                 case 'c':
600                         if(mod & MOD_CTRL) {
601                                 noclip = !noclip;
602                                 show_message(noclip ? "no clip" : "clip");
603                         }
604                         break;
605
606                 case 'f':
607                         toggle_flight();
608                         break;
609
610                 case 'p':
611                         if(mod & MOD_CTRL) {
612                                 fb_srgb = !fb_srgb;
613                                 show_message("gamma correction for non-sRGB framebuffers: %s\n", fb_srgb ? "off" : "on");
614                         }
615                         break;
616
617                 case '=':
618                         walk_speed *= 1.25;
619                         show_message("walk speed: %g", walk_speed);
620                         break;
621
622                 case '-':
623                         walk_speed *= 0.75;
624                         show_message("walk speed: %g", walk_speed);
625                         break;
626
627                 case ']':
628                         mouse_speed *= 1.2;
629                         show_message("mouse speed: %g", mouse_speed);
630                         break;
631
632                 case '[':
633                         mouse_speed *= 0.8;
634                         show_message("mouse speed: %g", mouse_speed);
635                         break;
636
637                 case 'b':
638                         show_blobs = !show_blobs;
639                         show_message("blobs: %s\n", show_blobs ? "on" : "off");
640                         break;
641
642                 case ' ':
643                         goatvr_recenter();
644                         show_message("VR recenter\n");
645                         break;
646
647                 case KEY_UP:
648                         exui_scroll(-1);
649                         break;
650
651                 case KEY_DOWN:
652                         exui_scroll(1);
653                         break;
654
655                 case KEY_LEFT:
656                         exui_change_tab(-1);
657                         break;
658
659                 case KEY_RIGHT:
660                         exui_change_tab(1);
661                         break;
662
663                 case KEY_F5:
664                 case KEY_F6:
665                 case KEY_F7:
666                 case KEY_F8:
667                         dbg_key_pending |= 1 << (key - KEY_F5);
668                         break;
669                 }
670         }
671
672         if(key < 256 && !(mod & (MOD_CTRL | MOD_ALT))) {
673                 keystate[key] = pressed;
674         }
675 }
676
677 void app_mouse_button(int bn, bool pressed, int x, int y)
678 {
679         static int press_x, press_y;
680
681         if(debug_gui) {
682                 debug_gui_mbutton(bn, pressed, x, y);
683                 return; // ignore mouse events while GUI is visible
684         }
685
686         prev_mx = x;
687         prev_my = y;
688         bnstate[bn] = pressed;
689
690         if(bn == 0) {
691                 ExSelection sel;
692                 Ray ray = calc_pick_ray(x, y);
693                 sel = exman->select(ray);
694
695                 if(pressed) {
696                         if(sel && (app_get_modifiers() & MOD_CTRL)) {
697                                 exsel_grab_mouse = sel;
698                                 Vec3 pos = sel.ex->node->get_position();
699                                 debug_log("grabbing... (%g %g %g)\n", pos.x, pos.y, pos.z);
700                                 exslot_mouse.node.set_position(pos);
701                                 exslot_mouse.node.set_rotation(sel.ex->node->get_rotation());
702                                 exslot_mouse.attach_exhibit(sel.ex, EXSLOT_ATTACH_TRANSIENT);
703                                 if(exsel_active) {
704                                         exsel_active = ExSelection::null;       // cancel active on grab
705                                 }
706                         }
707                         press_x = x;
708                         press_y = y;
709
710                 } else {
711                         if(exsel_grab_mouse) {
712                                 // cancel grab on mouse release
713                                 Exhibit *ex = exsel_grab_mouse.ex;
714                                 Vec3 pos = exslot_mouse.node.get_position();
715
716                                 debug_log("releasing at %g %g %g ...\n", pos.x, pos.y, pos.z);
717
718                                 exslot_mouse.detach_exhibit();
719
720                                 ExhibitSlot *slot = exman->nearest_empty_slot(pos, 100);
721                                 if(!slot) {
722                                         debug_log("no empty slot nearby\n");
723                                         if(ex->prev_slot && ex->prev_slot->empty()) {
724                                                 slot = ex->prev_slot;
725                                                 debug_log("using previous slot");
726                                         }
727                                 }
728
729                                 if(slot) {
730                                         slot->attach_exhibit(ex);
731                                 } else {
732                                         // nowhere to put it, so stash it for later
733                                         exslot_mouse.detach_exhibit();
734                                         exman->stash_exhibit(ex);
735                                         debug_log("no slots available, stashing\n");
736                                 }
737
738                                 exsel_grab_mouse = ExSelection::null;
739                         }
740
741                         if(abs(press_x - x) < 5 && abs(press_y - y) < 5) {
742                                 exsel_active = sel;     // select or deselect active exhibit
743                                 if(sel) {
744                                         debug_log("selecting...\n");
745                                 } else {
746                                         debug_log("deselecting...\n");
747                                 }
748                         }
749
750                         press_x = press_y = INT_MIN;
751                 }
752         }
753 }
754
755 static inline void mouse_look(float dx, float dy)
756 {
757         float scrsz = (float)win_height;
758         avatar.body_rot += dx * 512.0 / scrsz;
759         avatar.head_alt += dy * 512.0 / scrsz;
760
761         if(avatar.head_alt < -90) avatar.head_alt = -90;
762         if(avatar.head_alt > 90) avatar.head_alt = 90;
763 }
764
765 static void mouse_zoom(float dx, float dy)
766 {
767         cam_dist += dy * 0.1;
768         if(cam_dist < 0.0) cam_dist = 0.0;
769 }
770
771 void app_mouse_motion(int x, int y)
772 {
773         if(debug_gui) {
774                 debug_gui_mmotion(x, y);
775                 return; // ignore mouse events while GUI is visible
776         }
777
778         int dx = x - prev_mx;
779         int dy = y - prev_my;
780         prev_mx = x;
781         prev_my = y;
782
783         if(!dx && !dy) return;
784
785         if(exsel_grab_mouse) {
786                 Vec3 pos = exslot_mouse.node.get_node_position();
787                 Vec3 dir = transpose(view_matrix.upper3x3()) * Vec3(dx * 1.0, dy * -1.0, 0);
788
789                 exslot_mouse.node.set_position(pos + dir);
790         }
791
792         if(bnstate[2]) {
793                 mouse_look(dx, dy);
794         }
795 }
796
797 void app_mouse_delta(int dx, int dy)
798 {
799         if(bnstate[2]) {
800                 mouse_zoom(dx * mouse_speed, dy * mouse_speed);
801         } else {
802                 mouse_look(dx * mouse_speed, dy * mouse_speed);
803         }
804 }
805
806 void app_mouse_wheel(int dir)
807 {
808         if(debug_gui) {
809                 debug_gui_wheel(dir);
810         }
811 }
812
813 void app_gamepad_axis(int axis, float val)
814 {
815         switch(axis) {
816         case 0:
817                 joy_move.x = val;
818                 break;
819         case 1:
820                 joy_move.y = val;
821                 break;
822
823         case 2:
824                 joy_look.x = val;
825                 break;
826         case 3:
827                 joy_look.y = val;
828                 break;
829         }
830 }
831
832 void app_gamepad_button(int bn, bool pressed)
833 {
834         gpad_bnstate[bn] = pressed;
835
836         if(pressed) {
837                 switch(bn) {
838                 case GPAD_LSTICK:
839                         toggle_flight();
840                         break;
841
842                 case GPAD_X:
843                         show_blobs = !show_blobs;
844                         show_message("blobs: %s\n", show_blobs ? "on" : "off");
845                         break;
846
847                 case GPAD_START:
848                         goatvr_recenter();
849                         show_message("VR recenter\n");
850                         break;
851
852                 default:
853                         break;
854                 }
855         }
856 }
857
858 static void toggle_flight()
859 {
860         static float prev_walk_speed = -1.0;
861         if(prev_walk_speed < 0.0) {
862                 noclip = true;
863                 prev_walk_speed = walk_speed;
864                 walk_speed = 1000.0;
865                 show_message("fly mode\n");
866         } else {
867                 noclip = false;
868                 walk_speed = prev_walk_speed;
869                 prev_walk_speed = -1.0;
870                 show_message("walk mode\n");
871         }
872 }
873
874 static void calc_framerate()
875 {
876         //static int ncalc;
877         static int nframes;
878         static long prev_upd;
879
880         long elapsed = time_msec - prev_upd;
881         if(elapsed >= 1000) {
882                 framerate = (float)nframes / (float)(elapsed * 0.001);
883                 nframes = 1;
884                 prev_upd = time_msec;
885
886                 /*if(++ncalc >= 5) {
887                         printf("fps: %f\n", framerate);
888                         ncalc = 0;
889                 }*/
890         } else {
891                 ++nframes;
892         }
893 }
894
895 static Ray calc_pick_ray(int x, int y)
896 {
897         float nx = (float)x / (float)win_width;
898         float ny = (float)(win_height - y) / (float)win_height;
899
900         last_pick_ray = mouse_pick_ray(nx, ny, view_matrix, proj_matrix);
901         return last_pick_ray;
902 }