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