Disable connection timeout for singleplayer and server tabs
[oweals/minetest.git] / src / game.cpp
1 /*
2 Minetest
3 Copyright (C) 2010-2013 celeron55, Perttu Ahola <celeron55@gmail.com>
4
5 This program is free software; you can redistribute it and/or modify
6 it under the terms of the GNU Lesser General Public License as published by
7 the Free Software Foundation; either version 2.1 of the License, or
8 (at your option) any later version.
9
10 This program is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13 GNU Lesser General Public License for more details.
14
15 You should have received a copy of the GNU Lesser General Public License along
16 with this program; if not, write to the Free Software Foundation, Inc.,
17 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
18 */
19
20 #include "game.h"
21
22 #include <iomanip>
23 #include "camera.h"
24 #include "client.h"
25 #include "client/tile.h"     // For TextureSource
26 #include "clientmap.h"
27 #include "clouds.h"
28 #include "config.h"
29 #include "content_cao.h"
30 #include "drawscene.h"
31 #include "event_manager.h"
32 #include "fontengine.h"
33 #include "itemdef.h"
34 #include "log.h"
35 #include "filesys.h"
36 #include "gettext.h"
37 #include "guiChatConsole.h"
38 #include "guiFormSpecMenu.h"
39 #include "guiKeyChangeMenu.h"
40 #include "guiPasswordChange.h"
41 #include "guiVolumeChange.h"
42 #include "hud.h"
43 #include "logoutputbuffer.h"
44 #include "mainmenumanager.h"
45 #include "mapblock.h"
46 #include "nodedef.h"         // Needed for determining pointing to nodes
47 #include "nodemetadata.h"
48 #include "particles.h"
49 #include "profiler.h"
50 #include "quicktune_shortcutter.h"
51 #include "server.h"
52 #include "settings.h"
53 #include "shader.h"          // For ShaderSource
54 #include "sky.h"
55 #include "subgame.h"
56 #include "tool.h"
57 #include "util/directiontables.h"
58 #include "util/pointedthing.h"
59 #include "version.h"
60
61 #include "sound.h"
62
63 #if USE_SOUND
64         #include "sound_openal.h"
65 #endif
66
67 #ifdef HAVE_TOUCHSCREENGUI
68         #include "touchscreengui.h"
69 #endif
70
71 extern Settings *g_settings;
72 extern Profiler *g_profiler;
73
74 /*
75         Text input system
76 */
77
78 struct TextDestNodeMetadata : public TextDest {
79         TextDestNodeMetadata(v3s16 p, Client *client)
80         {
81                 m_p = p;
82                 m_client = client;
83         }
84         // This is deprecated I guess? -celeron55
85         void gotText(std::wstring text)
86         {
87                 std::string ntext = wide_to_narrow(text);
88                 infostream << "Submitting 'text' field of node at (" << m_p.X << ","
89                            << m_p.Y << "," << m_p.Z << "): " << ntext << std::endl;
90                 std::map<std::string, std::string> fields;
91                 fields["text"] = ntext;
92                 m_client->sendNodemetaFields(m_p, "", fields);
93         }
94         void gotText(std::map<std::string, std::string> fields)
95         {
96                 m_client->sendNodemetaFields(m_p, "", fields);
97         }
98
99         v3s16 m_p;
100         Client *m_client;
101 };
102
103 struct TextDestPlayerInventory : public TextDest {
104         TextDestPlayerInventory(Client *client)
105         {
106                 m_client = client;
107                 m_formname = "";
108         }
109         TextDestPlayerInventory(Client *client, std::string formname)
110         {
111                 m_client = client;
112                 m_formname = formname;
113         }
114         void gotText(std::map<std::string, std::string> fields)
115         {
116                 m_client->sendInventoryFields(m_formname, fields);
117         }
118
119         Client *m_client;
120 };
121
122 struct LocalFormspecHandler : public TextDest {
123         LocalFormspecHandler();
124         LocalFormspecHandler(std::string formname) :
125                 m_client(0)
126         {
127                 m_formname = formname;
128         }
129
130         LocalFormspecHandler(std::string formname, Client *client) :
131                 m_client(client)
132         {
133                 m_formname = formname;
134         }
135
136         void gotText(std::wstring message)
137         {
138                 errorstream << "LocalFormspecHandler::gotText old style message received" << std::endl;
139         }
140
141         void gotText(std::map<std::string, std::string> fields)
142         {
143                 if (m_formname == "MT_PAUSE_MENU") {
144                         if (fields.find("btn_sound") != fields.end()) {
145                                 g_gamecallback->changeVolume();
146                                 return;
147                         }
148
149                         if (fields.find("btn_key_config") != fields.end()) {
150                                 g_gamecallback->keyConfig();
151                                 return;
152                         }
153
154                         if (fields.find("btn_exit_menu") != fields.end()) {
155                                 g_gamecallback->disconnect();
156                                 return;
157                         }
158
159                         if (fields.find("btn_exit_os") != fields.end()) {
160                                 g_gamecallback->exitToOS();
161                                 return;
162                         }
163
164                         if (fields.find("btn_change_password") != fields.end()) {
165                                 g_gamecallback->changePassword();
166                                 return;
167                         }
168
169                         if (fields.find("quit") != fields.end()) {
170                                 return;
171                         }
172
173                         if (fields.find("btn_continue") != fields.end()) {
174                                 return;
175                         }
176                 }
177
178                 if (m_formname == "MT_CHAT_MENU") {
179                         assert(m_client != 0);
180
181                         if ((fields.find("btn_send") != fields.end()) ||
182                                         (fields.find("quit") != fields.end())) {
183                                 if (fields.find("f_text") != fields.end()) {
184                                         m_client->typeChatMessage(narrow_to_wide(fields["f_text"]));
185                                 }
186
187                                 return;
188                         }
189                 }
190
191                 if (m_formname == "MT_DEATH_SCREEN") {
192                         assert(m_client != 0);
193
194                         if ((fields.find("btn_respawn") != fields.end())) {
195                                 m_client->sendRespawn();
196                                 return;
197                         }
198
199                         if (fields.find("quit") != fields.end()) {
200                                 m_client->sendRespawn();
201                                 return;
202                         }
203                 }
204
205                 // don't show error message for unhandled cursor keys
206                 if ((fields.find("key_up") != fields.end()) ||
207                                 (fields.find("key_down") != fields.end()) ||
208                                 (fields.find("key_left") != fields.end()) ||
209                                 (fields.find("key_right") != fields.end())) {
210                         return;
211                 }
212
213                 errorstream << "LocalFormspecHandler::gotText unhandled >" << m_formname << "< event" << std::endl;
214                 int i = 0;
215
216                 for (std::map<std::string, std::string>::iterator iter = fields.begin();
217                                 iter != fields.end(); iter++) {
218                         errorstream << "\t" << i << ": " << iter->first << "=" << iter->second << std::endl;
219                         i++;
220                 }
221         }
222
223         Client *m_client;
224 };
225
226 /* Form update callback */
227
228 class NodeMetadataFormSource: public IFormSource
229 {
230 public:
231         NodeMetadataFormSource(ClientMap *map, v3s16 p):
232                 m_map(map),
233                 m_p(p)
234         {
235         }
236         std::string getForm()
237         {
238                 NodeMetadata *meta = m_map->getNodeMetadata(m_p);
239
240                 if (!meta)
241                         return "";
242
243                 return meta->getString("formspec");
244         }
245         std::string resolveText(std::string str)
246         {
247                 NodeMetadata *meta = m_map->getNodeMetadata(m_p);
248
249                 if (!meta)
250                         return str;
251
252                 return meta->resolveString(str);
253         }
254
255         ClientMap *m_map;
256         v3s16 m_p;
257 };
258
259 class PlayerInventoryFormSource: public IFormSource
260 {
261 public:
262         PlayerInventoryFormSource(Client *client):
263                 m_client(client)
264         {
265         }
266         std::string getForm()
267         {
268                 LocalPlayer *player = m_client->getEnv().getLocalPlayer();
269                 return player->inventory_formspec;
270         }
271
272         Client *m_client;
273 };
274
275 /*
276         Check if a node is pointable
277 */
278 inline bool isPointableNode(const MapNode &n,
279                             Client *client, bool liquids_pointable)
280 {
281         const ContentFeatures &features = client->getNodeDefManager()->get(n);
282         return features.pointable ||
283                (liquids_pointable && features.isLiquid());
284 }
285
286 /*
287         Find what the player is pointing at
288 */
289 PointedThing getPointedThing(Client *client, v3f player_position,
290                 v3f camera_direction, v3f camera_position, core::line3d<f32> shootline,
291                 f32 d, bool liquids_pointable, bool look_for_object, v3s16 camera_offset,
292                 std::vector<aabb3f> &hilightboxes, ClientActiveObject *&selected_object)
293 {
294         PointedThing result;
295
296         hilightboxes.clear();
297         selected_object = NULL;
298
299         INodeDefManager *nodedef = client->getNodeDefManager();
300         ClientMap &map = client->getEnv().getClientMap();
301
302         f32 mindistance = BS * 1001;
303
304         // First try to find a pointed at active object
305         if (look_for_object) {
306                 selected_object = client->getSelectedActiveObject(d * BS,
307                                   camera_position, shootline);
308
309                 if (selected_object != NULL) {
310                         if (selected_object->doShowSelectionBox()) {
311                                 aabb3f *selection_box = selected_object->getSelectionBox();
312                                 // Box should exist because object was
313                                 // returned in the first place
314                                 assert(selection_box);
315
316                                 v3f pos = selected_object->getPosition();
317                                 hilightboxes.push_back(aabb3f(
318                                                                selection_box->MinEdge + pos - intToFloat(camera_offset, BS),
319                                                                selection_box->MaxEdge + pos - intToFloat(camera_offset, BS)));
320                         }
321
322                         mindistance = (selected_object->getPosition() - camera_position).getLength();
323
324                         result.type = POINTEDTHING_OBJECT;
325                         result.object_id = selected_object->getId();
326                 }
327         }
328
329         // That didn't work, try to find a pointed at node
330
331
332         v3s16 pos_i = floatToInt(player_position, BS);
333
334         /*infostream<<"pos_i=("<<pos_i.X<<","<<pos_i.Y<<","<<pos_i.Z<<")"
335                         <<std::endl;*/
336
337         s16 a = d;
338         s16 ystart = pos_i.Y + 0 - (camera_direction.Y < 0 ? a : 1);
339         s16 zstart = pos_i.Z - (camera_direction.Z < 0 ? a : 1);
340         s16 xstart = pos_i.X - (camera_direction.X < 0 ? a : 1);
341         s16 yend = pos_i.Y + 1 + (camera_direction.Y > 0 ? a : 1);
342         s16 zend = pos_i.Z + (camera_direction.Z > 0 ? a : 1);
343         s16 xend = pos_i.X + (camera_direction.X > 0 ? a : 1);
344
345         // Prevent signed number overflow
346         if (yend == 32767)
347                 yend = 32766;
348
349         if (zend == 32767)
350                 zend = 32766;
351
352         if (xend == 32767)
353                 xend = 32766;
354
355         for (s16 y = ystart; y <= yend; y++)
356                 for (s16 z = zstart; z <= zend; z++)
357                         for (s16 x = xstart; x <= xend; x++) {
358                                 MapNode n;
359                                 bool is_valid_position;
360
361                                 n = map.getNodeNoEx(v3s16(x, y, z), &is_valid_position);
362                                 if (!is_valid_position)
363                                         continue;
364
365                                 if (!isPointableNode(n, client, liquids_pointable))
366                                         continue;
367
368                                 std::vector<aabb3f> boxes = n.getSelectionBoxes(nodedef);
369
370                                 v3s16 np(x, y, z);
371                                 v3f npf = intToFloat(np, BS);
372
373                                 for (std::vector<aabb3f>::const_iterator
374                                                 i = boxes.begin();
375                                                 i != boxes.end(); i++) {
376                                         aabb3f box = *i;
377                                         box.MinEdge += npf;
378                                         box.MaxEdge += npf;
379
380                                         for (u16 j = 0; j < 6; j++) {
381                                                 v3s16 facedir = g_6dirs[j];
382                                                 aabb3f facebox = box;
383
384                                                 f32 d = 0.001 * BS;
385
386                                                 if (facedir.X > 0)
387                                                         facebox.MinEdge.X = facebox.MaxEdge.X - d;
388                                                 else if (facedir.X < 0)
389                                                         facebox.MaxEdge.X = facebox.MinEdge.X + d;
390                                                 else if (facedir.Y > 0)
391                                                         facebox.MinEdge.Y = facebox.MaxEdge.Y - d;
392                                                 else if (facedir.Y < 0)
393                                                         facebox.MaxEdge.Y = facebox.MinEdge.Y + d;
394                                                 else if (facedir.Z > 0)
395                                                         facebox.MinEdge.Z = facebox.MaxEdge.Z - d;
396                                                 else if (facedir.Z < 0)
397                                                         facebox.MaxEdge.Z = facebox.MinEdge.Z + d;
398
399                                                 v3f centerpoint = facebox.getCenter();
400                                                 f32 distance = (centerpoint - camera_position).getLength();
401
402                                                 if (distance >= mindistance)
403                                                         continue;
404
405                                                 if (!facebox.intersectsWithLine(shootline))
406                                                         continue;
407
408                                                 v3s16 np_above = np + facedir;
409
410                                                 result.type = POINTEDTHING_NODE;
411                                                 result.node_undersurface = np;
412                                                 result.node_abovesurface = np_above;
413                                                 mindistance = distance;
414
415                                                 hilightboxes.clear();
416
417                                                 if (!g_settings->getBool("enable_node_highlighting")) {
418                                                         for (std::vector<aabb3f>::const_iterator
419                                                                         i2 = boxes.begin();
420                                                                         i2 != boxes.end(); i2++) {
421                                                                 aabb3f box = *i2;
422                                                                 box.MinEdge += npf + v3f(-d, -d, -d) - intToFloat(camera_offset, BS);
423                                                                 box.MaxEdge += npf + v3f(d, d, d) - intToFloat(camera_offset, BS);
424                                                                 hilightboxes.push_back(box);
425                                                         }
426                                                 }
427                                         }
428                                 }
429                         } // for coords
430
431         return result;
432 }
433
434 /* Profiler display */
435
436 void update_profiler_gui(gui::IGUIStaticText *guitext_profiler, FontEngine *fe,
437                 u32 show_profiler, u32 show_profiler_max, s32 screen_height)
438 {
439         if (show_profiler == 0) {
440                 guitext_profiler->setVisible(false);
441         } else {
442
443                 std::ostringstream os(std::ios_base::binary);
444                 g_profiler->printPage(os, show_profiler, show_profiler_max);
445                 std::wstring text = narrow_to_wide(os.str());
446                 guitext_profiler->setText(text.c_str());
447                 guitext_profiler->setVisible(true);
448
449                 s32 w = fe->getTextWidth(text.c_str());
450
451                 if (w < 400)
452                         w = 400;
453
454                 unsigned text_height = fe->getTextHeight();
455
456                 core::position2di upper_left, lower_right;
457
458                 upper_left.X  = 6;
459                 upper_left.Y  = (text_height + 5) * 2;
460                 lower_right.X = 12 + w;
461                 lower_right.Y = upper_left.Y + (text_height + 1) * MAX_PROFILER_TEXT_ROWS;
462
463                 if (lower_right.Y > screen_height * 2 / 3)
464                         lower_right.Y = screen_height * 2 / 3;
465
466                 core::rect<s32> rect(upper_left, lower_right);
467
468                 guitext_profiler->setRelativePosition(rect);
469                 guitext_profiler->setVisible(true);
470         }
471 }
472
473 class ProfilerGraph
474 {
475 private:
476         struct Piece {
477                 Profiler::GraphValues values;
478         };
479         struct Meta {
480                 float min;
481                 float max;
482                 video::SColor color;
483                 Meta(float initial = 0,
484                         video::SColor color = video::SColor(255, 255, 255, 255)):
485                         min(initial),
486                         max(initial),
487                         color(color)
488                 {}
489         };
490         std::vector<Piece> m_log;
491 public:
492         u32 m_log_max_size;
493
494         ProfilerGraph():
495                 m_log_max_size(200)
496         {}
497
498         void put(const Profiler::GraphValues &values)
499         {
500                 Piece piece;
501                 piece.values = values;
502                 m_log.push_back(piece);
503
504                 while (m_log.size() > m_log_max_size)
505                         m_log.erase(m_log.begin());
506         }
507
508         void draw(s32 x_left, s32 y_bottom, video::IVideoDriver *driver,
509                   gui::IGUIFont *font) const
510         {
511                 std::map<std::string, Meta> m_meta;
512
513                 for (std::vector<Piece>::const_iterator k = m_log.begin();
514                                 k != m_log.end(); k++) {
515                         const Piece &piece = *k;
516
517                         for (Profiler::GraphValues::const_iterator i = piece.values.begin();
518                                         i != piece.values.end(); i++) {
519                                 const std::string &id = i->first;
520                                 const float &value = i->second;
521                                 std::map<std::string, Meta>::iterator j =
522                                         m_meta.find(id);
523
524                                 if (j == m_meta.end()) {
525                                         m_meta[id] = Meta(value);
526                                         continue;
527                                 }
528
529                                 if (value < j->second.min)
530                                         j->second.min = value;
531
532                                 if (value > j->second.max)
533                                         j->second.max = value;
534                         }
535                 }
536
537                 // Assign colors
538                 static const video::SColor usable_colors[] = {
539                         video::SColor(255, 255, 100, 100),
540                         video::SColor(255, 90, 225, 90),
541                         video::SColor(255, 100, 100, 255),
542                         video::SColor(255, 255, 150, 50),
543                         video::SColor(255, 220, 220, 100)
544                 };
545                 static const u32 usable_colors_count =
546                         sizeof(usable_colors) / sizeof(*usable_colors);
547                 u32 next_color_i = 0;
548
549                 for (std::map<std::string, Meta>::iterator i = m_meta.begin();
550                                 i != m_meta.end(); i++) {
551                         Meta &meta = i->second;
552                         video::SColor color(255, 200, 200, 200);
553
554                         if (next_color_i < usable_colors_count)
555                                 color = usable_colors[next_color_i++];
556
557                         meta.color = color;
558                 }
559
560                 s32 graphh = 50;
561                 s32 textx = x_left + m_log_max_size + 15;
562                 s32 textx2 = textx + 200 - 15;
563                 s32 meta_i = 0;
564
565                 for (std::map<std::string, Meta>::const_iterator i = m_meta.begin();
566                                 i != m_meta.end(); i++) {
567                         const std::string &id = i->first;
568                         const Meta &meta = i->second;
569                         s32 x = x_left;
570                         s32 y = y_bottom - meta_i * 50;
571                         float show_min = meta.min;
572                         float show_max = meta.max;
573
574                         if (show_min >= -0.0001 && show_max >= -0.0001) {
575                                 if (show_min <= show_max * 0.5)
576                                         show_min = 0;
577                         }
578
579                         s32 texth = 15;
580                         char buf[10];
581                         snprintf(buf, 10, "%.3g", show_max);
582                         font->draw(narrow_to_wide(buf).c_str(),
583                                         core::rect<s32>(textx, y - graphh,
584                                                    textx2, y - graphh + texth),
585                                         meta.color);
586                         snprintf(buf, 10, "%.3g", show_min);
587                         font->draw(narrow_to_wide(buf).c_str(),
588                                         core::rect<s32>(textx, y - texth,
589                                                    textx2, y),
590                                         meta.color);
591                         font->draw(narrow_to_wide(id).c_str(),
592                                         core::rect<s32>(textx, y - graphh / 2 - texth / 2,
593                                                    textx2, y - graphh / 2 + texth / 2),
594                                         meta.color);
595                         s32 graph1y = y;
596                         s32 graph1h = graphh;
597                         bool relativegraph = (show_min != 0 && show_min != show_max);
598                         float lastscaledvalue = 0.0;
599                         bool lastscaledvalue_exists = false;
600
601                         for (std::vector<Piece>::const_iterator j = m_log.begin();
602                                         j != m_log.end(); j++) {
603                                 const Piece &piece = *j;
604                                 float value = 0;
605                                 bool value_exists = false;
606                                 Profiler::GraphValues::const_iterator k =
607                                         piece.values.find(id);
608
609                                 if (k != piece.values.end()) {
610                                         value = k->second;
611                                         value_exists = true;
612                                 }
613
614                                 if (!value_exists) {
615                                         x++;
616                                         lastscaledvalue_exists = false;
617                                         continue;
618                                 }
619
620                                 float scaledvalue = 1.0;
621
622                                 if (show_max != show_min)
623                                         scaledvalue = (value - show_min) / (show_max - show_min);
624
625                                 if (scaledvalue == 1.0 && value == 0) {
626                                         x++;
627                                         lastscaledvalue_exists = false;
628                                         continue;
629                                 }
630
631                                 if (relativegraph) {
632                                         if (lastscaledvalue_exists) {
633                                                 s32 ivalue1 = lastscaledvalue * graph1h;
634                                                 s32 ivalue2 = scaledvalue * graph1h;
635                                                 driver->draw2DLine(v2s32(x - 1, graph1y - ivalue1),
636                                                                    v2s32(x, graph1y - ivalue2), meta.color);
637                                         }
638
639                                         lastscaledvalue = scaledvalue;
640                                         lastscaledvalue_exists = true;
641                                 } else {
642                                         s32 ivalue = scaledvalue * graph1h;
643                                         driver->draw2DLine(v2s32(x, graph1y),
644                                                            v2s32(x, graph1y - ivalue), meta.color);
645                                 }
646
647                                 x++;
648                         }
649
650                         meta_i++;
651                 }
652         }
653 };
654
655 class NodeDugEvent: public MtEvent
656 {
657 public:
658         v3s16 p;
659         MapNode n;
660
661         NodeDugEvent(v3s16 p, MapNode n):
662                 p(p),
663                 n(n)
664         {}
665         const char *getType() const
666         {
667                 return "NodeDug";
668         }
669 };
670
671 class SoundMaker
672 {
673         ISoundManager *m_sound;
674         INodeDefManager *m_ndef;
675 public:
676         float m_player_step_timer;
677
678         SimpleSoundSpec m_player_step_sound;
679         SimpleSoundSpec m_player_leftpunch_sound;
680         SimpleSoundSpec m_player_rightpunch_sound;
681
682         SoundMaker(ISoundManager *sound, INodeDefManager *ndef):
683                 m_sound(sound),
684                 m_ndef(ndef),
685                 m_player_step_timer(0)
686         {
687         }
688
689         void playPlayerStep()
690         {
691                 if (m_player_step_timer <= 0 && m_player_step_sound.exists()) {
692                         m_player_step_timer = 0.03;
693                         m_sound->playSound(m_player_step_sound, false);
694                 }
695         }
696
697         static void viewBobbingStep(MtEvent *e, void *data)
698         {
699                 SoundMaker *sm = (SoundMaker *)data;
700                 sm->playPlayerStep();
701         }
702
703         static void playerRegainGround(MtEvent *e, void *data)
704         {
705                 SoundMaker *sm = (SoundMaker *)data;
706                 sm->playPlayerStep();
707         }
708
709         static void playerJump(MtEvent *e, void *data)
710         {
711                 //SoundMaker *sm = (SoundMaker*)data;
712         }
713
714         static void cameraPunchLeft(MtEvent *e, void *data)
715         {
716                 SoundMaker *sm = (SoundMaker *)data;
717                 sm->m_sound->playSound(sm->m_player_leftpunch_sound, false);
718         }
719
720         static void cameraPunchRight(MtEvent *e, void *data)
721         {
722                 SoundMaker *sm = (SoundMaker *)data;
723                 sm->m_sound->playSound(sm->m_player_rightpunch_sound, false);
724         }
725
726         static void nodeDug(MtEvent *e, void *data)
727         {
728                 SoundMaker *sm = (SoundMaker *)data;
729                 NodeDugEvent *nde = (NodeDugEvent *)e;
730                 sm->m_sound->playSound(sm->m_ndef->get(nde->n).sound_dug, false);
731         }
732
733         static void playerDamage(MtEvent *e, void *data)
734         {
735                 SoundMaker *sm = (SoundMaker *)data;
736                 sm->m_sound->playSound(SimpleSoundSpec("player_damage", 0.5), false);
737         }
738
739         static void playerFallingDamage(MtEvent *e, void *data)
740         {
741                 SoundMaker *sm = (SoundMaker *)data;
742                 sm->m_sound->playSound(SimpleSoundSpec("player_falling_damage", 0.5), false);
743         }
744
745         void registerReceiver(MtEventManager *mgr)
746         {
747                 mgr->reg("ViewBobbingStep", SoundMaker::viewBobbingStep, this);
748                 mgr->reg("PlayerRegainGround", SoundMaker::playerRegainGround, this);
749                 mgr->reg("PlayerJump", SoundMaker::playerJump, this);
750                 mgr->reg("CameraPunchLeft", SoundMaker::cameraPunchLeft, this);
751                 mgr->reg("CameraPunchRight", SoundMaker::cameraPunchRight, this);
752                 mgr->reg("NodeDug", SoundMaker::nodeDug, this);
753                 mgr->reg("PlayerDamage", SoundMaker::playerDamage, this);
754                 mgr->reg("PlayerFallingDamage", SoundMaker::playerFallingDamage, this);
755         }
756
757         void step(float dtime)
758         {
759                 m_player_step_timer -= dtime;
760         }
761 };
762
763 // Locally stored sounds don't need to be preloaded because of this
764 class GameOnDemandSoundFetcher: public OnDemandSoundFetcher
765 {
766         std::set<std::string> m_fetched;
767 public:
768         void fetchSounds(const std::string &name,
769                         std::set<std::string> &dst_paths,
770                         std::set<std::string> &dst_datas)
771         {
772                 if (m_fetched.count(name))
773                         return;
774
775                 m_fetched.insert(name);
776                 std::string base = porting::path_share + DIR_DELIM + "testsounds";
777                 dst_paths.insert(base + DIR_DELIM + name + ".ogg");
778                 dst_paths.insert(base + DIR_DELIM + name + ".0.ogg");
779                 dst_paths.insert(base + DIR_DELIM + name + ".1.ogg");
780                 dst_paths.insert(base + DIR_DELIM + name + ".2.ogg");
781                 dst_paths.insert(base + DIR_DELIM + name + ".3.ogg");
782                 dst_paths.insert(base + DIR_DELIM + name + ".4.ogg");
783                 dst_paths.insert(base + DIR_DELIM + name + ".5.ogg");
784                 dst_paths.insert(base + DIR_DELIM + name + ".6.ogg");
785                 dst_paths.insert(base + DIR_DELIM + name + ".7.ogg");
786                 dst_paths.insert(base + DIR_DELIM + name + ".8.ogg");
787                 dst_paths.insert(base + DIR_DELIM + name + ".9.ogg");
788         }
789 };
790
791 class GameGlobalShaderConstantSetter : public IShaderConstantSetter
792 {
793         Sky *m_sky;
794         bool *m_force_fog_off;
795         f32 *m_fog_range;
796         Client *m_client;
797         bool m_fogEnabled;
798
799 public:
800         void onSettingsChange(const std::string &name)
801         {
802                 if (name == "enable_fog")
803                         m_fogEnabled = g_settings->getBool("enable_fog");
804         }
805
806         static void SettingsCallback(const std::string name, void *userdata)
807         {
808                 reinterpret_cast<GameGlobalShaderConstantSetter*>(userdata)->onSettingsChange(name);
809         }
810
811         GameGlobalShaderConstantSetter(Sky *sky, bool *force_fog_off,
812                         f32 *fog_range, Client *client) :
813                 m_sky(sky),
814                 m_force_fog_off(force_fog_off),
815                 m_fog_range(fog_range),
816                 m_client(client)
817         {
818                 g_settings->registerChangedCallback("enable_fog", SettingsCallback, this);
819                 m_fogEnabled = g_settings->getBool("enable_fog");
820         }
821
822         ~GameGlobalShaderConstantSetter()
823         {
824                 g_settings->deregisterChangedCallback("enable_fog", SettingsCallback, this);
825         }
826
827         virtual void onSetConstants(video::IMaterialRendererServices *services,
828                         bool is_highlevel)
829         {
830                 if (!is_highlevel)
831                         return;
832
833                 // Background color
834                 video::SColor bgcolor = m_sky->getBgColor();
835                 video::SColorf bgcolorf(bgcolor);
836                 float bgcolorfa[4] = {
837                         bgcolorf.r,
838                         bgcolorf.g,
839                         bgcolorf.b,
840                         bgcolorf.a,
841                 };
842                 services->setPixelShaderConstant("skyBgColor", bgcolorfa, 4);
843
844                 // Fog distance
845                 float fog_distance = 10000 * BS;
846
847                 if (m_fogEnabled && !*m_force_fog_off)
848                         fog_distance = *m_fog_range;
849
850                 services->setPixelShaderConstant("fogDistance", &fog_distance, 1);
851
852                 // Day-night ratio
853                 u32 daynight_ratio = m_client->getEnv().getDayNightRatio();
854                 float daynight_ratio_f = (float)daynight_ratio / 1000.0;
855                 services->setPixelShaderConstant("dayNightRatio", &daynight_ratio_f, 1);
856
857                 u32 animation_timer = porting::getTimeMs() % 100000;
858                 float animation_timer_f = (float)animation_timer / 100000.0;
859                 services->setPixelShaderConstant("animationTimer", &animation_timer_f, 1);
860                 services->setVertexShaderConstant("animationTimer", &animation_timer_f, 1);
861
862                 LocalPlayer *player = m_client->getEnv().getLocalPlayer();
863                 v3f eye_position = player->getEyePosition();
864                 services->setPixelShaderConstant("eyePosition", (irr::f32 *)&eye_position, 3);
865                 services->setVertexShaderConstant("eyePosition", (irr::f32 *)&eye_position, 3);
866
867                 // Uniform sampler layers
868                 int layer0 = 0;
869                 int layer1 = 1;
870                 int layer2 = 2;
871                 // before 1.8 there isn't a "integer interface", only float
872 #if (IRRLICHT_VERSION_MAJOR == 1 && IRRLICHT_VERSION_MINOR < 8)
873                 services->setPixelShaderConstant("baseTexture" , (irr::f32 *)&layer0, 1);
874                 services->setPixelShaderConstant("normalTexture" , (irr::f32 *)&layer1, 1);
875                 services->setPixelShaderConstant("useNormalmap" , (irr::f32 *)&layer2, 1);
876 #else
877                 services->setPixelShaderConstant("baseTexture" , (irr::s32 *)&layer0, 1);
878                 services->setPixelShaderConstant("normalTexture" , (irr::s32 *)&layer1, 1);
879                 services->setPixelShaderConstant("useNormalmap" , (irr::s32 *)&layer2, 1);
880 #endif
881         }
882 };
883
884 bool nodePlacementPrediction(Client &client,
885                 const ItemDefinition &playeritem_def, v3s16 nodepos, v3s16 neighbourpos)
886 {
887         std::string prediction = playeritem_def.node_placement_prediction;
888         INodeDefManager *nodedef = client.ndef();
889         ClientMap &map = client.getEnv().getClientMap();
890         MapNode node;
891         bool is_valid_position;
892
893         node = map.getNodeNoEx(nodepos, &is_valid_position);
894         if (!is_valid_position)
895                 return false;
896
897         if (prediction != "" && !nodedef->get(node).rightclickable) {
898                 verbosestream << "Node placement prediction for "
899                               << playeritem_def.name << " is "
900                               << prediction << std::endl;
901                 v3s16 p = neighbourpos;
902
903                 // Place inside node itself if buildable_to
904                 MapNode n_under = map.getNodeNoEx(nodepos, &is_valid_position);
905                 if (is_valid_position)
906                 {
907                         if (nodedef->get(n_under).buildable_to)
908                                 p = nodepos;
909                         else {
910                                 node = map.getNodeNoEx(p, &is_valid_position);
911                                 if (is_valid_position &&!nodedef->get(node).buildable_to)
912                                         return false;
913                         }
914                 }
915
916                 // Find id of predicted node
917                 content_t id;
918                 bool found = nodedef->getId(prediction, id);
919
920                 if (!found) {
921                         errorstream << "Node placement prediction failed for "
922                                     << playeritem_def.name << " (places "
923                                     << prediction
924                                     << ") - Name not known" << std::endl;
925                         return false;
926                 }
927
928                 // Predict param2 for facedir and wallmounted nodes
929                 u8 param2 = 0;
930
931                 if (nodedef->get(id).param_type_2 == CPT2_WALLMOUNTED) {
932                         v3s16 dir = nodepos - neighbourpos;
933
934                         if (abs(dir.Y) > MYMAX(abs(dir.X), abs(dir.Z))) {
935                                 param2 = dir.Y < 0 ? 1 : 0;
936                         } else if (abs(dir.X) > abs(dir.Z)) {
937                                 param2 = dir.X < 0 ? 3 : 2;
938                         } else {
939                                 param2 = dir.Z < 0 ? 5 : 4;
940                         }
941                 }
942
943                 if (nodedef->get(id).param_type_2 == CPT2_FACEDIR) {
944                         v3s16 dir = nodepos - floatToInt(client.getEnv().getLocalPlayer()->getPosition(), BS);
945
946                         if (abs(dir.X) > abs(dir.Z)) {
947                                 param2 = dir.X < 0 ? 3 : 1;
948                         } else {
949                                 param2 = dir.Z < 0 ? 2 : 0;
950                         }
951                 }
952
953                 assert(param2 <= 5);
954
955                 //Check attachment if node is in group attached_node
956                 if (((ItemGroupList) nodedef->get(id).groups)["attached_node"] != 0) {
957                         static v3s16 wallmounted_dirs[8] = {
958                                 v3s16(0, 1, 0),
959                                 v3s16(0, -1, 0),
960                                 v3s16(1, 0, 0),
961                                 v3s16(-1, 0, 0),
962                                 v3s16(0, 0, 1),
963                                 v3s16(0, 0, -1),
964                         };
965                         v3s16 pp;
966
967                         if (nodedef->get(id).param_type_2 == CPT2_WALLMOUNTED)
968                                 pp = p + wallmounted_dirs[param2];
969                         else
970                                 pp = p + v3s16(0, -1, 0);
971
972                         if (!nodedef->get(map.getNodeNoEx(pp)).walkable)
973                                 return false;
974                 }
975
976                 // Add node to client map
977                 MapNode n(id, 0, param2);
978
979                 try {
980                         LocalPlayer *player = client.getEnv().getLocalPlayer();
981
982                         // Dont place node when player would be inside new node
983                         // NOTE: This is to be eventually implemented by a mod as client-side Lua
984                         if (!nodedef->get(n).walkable ||
985                                         g_settings->getBool("enable_build_where_you_stand") ||
986                                         (client.checkPrivilege("noclip") && g_settings->getBool("noclip")) ||
987                                         (nodedef->get(n).walkable &&
988                                          neighbourpos != player->getStandingNodePos() + v3s16(0, 1, 0) &&
989                                          neighbourpos != player->getStandingNodePos() + v3s16(0, 2, 0))) {
990
991                                 // This triggers the required mesh update too
992                                 client.addNode(p, n);
993                                 return true;
994                         }
995                 } catch (InvalidPositionException &e) {
996                         errorstream << "Node placement prediction failed for "
997                                     << playeritem_def.name << " (places "
998                                     << prediction
999                                     << ") - Position not loaded" << std::endl;
1000                 }
1001         }
1002
1003         return false;
1004 }
1005
1006 static inline void create_formspec_menu(GUIFormSpecMenu **cur_formspec,
1007                 InventoryManager *invmgr, IGameDef *gamedef,
1008                 IWritableTextureSource *tsrc, IrrlichtDevice *device,
1009                 IFormSource *fs_src, TextDest *txt_dest, Client *client)
1010 {
1011
1012         if (*cur_formspec == 0) {
1013                 *cur_formspec = new GUIFormSpecMenu(device, guiroot, -1, &g_menumgr,
1014                                                     invmgr, gamedef, tsrc, fs_src, txt_dest, client);
1015                 (*cur_formspec)->doPause = false;
1016
1017                 /*
1018                         Caution: do not call (*cur_formspec)->drop() here --
1019                         the reference might outlive the menu, so we will
1020                         periodically check if *cur_formspec is the only
1021                         remaining reference (i.e. the menu was removed)
1022                         and delete it in that case.
1023                 */
1024
1025         } else {
1026                 (*cur_formspec)->setFormSource(fs_src);
1027                 (*cur_formspec)->setTextDest(txt_dest);
1028         }
1029 }
1030
1031 #ifdef __ANDROID__
1032 #define SIZE_TAG "size[11,5.5]"
1033 #else
1034 #define SIZE_TAG "size[11,5.5,true]" // Fixed size on desktop
1035 #endif
1036
1037 static void show_chat_menu(GUIFormSpecMenu **cur_formspec,
1038                 InventoryManager *invmgr, IGameDef *gamedef,
1039                 IWritableTextureSource *tsrc, IrrlichtDevice *device,
1040                 Client *client, std::string text)
1041 {
1042         std::string formspec =
1043                 FORMSPEC_VERSION_STRING
1044                 SIZE_TAG
1045                 "field[3,2.35;6,0.5;f_text;;" + text + "]"
1046                 "button_exit[4,3;3,0.5;btn_send;" + wide_to_narrow(wstrgettext("Proceed")) + "]"
1047                 ;
1048
1049         /* Create menu */
1050         /* Note: FormspecFormSource and LocalFormspecHandler
1051          * are deleted by guiFormSpecMenu                     */
1052         FormspecFormSource *fs_src = new FormspecFormSource(formspec);
1053         LocalFormspecHandler *txt_dst = new LocalFormspecHandler("MT_CHAT_MENU", client);
1054
1055         create_formspec_menu(cur_formspec, invmgr, gamedef, tsrc, device, fs_src, txt_dst, NULL);
1056 }
1057
1058 static void show_deathscreen(GUIFormSpecMenu **cur_formspec,
1059                 InventoryManager *invmgr, IGameDef *gamedef,
1060                 IWritableTextureSource *tsrc, IrrlichtDevice *device, Client *client)
1061 {
1062         std::string formspec =
1063                 std::string(FORMSPEC_VERSION_STRING) +
1064                 SIZE_TAG
1065                 "bgcolor[#320000b4;true]"
1066                 "label[4.85,1.35;" + gettext("You died.") + "]"
1067                 "button_exit[4,3;3,0.5;btn_respawn;" + gettext("Respawn") + "]"
1068                 ;
1069
1070         /* Create menu */
1071         /* Note: FormspecFormSource and LocalFormspecHandler
1072          * are deleted by guiFormSpecMenu                     */
1073         FormspecFormSource *fs_src = new FormspecFormSource(formspec);
1074         LocalFormspecHandler *txt_dst = new LocalFormspecHandler("MT_DEATH_SCREEN", client);
1075
1076         create_formspec_menu(cur_formspec, invmgr, gamedef, tsrc, device,  fs_src, txt_dst, NULL);
1077 }
1078
1079 /******************************************************************************/
1080 static void show_pause_menu(GUIFormSpecMenu **cur_formspec,
1081                 InventoryManager *invmgr, IGameDef *gamedef,
1082                 IWritableTextureSource *tsrc, IrrlichtDevice *device,
1083                 bool singleplayermode)
1084 {
1085 #ifdef __ANDROID__
1086         std::string control_text = wide_to_narrow(wstrgettext("Default Controls:\n"
1087                                    "No menu visible:\n"
1088                                    "- single tap: button activate\n"
1089                                    "- double tap: place/use\n"
1090                                    "- slide finger: look around\n"
1091                                    "Menu/Inventory visible:\n"
1092                                    "- double tap (outside):\n"
1093                                    " -->close\n"
1094                                    "- touch stack, touch slot:\n"
1095                                    " --> move stack\n"
1096                                    "- touch&drag, tap 2nd finger\n"
1097                                    " --> place single item to slot\n"
1098                                                              ));
1099 #else
1100         std::string control_text = wide_to_narrow(wstrgettext("Default Controls:\n"
1101                                    "- WASD: move\n"
1102                                    "- Space: jump/climb\n"
1103                                    "- Shift: sneak/go down\n"
1104                                    "- Q: drop item\n"
1105                                    "- I: inventory\n"
1106                                    "- Mouse: turn/look\n"
1107                                    "- Mouse left: dig/punch\n"
1108                                    "- Mouse right: place/use\n"
1109                                    "- Mouse wheel: select item\n"
1110                                    "- T: chat\n"
1111                                                              ));
1112 #endif
1113
1114         float ypos = singleplayermode ? 0.5 : 0.1;
1115         std::ostringstream os;
1116
1117         os << FORMSPEC_VERSION_STRING  << SIZE_TAG
1118            << "button_exit[4," << (ypos++) << ";3,0.5;btn_continue;"
1119            << wide_to_narrow(wstrgettext("Continue"))     << "]";
1120
1121         if (!singleplayermode) {
1122                 os << "button_exit[4," << (ypos++) << ";3,0.5;btn_change_password;"
1123                    << wide_to_narrow(wstrgettext("Change Password")) << "]";
1124         }
1125
1126 #ifndef __ANDROID__
1127         os              << "button_exit[4," << (ypos++) << ";3,0.5;btn_sound;"
1128                         << wide_to_narrow(wstrgettext("Sound Volume")) << "]";
1129         os              << "button_exit[4," << (ypos++) << ";3,0.5;btn_key_config;"
1130                         << wide_to_narrow(wstrgettext("Change Keys"))  << "]";
1131 #endif
1132         os              << "button_exit[4," << (ypos++) << ";3,0.5;btn_exit_menu;"
1133                         << wide_to_narrow(wstrgettext("Exit to Menu")) << "]";
1134         os              << "button_exit[4," << (ypos++) << ";3,0.5;btn_exit_os;"
1135                         << wide_to_narrow(wstrgettext("Exit to OS"))   << "]"
1136                         << "textarea[7.5,0.25;3.9,6.25;;" << control_text << ";]"
1137                         << "textarea[0.4,0.25;3.5,6;;" << PROJECT_NAME "\n"
1138                         << g_build_info << "\n"
1139                         << "path_user = " << wrap_rows(porting::path_user, 20)
1140                         << "\n;]";
1141
1142         /* Create menu */
1143         /* Note: FormspecFormSource and LocalFormspecHandler  *
1144          * are deleted by guiFormSpecMenu                     */
1145         FormspecFormSource *fs_src = new FormspecFormSource(os.str());
1146         LocalFormspecHandler *txt_dst = new LocalFormspecHandler("MT_PAUSE_MENU");
1147
1148         create_formspec_menu(cur_formspec, invmgr, gamedef, tsrc, device,  fs_src, txt_dst, NULL);
1149         (*cur_formspec)->setFocus(L"btn_continue");
1150         (*cur_formspec)->doPause = true;
1151 }
1152
1153 /******************************************************************************/
1154 static void updateChat(Client &client, f32 dtime, bool show_debug,
1155                 const v2u32 &screensize, bool show_chat, u32 show_profiler,
1156                 ChatBackend &chat_backend, gui::IGUIStaticText *guitext_chat)
1157 {
1158         // Add chat log output for errors to be shown in chat
1159         static LogOutputBuffer chat_log_error_buf(LMT_ERROR);
1160
1161         // Get new messages from error log buffer
1162         while (!chat_log_error_buf.empty()) {
1163                 chat_backend.addMessage(L"", narrow_to_wide(chat_log_error_buf.get()));
1164         }
1165
1166         // Get new messages from client
1167         std::wstring message;
1168
1169         while (client.getChatMessage(message)) {
1170                 chat_backend.addUnparsedMessage(message);
1171         }
1172
1173         // Remove old messages
1174         chat_backend.step(dtime);
1175
1176         // Display all messages in a static text element
1177         unsigned int recent_chat_count = chat_backend.getRecentBuffer().getLineCount();
1178         std::wstring recent_chat       = chat_backend.getRecentChat();
1179         unsigned int line_height       = g_fontengine->getLineHeight();
1180
1181         guitext_chat->setText(recent_chat.c_str());
1182
1183         // Update gui element size and position
1184         s32 chat_y = 5 + line_height;
1185
1186         if (show_debug)
1187                 chat_y += line_height;
1188
1189         // first pass to calculate height of text to be set
1190         s32 width = std::min(g_fontengine->getTextWidth(recent_chat) + 10,
1191                              porting::getWindowSize().X - 20);
1192         core::rect<s32> rect(10, chat_y, width, chat_y + porting::getWindowSize().Y);
1193         guitext_chat->setRelativePosition(rect);
1194
1195         //now use real height of text and adjust rect according to this size
1196         rect = core::rect<s32>(10, chat_y, width,
1197                                chat_y + guitext_chat->getTextHeight());
1198
1199
1200         guitext_chat->setRelativePosition(rect);
1201         // Don't show chat if disabled or empty or profiler is enabled
1202         guitext_chat->setVisible(
1203                 show_chat && recent_chat_count != 0 && !show_profiler);
1204 }
1205
1206
1207 /****************************************************************************
1208  Fast key cache for main game loop
1209  ****************************************************************************/
1210
1211 /* This is faster than using getKeySetting with the tradeoff that functions
1212  * using it must make sure that it's initialised before using it and there is
1213  * no error handling (for example bounds checking). This is really intended for
1214  * use only in the main running loop of the client (the_game()) where the faster
1215  * (up to 10x faster) key lookup is an asset. Other parts of the codebase
1216  * (e.g. formspecs) should continue using getKeySetting().
1217  */
1218 struct KeyCache {
1219
1220         KeyCache() { populate(); }
1221
1222         enum {
1223                 // Player movement
1224                 KEYMAP_ID_FORWARD,
1225                 KEYMAP_ID_BACKWARD,
1226                 KEYMAP_ID_LEFT,
1227                 KEYMAP_ID_RIGHT,
1228                 KEYMAP_ID_JUMP,
1229                 KEYMAP_ID_SPECIAL1,
1230                 KEYMAP_ID_SNEAK,
1231
1232                 // Other
1233                 KEYMAP_ID_DROP,
1234                 KEYMAP_ID_INVENTORY,
1235                 KEYMAP_ID_CHAT,
1236                 KEYMAP_ID_CMD,
1237                 KEYMAP_ID_CONSOLE,
1238                 KEYMAP_ID_FREEMOVE,
1239                 KEYMAP_ID_FASTMOVE,
1240                 KEYMAP_ID_NOCLIP,
1241                 KEYMAP_ID_CINEMATIC,
1242                 KEYMAP_ID_SCREENSHOT,
1243                 KEYMAP_ID_TOGGLE_HUD,
1244                 KEYMAP_ID_TOGGLE_CHAT,
1245                 KEYMAP_ID_TOGGLE_FORCE_FOG_OFF,
1246                 KEYMAP_ID_TOGGLE_UPDATE_CAMERA,
1247                 KEYMAP_ID_TOGGLE_DEBUG,
1248                 KEYMAP_ID_TOGGLE_PROFILER,
1249                 KEYMAP_ID_CAMERA_MODE,
1250                 KEYMAP_ID_INCREASE_VIEWING_RANGE,
1251                 KEYMAP_ID_DECREASE_VIEWING_RANGE,
1252                 KEYMAP_ID_RANGESELECT,
1253
1254                 KEYMAP_ID_QUICKTUNE_NEXT,
1255                 KEYMAP_ID_QUICKTUNE_PREV,
1256                 KEYMAP_ID_QUICKTUNE_INC,
1257                 KEYMAP_ID_QUICKTUNE_DEC,
1258
1259                 KEYMAP_ID_DEBUG_STACKS,
1260
1261                 // Fake keycode for array size and internal checks
1262                 KEYMAP_INTERNAL_ENUM_COUNT
1263
1264
1265         };
1266
1267         void populate();
1268
1269         KeyPress key[KEYMAP_INTERNAL_ENUM_COUNT];
1270 };
1271
1272 void KeyCache::populate()
1273 {
1274         key[KEYMAP_ID_FORWARD]      = getKeySetting("keymap_forward");
1275         key[KEYMAP_ID_BACKWARD]     = getKeySetting("keymap_backward");
1276         key[KEYMAP_ID_LEFT]         = getKeySetting("keymap_left");
1277         key[KEYMAP_ID_RIGHT]        = getKeySetting("keymap_right");
1278         key[KEYMAP_ID_JUMP]         = getKeySetting("keymap_jump");
1279         key[KEYMAP_ID_SPECIAL1]     = getKeySetting("keymap_special1");
1280         key[KEYMAP_ID_SNEAK]        = getKeySetting("keymap_sneak");
1281
1282         key[KEYMAP_ID_DROP]         = getKeySetting("keymap_drop");
1283         key[KEYMAP_ID_INVENTORY]    = getKeySetting("keymap_inventory");
1284         key[KEYMAP_ID_CHAT]         = getKeySetting("keymap_chat");
1285         key[KEYMAP_ID_CMD]          = getKeySetting("keymap_cmd");
1286         key[KEYMAP_ID_CONSOLE]      = getKeySetting("keymap_console");
1287         key[KEYMAP_ID_FREEMOVE]     = getKeySetting("keymap_freemove");
1288         key[KEYMAP_ID_FASTMOVE]     = getKeySetting("keymap_fastmove");
1289         key[KEYMAP_ID_NOCLIP]       = getKeySetting("keymap_noclip");
1290         key[KEYMAP_ID_CINEMATIC]    = getKeySetting("keymap_cinematic");
1291         key[KEYMAP_ID_SCREENSHOT]   = getKeySetting("keymap_screenshot");
1292         key[KEYMAP_ID_TOGGLE_HUD]   = getKeySetting("keymap_toggle_hud");
1293         key[KEYMAP_ID_TOGGLE_CHAT]  = getKeySetting("keymap_toggle_chat");
1294         key[KEYMAP_ID_TOGGLE_FORCE_FOG_OFF]
1295                         = getKeySetting("keymap_toggle_force_fog_off");
1296         key[KEYMAP_ID_TOGGLE_UPDATE_CAMERA]
1297                         = getKeySetting("keymap_toggle_update_camera");
1298         key[KEYMAP_ID_TOGGLE_DEBUG]
1299                         = getKeySetting("keymap_toggle_debug");
1300         key[KEYMAP_ID_TOGGLE_PROFILER]
1301                         = getKeySetting("keymap_toggle_profiler");
1302         key[KEYMAP_ID_CAMERA_MODE]
1303                         = getKeySetting("keymap_camera_mode");
1304         key[KEYMAP_ID_INCREASE_VIEWING_RANGE]
1305                         = getKeySetting("keymap_increase_viewing_range_min");
1306         key[KEYMAP_ID_DECREASE_VIEWING_RANGE]
1307                         = getKeySetting("keymap_decrease_viewing_range_min");
1308         key[KEYMAP_ID_RANGESELECT]
1309                         = getKeySetting("keymap_rangeselect");
1310
1311         key[KEYMAP_ID_QUICKTUNE_NEXT] = getKeySetting("keymap_quicktune_next");
1312         key[KEYMAP_ID_QUICKTUNE_PREV] = getKeySetting("keymap_quicktune_prev");
1313         key[KEYMAP_ID_QUICKTUNE_INC]  = getKeySetting("keymap_quicktune_inc");
1314         key[KEYMAP_ID_QUICKTUNE_DEC]  = getKeySetting("keymap_quicktune_dec");
1315
1316         key[KEYMAP_ID_DEBUG_STACKS]   = getKeySetting("keymap_print_debug_stacks");
1317 }
1318
1319
1320 /****************************************************************************
1321
1322  ****************************************************************************/
1323
1324 const float object_hit_delay = 0.2;
1325
1326 struct FpsControl {
1327         u32 last_time, busy_time, sleep_time;
1328 };
1329
1330
1331 /* The reason the following structs are not anonymous structs within the
1332  * class is that they are not used by the majority of member functions and
1333  * many functions that do require objects of thse types do not modify them
1334  * (so they can be passed as a const qualified parameter)
1335  */
1336 struct CameraOrientation {
1337         f32 camera_yaw;    // "right/left"
1338         f32 camera_pitch;  // "up/down"
1339 };
1340
1341 struct GameRunData {
1342         u16 dig_index;
1343         u16 new_playeritem;
1344         PointedThing pointed_old;
1345         bool digging;
1346         bool ldown_for_dig;
1347         bool left_punch;
1348         bool update_wielded_item_trigger;
1349         bool reset_jump_timer;
1350         float nodig_delay_timer;
1351         float dig_time;
1352         float dig_time_complete;
1353         float repeat_rightclick_timer;
1354         float object_hit_delay_timer;
1355         float time_from_last_punch;
1356         ClientActiveObject *selected_object;
1357
1358         float jump_timer;
1359         float damage_flash;
1360         float update_draw_list_timer;
1361         float statustext_time;
1362
1363         f32 fog_range;
1364
1365         v3f update_draw_list_last_cam_dir;
1366
1367         u32 profiler_current_page;
1368         u32 profiler_max_page;     // Number of pages
1369
1370         float time_of_day;
1371         float time_of_day_smooth;
1372 };
1373
1374 struct Jitter {
1375         f32 max, min, avg, counter, max_sample, min_sample, max_fraction;
1376 };
1377
1378 struct RunStats {
1379         u32 drawtime;
1380         u32 beginscenetime;
1381         u32 endscenetime;
1382
1383         Jitter dtime_jitter, busy_time_jitter;
1384 };
1385
1386 /* Flags that can, or may, change during main game loop
1387  */
1388 struct VolatileRunFlags {
1389         bool invert_mouse;
1390         bool show_chat;
1391         bool show_hud;
1392         bool force_fog_off;
1393         bool show_debug;
1394         bool show_profiler_graph;
1395         bool disable_camera_update;
1396         bool first_loop_after_window_activation;
1397         bool camera_offset_changed;
1398 };
1399
1400
1401 /****************************************************************************
1402  THE GAME
1403  ****************************************************************************/
1404
1405 /* This is not intended to be a public class. If a public class becomes
1406  * desirable then it may be better to create another 'wrapper' class that
1407  * hides most of the stuff in this class (nothing in this class is required
1408  * by any other file) but exposes the public methods/data only.
1409  */
1410 class Game
1411 {
1412 public:
1413         Game();
1414         ~Game();
1415
1416         bool startup(bool *kill,
1417                         bool random_input,
1418                         InputHandler *input,
1419                         IrrlichtDevice *device,
1420                         const std::string &map_dir,
1421                         const std::string &playername,
1422                         const std::string &password,
1423                         // If address is "", local server is used and address is updated
1424                         std::string *address,
1425                         u16 port,
1426                         std::string &error_message,
1427                         ChatBackend *chat_backend,
1428                         const SubgameSpec &gamespec,    // Used for local game
1429                         bool simple_singleplayer_mode);
1430
1431         void run();
1432         void shutdown();
1433
1434 protected:
1435
1436         void extendedResourceCleanup();
1437
1438         // Basic initialisation
1439         bool init(const std::string &map_dir, std::string *address,
1440                         u16 port,
1441                         const SubgameSpec &gamespec);
1442         bool initSound();
1443         bool createSingleplayerServer(const std::string map_dir,
1444                         const SubgameSpec &gamespec, u16 port, std::string *address);
1445
1446         // Client creation
1447         bool createClient(const std::string &playername,
1448                         const std::string &password, std::string *address, u16 port);
1449         bool initGui();
1450
1451         // Client connection
1452         bool connectToServer(const std::string &playername,
1453                         const std::string &password, std::string *address, u16 port,
1454                         bool *connect_ok, bool *aborted);
1455         bool getServerContent(bool *aborted);
1456
1457         // Main loop
1458
1459         void updateInteractTimers(GameRunData *runData, f32 dtime);
1460         bool checkConnection();
1461         bool handleCallbacks();
1462         void processQueues();
1463         void updateProfilers(const GameRunData &runData, const RunStats &stats,
1464                         const FpsControl &draw_times, f32 dtime);
1465         void addProfilerGraphs(const RunStats &stats, const FpsControl &draw_times,
1466                         f32 dtime);
1467         void updateStats(RunStats *stats, const FpsControl &draw_times, f32 dtime);
1468
1469         void processUserInput(VolatileRunFlags *flags, GameRunData *runData,
1470                         f32 dtime);
1471         void processKeyboardInput(VolatileRunFlags *flags,
1472                         float *statustext_time,
1473                         float *jump_timer,
1474                         bool *reset_jump_timer,
1475                         u32 *profiler_current_page,
1476                         u32 profiler_max_page);
1477         void processItemSelection(u16 *new_playeritem);
1478
1479         void dropSelectedItem();
1480         void openInventory();
1481         void openConsole();
1482         void toggleFreeMove(float *statustext_time);
1483         void toggleFreeMoveAlt(float *statustext_time, float *jump_timer);
1484         void toggleFast(float *statustext_time);
1485         void toggleNoClip(float *statustext_time);
1486         void toggleCinematic(float *statustext_time);
1487
1488         void toggleChat(float *statustext_time, bool *flag);
1489         void toggleHud(float *statustext_time, bool *flag);
1490         void toggleFog(float *statustext_time, bool *flag);
1491         void toggleDebug(float *statustext_time, bool *show_debug,
1492                         bool *show_profiler_graph);
1493         void toggleUpdateCamera(float *statustext_time, bool *flag);
1494         void toggleProfiler(float *statustext_time, u32 *profiler_current_page,
1495                         u32 profiler_max_page);
1496
1497         void increaseViewRange(float *statustext_time);
1498         void decreaseViewRange(float *statustext_time);
1499         void toggleFullViewRange(float *statustext_time);
1500
1501         void updateCameraDirection(CameraOrientation *cam, VolatileRunFlags *flags);
1502         void updateCameraOrientation(CameraOrientation *cam,
1503                         const VolatileRunFlags &flags);
1504         void updatePlayerControl(const CameraOrientation &cam);
1505         void step(f32 *dtime);
1506         void processClientEvents(CameraOrientation *cam, float *damage_flash);
1507         void updateCamera(VolatileRunFlags *flags, u32 busy_time, f32 dtime,
1508                         float time_from_last_punch);
1509         void updateSound(f32 dtime);
1510         void processPlayerInteraction(std::vector<aabb3f> &highlight_boxes,
1511                         GameRunData *runData, f32 dtime, bool show_hud,
1512                         bool show_debug);
1513         void handlePointingAtNode(GameRunData *runData,
1514                         const PointedThing &pointed, const ItemDefinition &playeritem_def,
1515                         const ToolCapabilities &playeritem_toolcap, f32 dtime);
1516         void handlePointingAtObject(GameRunData *runData,
1517                         const PointedThing &pointed, const ItemStack &playeritem,
1518                         const v3f &player_position, bool show_debug);
1519         void handleDigging(GameRunData *runData, const PointedThing &pointed,
1520                         const v3s16 &nodepos, const ToolCapabilities &playeritem_toolcap,
1521                         f32 dtime);
1522         void updateFrame(std::vector<aabb3f> &highlight_boxes, ProfilerGraph *graph,
1523                         RunStats *stats, GameRunData *runData,
1524                         f32 dtime, const VolatileRunFlags &flags, const CameraOrientation &cam);
1525         void updateGui(float *statustext_time, const RunStats &stats,
1526                         const GameRunData& runData, f32 dtime, const VolatileRunFlags &flags,
1527                         const CameraOrientation &cam);
1528         void updateProfilerGraphs(ProfilerGraph *graph);
1529
1530         // Misc
1531         void limitFps(FpsControl *fps_timings, f32 *dtime);
1532
1533         void showOverlayMessage(const wchar_t *msg, float dtime, int percent,
1534                         bool draw_clouds = true);
1535
1536 private:
1537         InputHandler *input;
1538
1539         Client *client;
1540         Server *server;
1541
1542         IWritableTextureSource *texture_src;
1543         IWritableShaderSource *shader_src;
1544
1545         // When created, these will be filled with data received from the server
1546         IWritableItemDefManager *itemdef_manager;
1547         IWritableNodeDefManager *nodedef_manager;
1548
1549         GameOnDemandSoundFetcher soundfetcher; // useful when testing
1550         ISoundManager *sound;
1551         bool sound_is_dummy;
1552         SoundMaker *soundmaker;
1553
1554         ChatBackend *chat_backend;
1555
1556         GUIFormSpecMenu *current_formspec;
1557
1558         EventManager *eventmgr;
1559         QuicktuneShortcutter *quicktune;
1560
1561         GUIChatConsole *gui_chat_console; // Free using ->Drop()
1562         MapDrawControl *draw_control;
1563         Camera *camera;
1564         Clouds *clouds;                   // Free using ->Drop()
1565         Sky *sky;                         // Free using ->Drop()
1566         Inventory *local_inventory;
1567         Hud *hud;
1568
1569         /* 'cache'
1570            This class does take ownership/responsibily for cleaning up etc of any of
1571            these items (e.g. device)
1572         */
1573         IrrlichtDevice *device;
1574         video::IVideoDriver *driver;
1575         scene::ISceneManager *smgr;
1576         bool *kill;
1577         std::string *error_message;
1578         IGameDef *gamedef;                     // Convenience (same as *client)
1579         scene::ISceneNode *skybox;
1580
1581         bool random_input;
1582         bool simple_singleplayer_mode;
1583         /* End 'cache' */
1584
1585         /* Pre-calculated values
1586          */
1587         int crack_animation_length;
1588
1589         /* GUI stuff
1590          */
1591         gui::IGUIStaticText *guitext;          // First line of debug text
1592         gui::IGUIStaticText *guitext2;         // Second line of debug text
1593         gui::IGUIStaticText *guitext_info;     // At the middle of the screen
1594         gui::IGUIStaticText *guitext_status;
1595         gui::IGUIStaticText *guitext_chat;         // Chat text
1596         gui::IGUIStaticText *guitext_profiler; // Profiler text
1597
1598         std::wstring infotext;
1599         std::wstring statustext;
1600
1601         KeyCache keycache;
1602
1603         IntervalLimiter profiler_interval;
1604
1605         /* TODO: Add a callback function so these can be updated when a setting
1606          *       changes.  At this point in time it doesn't matter (e.g. /set
1607          *       is documented to change server settings only)
1608          *
1609          * TODO: Local caching of settings is not optimal and should at some stage
1610          *       be updated to use a global settings object for getting thse values
1611          *       (as opposed to the this local caching). This can be addressed in
1612          *       a later release.
1613          */
1614         bool m_cache_doubletap_jump;
1615         bool m_cache_enable_node_highlighting;
1616         bool m_cache_enable_clouds;
1617         bool m_cache_enable_particles;
1618         bool m_cache_enable_fog;
1619         f32  m_cache_mouse_sensitivity;
1620         f32  m_repeat_right_click_time;
1621 };
1622
1623 Game::Game() :
1624         client(NULL),
1625         server(NULL),
1626         texture_src(NULL),
1627         shader_src(NULL),
1628         itemdef_manager(NULL),
1629         nodedef_manager(NULL),
1630         sound(NULL),
1631         sound_is_dummy(false),
1632         soundmaker(NULL),
1633         chat_backend(NULL),
1634         current_formspec(NULL),
1635         eventmgr(NULL),
1636         quicktune(NULL),
1637         gui_chat_console(NULL),
1638         draw_control(NULL),
1639         camera(NULL),
1640         clouds(NULL),
1641         sky(NULL),
1642         local_inventory(NULL),
1643         hud(NULL)
1644 {
1645         m_cache_doubletap_jump            = g_settings->getBool("doubletap_jump");
1646         m_cache_enable_node_highlighting  = g_settings->getBool("enable_node_highlighting");
1647         m_cache_enable_clouds             = g_settings->getBool("enable_clouds");
1648         m_cache_enable_particles          = g_settings->getBool("enable_particles");
1649         m_cache_enable_fog                = g_settings->getBool("enable_fog");
1650         m_cache_mouse_sensitivity         = g_settings->getFloat("mouse_sensitivity");
1651         m_repeat_right_click_time         = g_settings->getFloat("repeat_rightclick_time");
1652
1653         m_cache_mouse_sensitivity = rangelim(m_cache_mouse_sensitivity, 0.001, 100.0);
1654 }
1655
1656
1657
1658 /****************************************************************************
1659  MinetestApp Public
1660  ****************************************************************************/
1661
1662 Game::~Game()
1663 {
1664         delete client;
1665         delete soundmaker;
1666         if (!sound_is_dummy)
1667                 delete sound;
1668
1669         delete server; // deleted first to stop all server threads
1670
1671         delete hud;
1672         delete local_inventory;
1673         delete camera;
1674         delete quicktune;
1675         delete eventmgr;
1676         delete texture_src;
1677         delete shader_src;
1678         delete nodedef_manager;
1679         delete itemdef_manager;
1680         delete draw_control;
1681
1682         extendedResourceCleanup();
1683 }
1684
1685 bool Game::startup(bool *kill,
1686                 bool random_input,
1687                 InputHandler *input,
1688                 IrrlichtDevice *device,
1689                 const std::string &map_dir,
1690                 const std::string &playername,
1691                 const std::string &password,
1692                 std::string *address,     // can change if simple_singleplayer_mode
1693                 u16 port,
1694                 std::string &error_message,
1695                 ChatBackend *chat_backend,
1696                 const SubgameSpec &gamespec,
1697                 bool simple_singleplayer_mode)
1698 {
1699         // "cache"
1700         this->device        = device;
1701         this->kill          = kill;
1702         this->error_message = &error_message;
1703         this->random_input  = random_input;
1704         this->input         = input;
1705         this->chat_backend  = chat_backend;
1706         this->simple_singleplayer_mode = simple_singleplayer_mode;
1707
1708         driver              = device->getVideoDriver();
1709         smgr                = device->getSceneManager();
1710
1711         smgr->getParameters()->setAttribute(scene::OBJ_LOADER_IGNORE_MATERIAL_FILES, true);
1712
1713         if (!init(map_dir, address, port, gamespec))
1714                 return false;
1715
1716         if (!createClient(playername, password, address, port))
1717                 return false;
1718
1719         return true;
1720 }
1721
1722
1723 void Game::run()
1724 {
1725         ProfilerGraph graph;
1726         RunStats stats              = { 0 };
1727         CameraOrientation cam_view_target  = { 0 };
1728         CameraOrientation cam_view  = { 0 };
1729         GameRunData runData         = { 0 };
1730         FpsControl draw_times       = { 0 };
1731         VolatileRunFlags flags      = { 0 };
1732         f32 dtime; // in seconds
1733
1734         runData.time_from_last_punch  = 10.0;
1735         runData.profiler_max_page = 3;
1736         runData.update_wielded_item_trigger = true;
1737
1738         flags.show_chat = true;
1739         flags.show_hud = true;
1740         flags.show_debug = g_settings->getBool("show_debug");
1741         flags.invert_mouse = g_settings->getBool("invert_mouse");
1742         flags.first_loop_after_window_activation = true;
1743
1744         /* Clear the profiler */
1745         Profiler::GraphValues dummyvalues;
1746         g_profiler->graphGet(dummyvalues);
1747
1748         draw_times.last_time = device->getTimer()->getTime();
1749
1750         shader_src->addGlobalConstantSetter(new GameGlobalShaderConstantSetter(
1751                         sky,
1752                         &flags.force_fog_off,
1753                         &runData.fog_range,
1754                         client));
1755
1756         std::vector<aabb3f> highlight_boxes;
1757
1758         set_light_table(g_settings->getFloat("display_gamma"));
1759
1760         while (device->run() && !(*kill || g_gamecallback->shutdown_requested)) {
1761
1762                 /* Must be called immediately after a device->run() call because it
1763                  * uses device->getTimer()->getTime()
1764                  */
1765                 limitFps(&draw_times, &dtime);
1766
1767                 updateStats(&stats, draw_times, dtime);
1768                 updateInteractTimers(&runData, dtime);
1769
1770                 if (!checkConnection())
1771                         break;
1772                 if (!handleCallbacks())
1773                         break;
1774
1775                 processQueues();
1776
1777                 infotext = L"";
1778                 hud->resizeHotbar();
1779
1780                 updateProfilers(runData, stats, draw_times, dtime);
1781                 processUserInput(&flags, &runData, dtime);
1782                 // Update camera before player movement to avoid camera lag of one frame
1783                 updateCameraDirection(&cam_view_target, &flags);
1784                 float cam_smoothing = 0;
1785                 if (g_settings->getBool("cinematic"))
1786                         cam_smoothing = 1 - g_settings->getFloat("cinematic_camera_smoothing");
1787                 else
1788                         cam_smoothing = 1 - g_settings->getFloat("camera_smoothing");
1789                 cam_smoothing = rangelim(cam_smoothing, 0.01f, 1.0f);
1790                 cam_view.camera_yaw += (cam_view_target.camera_yaw -
1791                                 cam_view.camera_yaw) * cam_smoothing;
1792                 cam_view.camera_pitch += (cam_view_target.camera_pitch -
1793                                 cam_view.camera_pitch) * cam_smoothing;
1794                 updatePlayerControl(cam_view);
1795                 step(&dtime);
1796                 processClientEvents(&cam_view, &runData.damage_flash);
1797                 updateCamera(&flags, draw_times.busy_time, dtime,
1798                                 runData.time_from_last_punch);
1799                 updateSound(dtime);
1800                 processPlayerInteraction(highlight_boxes, &runData, dtime,
1801                                 flags.show_hud, flags.show_debug);
1802                 updateFrame(highlight_boxes, &graph, &stats, &runData, dtime,
1803                                 flags, cam_view);
1804                 updateProfilerGraphs(&graph);
1805         }
1806 }
1807
1808
1809 void Game::shutdown()
1810 {
1811         showOverlayMessage(wgettext("Shutting down..."), 0, 0, false);
1812
1813         if (clouds)
1814                 clouds->drop();
1815
1816         if (gui_chat_console)
1817                 gui_chat_console->drop();
1818
1819         if (sky)
1820                 sky->drop();
1821
1822         /* cleanup menus */
1823         while (g_menumgr.menuCount() > 0) {
1824                 g_menumgr.m_stack.front()->setVisible(false);
1825                 g_menumgr.deletingMenu(g_menumgr.m_stack.front());
1826         }
1827
1828         if (current_formspec) {
1829                 current_formspec->drop();
1830                 current_formspec = NULL;
1831         }
1832
1833         chat_backend->addMessage(L"", L"# Disconnected.");
1834         chat_backend->addMessage(L"", L"");
1835
1836         if (client) {
1837                 client->Stop();
1838                 while (!client->isShutdown()) {
1839                         assert(texture_src != NULL);
1840                         assert(shader_src != NULL);
1841                         texture_src->processQueue();
1842                         shader_src->processQueue();
1843                         sleep_ms(100);
1844                 }
1845         }
1846 }
1847
1848
1849 /****************************************************************************/
1850 /****************************************************************************
1851  Startup
1852  ****************************************************************************/
1853 /****************************************************************************/
1854
1855 bool Game::init(
1856                 const std::string &map_dir,
1857                 std::string *address,
1858                 u16 port,
1859                 const SubgameSpec &gamespec)
1860 {
1861         showOverlayMessage(wgettext("Loading..."), 0, 0);
1862
1863         texture_src = createTextureSource(device);
1864         shader_src = createShaderSource(device);
1865
1866         itemdef_manager = createItemDefManager();
1867         nodedef_manager = createNodeDefManager();
1868
1869         eventmgr = new EventManager();
1870         quicktune = new QuicktuneShortcutter();
1871
1872         if (!(texture_src && shader_src && itemdef_manager && nodedef_manager
1873                         && eventmgr && quicktune))
1874                 return false;
1875
1876         if (!initSound())
1877                 return false;
1878
1879         // Create a server if not connecting to an existing one
1880         if (*address == "") {
1881                 if (!createSingleplayerServer(map_dir, gamespec, port, address))
1882                         return false;
1883         }
1884
1885         return true;
1886 }
1887
1888 bool Game::initSound()
1889 {
1890 #if USE_SOUND
1891         if (g_settings->getBool("enable_sound")) {
1892                 infostream << "Attempting to use OpenAL audio" << std::endl;
1893                 sound = createOpenALSoundManager(&soundfetcher);
1894                 if (!sound)
1895                         infostream << "Failed to initialize OpenAL audio" << std::endl;
1896         } else
1897                 infostream << "Sound disabled." << std::endl;
1898 #endif
1899
1900         if (!sound) {
1901                 infostream << "Using dummy audio." << std::endl;
1902                 sound = &dummySoundManager;
1903                 sound_is_dummy = true;
1904         }
1905
1906         soundmaker = new SoundMaker(sound, nodedef_manager);
1907         if (!soundmaker)
1908                 return false;
1909
1910         soundmaker->registerReceiver(eventmgr);
1911
1912         return true;
1913 }
1914
1915 bool Game::createSingleplayerServer(const std::string map_dir,
1916                 const SubgameSpec &gamespec, u16 port, std::string *address)
1917 {
1918         showOverlayMessage(wgettext("Creating server..."), 0, 5);
1919
1920         std::string bind_str = g_settings->get("bind_address");
1921         Address bind_addr(0, 0, 0, 0, port);
1922
1923         if (g_settings->getBool("ipv6_server")) {
1924                 bind_addr.setAddress((IPv6AddressBytes *) NULL);
1925         }
1926
1927         try {
1928                 bind_addr.Resolve(bind_str.c_str());
1929         } catch (ResolveError &e) {
1930                 infostream << "Resolving bind address \"" << bind_str
1931                            << "\" failed: " << e.what()
1932                            << " -- Listening on all addresses." << std::endl;
1933         }
1934
1935         if (bind_addr.isIPv6() && !g_settings->getBool("enable_ipv6")) {
1936                 *error_message = "Unable to listen on " +
1937                                 bind_addr.serializeString() +
1938                                 " because IPv6 is disabled";
1939                 errorstream << *error_message << std::endl;
1940                 return false;
1941         }
1942
1943         server = new Server(map_dir, gamespec, simple_singleplayer_mode,
1944                             bind_addr.isIPv6());
1945
1946         server->start(bind_addr);
1947
1948         return true;
1949 }
1950
1951 bool Game::createClient(const std::string &playername,
1952                 const std::string &password, std::string *address, u16 port)
1953 {
1954         showOverlayMessage(wgettext("Creating client..."), 0, 10);
1955
1956         draw_control = new MapDrawControl;
1957         if (!draw_control)
1958                 return false;
1959
1960         bool could_connect, connect_aborted;
1961
1962         if (!connectToServer(playername, password, address, port,
1963                         &could_connect, &connect_aborted))
1964                 return false;
1965
1966         if (!could_connect) {
1967                 if (error_message->empty() && !connect_aborted) {
1968                         // Should not happen if error messages are set properly
1969                         *error_message = "Connection failed for unknown reason";
1970                         errorstream << *error_message << std::endl;
1971                 }
1972                 return false;
1973         }
1974
1975         if (!getServerContent(&connect_aborted)) {
1976                 if (error_message->empty() && !connect_aborted) {
1977                         // Should not happen if error messages are set properly
1978                         *error_message = "Connection failed for unknown reason";
1979                         errorstream << *error_message << std::endl;
1980                 }
1981                 return false;
1982         }
1983
1984         // Update cached textures, meshes and materials
1985         client->afterContentReceived(device);
1986
1987         /* Camera
1988          */
1989         camera = new Camera(smgr, *draw_control, gamedef);
1990         if (!camera || !camera->successfullyCreated(*error_message))
1991                 return false;
1992
1993         /* Clouds
1994          */
1995         if (m_cache_enable_clouds) {
1996                 clouds = new Clouds(smgr->getRootSceneNode(), smgr, -1, time(0));
1997                 if (!clouds) {
1998                         *error_message = "Memory allocation error (clouds)";
1999                         errorstream << *error_message << std::endl;
2000                         return false;
2001                 }
2002         }
2003
2004         /* Skybox
2005          */
2006         sky = new Sky(smgr->getRootSceneNode(), smgr, -1, texture_src);
2007         skybox = NULL;  // This is used/set later on in the main run loop
2008
2009         local_inventory = new Inventory(itemdef_manager);
2010
2011         if (!(sky && local_inventory)) {
2012                 *error_message = "Memory allocation error (sky or local inventory)";
2013                 errorstream << *error_message << std::endl;
2014                 return false;
2015         }
2016
2017         /* Pre-calculated values
2018          */
2019         video::ITexture *t = texture_src->getTexture("crack_anylength.png");
2020         if (t) {
2021                 v2u32 size = t->getOriginalSize();
2022                 crack_animation_length = size.Y / size.X;
2023         } else {
2024                 crack_animation_length = 5;
2025         }
2026
2027         if (!initGui())
2028                 return false;
2029
2030         /* Set window caption
2031          */
2032         std::wstring str = narrow_to_wide(PROJECT_NAME);
2033         str += L" [";
2034         str += driver->getName();
2035         str += L"]";
2036         device->setWindowCaption(str.c_str());
2037
2038         LocalPlayer *player = client->getEnv().getLocalPlayer();
2039         player->hurt_tilt_timer = 0;
2040         player->hurt_tilt_strength = 0;
2041
2042         hud = new Hud(driver, smgr, guienv, gamedef, player, local_inventory);
2043
2044         if (!hud) {
2045                 *error_message = "Memory error: could not create HUD";
2046                 errorstream << *error_message << std::endl;
2047                 return false;
2048         }
2049
2050         return true;
2051 }
2052
2053 bool Game::initGui()
2054 {
2055         // First line of debug text
2056         guitext = guienv->addStaticText(
2057                         narrow_to_wide(PROJECT_NAME).c_str(),
2058                         core::rect<s32>(0, 0, 0, 0),
2059                         false, false, guiroot);
2060
2061         // Second line of debug text
2062         guitext2 = guienv->addStaticText(
2063                         L"",
2064                         core::rect<s32>(0, 0, 0, 0),
2065                         false, false, guiroot);
2066
2067         // At the middle of the screen
2068         // Object infos are shown in this
2069         guitext_info = guienv->addStaticText(
2070                         L"",
2071                         core::rect<s32>(0, 0, 400, g_fontengine->getTextHeight() * 5 + 5) + v2s32(100, 200),
2072                         false, true, guiroot);
2073
2074         // Status text (displays info when showing and hiding GUI stuff, etc.)
2075         guitext_status = guienv->addStaticText(
2076                         L"<Status>",
2077                         core::rect<s32>(0, 0, 0, 0),
2078                         false, false, guiroot);
2079         guitext_status->setVisible(false);
2080
2081         // Chat text
2082         guitext_chat = guienv->addStaticText(
2083                         L"",
2084                         core::rect<s32>(0, 0, 0, 0),
2085                         //false, false); // Disable word wrap as of now
2086                         false, true, guiroot);
2087         // Remove stale "recent" chat messages from previous connections
2088         chat_backend->clearRecentChat();
2089
2090         // Chat backend and console
2091         gui_chat_console = new GUIChatConsole(guienv, guienv->getRootGUIElement(),
2092                         -1, chat_backend, client);
2093         if (!gui_chat_console) {
2094                 *error_message = "Could not allocate memory for chat console";
2095                 errorstream << *error_message << std::endl;
2096                 return false;
2097         }
2098
2099         // Profiler text (size is updated when text is updated)
2100         guitext_profiler = guienv->addStaticText(
2101                         L"<Profiler>",
2102                         core::rect<s32>(0, 0, 0, 0),
2103                         false, false, guiroot);
2104         guitext_profiler->setBackgroundColor(video::SColor(120, 0, 0, 0));
2105         guitext_profiler->setVisible(false);
2106         guitext_profiler->setWordWrap(true);
2107
2108 #ifdef HAVE_TOUCHSCREENGUI
2109
2110         if (g_touchscreengui)
2111                 g_touchscreengui->init(texture_src, porting::getDisplayDensity());
2112
2113 #endif
2114
2115         return true;
2116 }
2117
2118 bool Game::connectToServer(const std::string &playername,
2119                 const std::string &password, std::string *address, u16 port,
2120                 bool *connect_ok, bool *aborted)
2121 {
2122         *connect_ok = false;    // Let's not be overly optimistic
2123         *aborted = false;
2124         bool local_server_mode = false;
2125
2126         showOverlayMessage(wgettext("Resolving address..."), 0, 15);
2127
2128         Address connect_address(0, 0, 0, 0, port);
2129
2130         try {
2131                 connect_address.Resolve(address->c_str());
2132
2133                 if (connect_address.isZero()) { // i.e. INADDR_ANY, IN6ADDR_ANY
2134                         //connect_address.Resolve("localhost");
2135                         if (connect_address.isIPv6()) {
2136                                 IPv6AddressBytes addr_bytes;
2137                                 addr_bytes.bytes[15] = 1;
2138                                 connect_address.setAddress(&addr_bytes);
2139                         } else {
2140                                 connect_address.setAddress(127, 0, 0, 1);
2141                         }
2142                         local_server_mode = true;
2143                 }
2144         } catch (ResolveError &e) {
2145                 *error_message = std::string("Couldn't resolve address: ") + e.what();
2146                 errorstream << *error_message << std::endl;
2147                 return false;
2148         }
2149
2150         if (connect_address.isIPv6() && !g_settings->getBool("enable_ipv6")) {
2151                 *error_message = "Unable to connect to " +
2152                                 connect_address.serializeString() +
2153                                 " because IPv6 is disabled";
2154                 errorstream << *error_message << std::endl;
2155                 return false;
2156         }
2157
2158         client = new Client(device,
2159                         playername.c_str(), password,
2160                         *draw_control, texture_src, shader_src,
2161                         itemdef_manager, nodedef_manager, sound, eventmgr,
2162                         connect_address.isIPv6());
2163
2164         if (!client)
2165                 return false;
2166
2167         gamedef = client;       // Client acts as our GameDef
2168
2169         infostream << "Connecting to server at ";
2170         connect_address.print(&infostream);
2171         infostream << std::endl;
2172
2173         client->connect(connect_address, *address,
2174                 simple_singleplayer_mode || local_server_mode);
2175
2176         /*
2177                 Wait for server to accept connection
2178         */
2179
2180         try {
2181                 input->clear();
2182
2183                 FpsControl fps_control = { 0 };
2184                 f32 dtime;
2185                 f32 wait_time = 0; // in seconds
2186
2187                 fps_control.last_time = device->getTimer()->getTime();
2188
2189                 while (device->run()) {
2190
2191                         limitFps(&fps_control, &dtime);
2192
2193                         // Update client and server
2194                         client->step(dtime);
2195
2196                         if (server != NULL)
2197                                 server->step(dtime);
2198
2199                         // End condition
2200                         if (client->getState() == LC_Init) {
2201                                 *connect_ok = true;
2202                                 break;
2203                         }
2204
2205                         // Break conditions
2206                         if (client->accessDenied()) {
2207                                 *error_message = "Access denied. Reason: "
2208                                                 + client->accessDeniedReason();
2209                                 errorstream << *error_message << std::endl;
2210                                 break;
2211                         }
2212
2213                         if (input->wasKeyDown(EscapeKey) || input->wasKeyDown(CancelKey)) {
2214                                 *aborted = true;
2215                                 infostream << "Connect aborted [Escape]" << std::endl;
2216                                 break;
2217                         }
2218
2219                         wait_time += dtime;
2220                         // Only time out if we aren't waiting for the server we started
2221                         if ((*address != "") && (wait_time > 10)) {
2222                                 *error_message = "Connection timed out.";
2223                                 errorstream << *error_message << std::endl;
2224                                 break;
2225                         }
2226
2227                         // Update status
2228                         showOverlayMessage(wgettext("Connecting to server..."), dtime, 20);
2229                 }
2230         } catch (con::PeerNotFoundException &e) {
2231                 // TODO: Should something be done here? At least an info/error
2232                 // message?
2233                 return false;
2234         }
2235
2236         return true;
2237 }
2238
2239 bool Game::getServerContent(bool *aborted)
2240 {
2241         input->clear();
2242
2243         FpsControl fps_control = { 0 };
2244         f32 dtime; // in seconds
2245
2246         fps_control.last_time = device->getTimer()->getTime();
2247
2248         while (device->run()) {
2249
2250                 limitFps(&fps_control, &dtime);
2251
2252                 // Update client and server
2253                 client->step(dtime);
2254
2255                 if (server != NULL)
2256                         server->step(dtime);
2257
2258                 // End condition
2259                 if (client->mediaReceived() && client->itemdefReceived() &&
2260                                 client->nodedefReceived()) {
2261                         break;
2262                 }
2263
2264                 // Error conditions
2265                 if (!checkConnection())
2266                         return false;
2267
2268                 if (client->getState() < LC_Init) {
2269                         *error_message = "Client disconnected";
2270                         errorstream << *error_message << std::endl;
2271                         return false;
2272                 }
2273
2274                 if (input->wasKeyDown(EscapeKey) || input->wasKeyDown(CancelKey)) {
2275                         *aborted = true;
2276                         infostream << "Connect aborted [Escape]" << std::endl;
2277                         return false;
2278                 }
2279
2280                 // Display status
2281                 int progress = 25;
2282
2283                 if (!client->itemdefReceived()) {
2284                         const wchar_t *text = wgettext("Item definitions...");
2285                         progress = 25;
2286                         draw_load_screen(text, device, guienv, dtime, progress);
2287                         delete[] text;
2288                 } else if (!client->nodedefReceived()) {
2289                         const wchar_t *text = wgettext("Node definitions...");
2290                         progress = 30;
2291                         draw_load_screen(text, device, guienv, dtime, progress);
2292                         delete[] text;
2293                 } else {
2294                         std::stringstream message;
2295                         message.precision(3);
2296                         message << gettext("Media...");
2297
2298                         if ((USE_CURL == 0) ||
2299                                         (!g_settings->getBool("enable_remote_media_server"))) {
2300                                 float cur = client->getCurRate();
2301                                 std::string cur_unit = gettext(" KB/s");
2302
2303                                 if (cur > 900) {
2304                                         cur /= 1024.0;
2305                                         cur_unit = gettext(" MB/s");
2306                                 }
2307
2308                                 message << " ( " << cur << cur_unit << " )";
2309                         }
2310
2311                         progress = 30 + client->mediaReceiveProgress() * 35 + 0.5;
2312                         draw_load_screen(narrow_to_wide(message.str()), device,
2313                                         guienv, dtime, progress);
2314                 }
2315         }
2316
2317         return true;
2318 }
2319
2320
2321 /****************************************************************************/
2322 /****************************************************************************
2323  Run
2324  ****************************************************************************/
2325 /****************************************************************************/
2326
2327 inline void Game::updateInteractTimers(GameRunData *runData, f32 dtime)
2328 {
2329         if (runData->nodig_delay_timer >= 0)
2330                 runData->nodig_delay_timer -= dtime;
2331
2332         if (runData->object_hit_delay_timer >= 0)
2333                 runData->object_hit_delay_timer -= dtime;
2334
2335         runData->time_from_last_punch += dtime;
2336 }
2337
2338
2339 /* returns false if game should exit, otherwise true
2340  */
2341 inline bool Game::checkConnection()
2342 {
2343         if (client->accessDenied()) {
2344                 *error_message = "Access denied. Reason: "
2345                                 + client->accessDeniedReason();
2346                 errorstream << *error_message << std::endl;
2347                 return false;
2348         }
2349
2350         return true;
2351 }
2352
2353
2354 /* returns false if game should exit, otherwise true
2355  */
2356 inline bool Game::handleCallbacks()
2357 {
2358         if (g_gamecallback->disconnect_requested) {
2359                 g_gamecallback->disconnect_requested = false;
2360                 return false;
2361         }
2362
2363         if (g_gamecallback->changepassword_requested) {
2364                 (new GUIPasswordChange(guienv, guiroot, -1,
2365                                        &g_menumgr, client))->drop();
2366                 g_gamecallback->changepassword_requested = false;
2367         }
2368
2369         if (g_gamecallback->changevolume_requested) {
2370                 (new GUIVolumeChange(guienv, guiroot, -1,
2371                                      &g_menumgr, client))->drop();
2372                 g_gamecallback->changevolume_requested = false;
2373         }
2374
2375         if (g_gamecallback->keyconfig_requested) {
2376                 (new GUIKeyChangeMenu(guienv, guiroot, -1,
2377                                       &g_menumgr))->drop();
2378                 g_gamecallback->keyconfig_requested = false;
2379         }
2380
2381         if (g_gamecallback->keyconfig_changed) {
2382                 keycache.populate(); // update the cache with new settings
2383                 g_gamecallback->keyconfig_changed = false;
2384         }
2385
2386         return true;
2387 }
2388
2389
2390 void Game::processQueues()
2391 {
2392         texture_src->processQueue();
2393         itemdef_manager->processQueue(gamedef);
2394         shader_src->processQueue();
2395 }
2396
2397
2398 void Game::updateProfilers(const GameRunData &runData, const RunStats &stats,
2399                 const FpsControl &draw_times, f32 dtime)
2400 {
2401         float profiler_print_interval =
2402                         g_settings->getFloat("profiler_print_interval");
2403         bool print_to_log = true;
2404
2405         if (profiler_print_interval == 0) {
2406                 print_to_log = false;
2407                 profiler_print_interval = 5;
2408         }
2409
2410         if (profiler_interval.step(dtime, profiler_print_interval)) {
2411                 if (print_to_log) {
2412                         infostream << "Profiler:" << std::endl;
2413                         g_profiler->print(infostream);
2414                 }
2415
2416                 update_profiler_gui(guitext_profiler, g_fontengine,
2417                                 runData.profiler_current_page, runData.profiler_max_page,
2418                                 driver->getScreenSize().Height);
2419
2420                 g_profiler->clear();
2421         }
2422
2423         addProfilerGraphs(stats, draw_times, dtime);
2424 }
2425
2426
2427 void Game::addProfilerGraphs(const RunStats &stats,
2428                 const FpsControl &draw_times, f32 dtime)
2429 {
2430         g_profiler->graphAdd("mainloop_other",
2431                         draw_times.busy_time / 1000.0f - stats.drawtime / 1000.0f);
2432
2433         if (draw_times.sleep_time != 0)
2434                 g_profiler->graphAdd("mainloop_sleep", draw_times.sleep_time / 1000.0f);
2435         g_profiler->graphAdd("mainloop_dtime", dtime);
2436
2437         g_profiler->add("Elapsed time", dtime);
2438         g_profiler->avg("FPS", 1. / dtime);
2439 }
2440
2441
2442 void Game::updateStats(RunStats *stats, const FpsControl &draw_times,
2443                 f32 dtime)
2444 {
2445
2446         f32 jitter;
2447         Jitter *jp;
2448
2449         /* Time average and jitter calculation
2450          */
2451         jp = &stats->dtime_jitter;
2452         jp->avg = jp->avg * 0.96 + dtime * 0.04;
2453
2454         jitter = dtime - jp->avg;
2455
2456         if (jitter > jp->max)
2457                 jp->max = jitter;
2458
2459         jp->counter += dtime;
2460
2461         if (jp->counter > 0.0) {
2462                 jp->counter -= 3.0;
2463                 jp->max_sample = jp->max;
2464                 jp->max_fraction = jp->max_sample / (jp->avg + 0.001);
2465                 jp->max = 0.0;
2466         }
2467
2468         /* Busytime average and jitter calculation
2469          */
2470         jp = &stats->busy_time_jitter;
2471         jp->avg = jp->avg + draw_times.busy_time * 0.02;
2472
2473         jitter = draw_times.busy_time - jp->avg;
2474
2475         if (jitter > jp->max)
2476                 jp->max = jitter;
2477         if (jitter < jp->min)
2478                 jp->min = jitter;
2479
2480         jp->counter += dtime;
2481
2482         if (jp->counter > 0.0) {
2483                 jp->counter -= 3.0;
2484                 jp->max_sample = jp->max;
2485                 jp->min_sample = jp->min;
2486                 jp->max = 0.0;
2487                 jp->min = 0.0;
2488         }
2489 }
2490
2491
2492
2493 /****************************************************************************
2494  Input handling
2495  ****************************************************************************/
2496
2497 void Game::processUserInput(VolatileRunFlags *flags,
2498                 GameRunData *runData, f32 dtime)
2499 {
2500         // Reset input if window not active or some menu is active
2501         if (device->isWindowActive() == false
2502                         || noMenuActive() == false
2503                         || guienv->hasFocus(gui_chat_console)) {
2504                 input->clear();
2505         }
2506
2507         if (!guienv->hasFocus(gui_chat_console) && gui_chat_console->isOpen()) {
2508                 gui_chat_console->closeConsoleAtOnce();
2509         }
2510
2511         // Input handler step() (used by the random input generator)
2512         input->step(dtime);
2513
2514 #ifdef HAVE_TOUCHSCREENGUI
2515
2516         if (g_touchscreengui) {
2517                 g_touchscreengui->step(dtime);
2518         }
2519
2520 #endif
2521 #ifdef __ANDROID__
2522
2523         if (current_formspec != 0)
2524                 current_formspec->getAndroidUIInput();
2525
2526 #endif
2527
2528         // Increase timer for double tap of "keymap_jump"
2529         if (m_cache_doubletap_jump && runData->jump_timer <= 0.2)
2530                 runData->jump_timer += dtime;
2531
2532         processKeyboardInput(
2533                         flags,
2534                         &runData->statustext_time,
2535                         &runData->jump_timer,
2536                         &runData->reset_jump_timer,
2537                         &runData->profiler_current_page,
2538                         runData->profiler_max_page);
2539
2540         processItemSelection(&runData->new_playeritem);
2541 }
2542
2543
2544 void Game::processKeyboardInput(VolatileRunFlags *flags,
2545                 float *statustext_time,
2546                 float *jump_timer,
2547                 bool *reset_jump_timer,
2548                 u32 *profiler_current_page,
2549                 u32 profiler_max_page)
2550 {
2551
2552         //TimeTaker tt("process kybd input", NULL, PRECISION_NANO);
2553
2554         if (input->wasKeyDown(keycache.key[KeyCache::KEYMAP_ID_DROP])) {
2555                 dropSelectedItem();
2556         } else if (input->wasKeyDown(keycache.key[KeyCache::KEYMAP_ID_INVENTORY])) {
2557                 openInventory();
2558         } else if (input->wasKeyDown(EscapeKey) || input->wasKeyDown(CancelKey)) {
2559                 show_pause_menu(&current_formspec, client, gamedef, texture_src, device,
2560                                 simple_singleplayer_mode);
2561         } else if (input->wasKeyDown(keycache.key[KeyCache::KEYMAP_ID_CHAT])) {
2562                 show_chat_menu(&current_formspec, client, gamedef, texture_src, device,
2563                                 client, "");
2564         } else if (input->wasKeyDown(keycache.key[KeyCache::KEYMAP_ID_CMD])) {
2565                 show_chat_menu(&current_formspec, client, gamedef, texture_src, device,
2566                                 client, "/");
2567         } else if (input->wasKeyDown(keycache.key[KeyCache::KEYMAP_ID_CONSOLE])) {
2568                 openConsole();
2569         } else if (input->wasKeyDown(keycache.key[KeyCache::KEYMAP_ID_FREEMOVE])) {
2570                 toggleFreeMove(statustext_time);
2571         } else if (input->wasKeyDown(keycache.key[KeyCache::KEYMAP_ID_JUMP])) {
2572                 toggleFreeMoveAlt(statustext_time, jump_timer);
2573                 *reset_jump_timer = true;
2574         } else if (input->wasKeyDown(keycache.key[KeyCache::KEYMAP_ID_FASTMOVE])) {
2575                 toggleFast(statustext_time);
2576         } else if (input->wasKeyDown(keycache.key[KeyCache::KEYMAP_ID_NOCLIP])) {
2577                 toggleNoClip(statustext_time);
2578         } else if (input->wasKeyDown(keycache.key[KeyCache::KEYMAP_ID_CINEMATIC])) {
2579                 toggleCinematic(statustext_time);
2580         } else if (input->wasKeyDown(keycache.key[KeyCache::KEYMAP_ID_SCREENSHOT])) {
2581                 client->makeScreenshot(device);
2582         } else if (input->wasKeyDown(keycache.key[KeyCache::KEYMAP_ID_TOGGLE_HUD])) {
2583                 toggleHud(statustext_time, &flags->show_hud);
2584         } else if (input->wasKeyDown(keycache.key[KeyCache::KEYMAP_ID_TOGGLE_CHAT])) {
2585                 toggleChat(statustext_time, &flags->show_chat);
2586         } else if (input->wasKeyDown(keycache.key[KeyCache::KEYMAP_ID_TOGGLE_FORCE_FOG_OFF])) {
2587                 toggleFog(statustext_time, &flags->force_fog_off);
2588         } else if (input->wasKeyDown(keycache.key[KeyCache::KEYMAP_ID_TOGGLE_UPDATE_CAMERA])) {
2589                 toggleUpdateCamera(statustext_time, &flags->disable_camera_update);
2590         } else if (input->wasKeyDown(keycache.key[KeyCache::KEYMAP_ID_TOGGLE_DEBUG])) {
2591                 toggleDebug(statustext_time, &flags->show_debug, &flags->show_profiler_graph);
2592         } else if (input->wasKeyDown(keycache.key[KeyCache::KEYMAP_ID_TOGGLE_PROFILER])) {
2593                 toggleProfiler(statustext_time, profiler_current_page, profiler_max_page);
2594         } else if (input->wasKeyDown(keycache.key[KeyCache::KEYMAP_ID_INCREASE_VIEWING_RANGE])) {
2595                 increaseViewRange(statustext_time);
2596         } else if (input->wasKeyDown(keycache.key[KeyCache::KEYMAP_ID_DECREASE_VIEWING_RANGE])) {
2597                 decreaseViewRange(statustext_time);
2598         } else if (input->wasKeyDown(keycache.key[KeyCache::KEYMAP_ID_RANGESELECT])) {
2599                 toggleFullViewRange(statustext_time);
2600         } else if (input->wasKeyDown(keycache.key[KeyCache::KEYMAP_ID_QUICKTUNE_NEXT]))
2601                 quicktune->next();
2602         else if (input->wasKeyDown(keycache.key[KeyCache::KEYMAP_ID_QUICKTUNE_PREV]))
2603                 quicktune->prev();
2604         else if (input->wasKeyDown(keycache.key[KeyCache::KEYMAP_ID_QUICKTUNE_INC]))
2605                 quicktune->inc();
2606         else if (input->wasKeyDown(keycache.key[KeyCache::KEYMAP_ID_QUICKTUNE_DEC]))
2607                 quicktune->dec();
2608         else if (input->wasKeyDown(keycache.key[KeyCache::KEYMAP_ID_DEBUG_STACKS])) {
2609                 // Print debug stacks
2610                 dstream << "-----------------------------------------"
2611                         << std::endl;
2612                 dstream << DTIME << "Printing debug stacks:" << std::endl;
2613                 dstream << "-----------------------------------------"
2614                         << std::endl;
2615                 debug_stacks_print();
2616         }
2617
2618         if (!input->isKeyDown(getKeySetting("keymap_jump")) && *reset_jump_timer) {
2619                 *reset_jump_timer = false;
2620                 *jump_timer = 0.0;
2621         }
2622
2623         //tt.stop();
2624
2625         if (quicktune->hasMessage()) {
2626                 std::string msg = quicktune->getMessage();
2627                 statustext = narrow_to_wide(msg);
2628                 *statustext_time = 0;
2629         }
2630 }
2631
2632
2633 void Game::processItemSelection(u16 *new_playeritem)
2634 {
2635         LocalPlayer *player = client->getEnv().getLocalPlayer();
2636
2637         /* Item selection using mouse wheel
2638          */
2639         *new_playeritem = client->getPlayerItem();
2640
2641         s32 wheel = input->getMouseWheel();
2642         u16 max_item = MYMIN(PLAYER_INVENTORY_SIZE - 1,
2643                                  player->hud_hotbar_itemcount - 1);
2644
2645         if (wheel < 0)
2646                 *new_playeritem = *new_playeritem < max_item ? *new_playeritem + 1 : 0;
2647         else if (wheel > 0)
2648                 *new_playeritem = *new_playeritem > 0 ? *new_playeritem - 1 : max_item;
2649         // else wheel == 0
2650
2651
2652         /* Item selection using keyboard
2653          */
2654         for (u16 i = 0; i < 10; i++) {
2655                 static const KeyPress *item_keys[10] = {
2656                         NumberKey + 1, NumberKey + 2, NumberKey + 3, NumberKey + 4,
2657                         NumberKey + 5, NumberKey + 6, NumberKey + 7, NumberKey + 8,
2658                         NumberKey + 9, NumberKey + 0,
2659                 };
2660
2661                 if (input->wasKeyDown(*item_keys[i])) {
2662                         if (i < PLAYER_INVENTORY_SIZE && i < player->hud_hotbar_itemcount) {
2663                                 *new_playeritem = i;
2664                                 infostream << "Selected item: " << new_playeritem << std::endl;
2665                         }
2666                         break;
2667                 }
2668         }
2669 }
2670
2671
2672 void Game::dropSelectedItem()
2673 {
2674         IDropAction *a = new IDropAction();
2675         a->count = 0;
2676         a->from_inv.setCurrentPlayer();
2677         a->from_list = "main";
2678         a->from_i = client->getPlayerItem();
2679         client->inventoryAction(a);
2680 }
2681
2682
2683 void Game::openInventory()
2684 {
2685         /*
2686          * Don't permit to open inventory is CAO or player doesn't exists.
2687          * This prevent showing an empty inventory at player load
2688          */
2689
2690         LocalPlayer *player = client->getEnv().getLocalPlayer();
2691         if (player == NULL || player->getCAO() == NULL)
2692                 return;
2693
2694         infostream << "the_game: " << "Launching inventory" << std::endl;
2695
2696         PlayerInventoryFormSource *fs_src = new PlayerInventoryFormSource(client);
2697         TextDest *txt_dst = new TextDestPlayerInventory(client);
2698
2699         create_formspec_menu(&current_formspec, client, gamedef, texture_src,
2700                         device, fs_src, txt_dst, client);
2701
2702         InventoryLocation inventoryloc;
2703         inventoryloc.setCurrentPlayer();
2704         current_formspec->setFormSpec(fs_src->getForm(), inventoryloc);
2705 }
2706
2707
2708 void Game::openConsole()
2709 {
2710         if (!gui_chat_console->isOpenInhibited()) {
2711                 // Open up to over half of the screen
2712                 gui_chat_console->openConsole(0.6);
2713                 guienv->setFocus(gui_chat_console);
2714         }
2715 }
2716
2717
2718 void Game::toggleFreeMove(float *statustext_time)
2719 {
2720         static const wchar_t *msg[] = { L"free_move disabled", L"free_move enabled" };
2721
2722         bool free_move = !g_settings->getBool("free_move");
2723         g_settings->set("free_move", bool_to_cstr(free_move));
2724
2725         *statustext_time = 0;
2726         statustext = msg[free_move];
2727         if (free_move && !client->checkPrivilege("fly"))
2728                 statustext += L" (note: no 'fly' privilege)";
2729 }
2730
2731
2732 void Game::toggleFreeMoveAlt(float *statustext_time, float *jump_timer)
2733 {
2734         if (m_cache_doubletap_jump && *jump_timer < 0.2f)
2735                 toggleFreeMove(statustext_time);
2736 }
2737
2738
2739 void Game::toggleFast(float *statustext_time)
2740 {
2741         static const wchar_t *msg[] = { L"fast_move disabled", L"fast_move enabled" };
2742         bool fast_move = !g_settings->getBool("fast_move");
2743         g_settings->set("fast_move", bool_to_cstr(fast_move));
2744
2745         *statustext_time = 0;
2746         statustext = msg[fast_move];
2747
2748         if (fast_move && !client->checkPrivilege("fast"))
2749                 statustext += L" (note: no 'fast' privilege)";
2750 }
2751
2752
2753 void Game::toggleNoClip(float *statustext_time)
2754 {
2755         static const wchar_t *msg[] = { L"noclip disabled", L"noclip enabled" };
2756         bool noclip = !g_settings->getBool("noclip");
2757         g_settings->set("noclip", bool_to_cstr(noclip));
2758
2759         *statustext_time = 0;
2760         statustext = msg[noclip];
2761
2762         if (noclip && !client->checkPrivilege("noclip"))
2763                 statustext += L" (note: no 'noclip' privilege)";
2764 }
2765
2766 void Game::toggleCinematic(float *statustext_time)
2767 {
2768         static const wchar_t *msg[] = { L"cinematic disabled", L"cinematic enabled" };
2769         bool cinematic = !g_settings->getBool("cinematic");
2770         g_settings->set("cinematic", bool_to_cstr(cinematic));
2771
2772         *statustext_time = 0;
2773         statustext = msg[cinematic];
2774 }
2775
2776
2777 void Game::toggleChat(float *statustext_time, bool *flag)
2778 {
2779         static const wchar_t *msg[] = { L"Chat hidden", L"Chat shown" };
2780
2781         *flag = !*flag;
2782         *statustext_time = 0;
2783         statustext = msg[*flag];
2784 }
2785
2786
2787 void Game::toggleHud(float *statustext_time, bool *flag)
2788 {
2789         static const wchar_t *msg[] = { L"HUD hidden", L"HUD shown" };
2790
2791         *flag = !*flag;
2792         *statustext_time = 0;
2793         statustext = msg[*flag];
2794         if (g_settings->getBool("enable_node_highlighting"))
2795                 client->setHighlighted(client->getHighlighted(), *flag);
2796 }
2797
2798
2799 void Game::toggleFog(float *statustext_time, bool *flag)
2800 {
2801         static const wchar_t *msg[] = { L"Fog enabled", L"Fog disabled" };
2802
2803         *flag = !*flag;
2804         *statustext_time = 0;
2805         statustext = msg[*flag];
2806 }
2807
2808
2809 void Game::toggleDebug(float *statustext_time, bool *show_debug,
2810                 bool *show_profiler_graph)
2811 {
2812         // Initial / 3x toggle: Chat only
2813         // 1x toggle: Debug text with chat
2814         // 2x toggle: Debug text with profiler graph
2815         if (!*show_debug) {
2816                 *show_debug = true;
2817                 *show_profiler_graph = false;
2818                 statustext = L"Debug info shown";
2819         } else if (*show_profiler_graph) {
2820                 *show_debug = false;
2821                 *show_profiler_graph = false;
2822                 statustext = L"Debug info and profiler graph hidden";
2823         } else {
2824                 *show_profiler_graph = true;
2825                 statustext = L"Profiler graph shown";
2826         }
2827         *statustext_time = 0;
2828 }
2829
2830
2831 void Game::toggleUpdateCamera(float *statustext_time, bool *flag)
2832 {
2833         static const wchar_t *msg[] = {
2834                 L"Camera update enabled",
2835                 L"Camera update disabled"
2836         };
2837
2838         *flag = !*flag;
2839         *statustext_time = 0;
2840         statustext = msg[*flag];
2841 }
2842
2843
2844 void Game::toggleProfiler(float *statustext_time, u32 *profiler_current_page,
2845                 u32 profiler_max_page)
2846 {
2847         *profiler_current_page = (*profiler_current_page + 1) % (profiler_max_page + 1);
2848
2849         // FIXME: This updates the profiler with incomplete values
2850         update_profiler_gui(guitext_profiler, g_fontengine, *profiler_current_page,
2851                         profiler_max_page, driver->getScreenSize().Height);
2852
2853         if (*profiler_current_page != 0) {
2854                 std::wstringstream sstr;
2855                 sstr << "Profiler shown (page " << *profiler_current_page
2856                      << " of " << profiler_max_page << ")";
2857                 statustext = sstr.str();
2858         } else {
2859                 statustext = L"Profiler hidden";
2860         }
2861         *statustext_time = 0;
2862 }
2863
2864
2865 void Game::increaseViewRange(float *statustext_time)
2866 {
2867         s16 range = g_settings->getS16("viewing_range_nodes_min");
2868         s16 range_new = range + 10;
2869         g_settings->set("viewing_range_nodes_min", itos(range_new));
2870         statustext = narrow_to_wide("Minimum viewing range changed to "
2871                         + itos(range_new));
2872         *statustext_time = 0;
2873 }
2874
2875
2876 void Game::decreaseViewRange(float *statustext_time)
2877 {
2878         s16 range = g_settings->getS16("viewing_range_nodes_min");
2879         s16 range_new = range - 10;
2880
2881         if (range_new < 0)
2882                 range_new = range;
2883
2884         g_settings->set("viewing_range_nodes_min", itos(range_new));
2885         statustext = narrow_to_wide("Minimum viewing range changed to "
2886                         + itos(range_new));
2887         *statustext_time = 0;
2888 }
2889
2890
2891 void Game::toggleFullViewRange(float *statustext_time)
2892 {
2893         static const wchar_t *msg[] = {
2894                 L"Disabled full viewing range",
2895                 L"Enabled full viewing range"
2896         };
2897
2898         draw_control->range_all = !draw_control->range_all;
2899         infostream << msg[draw_control->range_all] << std::endl;
2900         statustext = msg[draw_control->range_all];
2901         *statustext_time = 0;
2902 }
2903
2904
2905 void Game::updateCameraDirection(CameraOrientation *cam,
2906                 VolatileRunFlags *flags)
2907 {
2908         if ((device->isWindowActive() && noMenuActive()) || random_input) {
2909
2910 #ifndef __ANDROID__
2911                 if (!random_input) {
2912                         // Mac OSX gets upset if this is set every frame
2913                         if (device->getCursorControl()->isVisible())
2914                                 device->getCursorControl()->setVisible(false);
2915                 }
2916 #endif
2917
2918                 if (flags->first_loop_after_window_activation)
2919                         flags->first_loop_after_window_activation = false;
2920                 else
2921                         updateCameraOrientation(cam, *flags);
2922
2923                 input->setMousePos((driver->getScreenSize().Width / 2),
2924                                 (driver->getScreenSize().Height / 2));
2925         } else {
2926
2927 #ifndef ANDROID
2928                 // Mac OSX gets upset if this is set every frame
2929                 if (device->getCursorControl()->isVisible() == false)
2930                         device->getCursorControl()->setVisible(true);
2931 #endif
2932
2933                 if (!flags->first_loop_after_window_activation)
2934                         flags->first_loop_after_window_activation = true;
2935
2936         }
2937 }
2938
2939
2940 void Game::updateCameraOrientation(CameraOrientation *cam,
2941                 const VolatileRunFlags &flags)
2942 {
2943 #ifdef HAVE_TOUCHSCREENGUI
2944         if (g_touchscreengui) {
2945                 cam->camera_yaw   = g_touchscreengui->getYaw();
2946                 cam->camera_pitch = g_touchscreengui->getPitch();
2947         } else {
2948 #endif
2949                 s32 dx = input->getMousePos().X - (driver->getScreenSize().Width / 2);
2950                 s32 dy = input->getMousePos().Y - (driver->getScreenSize().Height / 2);
2951
2952                 if (flags.invert_mouse
2953                                 || camera->getCameraMode() == CAMERA_MODE_THIRD_FRONT) {
2954                         dy = -dy;
2955                 }
2956
2957                 cam->camera_yaw   -= dx * m_cache_mouse_sensitivity;
2958                 cam->camera_pitch += dy * m_cache_mouse_sensitivity;
2959
2960 #ifdef HAVE_TOUCHSCREENGUI
2961         }
2962 #endif
2963
2964         cam->camera_pitch = rangelim(cam->camera_pitch, -89.5, 89.5);
2965 }
2966
2967
2968 void Game::updatePlayerControl(const CameraOrientation &cam)
2969 {
2970         //TimeTaker tt("update player control", NULL, PRECISION_NANO);
2971
2972         PlayerControl control(
2973                 input->isKeyDown(keycache.key[KeyCache::KEYMAP_ID_FORWARD]),
2974                 input->isKeyDown(keycache.key[KeyCache::KEYMAP_ID_BACKWARD]),
2975                 input->isKeyDown(keycache.key[KeyCache::KEYMAP_ID_LEFT]),
2976                 input->isKeyDown(keycache.key[KeyCache::KEYMAP_ID_RIGHT]),
2977                 input->isKeyDown(keycache.key[KeyCache::KEYMAP_ID_JUMP]),
2978                 input->isKeyDown(keycache.key[KeyCache::KEYMAP_ID_SPECIAL1]),
2979                 input->isKeyDown(keycache.key[KeyCache::KEYMAP_ID_SNEAK]),
2980                 input->getLeftState(),
2981                 input->getRightState(),
2982                 cam.camera_pitch,
2983                 cam.camera_yaw
2984         );
2985
2986         u32 keypress_bits =
2987                         ( (u32)(input->isKeyDown(keycache.key[KeyCache::KEYMAP_ID_FORWARD])  & 0x1) << 0) |
2988                         ( (u32)(input->isKeyDown(keycache.key[KeyCache::KEYMAP_ID_BACKWARD]) & 0x1) << 1) |
2989                         ( (u32)(input->isKeyDown(keycache.key[KeyCache::KEYMAP_ID_LEFT])     & 0x1) << 2) |
2990                         ( (u32)(input->isKeyDown(keycache.key[KeyCache::KEYMAP_ID_RIGHT])    & 0x1) << 3) |
2991                         ( (u32)(input->isKeyDown(keycache.key[KeyCache::KEYMAP_ID_JUMP])     & 0x1) << 4) |
2992                         ( (u32)(input->isKeyDown(keycache.key[KeyCache::KEYMAP_ID_SPECIAL1]) & 0x1) << 5) |
2993                         ( (u32)(input->isKeyDown(keycache.key[KeyCache::KEYMAP_ID_SNEAK])    & 0x1) << 6) |
2994                         ( (u32)(input->getLeftState()                                        & 0x1) << 7) |
2995                         ( (u32)(input->getRightState()                                       & 0x1) << 8
2996                 );
2997
2998 #ifdef ANDROID
2999         /* For Android, invert the meaning of holding down the fast button (i.e.
3000          * holding down the fast button -- if there is one -- means walk), unless
3001          * performing an action, sneaking or jumping.
3002          */
3003         const u32 autofast_exludebits =
3004                           (1U << 4) | (1U << 6)     // jump, sneak
3005                         | (1U << 7) | (1U << 8);    // left state, right state
3006
3007         if ((keypress_bits & autofast_exludebits) == 0) {
3008                 control.aux1 = control.aux1 ^ true;
3009                 keypress_bits ^= ((u32)(1U << 5));
3010         }
3011 #endif
3012
3013         client->setPlayerControl(control);
3014         LocalPlayer *player = client->getEnv().getLocalPlayer();
3015         player->keyPressed = keypress_bits;
3016
3017         //tt.stop();
3018 }
3019
3020
3021 inline void Game::step(f32 *dtime)
3022 {
3023         bool can_be_and_is_paused =
3024                         (simple_singleplayer_mode && g_menumgr.pausesGame());
3025
3026         if (can_be_and_is_paused) {     // This is for a singleplayer server
3027                 *dtime = 0;             // No time passes
3028         } else {
3029                 if (server != NULL) {
3030                         //TimeTaker timer("server->step(dtime)");
3031                         server->step(*dtime);
3032                 }
3033
3034                 //TimeTaker timer("client.step(dtime)");
3035                 client->step(*dtime);
3036         }
3037 }
3038
3039
3040 void Game::processClientEvents(CameraOrientation *cam, float *damage_flash)
3041 {
3042         ClientEvent event = client->getClientEvent();
3043
3044         LocalPlayer *player = client->getEnv().getLocalPlayer();
3045
3046         for ( ; event.type != CE_NONE; event = client->getClientEvent()) {
3047
3048                 if (event.type == CE_PLAYER_DAMAGE &&
3049                                 client->getHP() != 0) {
3050                         //u16 damage = event.player_damage.amount;
3051                         //infostream<<"Player damage: "<<damage<<std::endl;
3052
3053                         *damage_flash += 100.0;
3054                         *damage_flash += 8.0 * event.player_damage.amount;
3055
3056                         player->hurt_tilt_timer = 1.5;
3057                         player->hurt_tilt_strength = event.player_damage.amount / 4;
3058                         player->hurt_tilt_strength = rangelim(player->hurt_tilt_strength, 1.0, 4.0);
3059
3060                         MtEvent *e = new SimpleTriggerEvent("PlayerDamage");
3061                         gamedef->event()->put(e);
3062                 } else if (event.type == CE_PLAYER_FORCE_MOVE) {
3063                         cam->camera_yaw = event.player_force_move.yaw;
3064                         cam->camera_pitch = event.player_force_move.pitch;
3065                 } else if (event.type == CE_DEATHSCREEN) {
3066                         show_deathscreen(&current_formspec, client, gamedef, texture_src,
3067                                          device, client);
3068
3069                         chat_backend->addMessage(L"", L"You died.");
3070
3071                         /* Handle visualization */
3072                         *damage_flash = 0;
3073                         player->hurt_tilt_timer = 0;
3074                         player->hurt_tilt_strength = 0;
3075
3076                 } else if (event.type == CE_SHOW_FORMSPEC) {
3077                         FormspecFormSource *fs_src =
3078                                 new FormspecFormSource(*(event.show_formspec.formspec));
3079                         TextDestPlayerInventory *txt_dst =
3080                                 new TextDestPlayerInventory(client, *(event.show_formspec.formname));
3081
3082                         create_formspec_menu(&current_formspec, client, gamedef,
3083                                              texture_src, device, fs_src, txt_dst, client);
3084
3085                         delete(event.show_formspec.formspec);
3086                         delete(event.show_formspec.formname);
3087                 } else if ((event.type == CE_SPAWN_PARTICLE) ||
3088                                 (event.type == CE_ADD_PARTICLESPAWNER) ||
3089                                 (event.type == CE_DELETE_PARTICLESPAWNER)) {
3090                         client->getParticleManager()->handleParticleEvent(&event, gamedef,
3091                                         smgr, player);
3092                 } else if (event.type == CE_HUDADD) {
3093                         u32 id = event.hudadd.id;
3094
3095                         LocalPlayer *player = client->getEnv().getLocalPlayer();
3096                         HudElement *e = player->getHud(id);
3097
3098                         if (e != NULL) {
3099                                 delete event.hudadd.pos;
3100                                 delete event.hudadd.name;
3101                                 delete event.hudadd.scale;
3102                                 delete event.hudadd.text;
3103                                 delete event.hudadd.align;
3104                                 delete event.hudadd.offset;
3105                                 delete event.hudadd.world_pos;
3106                                 delete event.hudadd.size;
3107                                 continue;
3108                         }
3109
3110                         e = new HudElement;
3111                         e->type   = (HudElementType)event.hudadd.type;
3112                         e->pos    = *event.hudadd.pos;
3113                         e->name   = *event.hudadd.name;
3114                         e->scale  = *event.hudadd.scale;
3115                         e->text   = *event.hudadd.text;
3116                         e->number = event.hudadd.number;
3117                         e->item   = event.hudadd.item;
3118                         e->dir    = event.hudadd.dir;
3119                         e->align  = *event.hudadd.align;
3120                         e->offset = *event.hudadd.offset;
3121                         e->world_pos = *event.hudadd.world_pos;
3122                         e->size = *event.hudadd.size;
3123
3124                         u32 new_id = player->addHud(e);
3125                         //if this isn't true our huds aren't consistent
3126                         sanity_check(new_id == id);
3127
3128                         delete event.hudadd.pos;
3129                         delete event.hudadd.name;
3130                         delete event.hudadd.scale;
3131                         delete event.hudadd.text;
3132                         delete event.hudadd.align;
3133                         delete event.hudadd.offset;
3134                         delete event.hudadd.world_pos;
3135                         delete event.hudadd.size;
3136                 } else if (event.type == CE_HUDRM) {
3137                         HudElement *e = player->removeHud(event.hudrm.id);
3138
3139                         if (e != NULL)
3140                                 delete(e);
3141                 } else if (event.type == CE_HUDCHANGE) {
3142                         u32 id = event.hudchange.id;
3143                         HudElement *e = player->getHud(id);
3144
3145                         if (e == NULL) {
3146                                 delete event.hudchange.v3fdata;
3147                                 delete event.hudchange.v2fdata;
3148                                 delete event.hudchange.sdata;
3149                                 delete event.hudchange.v2s32data;
3150                                 continue;
3151                         }
3152
3153                         switch (event.hudchange.stat) {
3154                         case HUD_STAT_POS:
3155                                 e->pos = *event.hudchange.v2fdata;
3156                                 break;
3157
3158                         case HUD_STAT_NAME:
3159                                 e->name = *event.hudchange.sdata;
3160                                 break;
3161
3162                         case HUD_STAT_SCALE:
3163                                 e->scale = *event.hudchange.v2fdata;
3164                                 break;
3165
3166                         case HUD_STAT_TEXT:
3167                                 e->text = *event.hudchange.sdata;
3168                                 break;
3169
3170                         case HUD_STAT_NUMBER:
3171                                 e->number = event.hudchange.data;
3172                                 break;
3173
3174                         case HUD_STAT_ITEM:
3175                                 e->item = event.hudchange.data;
3176                                 break;
3177
3178                         case HUD_STAT_DIR:
3179                                 e->dir = event.hudchange.data;
3180                                 break;
3181
3182                         case HUD_STAT_ALIGN:
3183                                 e->align = *event.hudchange.v2fdata;
3184                                 break;
3185
3186                         case HUD_STAT_OFFSET:
3187                                 e->offset = *event.hudchange.v2fdata;
3188                                 break;
3189
3190                         case HUD_STAT_WORLD_POS:
3191                                 e->world_pos = *event.hudchange.v3fdata;
3192                                 break;
3193
3194                         case HUD_STAT_SIZE:
3195                                 e->size = *event.hudchange.v2s32data;
3196                                 break;
3197                         }
3198
3199                         delete event.hudchange.v3fdata;
3200                         delete event.hudchange.v2fdata;
3201                         delete event.hudchange.sdata;
3202                         delete event.hudchange.v2s32data;
3203                 } else if (event.type == CE_SET_SKY) {
3204                         sky->setVisible(false);
3205
3206                         if (skybox) {
3207                                 skybox->remove();
3208                                 skybox = NULL;
3209                         }
3210
3211                         // Handle according to type
3212                         if (*event.set_sky.type == "regular") {
3213                                 sky->setVisible(true);
3214                         } else if (*event.set_sky.type == "skybox" &&
3215                                         event.set_sky.params->size() == 6) {
3216                                 sky->setFallbackBgColor(*event.set_sky.bgcolor);
3217                                 skybox = smgr->addSkyBoxSceneNode(
3218                                                  texture_src->getTextureForMesh((*event.set_sky.params)[0]),
3219                                                  texture_src->getTextureForMesh((*event.set_sky.params)[1]),
3220                                                  texture_src->getTextureForMesh((*event.set_sky.params)[2]),
3221                                                  texture_src->getTextureForMesh((*event.set_sky.params)[3]),
3222                                                  texture_src->getTextureForMesh((*event.set_sky.params)[4]),
3223                                                  texture_src->getTextureForMesh((*event.set_sky.params)[5]));
3224                         }
3225                         // Handle everything else as plain color
3226                         else {
3227                                 if (*event.set_sky.type != "plain")
3228                                         infostream << "Unknown sky type: "
3229                                                    << (*event.set_sky.type) << std::endl;
3230
3231                                 sky->setFallbackBgColor(*event.set_sky.bgcolor);
3232                         }
3233
3234                         delete event.set_sky.bgcolor;
3235                         delete event.set_sky.type;
3236                         delete event.set_sky.params;
3237                 } else if (event.type == CE_OVERRIDE_DAY_NIGHT_RATIO) {
3238                         bool enable = event.override_day_night_ratio.do_override;
3239                         u32 value = event.override_day_night_ratio.ratio_f * 1000;
3240                         client->getEnv().setDayNightRatioOverride(enable, value);
3241                 }
3242         }
3243 }
3244
3245
3246 void Game::updateCamera(VolatileRunFlags *flags, u32 busy_time,
3247                 f32 dtime, float time_from_last_punch)
3248 {
3249         LocalPlayer *player = client->getEnv().getLocalPlayer();
3250
3251         /*
3252                 For interaction purposes, get info about the held item
3253                 - What item is it?
3254                 - Is it a usable item?
3255                 - Can it point to liquids?
3256         */
3257         ItemStack playeritem;
3258         {
3259                 InventoryList *mlist = local_inventory->getList("main");
3260
3261                 if (mlist && client->getPlayerItem() < mlist->getSize())
3262                         playeritem = mlist->getItem(client->getPlayerItem());
3263         }
3264
3265         ToolCapabilities playeritem_toolcap =
3266                 playeritem.getToolCapabilities(itemdef_manager);
3267
3268         v3s16 old_camera_offset = camera->getOffset();
3269
3270         if (input->wasKeyDown(keycache.key[KeyCache::KEYMAP_ID_CAMERA_MODE])) {
3271                 GenericCAO *playercao = player->getCAO();
3272
3273                 // If playercao not loaded, don't change camera
3274                 if (playercao == NULL)
3275                         return;
3276
3277                 camera->toggleCameraMode();
3278
3279                 playercao->setVisible(camera->getCameraMode() > CAMERA_MODE_FIRST);
3280         }
3281
3282         float full_punch_interval = playeritem_toolcap.full_punch_interval;
3283         float tool_reload_ratio = time_from_last_punch / full_punch_interval;
3284
3285         tool_reload_ratio = MYMIN(tool_reload_ratio, 1.0);
3286         camera->update(player, dtime, busy_time / 1000.0f, tool_reload_ratio,
3287                       client->getEnv());
3288         camera->step(dtime);
3289
3290         v3f camera_position = camera->getPosition();
3291         v3f camera_direction = camera->getDirection();
3292         f32 camera_fov = camera->getFovMax();
3293         v3s16 camera_offset = camera->getOffset();
3294
3295         flags->camera_offset_changed = (camera_offset != old_camera_offset);
3296
3297         if (!flags->disable_camera_update) {
3298                 client->getEnv().getClientMap().updateCamera(camera_position,
3299                                 camera_direction, camera_fov, camera_offset);
3300
3301                 if (flags->camera_offset_changed) {
3302                         client->updateCameraOffset(camera_offset);
3303                         client->getEnv().updateCameraOffset(camera_offset);
3304
3305                         if (clouds)
3306                                 clouds->updateCameraOffset(camera_offset);
3307                 }
3308         }
3309 }
3310
3311
3312 void Game::updateSound(f32 dtime)
3313 {
3314         // Update sound listener
3315         v3s16 camera_offset = camera->getOffset();
3316         sound->updateListener(camera->getCameraNode()->getPosition() + intToFloat(camera_offset, BS),
3317                               v3f(0, 0, 0), // velocity
3318                               camera->getDirection(),
3319                               camera->getCameraNode()->getUpVector());
3320         sound->setListenerGain(g_settings->getFloat("sound_volume"));
3321
3322
3323         //      Update sound maker
3324         soundmaker->step(dtime);
3325
3326         LocalPlayer *player = client->getEnv().getLocalPlayer();
3327
3328         ClientMap &map = client->getEnv().getClientMap();
3329         MapNode n = map.getNodeNoEx(player->getStandingNodePos());
3330         soundmaker->m_player_step_sound = nodedef_manager->get(n).sound_footstep;
3331 }
3332
3333
3334 void Game::processPlayerInteraction(std::vector<aabb3f> &highlight_boxes,
3335                 GameRunData *runData, f32 dtime, bool show_hud, bool show_debug)
3336 {
3337         LocalPlayer *player = client->getEnv().getLocalPlayer();
3338
3339         ItemStack playeritem;
3340         {
3341                 InventoryList *mlist = local_inventory->getList("main");
3342
3343                 if (mlist && client->getPlayerItem() < mlist->getSize())
3344                         playeritem = mlist->getItem(client->getPlayerItem());
3345         }
3346
3347         const ItemDefinition &playeritem_def =
3348                         playeritem.getDefinition(itemdef_manager);
3349
3350         v3f player_position  = player->getPosition();
3351         v3f camera_position  = camera->getPosition();
3352         v3f camera_direction = camera->getDirection();
3353         v3s16 camera_offset  = camera->getOffset();
3354
3355
3356         /*
3357                 Calculate what block is the crosshair pointing to
3358         */
3359
3360         f32 d = playeritem_def.range; // max. distance
3361         f32 d_hand = itemdef_manager->get("").range;
3362
3363         if (d < 0 && d_hand >= 0)
3364                 d = d_hand;
3365         else if (d < 0)
3366                 d = 4.0;
3367
3368         core::line3d<f32> shootline;
3369
3370         if (camera->getCameraMode() != CAMERA_MODE_THIRD_FRONT) {
3371
3372                 shootline = core::line3d<f32>(camera_position,
3373                                                 camera_position + camera_direction * BS * (d + 1));
3374
3375         } else {
3376             // prevent player pointing anything in front-view
3377                 if (camera->getCameraMode() == CAMERA_MODE_THIRD_FRONT)
3378                         shootline = core::line3d<f32>(0, 0, 0, 0, 0, 0);
3379         }
3380
3381 #ifdef HAVE_TOUCHSCREENGUI
3382
3383         if ((g_settings->getBool("touchtarget")) && (g_touchscreengui)) {
3384                 shootline = g_touchscreengui->getShootline();
3385                 shootline.start += intToFloat(camera_offset, BS);
3386                 shootline.end += intToFloat(camera_offset, BS);
3387         }
3388
3389 #endif
3390
3391         PointedThing pointed = getPointedThing(
3392                         // input
3393                         client, player_position, camera_direction,
3394                         camera_position, shootline, d,
3395                         playeritem_def.liquids_pointable,
3396                         !runData->ldown_for_dig,
3397                         camera_offset,
3398                         // output
3399                         highlight_boxes,
3400                         runData->selected_object);
3401
3402         if (pointed != runData->pointed_old) {
3403                 infostream << "Pointing at " << pointed.dump() << std::endl;
3404
3405                 if (m_cache_enable_node_highlighting) {
3406                         if (pointed.type == POINTEDTHING_NODE) {
3407                                 client->setHighlighted(pointed.node_undersurface, show_hud);
3408                         } else {
3409                                 client->setHighlighted(pointed.node_undersurface, false);
3410                         }
3411                 }
3412         }
3413
3414         /*
3415                 Stop digging when
3416                 - releasing left mouse button
3417                 - pointing away from node
3418         */
3419         if (runData->digging) {
3420                 if (input->getLeftReleased()) {
3421                         infostream << "Left button released"
3422                                    << " (stopped digging)" << std::endl;
3423                         runData->digging = false;
3424                 } else if (pointed != runData->pointed_old) {
3425                         if (pointed.type == POINTEDTHING_NODE
3426                                         && runData->pointed_old.type == POINTEDTHING_NODE
3427                                         && pointed.node_undersurface
3428                                                         == runData->pointed_old.node_undersurface) {
3429                                 // Still pointing to the same node, but a different face.
3430                                 // Don't reset.
3431                         } else {
3432                                 infostream << "Pointing away from node"
3433                                            << " (stopped digging)" << std::endl;
3434                                 runData->digging = false;
3435                         }
3436                 }
3437
3438                 if (!runData->digging) {
3439                         client->interact(1, runData->pointed_old);
3440                         client->setCrack(-1, v3s16(0, 0, 0));
3441                         runData->dig_time = 0.0;
3442                 }
3443         }
3444
3445         if (!runData->digging && runData->ldown_for_dig && !input->getLeftState()) {
3446                 runData->ldown_for_dig = false;
3447         }
3448
3449         runData->left_punch = false;
3450
3451         soundmaker->m_player_leftpunch_sound.name = "";
3452
3453         if (input->getRightState())
3454                 runData->repeat_rightclick_timer += dtime;
3455         else
3456                 runData->repeat_rightclick_timer = 0;
3457
3458         if (playeritem_def.usable && input->getLeftState()) {
3459                 if (input->getLeftClicked())
3460                         client->interact(4, pointed);
3461         } else if (pointed.type == POINTEDTHING_NODE) {
3462                 ToolCapabilities playeritem_toolcap =
3463                                 playeritem.getToolCapabilities(itemdef_manager);
3464                 handlePointingAtNode(runData, pointed, playeritem_def,
3465                                 playeritem_toolcap, dtime);
3466         } else if (pointed.type == POINTEDTHING_OBJECT) {
3467                 handlePointingAtObject(runData, pointed, playeritem,
3468                                 player_position, show_debug);
3469         } else if (input->getLeftState()) {
3470                 // When button is held down in air, show continuous animation
3471                 runData->left_punch = true;
3472         }
3473
3474         runData->pointed_old = pointed;
3475
3476         if (runData->left_punch || input->getLeftClicked())
3477                 camera->setDigging(0); // left click animation
3478
3479         input->resetLeftClicked();
3480         input->resetRightClicked();
3481
3482         input->resetLeftReleased();
3483         input->resetRightReleased();
3484 }
3485
3486
3487 void Game::handlePointingAtNode(GameRunData *runData,
3488                 const PointedThing &pointed, const ItemDefinition &playeritem_def,
3489                 const ToolCapabilities &playeritem_toolcap, f32 dtime)
3490 {
3491         v3s16 nodepos = pointed.node_undersurface;
3492         v3s16 neighbourpos = pointed.node_abovesurface;
3493
3494         /*
3495                 Check information text of node
3496         */
3497
3498         ClientMap &map = client->getEnv().getClientMap();
3499         NodeMetadata *meta = map.getNodeMetadata(nodepos);
3500
3501         if (meta) {
3502                 infotext = narrow_to_wide(meta->getString("infotext"));
3503         } else {
3504                 MapNode n = map.getNodeNoEx(nodepos);
3505
3506                 if (nodedef_manager->get(n).tiledef[0].name == "unknown_node.png") {
3507                         infotext = L"Unknown node: ";
3508                         infotext += narrow_to_wide(nodedef_manager->get(n).name);
3509                 }
3510         }
3511
3512         if (runData->nodig_delay_timer <= 0.0 && input->getLeftState()
3513                         && client->checkPrivilege("interact")) {
3514                 handleDigging(runData, pointed, nodepos, playeritem_toolcap, dtime);
3515         }
3516
3517         if ((input->getRightClicked() ||
3518                         runData->repeat_rightclick_timer >= m_repeat_right_click_time) &&
3519                         client->checkPrivilege("interact")) {
3520                 runData->repeat_rightclick_timer = 0;
3521                 infostream << "Ground right-clicked" << std::endl;
3522
3523                 if (meta && meta->getString("formspec") != "" && !random_input
3524                                 && !input->isKeyDown(getKeySetting("keymap_sneak"))) {
3525                         infostream << "Launching custom inventory view" << std::endl;
3526
3527                         InventoryLocation inventoryloc;
3528                         inventoryloc.setNodeMeta(nodepos);
3529
3530                         NodeMetadataFormSource *fs_src = new NodeMetadataFormSource(
3531                                 &client->getEnv().getClientMap(), nodepos);
3532                         TextDest *txt_dst = new TextDestNodeMetadata(nodepos, client);
3533
3534                         create_formspec_menu(&current_formspec, client, gamedef,
3535                                              texture_src, device, fs_src, txt_dst, client);
3536
3537                         current_formspec->setFormSpec(meta->getString("formspec"), inventoryloc);
3538                 } else {
3539                         // Report right click to server
3540
3541                         camera->setDigging(1);  // right click animation (always shown for feedback)
3542
3543                         // If the wielded item has node placement prediction,
3544                         // make that happen
3545                         bool placed = nodePlacementPrediction(*client,
3546                                         playeritem_def,
3547                                         nodepos, neighbourpos);
3548
3549                         if (placed) {
3550                                 // Report to server
3551                                 client->interact(3, pointed);
3552                                 // Read the sound
3553                                 soundmaker->m_player_rightpunch_sound =
3554                                                 playeritem_def.sound_place;
3555                         } else {
3556                                 soundmaker->m_player_rightpunch_sound =
3557                                                 SimpleSoundSpec();
3558                         }
3559
3560                         if (playeritem_def.node_placement_prediction == "" ||
3561                                         nodedef_manager->get(map.getNodeNoEx(nodepos)).rightclickable)
3562                                 client->interact(3, pointed); // Report to server
3563                 }
3564         }
3565 }
3566
3567
3568 void Game::handlePointingAtObject(GameRunData *runData,
3569                 const PointedThing &pointed,
3570                 const ItemStack &playeritem,
3571                 const v3f &player_position,
3572                 bool show_debug)
3573 {
3574         infotext = narrow_to_wide(runData->selected_object->infoText());
3575
3576         if (infotext == L"" && show_debug) {
3577                 infotext = narrow_to_wide(runData->selected_object->debugInfoText());
3578         }
3579
3580         if (input->getLeftState()) {
3581                 bool do_punch = false;
3582                 bool do_punch_damage = false;
3583
3584                 if (runData->object_hit_delay_timer <= 0.0) {
3585                         do_punch = true;
3586                         do_punch_damage = true;
3587                         runData->object_hit_delay_timer = object_hit_delay;
3588                 }
3589
3590                 if (input->getLeftClicked())
3591                         do_punch = true;
3592
3593                 if (do_punch) {
3594                         infostream << "Left-clicked object" << std::endl;
3595                         runData->left_punch = true;
3596                 }
3597
3598                 if (do_punch_damage) {
3599                         // Report direct punch
3600                         v3f objpos = runData->selected_object->getPosition();
3601                         v3f dir = (objpos - player_position).normalize();
3602
3603                         bool disable_send = runData->selected_object->directReportPunch(
3604                                         dir, &playeritem, runData->time_from_last_punch);
3605                         runData->time_from_last_punch = 0;
3606
3607                         if (!disable_send)
3608                                 client->interact(0, pointed);
3609                 }
3610         } else if (input->getRightClicked()) {
3611                 infostream << "Right-clicked object" << std::endl;
3612                 client->interact(3, pointed);  // place
3613         }
3614 }
3615
3616
3617 void Game::handleDigging(GameRunData *runData,
3618                 const PointedThing &pointed, const v3s16 &nodepos,
3619                 const ToolCapabilities &playeritem_toolcap, f32 dtime)
3620 {
3621         if (!runData->digging) {
3622                 infostream << "Started digging" << std::endl;
3623                 client->interact(0, pointed);
3624                 runData->digging = true;
3625                 runData->ldown_for_dig = true;
3626         }
3627
3628         LocalPlayer *player = client->getEnv().getLocalPlayer();
3629         ClientMap &map = client->getEnv().getClientMap();
3630         MapNode n = client->getEnv().getClientMap().getNodeNoEx(nodepos);
3631
3632         // NOTE: Similar piece of code exists on the server side for
3633         // cheat detection.
3634         // Get digging parameters
3635         DigParams params = getDigParams(nodedef_manager->get(n).groups,
3636                         &playeritem_toolcap);
3637
3638         // If can't dig, try hand
3639         if (!params.diggable) {
3640                 const ItemDefinition &hand = itemdef_manager->get("");
3641                 const ToolCapabilities *tp = hand.tool_capabilities;
3642
3643                 if (tp)
3644                         params = getDigParams(nodedef_manager->get(n).groups, tp);
3645         }
3646
3647         if (params.diggable == false) {
3648                 // I guess nobody will wait for this long
3649                 runData->dig_time_complete = 10000000.0;
3650         } else {
3651                 runData->dig_time_complete = params.time;
3652
3653                 if (m_cache_enable_particles) {
3654                         const ContentFeatures &features =
3655                                         client->getNodeDefManager()->get(n);
3656                         client->getParticleManager()->addPunchingParticles(gamedef, smgr,
3657                                         player, nodepos, features.tiles);
3658                 }
3659         }
3660
3661         if (runData->dig_time_complete >= 0.001) {
3662                 runData->dig_index = (float)crack_animation_length
3663                                 * runData->dig_time
3664                                 / runData->dig_time_complete;
3665         } else {
3666                 // This is for torches
3667                 runData->dig_index = crack_animation_length;
3668         }
3669
3670         SimpleSoundSpec sound_dig = nodedef_manager->get(n).sound_dig;
3671
3672         if (sound_dig.exists() && params.diggable) {
3673                 if (sound_dig.name == "__group") {
3674                         if (params.main_group != "") {
3675                                 soundmaker->m_player_leftpunch_sound.gain = 0.5;
3676                                 soundmaker->m_player_leftpunch_sound.name =
3677                                                 std::string("default_dig_") +
3678                                                 params.main_group;
3679                         }
3680                 } else {
3681                         soundmaker->m_player_leftpunch_sound = sound_dig;
3682                 }
3683         }
3684
3685         // Don't show cracks if not diggable
3686         if (runData->dig_time_complete >= 100000.0) {
3687         } else if (runData->dig_index < crack_animation_length) {
3688                 //TimeTaker timer("client.setTempMod");
3689                 //infostream<<"dig_index="<<dig_index<<std::endl;
3690                 client->setCrack(runData->dig_index, nodepos);
3691         } else {
3692                 infostream << "Digging completed" << std::endl;
3693                 client->interact(2, pointed);
3694                 client->setCrack(-1, v3s16(0, 0, 0));
3695                 bool is_valid_position;
3696                 MapNode wasnode = map.getNodeNoEx(nodepos, &is_valid_position);
3697                 if (is_valid_position)
3698                         client->removeNode(nodepos);
3699
3700                 if (m_cache_enable_particles) {
3701                         const ContentFeatures &features =
3702                                 client->getNodeDefManager()->get(wasnode);
3703                         client->getParticleManager()->addDiggingParticles(gamedef, smgr,
3704                                         player, nodepos, features.tiles);
3705                 }
3706
3707                 runData->dig_time = 0;
3708                 runData->digging = false;
3709
3710                 runData->nodig_delay_timer =
3711                                 runData->dig_time_complete / (float)crack_animation_length;
3712
3713                 // We don't want a corresponding delay to
3714                 // very time consuming nodes
3715                 if (runData->nodig_delay_timer > 0.3)
3716                         runData->nodig_delay_timer = 0.3;
3717
3718                 // We want a slight delay to very little
3719                 // time consuming nodes
3720                 const float mindelay = 0.15;
3721
3722                 if (runData->nodig_delay_timer < mindelay)
3723                         runData->nodig_delay_timer = mindelay;
3724
3725                 // Send event to trigger sound
3726                 MtEvent *e = new NodeDugEvent(nodepos, wasnode);
3727                 gamedef->event()->put(e);
3728         }
3729
3730         if (runData->dig_time_complete < 100000.0) {
3731                 runData->dig_time += dtime;
3732         } else {
3733                 runData->dig_time = 0;
3734                 client->setCrack(-1, nodepos);
3735         }
3736
3737         camera->setDigging(0);  // left click animation
3738 }
3739
3740
3741 void Game::updateFrame(std::vector<aabb3f> &highlight_boxes,
3742                 ProfilerGraph *graph, RunStats *stats, GameRunData *runData,
3743                 f32 dtime, const VolatileRunFlags &flags, const CameraOrientation &cam)
3744 {
3745         LocalPlayer *player = client->getEnv().getLocalPlayer();
3746
3747         /*
3748                 Fog range
3749         */
3750
3751         if (draw_control->range_all) {
3752                 runData->fog_range = 100000 * BS;
3753         } else {
3754                 runData->fog_range = draw_control->wanted_range * BS
3755                                 + 0.0 * MAP_BLOCKSIZE * BS;
3756                 runData->fog_range = MYMIN(
3757                                 runData->fog_range,
3758                                 (draw_control->farthest_drawn + 20) * BS);
3759                 runData->fog_range *= 0.9;
3760         }
3761
3762         /*
3763                 Calculate general brightness
3764         */
3765         u32 daynight_ratio = client->getEnv().getDayNightRatio();
3766         float time_brightness = decode_light_f((float)daynight_ratio / 1000.0);
3767         float direct_brightness;
3768         bool sunlight_seen;
3769
3770         if (g_settings->getBool("free_move")) {
3771                 direct_brightness = time_brightness;
3772                 sunlight_seen = true;
3773         } else {
3774                 ScopeProfiler sp(g_profiler, "Detecting background light", SPT_AVG);
3775                 float old_brightness = sky->getBrightness();
3776                 direct_brightness = client->getEnv().getClientMap()
3777                                 .getBackgroundBrightness(MYMIN(runData->fog_range * 1.2, 60 * BS),
3778                                         daynight_ratio, (int)(old_brightness * 255.5), &sunlight_seen)
3779                                     / 255.0;
3780         }
3781
3782         float time_of_day = runData->time_of_day;
3783         float time_of_day_smooth = runData->time_of_day_smooth;
3784
3785         time_of_day = client->getEnv().getTimeOfDayF();
3786
3787         const float maxsm = 0.05;
3788         const float todsm = 0.05;
3789
3790         if (fabs(time_of_day - time_of_day_smooth) > maxsm &&
3791                         fabs(time_of_day - time_of_day_smooth + 1.0) > maxsm &&
3792                         fabs(time_of_day - time_of_day_smooth - 1.0) > maxsm)
3793                 time_of_day_smooth = time_of_day;
3794
3795         if (time_of_day_smooth > 0.8 && time_of_day < 0.2)
3796                 time_of_day_smooth = time_of_day_smooth * (1.0 - todsm)
3797                                 + (time_of_day + 1.0) * todsm;
3798         else
3799                 time_of_day_smooth = time_of_day_smooth * (1.0 - todsm)
3800                                 + time_of_day * todsm;
3801
3802         runData->time_of_day = time_of_day;
3803         runData->time_of_day_smooth = time_of_day_smooth;
3804
3805         sky->update(time_of_day_smooth, time_brightness, direct_brightness,
3806                         sunlight_seen, camera->getCameraMode(), player->getYaw(),
3807                         player->getPitch());
3808
3809         /*
3810                 Update clouds
3811         */
3812         if (clouds) {
3813                 v3f player_position = player->getPosition();
3814                 if (sky->getCloudsVisible()) {
3815                         clouds->setVisible(true);
3816                         clouds->step(dtime);
3817                         clouds->update(v2f(player_position.X, player_position.Z),
3818                                        sky->getCloudColor());
3819                 } else {
3820                         clouds->setVisible(false);
3821                 }
3822         }
3823
3824         /*
3825                 Update particles
3826         */
3827         client->getParticleManager()->step(dtime);
3828
3829         /*
3830                 Fog
3831         */
3832
3833         if (m_cache_enable_fog && !flags.force_fog_off) {
3834                 driver->setFog(
3835                                 sky->getBgColor(),
3836                                 video::EFT_FOG_LINEAR,
3837                                 runData->fog_range * 0.4,
3838                                 runData->fog_range * 1.0,
3839                                 0.01,
3840                                 false, // pixel fog
3841                                 false // range fog
3842                 );
3843         } else {
3844                 driver->setFog(
3845                                 sky->getBgColor(),
3846                                 video::EFT_FOG_LINEAR,
3847                                 100000 * BS,
3848                                 110000 * BS,
3849                                 0.01,
3850                                 false, // pixel fog
3851                                 false // range fog
3852                 );
3853         }
3854
3855         /*
3856                 Get chat messages from client
3857         */
3858
3859         v2u32 screensize = driver->getScreenSize();
3860
3861         updateChat(*client, dtime, flags.show_debug, screensize,
3862                         flags.show_chat, runData->profiler_current_page,
3863                         *chat_backend, guitext_chat);
3864
3865         /*
3866                 Inventory
3867         */
3868
3869         if (client->getPlayerItem() != runData->new_playeritem)
3870                 client->selectPlayerItem(runData->new_playeritem);
3871
3872         // Update local inventory if it has changed
3873         if (client->getLocalInventoryUpdated()) {
3874                 //infostream<<"Updating local inventory"<<std::endl;
3875                 client->getLocalInventory(*local_inventory);
3876                 runData->update_wielded_item_trigger = true;
3877         }
3878
3879         if (runData->update_wielded_item_trigger) {
3880                 // Update wielded tool
3881                 InventoryList *mlist = local_inventory->getList("main");
3882
3883                 if (mlist && (client->getPlayerItem() < mlist->getSize())) {
3884                         ItemStack item = mlist->getItem(client->getPlayerItem());
3885                         camera->wield(item);
3886                 }
3887                 runData->update_wielded_item_trigger = false;
3888         }
3889
3890         /*
3891                 Update block draw list every 200ms or when camera direction has
3892                 changed much
3893         */
3894         runData->update_draw_list_timer += dtime;
3895
3896         v3f camera_direction = camera->getDirection();
3897         if (runData->update_draw_list_timer >= 0.2
3898                         || runData->update_draw_list_last_cam_dir.getDistanceFrom(camera_direction) > 0.2
3899                         || flags.camera_offset_changed) {
3900                 runData->update_draw_list_timer = 0;
3901                 client->getEnv().getClientMap().updateDrawList(driver);
3902                 runData->update_draw_list_last_cam_dir = camera_direction;
3903         }
3904
3905         updateGui(&runData->statustext_time, *stats, *runData, dtime, flags, cam);
3906
3907         /*
3908            make sure menu is on top
3909            1. Delete formspec menu reference if menu was removed
3910            2. Else, make sure formspec menu is on top
3911         */
3912         if (current_formspec) {
3913                 if (current_formspec->getReferenceCount() == 1) {
3914                         current_formspec->drop();
3915                         current_formspec = NULL;
3916                 } else if (!noMenuActive()) {
3917                         guiroot->bringToFront(current_formspec);
3918                 }
3919         }
3920
3921         /*
3922                 Drawing begins
3923         */
3924
3925         video::SColor skycolor = sky->getSkyColor();
3926
3927         TimeTaker tt_draw("mainloop: draw");
3928         {
3929                 TimeTaker timer("beginScene");
3930                 driver->beginScene(true, true, skycolor);
3931                 stats->beginscenetime = timer.stop(true);
3932         }
3933
3934         draw_scene(driver, smgr, *camera, *client, player, *hud, guienv,
3935                         highlight_boxes, screensize, skycolor, flags.show_hud);
3936
3937         /*
3938                 Profiler graph
3939         */
3940         if (flags.show_profiler_graph)
3941                 graph->draw(10, screensize.Y - 10, driver, g_fontengine->getFont());
3942
3943         /*
3944                 Damage flash
3945         */
3946         if (runData->damage_flash > 0.0) {
3947                 video::SColor color(std::min(runData->damage_flash, 180.0f),
3948                                 180,
3949                                 0,
3950                                 0);
3951                 driver->draw2DRectangle(color,
3952                                         core::rect<s32>(0, 0, screensize.X, screensize.Y),
3953                                         NULL);
3954
3955                 runData->damage_flash -= 100.0 * dtime;
3956         }
3957
3958         /*
3959                 Damage camera tilt
3960         */
3961         if (player->hurt_tilt_timer > 0.0) {
3962                 player->hurt_tilt_timer -= dtime * 5;
3963
3964                 if (player->hurt_tilt_timer < 0)
3965                         player->hurt_tilt_strength = 0;
3966         }
3967
3968         /*
3969                 End scene
3970         */
3971         {
3972                 TimeTaker timer("endScene");
3973                 driver->endScene();
3974                 stats->endscenetime = timer.stop(true);
3975         }
3976
3977         stats->drawtime = tt_draw.stop(true);
3978         g_profiler->graphAdd("mainloop_draw", stats->drawtime / 1000.0f);
3979 }
3980
3981
3982 inline static const char *yawToDirectionString(int yaw)
3983 {
3984         // NOTE: TODO: This can be done mathematically without the else/else-if
3985         // cascade.
3986
3987         const char *player_direction;
3988
3989         yaw = wrapDegrees_0_360(yaw);
3990
3991         if (yaw >= 45 && yaw < 135)
3992                 player_direction = "West [-X]";
3993         else if (yaw >= 135 && yaw < 225)
3994                 player_direction = "South [-Z]";
3995         else if (yaw >= 225 && yaw < 315)
3996                 player_direction = "East [+X]";
3997         else
3998                 player_direction = "North [+Z]";
3999
4000         return player_direction;
4001 }
4002
4003
4004 void Game::updateGui(float *statustext_time, const RunStats &stats,
4005                 const GameRunData& runData, f32 dtime, const VolatileRunFlags &flags,
4006                 const CameraOrientation &cam)
4007 {
4008         v2u32 screensize = driver->getScreenSize();
4009         LocalPlayer *player = client->getEnv().getLocalPlayer();
4010         v3f player_position = player->getPosition();
4011
4012         if (flags.show_debug) {
4013                 static float drawtime_avg = 0;
4014                 drawtime_avg = drawtime_avg * 0.95 + stats.drawtime * 0.05;
4015
4016                 u16 fps = 1.0 / stats.dtime_jitter.avg;
4017                 //s32 fps = driver->getFPS();
4018
4019                 std::ostringstream os(std::ios_base::binary);
4020                 os << std::fixed
4021                    << PROJECT_NAME " " << g_version_hash
4022                    << " FPS = " << fps
4023                    << " (R: range_all=" << draw_control->range_all << ")"
4024                    << std::setprecision(0)
4025                    << " drawtime = " << drawtime_avg
4026                    << std::setprecision(1)
4027                    << ", dtime_jitter = "
4028                    << (stats.dtime_jitter.max_fraction * 100.0) << " %"
4029                    << std::setprecision(1)
4030                    << ", v_range = " << draw_control->wanted_range
4031                    << std::setprecision(3)
4032                    << ", RTT = " << client->getRTT();
4033                 guitext->setText(narrow_to_wide(os.str()).c_str());
4034                 guitext->setVisible(true);
4035         } else if (flags.show_hud || flags.show_chat) {
4036                 std::ostringstream os(std::ios_base::binary);
4037                 os << PROJECT_NAME " " << g_version_hash;
4038                 guitext->setText(narrow_to_wide(os.str()).c_str());
4039                 guitext->setVisible(true);
4040         } else {
4041                 guitext->setVisible(false);
4042         }
4043
4044         if (guitext->isVisible()) {
4045                 core::rect<s32> rect(
4046                                 5,              5,
4047                                 screensize.X,   5 + g_fontengine->getTextHeight()
4048                 );
4049                 guitext->setRelativePosition(rect);
4050         }
4051
4052         if (flags.show_debug) {
4053                 std::ostringstream os(std::ios_base::binary);
4054                 os << std::setprecision(1) << std::fixed
4055                    << "(" << (player_position.X / BS)
4056                    << ", " << (player_position.Y / BS)
4057                    << ", " << (player_position.Z / BS)
4058                    << ") (yaw=" << (wrapDegrees_0_360(cam.camera_yaw))
4059                    << " " << yawToDirectionString(cam.camera_yaw)
4060                    << ") (seed = " << ((u64)client->getMapSeed())
4061                    << ")";
4062
4063                 if (runData.pointed_old.type == POINTEDTHING_NODE) {
4064                         ClientMap &map = client->getEnv().getClientMap();
4065                         const INodeDefManager *nodedef = client->getNodeDefManager();
4066                         MapNode n = map.getNodeNoEx(runData.pointed_old.node_undersurface);
4067                         if (n.getContent() != CONTENT_IGNORE && nodedef->get(n).name != "unknown") {
4068                                 const ContentFeatures &features = nodedef->get(n);
4069                                 os << " (pointing_at = " << nodedef->get(n).name
4070                                    << " - " << features.tiledef[0].name.c_str()
4071                                    << ")";
4072                         }
4073                 }
4074
4075                 guitext2->setText(narrow_to_wide(os.str()).c_str());
4076                 guitext2->setVisible(true);
4077
4078                 core::rect<s32> rect(
4079                                 5,             5 + g_fontengine->getTextHeight(),
4080                                 screensize.X,  5 + g_fontengine->getTextHeight() * 2
4081                 );
4082                 guitext2->setRelativePosition(rect);
4083         } else {
4084                 guitext2->setVisible(false);
4085         }
4086
4087         guitext_info->setText(infotext.c_str());
4088         guitext_info->setVisible(flags.show_hud && g_menumgr.menuCount() == 0);
4089
4090         float statustext_time_max = 1.5;
4091
4092         if (!statustext.empty()) {
4093                 *statustext_time += dtime;
4094
4095                 if (*statustext_time >= statustext_time_max) {
4096                         statustext = L"";
4097                         *statustext_time = 0;
4098                 }
4099         }
4100
4101         guitext_status->setText(statustext.c_str());
4102         guitext_status->setVisible(!statustext.empty());
4103
4104         if (!statustext.empty()) {
4105                 s32 status_width  = guitext_status->getTextWidth();
4106                 s32 status_height = guitext_status->getTextHeight();
4107                 s32 status_y = screensize.Y - 150;
4108                 s32 status_x = (screensize.X - status_width) / 2;
4109                 core::rect<s32> rect(
4110                                 status_x , status_y - status_height,
4111                                 status_x + status_width, status_y
4112                 );
4113                 guitext_status->setRelativePosition(rect);
4114
4115                 // Fade out
4116                 video::SColor initial_color(255, 0, 0, 0);
4117
4118                 if (guienv->getSkin())
4119                         initial_color = guienv->getSkin()->getColor(gui::EGDC_BUTTON_TEXT);
4120
4121                 video::SColor final_color = initial_color;
4122                 final_color.setAlpha(0);
4123                 video::SColor fade_color = initial_color.getInterpolated_quadratic(
4124                                 initial_color, final_color,
4125                                 pow(*statustext_time / statustext_time_max, 2.0f));
4126                 guitext_status->setOverrideColor(fade_color);
4127                 guitext_status->enableOverrideColor(true);
4128         }
4129 }
4130
4131
4132 /* Log times and stuff for visualization */
4133 inline void Game::updateProfilerGraphs(ProfilerGraph *graph)
4134 {
4135         Profiler::GraphValues values;
4136         g_profiler->graphGet(values);
4137         graph->put(values);
4138 }
4139
4140
4141
4142 /****************************************************************************
4143  Misc
4144  ****************************************************************************/
4145
4146 /* On some computers framerate doesn't seem to be automatically limited
4147  */
4148 inline void Game::limitFps(FpsControl *fps_timings, f32 *dtime)
4149 {
4150         // not using getRealTime is necessary for wine
4151         device->getTimer()->tick(); // Maker sure device time is up-to-date
4152         u32 time = device->getTimer()->getTime();
4153         u32 last_time = fps_timings->last_time;
4154
4155         if (time > last_time)  // Make sure time hasn't overflowed
4156                 fps_timings->busy_time = time - last_time;
4157         else
4158                 fps_timings->busy_time = 0;
4159
4160         u32 frametime_min = 1000 / (g_menumgr.pausesGame()
4161                         ? g_settings->getFloat("pause_fps_max")
4162                         : g_settings->getFloat("fps_max"));
4163
4164         if (fps_timings->busy_time < frametime_min) {
4165                 fps_timings->sleep_time = frametime_min - fps_timings->busy_time;
4166                 device->sleep(fps_timings->sleep_time);
4167         } else {
4168                 fps_timings->sleep_time = 0;
4169         }
4170
4171         /* Get the new value of the device timer. Note that device->sleep() may
4172          * not sleep for the entire requested time as sleep may be interrupted and
4173          * therefore it is arguably more accurate to get the new time from the
4174          * device rather than calculating it by adding sleep_time to time.
4175          */
4176
4177         device->getTimer()->tick(); // Update device timer
4178         time = device->getTimer()->getTime();
4179
4180         if (time > last_time)  // Make sure last_time hasn't overflowed
4181                 *dtime = (time - last_time) / 1000.0;
4182         else
4183                 *dtime = 0;
4184
4185         fps_timings->last_time = time;
4186 }
4187
4188 // Note: This will free (using delete[])! \p msg. If you want to use it later,
4189 // pass a copy of it to this function
4190 // Note: \p msg must be allocated using new (not malloc())
4191 void Game::showOverlayMessage(const wchar_t *msg, float dtime,
4192                 int percent, bool draw_clouds)
4193 {
4194         draw_load_screen(msg, device, guienv, dtime, percent, draw_clouds);
4195         delete[] msg;
4196 }
4197
4198
4199 /****************************************************************************/
4200 /****************************************************************************
4201  Shutdown / cleanup
4202  ****************************************************************************/
4203 /****************************************************************************/
4204
4205 void Game::extendedResourceCleanup()
4206 {
4207         // Extended resource accounting
4208         infostream << "Irrlicht resources after cleanup:" << std::endl;
4209         infostream << "\tRemaining meshes   : "
4210                    << device->getSceneManager()->getMeshCache()->getMeshCount() << std::endl;
4211         infostream << "\tRemaining textures : "
4212                    << driver->getTextureCount() << std::endl;
4213
4214         for (unsigned int i = 0; i < driver->getTextureCount(); i++) {
4215                 irr::video::ITexture *texture = driver->getTextureByIndex(i);
4216                 infostream << "\t\t" << i << ":" << texture->getName().getPath().c_str()
4217                            << std::endl;
4218         }
4219
4220         clearTextureNameCache();
4221         infostream << "\tRemaining materials: "
4222                << driver-> getMaterialRendererCount()
4223                        << " (note: irrlicht doesn't support removing renderers)" << std::endl;
4224 }
4225
4226
4227 /****************************************************************************/
4228 /****************************************************************************
4229  extern function for launching the game
4230  ****************************************************************************/
4231 /****************************************************************************/
4232
4233 void the_game(bool *kill,
4234                 bool random_input,
4235                 InputHandler *input,
4236                 IrrlichtDevice *device,
4237
4238                 const std::string &map_dir,
4239                 const std::string &playername,
4240                 const std::string &password,
4241                 const std::string &address,         // If empty local server is created
4242                 u16 port,
4243
4244                 std::string &error_message,
4245                 ChatBackend &chat_backend,
4246                 const SubgameSpec &gamespec,        // Used for local game
4247                 bool simple_singleplayer_mode)
4248 {
4249         Game game;
4250
4251         /* Make a copy of the server address because if a local singleplayer server
4252          * is created then this is updated and we don't want to change the value
4253          * passed to us by the calling function
4254          */
4255         std::string server_address = address;
4256
4257         try {
4258
4259                 if (game.startup(kill, random_input, input, device, map_dir,
4260                                 playername, password, &server_address, port,
4261                                 error_message, &chat_backend, gamespec,
4262                                 simple_singleplayer_mode)) {
4263                         game.run();
4264                         game.shutdown();
4265                 }
4266
4267         } catch (SerializationError &e) {
4268                 error_message = std::string("A serialization error occurred:\n")
4269                                 + e.what() + "\n\nThe server is probably "
4270                                 " running a different version of " PROJECT_NAME ".";
4271                 errorstream << error_message << std::endl;
4272         } catch (ServerError &e) {
4273                 error_message = e.what();
4274                 errorstream << "ServerError: " << error_message << std::endl;
4275         } catch (ModError &e) {
4276                 error_message = e.what() + strgettext("\nCheck debug.txt for details.");
4277                 errorstream << "ModError: " << error_message << std::endl;
4278         }
4279 }
4280