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