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