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