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