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