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