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