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