continuing the avatar class
[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         // use goatvr sticks for joystick input
282         int num_vr_sticks = goatvr_num_sticks();
283         if(num_vr_sticks > 0) {
284                 float p[2];
285                 goatvr_stick_pos(0, p);
286                 joy_move.x = p[0];
287                 joy_move.y = -p[1];
288         }
289         if(num_vr_sticks > 1) {
290                 float p[2];
291                 goatvr_stick_pos(1, p);
292                 joy_look.x = p[0];
293         }
294
295
296         float speed = walk_speed * dt;
297         Vec3 dir;
298
299         // joystick
300         float jdeadsq = joy_deadzone * joy_deadzone;
301         float jmove_lensq = length_sq(joy_move);
302         float jlook_lensq = length_sq(joy_look);
303
304         if(jmove_lensq > jdeadsq) {
305                 float len = sqrt(jmove_lensq);
306                 jmove_lensq -= jdeadsq;
307
308                 float mag = len * len;
309                 dir.x += mag * joy_move.x / len * 2.0 * speed;
310                 dir.z += mag * joy_move.y / len * 2.0 * speed;
311         }
312         if(jlook_lensq > jdeadsq) {
313                 float len = sqrt(jlook_lensq);
314                 jlook_lensq -= jdeadsq;
315
316                 float mag = len * len;
317                 avatar.body_rot += mag * joy_look.x / len * 200.0 * dt;
318                 avatar.head_alt += mag * joy_look.y / len * 100.0 * dt;
319                 if(avatar.head_alt < -90.0f) avatar.head_alt = -90.0f;
320                 if(avatar.head_alt > 90.0f) avatar.head_alt = 90.0f;
321         }
322
323         // keyboard move
324         if(keystate[(int)'w']) {
325                 dir.z -= speed;
326         }
327         if(keystate[(int)'s']) {
328                 dir.z += speed;
329         }
330         if(keystate[(int)'d']) {
331                 dir.x += speed;
332         }
333         if(keystate[(int)'a']) {
334                 dir.x -= speed;
335         }
336         if(keystate[(int)'q'] || gpad_bnstate[GPAD_UP]) {
337                 avatar.pos.y += speed;
338         }
339         if(keystate[(int)'z'] || gpad_bnstate[GPAD_DOWN]) {
340                 avatar.pos.y -= speed;
341         }
342
343         float theta = M_PI * avatar.body_rot / 180.0f;
344         Vec3 newpos;
345         newpos.x = avatar.pos.x + cos(theta) * dir.x - sin(theta) * dir.z;
346         newpos.y = avatar.pos.y;
347         newpos.z = avatar.pos.z + sin(theta) * dir.x + cos(theta) * dir.z;
348
349         if(noclip) {
350                 avatar.pos = newpos;
351         } else {
352                 if(!constrain_walk_mesh(newpos, &avatar.pos)) {
353                         float dtheta = M_PI / 32.0;
354                         float theta = dtheta;
355                         Vec2 dir2d = newpos.xz() - avatar.pos.xz();
356
357                         for(int i=0; i<16; i++) {
358                                 Vec2 dvec = rotate(dir2d, theta);
359                                 Vec3 pos = avatar.pos + Vec3(dvec.x, 0, dvec.y);
360                                 if(constrain_walk_mesh(pos, &avatar.pos)) {
361                                         break;
362                                 }
363                                 dvec = rotate(dir2d, -theta);
364                                 pos = avatar.pos + Vec3(dvec.x, 0, dvec.y);
365                                 if(constrain_walk_mesh(pos, &avatar.pos)) {
366                                         break;
367                                 }
368                                 theta += dtheta;
369                         }
370                 }
371                 floor_y = avatar.pos.y - user_eye_height;
372         }
373
374         // TODO move to the avatar system
375         // calculate mouselook view matrix
376         mouse_view_matrix = Mat4::identity;
377         mouse_view_matrix.pre_translate(0, 0, -cam_dist);
378         if(!have_headtracking) {
379                 mouse_view_matrix.pre_rotate_x(deg_to_rad(avatar.head_alt));
380         }
381         mouse_view_matrix.pre_rotate_y(deg_to_rad(avatar.body_rot));
382         mouse_view_matrix.pre_translate(-avatar.pos.x, -avatar.pos.y, -avatar.pos.z);
383
384
385         // update hand-tracking
386         if(have_handtracking) {
387                 update_vrhands(&avatar);
388
389                 if(vrhand[0].valid) {
390                         exslot_left.node.set_position(vrhand[0].pos);
391                         exslot_left.node.set_rotation(vrhand[0].rot);
392
393                         // right hand takes precedence for hover
394                         if(!exsel_grab_left && !exsel_hover) {
395                                 exsel_hover = exman->select(Sphere(vrhand[0].pos, 5));
396                         }
397                 }
398                 if(vrhand[1].valid) {
399                         exslot_right.node.set_position(vrhand[1].pos);
400                         exslot_right.node.set_rotation(vrhand[1].rot);
401
402                         if(!exsel_grab_right) {
403                                 exsel_hover = exman->select(Sphere(vrhand[1].pos, 5));
404                         }
405                 }
406
407         } else {
408                 // check if an exhibit is hovered-over by mouse (only if we don't have one grabbed)
409                 if(!exsel_grab_mouse) {
410                         Ray ray = calc_pick_ray(prev_mx, prev_my);
411                         exsel_hover = exman->select(ray);
412                 }
413
414                 // TODO do this properly
415                 // set the position of the left hand at a suitable position for the exhibit UI
416                 dir = rotate(Vec3(-0.46, -0.1, -1), Vec3(0, 1, 0), deg_to_rad(-avatar.body_rot));
417                 exslot_left.node.set_position(avatar.pos + dir * 30); // magic: distance in front
418         }
419
420         if(!exslot_right.empty()) exslot_right.node.update(dt);
421         // always update the left slot, because it's the anchor point of the exhibit ui
422         exslot_left.node.update(dt);
423 }
424
425 void app_display()
426 {
427         float dt = (float)(time_msec - prev_msec) / 1000.0f;
428         prev_msec = time_msec;
429
430         if(debug_gui) {
431                 ImGui::GetIOPtr()->DeltaTime = dt;
432                 ImGui::NewFrame();
433
434                 //ImGui::ShowTestWindow();
435         }
436
437         glClearColor(1, 1, 1, 1);
438
439         if(opt.vr) {
440                 // VR mode
441                 goatvr_draw_start();
442                 glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
443
444                 unsigned int gfbo = goatvr_get_fbo();
445
446                 update(dt);
447
448                 for(int i=0; i<2; i++) {
449                         // for each eye
450                         goatvr_draw_eye(i);
451                         if(gfbo) {
452                                 vp_width = goatvr_get_fb_eye_width(i);
453                                 vp_height = goatvr_get_fb_eye_height(i);
454
455                                 // this is a lightweight operation
456                                 goatvr_rtarg->create_wrap_fbo(gfbo, vp_width, vp_height);
457                                 push_render_target(goatvr_rtarg, RT_FAKE);
458                         } else {
459                                 vp_width = win_width / 2;
460                         }
461
462                         proj_matrix = goatvr_projection_matrix(i, NEAR_CLIP, FAR_CLIP);
463                         glMatrixMode(GL_PROJECTION);
464                         glLoadMatrixf(proj_matrix[0]);
465
466                         view_matrix = mouse_view_matrix * Mat4(goatvr_view_matrix(i));
467                         glMatrixMode(GL_MODELVIEW);
468                         glLoadMatrixf(view_matrix[0]);
469
470                         draw_scene();
471                         if(have_handtracking) {
472                                 draw_vrhands();
473                         }
474
475                         if(debug_gui) {
476                                 ImGui::Render();
477                         }
478
479                         if(gfbo) {
480                                 pop_render_target(RT_FAKE);
481                         }
482                 }
483
484                 goatvr_draw_done();
485
486                 vp_width = win_width;
487                 vp_height = win_height;
488
489                 if(should_swap) {
490                         app_swap_buffers();
491                 }
492
493         } else {
494                 glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
495
496                 update(dt);
497
498                 proj_matrix.perspective(deg_to_rad(50.0), win_aspect, NEAR_CLIP, FAR_CLIP);
499                 glMatrixMode(GL_PROJECTION);
500                 glLoadMatrixf(proj_matrix[0]);
501
502                 view_matrix = mouse_view_matrix;
503                 glMatrixMode(GL_MODELVIEW);
504                 glLoadMatrixf(view_matrix[0]);
505
506                 draw_scene();
507
508                 if(!fb_srgb && sdr_post_gamma) {
509                         slow_post(sdr_post_gamma);
510                         glUseProgram(0);
511                 }
512
513                 if(debug_gui) {
514                         ImGui::Render();
515                 }
516                 app_swap_buffers();
517         }
518         assert(glGetError() == GL_NO_ERROR);
519
520         calc_framerate();
521 }
522
523
524 static void draw_scene()
525 {
526         rend->draw();
527         exman->draw();
528
529         if(have_handtracking) {
530                 Mat4 head_xform = inverse(mouse_view_matrix);//goatvr_head_matrix();
531                 Mat4 head_dir_xform = head_xform.upper3x3();
532
533                 glUseProgram(0);
534                 glPushAttrib(GL_ENABLE_BIT);
535                 glDisable(GL_LIGHTING);
536                 glBegin(GL_LINES);
537                 for(int i=0; i<2; i++) {
538                         if(vrhand[i].valid) {
539                                 glColor3f(i, 1 - i, i);
540                         } else {
541                                 glColor3f(0.5, 0.5, 0.5);
542                         }
543                         Vec3 v = head_xform * vrhand[i].pos;
544                         Vec3 dir = head_dir_xform * rotate(Vec3(0, 0, -1), vrhand[i].rot) * 20.0f;
545                         Vec3 up = head_dir_xform * rotate(Vec3(0, 1, 0), vrhand[i].rot) * 10.0f;
546                         Vec3 right = head_dir_xform * rotate(Vec3(1, 0, 0), vrhand[i].rot) * 10.0f;
547
548                         glVertex3f(v.x, v.y, v.z);
549                         glVertex3f(v.x + dir.x, v.y + dir.y, v.z + dir.z);
550                         glVertex3f(v.x - right.x, v.y - right.y, v.z - right.z);
551                         glVertex3f(v.x + right.x, v.y + right.y, v.z + right.z);
552                         glVertex3f(v.x - up.x, v.y - up.y, v.z - up.z);
553                         glVertex3f(v.x + up.x, v.y + up.y, v.z + up.z);
554                 }
555                 glEnd();
556                 glPopAttrib();
557         }
558
559         if(debug_gui && dbg_sel_node) {
560                 AABox bvol = dbg_sel_node->get_bounds();
561                 draw_geom_object(&bvol);
562         }
563
564         if(show_walk_mesh && mscn->walk_mesh) {
565                 glPushAttrib(GL_ENABLE_BIT);
566                 glEnable(GL_BLEND);
567                 glBlendFunc(GL_ONE, GL_ONE);
568                 glEnable(GL_POLYGON_OFFSET_FILL);
569
570                 glUseProgram(0);
571
572                 glPolygonOffset(-1, 1);
573                 glDepthMask(0);
574
575                 glColor3f(0.3, 0.08, 0.01);
576                 mscn->walk_mesh->draw();
577
578                 glDepthMask(1);
579
580                 glPopAttrib();
581         }
582
583         exui_draw();
584
585         print_text(Vec2(9 * win_width / 10, 20), Vec3(1, 1, 0), "fps: %.1f", framerate);
586         draw_ui();
587 }
588
589
590 void app_reshape(int x, int y)
591 {
592         glViewport(0, 0, x, y);
593         goatvr_set_fb_size(x, y, 1.0f);
594         debug_gui_reshape(x, y);
595
596         vp_width = x;
597         vp_height = y;
598 }
599
600 void app_keyboard(int key, bool pressed)
601 {
602         unsigned int mod = app_get_modifiers();
603
604         if(debug_gui && !(pressed && (key == '`' || key == 27))) {
605                 debug_gui_key(key, pressed, mod);
606                 return; // ignore all keystrokes when GUI is visible
607         }
608
609         if(pressed) {
610                 switch(key) {
611                 case 27:
612                         app_quit();
613                         break;
614
615                 case '\n':
616                 case '\r':
617                         if(mod & MOD_ALT) {
618                                 app_toggle_fullscreen();
619                         }
620                         break;
621
622                 case '`':
623                         debug_gui = !debug_gui;
624                         show_message("debug gui %s", debug_gui ? "enabled" : "disabled");
625                         break;
626
627                 case 'm':
628                         app_toggle_grab_mouse();
629                         show_message("mouse %s", app_is_mouse_grabbed() ? "grabbed" : "released");
630                         break;
631
632                 case 'w':
633                         if(mod & MOD_CTRL) {
634                                 show_walk_mesh = !show_walk_mesh;
635                                 show_message("walk mesh: %s", show_walk_mesh ? "on" : "off");
636                         }
637                         break;
638
639                 case 'c':
640                         if(mod & MOD_CTRL) {
641                                 noclip = !noclip;
642                                 show_message(noclip ? "no clip" : "clip");
643                         }
644                         break;
645
646                 case 'f':
647                         toggle_flight();
648                         break;
649
650                 case 'p':
651                         if(mod & MOD_CTRL) {
652                                 fb_srgb = !fb_srgb;
653                                 show_message("gamma correction for non-sRGB framebuffers: %s\n", fb_srgb ? "off" : "on");
654                         }
655                         break;
656
657                 case '=':
658                         walk_speed *= 1.25;
659                         show_message("walk speed: %g", walk_speed);
660                         break;
661
662                 case '-':
663                         walk_speed *= 0.75;
664                         show_message("walk speed: %g", walk_speed);
665                         break;
666
667                 case ']':
668                         mouse_speed *= 1.2;
669                         show_message("mouse speed: %g", mouse_speed);
670                         break;
671
672                 case '[':
673                         mouse_speed *= 0.8;
674                         show_message("mouse speed: %g", mouse_speed);
675                         break;
676
677                 case 'b':
678                         show_blobs = !show_blobs;
679                         show_message("blobs: %s\n", show_blobs ? "on" : "off");
680                         break;
681
682                 case ' ':
683                         goatvr_recenter();
684                         show_message("VR recenter\n");
685                         break;
686
687                 case KEY_UP:
688                         exui_scroll(-1);
689                         break;
690
691                 case KEY_DOWN:
692                         exui_scroll(1);
693                         break;
694
695                 case KEY_LEFT:
696                         exui_change_tab(-1);
697                         break;
698
699                 case KEY_RIGHT:
700                         exui_change_tab(1);
701                         break;
702
703                 case KEY_F5:
704                 case KEY_F6:
705                 case KEY_F7:
706                 case KEY_F8:
707                         dbg_key_pending |= 1 << (key - KEY_F5);
708                         break;
709                 }
710         }
711
712         if(key < 256 && !(mod & (MOD_CTRL | MOD_ALT))) {
713                 keystate[key] = pressed;
714         }
715 }
716
717 void app_mouse_button(int bn, bool pressed, int x, int y)
718 {
719         static int press_x, press_y;
720
721         if(debug_gui) {
722                 debug_gui_mbutton(bn, pressed, x, y);
723                 return; // ignore mouse events while GUI is visible
724         }
725
726         prev_mx = x;
727         prev_my = y;
728         bnstate[bn] = pressed;
729
730         if(bn == 0) {
731                 ExSelection sel;
732                 Ray ray = calc_pick_ray(x, y);
733                 sel = exman->select(ray);
734
735                 if(pressed) {
736                         if(sel && (app_get_modifiers() & MOD_CTRL)) {
737                                 exsel_grab_mouse = sel;
738                                 Vec3 pos = sel.ex->node->get_position();
739                                 debug_log("grabbing... (%g %g %g)\n", pos.x, pos.y, pos.z);
740                                 exslot_mouse.node.set_position(pos);
741                                 exslot_mouse.node.set_rotation(sel.ex->node->get_rotation());
742                                 exslot_mouse.attach_exhibit(sel.ex, EXSLOT_ATTACH_TRANSIENT);
743                                 if(exsel_active) {
744                                         exsel_active = ExSelection::null;       // cancel active on grab
745                                 }
746                         }
747                         press_x = x;
748                         press_y = y;
749
750                 } else {
751                         if(exsel_grab_mouse) {
752                                 // cancel grab on mouse release
753                                 Exhibit *ex = exsel_grab_mouse.ex;
754                                 Vec3 pos = exslot_mouse.node.get_position();
755
756                                 debug_log("releasing at %g %g %g ...\n", pos.x, pos.y, pos.z);
757
758                                 exslot_mouse.detach_exhibit();
759
760                                 ExhibitSlot *slot = exman->nearest_empty_slot(pos, 100);
761                                 if(!slot) {
762                                         debug_log("no empty slot nearby\n");
763                                         if(ex->prev_slot && ex->prev_slot->empty()) {
764                                                 slot = ex->prev_slot;
765                                                 debug_log("using previous slot");
766                                         }
767                                 }
768
769                                 if(slot) {
770                                         slot->attach_exhibit(ex);
771                                 } else {
772                                         // nowhere to put it, so stash it for later
773                                         exslot_mouse.detach_exhibit();
774                                         exman->stash_exhibit(ex);
775                                         debug_log("no slots available, stashing\n");
776                                 }
777
778                                 exsel_grab_mouse = ExSelection::null;
779                         }
780
781                         if(abs(press_x - x) < 5 && abs(press_y - y) < 5) {
782                                 exsel_active = sel;     // select or deselect active exhibit
783                                 if(sel) {
784                                         debug_log("selecting...\n");
785                                 } else {
786                                         debug_log("deselecting...\n");
787                                 }
788                         }
789
790                         press_x = press_y = INT_MIN;
791                 }
792         }
793 }
794
795 static inline void mouse_look(float dx, float dy)
796 {
797         float scrsz = (float)win_height;
798         avatar.body_rot += dx * 512.0 / scrsz;
799         avatar.head_alt += dy * 512.0 / scrsz;
800
801         if(avatar.head_alt < -90) avatar.head_alt = -90;
802         if(avatar.head_alt > 90) avatar.head_alt = 90;
803 }
804
805 static void mouse_zoom(float dx, float dy)
806 {
807         cam_dist += dy * 0.1;
808         if(cam_dist < 0.0) cam_dist = 0.0;
809 }
810
811 void app_mouse_motion(int x, int y)
812 {
813         if(debug_gui) {
814                 debug_gui_mmotion(x, y);
815                 return; // ignore mouse events while GUI is visible
816         }
817
818         int dx = x - prev_mx;
819         int dy = y - prev_my;
820         prev_mx = x;
821         prev_my = y;
822
823         if(!dx && !dy) return;
824
825         if(exsel_grab_mouse) {
826                 Vec3 pos = exslot_mouse.node.get_node_position();
827                 Vec3 dir = transpose(view_matrix.upper3x3()) * Vec3(dx * 1.0, dy * -1.0, 0);
828
829                 exslot_mouse.node.set_position(pos + dir);
830         }
831
832         if(bnstate[2]) {
833                 mouse_look(dx, dy);
834         }
835 }
836
837 void app_mouse_delta(int dx, int dy)
838 {
839         if(bnstate[2]) {
840                 mouse_zoom(dx * mouse_speed, dy * mouse_speed);
841         } else {
842                 mouse_look(dx * mouse_speed, dy * mouse_speed);
843         }
844 }
845
846 void app_mouse_wheel(int dir)
847 {
848         if(debug_gui) {
849                 debug_gui_wheel(dir);
850         }
851 }
852
853 void app_gamepad_axis(int axis, float val)
854 {
855         switch(axis) {
856         case 0:
857                 joy_move.x = val;
858                 break;
859         case 1:
860                 joy_move.y = val;
861                 break;
862
863         case 2:
864                 joy_look.x = val;
865                 break;
866         case 3:
867                 joy_look.y = val;
868                 break;
869         }
870 }
871
872 void app_gamepad_button(int bn, bool pressed)
873 {
874         gpad_bnstate[bn] = pressed;
875
876         if(pressed) {
877                 switch(bn) {
878                 case GPAD_LSTICK:
879                         toggle_flight();
880                         break;
881
882                 case GPAD_X:
883                         show_blobs = !show_blobs;
884                         show_message("blobs: %s\n", show_blobs ? "on" : "off");
885                         break;
886
887                 case GPAD_START:
888                         goatvr_recenter();
889                         show_message("VR recenter\n");
890                         break;
891
892                 default:
893                         break;
894                 }
895         }
896 }
897
898 static void toggle_flight()
899 {
900         static float prev_walk_speed = -1.0;
901         if(prev_walk_speed < 0.0) {
902                 noclip = true;
903                 prev_walk_speed = walk_speed;
904                 walk_speed = 1000.0;
905                 show_message("fly mode\n");
906         } else {
907                 noclip = false;
908                 walk_speed = prev_walk_speed;
909                 prev_walk_speed = -1.0;
910                 show_message("walk mode\n");
911         }
912 }
913
914 static void calc_framerate()
915 {
916         //static int ncalc;
917         static int nframes;
918         static long prev_upd;
919
920         long elapsed = time_msec - prev_upd;
921         if(elapsed >= 1000) {
922                 framerate = (float)nframes / (float)(elapsed * 0.001);
923                 nframes = 1;
924                 prev_upd = time_msec;
925
926                 /*if(++ncalc >= 5) {
927                         printf("fps: %f\n", framerate);
928                         ncalc = 0;
929                 }*/
930         } else {
931                 ++nframes;
932         }
933 }
934
935 static Ray calc_pick_ray(int x, int y)
936 {
937         float nx = (float)x / (float)win_width;
938         float ny = (float)(win_height - y) / (float)win_height;
939
940         last_pick_ray = mouse_pick_ray(nx, ny, view_matrix, proj_matrix);
941         return last_pick_ray;
942 }