Cleanup in content_mapblock (#5746)
[oweals/minetest.git] / src / game.cpp
1 /*
2 Minetest
3 Copyright (C) 2010-2013 celeron55, Perttu Ahola <celeron55@gmail.com>
4
5 This program is free software; you can redistribute it and/or modify
6 it under the terms of the GNU Lesser General Public License as published by
7 the Free Software Foundation; either version 2.1 of the License, or
8 (at your option) any later version.
9
10 This program is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13 GNU Lesser General Public License for more details.
14
15 You should have received a copy of the GNU Lesser General Public License along
16 with this program; if not, write to the Free Software Foundation, Inc.,
17 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
18 */
19
20 #include "game.h"
21
22 #include <iomanip>
23 #include "camera.h"
24 #include "client.h"
25 #include "client/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
1705         showOverlayMessage(wgettext("Shutting down..."), 0, 0, false);
1706
1707         if (clouds)
1708                 clouds->drop();
1709
1710         if (gui_chat_console)
1711                 gui_chat_console->drop();
1712
1713         if (sky)
1714                 sky->drop();
1715
1716         /* cleanup menus */
1717         while (g_menumgr.menuCount() > 0) {
1718                 g_menumgr.m_stack.front()->setVisible(false);
1719                 g_menumgr.deletingMenu(g_menumgr.m_stack.front());
1720         }
1721
1722         if (current_formspec) {
1723                 current_formspec->drop();
1724                 current_formspec = NULL;
1725         }
1726
1727         chat_backend->addMessage(L"", L"# Disconnected.");
1728         chat_backend->addMessage(L"", L"");
1729
1730         if (client) {
1731                 client->Stop();
1732                 while (!client->isShutdown()) {
1733                         assert(texture_src != NULL);
1734                         assert(shader_src != NULL);
1735                         texture_src->processQueue();
1736                         shader_src->processQueue();
1737                         sleep_ms(100);
1738                 }
1739         }
1740 }
1741
1742
1743 /****************************************************************************/
1744 /****************************************************************************
1745  Startup
1746  ****************************************************************************/
1747 /****************************************************************************/
1748
1749 bool Game::init(
1750                 const std::string &map_dir,
1751                 std::string *address,
1752                 u16 port,
1753                 const SubgameSpec &gamespec)
1754 {
1755         texture_src = createTextureSource(device);
1756
1757         showOverlayMessage(wgettext("Loading..."), 0, 0);
1758
1759         shader_src = createShaderSource(device);
1760
1761         itemdef_manager = createItemDefManager();
1762         nodedef_manager = createNodeDefManager();
1763
1764         eventmgr = new EventManager();
1765         quicktune = new QuicktuneShortcutter();
1766
1767         if (!(texture_src && shader_src && itemdef_manager && nodedef_manager
1768                         && eventmgr && quicktune))
1769                 return false;
1770
1771         if (!initSound())
1772                 return false;
1773
1774         // Create a server if not connecting to an existing one
1775         if (*address == "") {
1776                 if (!createSingleplayerServer(map_dir, gamespec, port, address))
1777                         return false;
1778         }
1779
1780         return true;
1781 }
1782
1783 bool Game::initSound()
1784 {
1785 #if USE_SOUND
1786         if (g_settings->getBool("enable_sound")) {
1787                 infostream << "Attempting to use OpenAL audio" << std::endl;
1788                 sound = createOpenALSoundManager(&soundfetcher);
1789                 if (!sound)
1790                         infostream << "Failed to initialize OpenAL audio" << std::endl;
1791         } else
1792                 infostream << "Sound disabled." << std::endl;
1793 #endif
1794
1795         if (!sound) {
1796                 infostream << "Using dummy audio." << std::endl;
1797                 sound = &dummySoundManager;
1798                 sound_is_dummy = true;
1799         }
1800
1801         soundmaker = new SoundMaker(sound, nodedef_manager);
1802         if (!soundmaker)
1803                 return false;
1804
1805         soundmaker->registerReceiver(eventmgr);
1806
1807         return true;
1808 }
1809
1810 bool Game::createSingleplayerServer(const std::string &map_dir,
1811                 const SubgameSpec &gamespec, u16 port, std::string *address)
1812 {
1813         showOverlayMessage(wgettext("Creating server..."), 0, 5);
1814
1815         std::string bind_str = g_settings->get("bind_address");
1816         Address bind_addr(0, 0, 0, 0, port);
1817
1818         if (g_settings->getBool("ipv6_server")) {
1819                 bind_addr.setAddress((IPv6AddressBytes *) NULL);
1820         }
1821
1822         try {
1823                 bind_addr.Resolve(bind_str.c_str());
1824         } catch (ResolveError &e) {
1825                 infostream << "Resolving bind address \"" << bind_str
1826                            << "\" failed: " << e.what()
1827                            << " -- Listening on all addresses." << std::endl;
1828         }
1829
1830         if (bind_addr.isIPv6() && !g_settings->getBool("enable_ipv6")) {
1831                 *error_message = "Unable to listen on " +
1832                                 bind_addr.serializeString() +
1833                                 " because IPv6 is disabled";
1834                 errorstream << *error_message << std::endl;
1835                 return false;
1836         }
1837
1838         server = new Server(map_dir, gamespec, simple_singleplayer_mode,
1839                             bind_addr.isIPv6(), false);
1840
1841         server->start(bind_addr);
1842
1843         return true;
1844 }
1845
1846 bool Game::createClient(const std::string &playername,
1847                 const std::string &password, std::string *address, u16 port)
1848 {
1849         showOverlayMessage(wgettext("Creating client..."), 0, 10);
1850
1851         draw_control = new MapDrawControl;
1852         if (!draw_control)
1853                 return false;
1854
1855         bool could_connect, connect_aborted;
1856
1857         if (!connectToServer(playername, password, address, port,
1858                         &could_connect, &connect_aborted))
1859                 return false;
1860
1861         if (!could_connect) {
1862                 if (error_message->empty() && !connect_aborted) {
1863                         // Should not happen if error messages are set properly
1864                         *error_message = "Connection failed for unknown reason";
1865                         errorstream << *error_message << std::endl;
1866                 }
1867                 return false;
1868         }
1869
1870         if (!getServerContent(&connect_aborted)) {
1871                 if (error_message->empty() && !connect_aborted) {
1872                         // Should not happen if error messages are set properly
1873                         *error_message = "Connection failed for unknown reason";
1874                         errorstream << *error_message << std::endl;
1875                 }
1876                 return false;
1877         }
1878
1879         GameGlobalShaderConstantSetterFactory *scsf = new GameGlobalShaderConstantSetterFactory(
1880                         &flags.force_fog_off, &runData.fog_range, client);
1881         shader_src->addShaderConstantSetterFactory(scsf);
1882
1883         // Update cached textures, meshes and materials
1884         client->afterContentReceived(device);
1885
1886         /* Camera
1887          */
1888         camera = new Camera(smgr, *draw_control, client);
1889         if (!camera || !camera->successfullyCreated(*error_message))
1890                 return false;
1891         client->setCamera(camera);
1892
1893         /* Clouds
1894          */
1895         if (m_cache_enable_clouds) {
1896                 clouds = new Clouds(smgr->getRootSceneNode(), smgr, -1, time(0));
1897                 if (!clouds) {
1898                         *error_message = "Memory allocation error (clouds)";
1899                         errorstream << *error_message << std::endl;
1900                         return false;
1901                 }
1902         }
1903
1904         /* Skybox
1905          */
1906         sky = new Sky(smgr->getRootSceneNode(), smgr, -1, texture_src);
1907         scsf->setSky(sky);
1908         skybox = NULL;  // This is used/set later on in the main run loop
1909
1910         local_inventory = new Inventory(itemdef_manager);
1911
1912         if (!(sky && local_inventory)) {
1913                 *error_message = "Memory allocation error (sky or local inventory)";
1914                 errorstream << *error_message << std::endl;
1915                 return false;
1916         }
1917
1918         /* Pre-calculated values
1919          */
1920         video::ITexture *t = texture_src->getTexture("crack_anylength.png");
1921         if (t) {
1922                 v2u32 size = t->getOriginalSize();
1923                 crack_animation_length = size.Y / size.X;
1924         } else {
1925                 crack_animation_length = 5;
1926         }
1927
1928         if (!initGui())
1929                 return false;
1930
1931         /* Set window caption
1932          */
1933         std::wstring str = utf8_to_wide(PROJECT_NAME_C);
1934         str += L" ";
1935         str += utf8_to_wide(g_version_hash);
1936         str += L" [";
1937         str += driver->getName();
1938         str += L"]";
1939         device->setWindowCaption(str.c_str());
1940
1941         LocalPlayer *player = client->getEnv().getLocalPlayer();
1942         player->hurt_tilt_timer = 0;
1943         player->hurt_tilt_strength = 0;
1944
1945         hud = new Hud(driver, smgr, guienv, client, player, local_inventory);
1946
1947         if (!hud) {
1948                 *error_message = "Memory error: could not create HUD";
1949                 errorstream << *error_message << std::endl;
1950                 return false;
1951         }
1952
1953         mapper = client->getMinimap();
1954         if (mapper)
1955                 mapper->setMinimapMode(MINIMAP_MODE_OFF);
1956
1957         return true;
1958 }
1959
1960 bool Game::initGui()
1961 {
1962         // First line of debug text
1963         guitext = addStaticText(guienv,
1964                         utf8_to_wide(PROJECT_NAME_C).c_str(),
1965                         core::rect<s32>(0, 0, 0, 0),
1966                         false, false, guiroot);
1967
1968         // Second line of debug text
1969         guitext2 = addStaticText(guienv,
1970                         L"",
1971                         core::rect<s32>(0, 0, 0, 0),
1972                         false, false, guiroot);
1973
1974         // At the middle of the screen
1975         // Object infos are shown in this
1976         guitext_info = addStaticText(guienv,
1977                         L"",
1978                         core::rect<s32>(0, 0, 400, g_fontengine->getTextHeight() * 5 + 5) + v2s32(100, 200),
1979                         false, true, guiroot);
1980
1981         // Status text (displays info when showing and hiding GUI stuff, etc.)
1982         guitext_status = addStaticText(guienv,
1983                         L"<Status>",
1984                         core::rect<s32>(0, 0, 0, 0),
1985                         false, false, guiroot);
1986         guitext_status->setVisible(false);
1987
1988         // Chat text
1989         guitext_chat = addStaticText(
1990                         guienv,
1991                         L"",
1992                         core::rect<s32>(0, 0, 0, 0),
1993                         //false, false); // Disable word wrap as of now
1994                         false, true, guiroot);
1995
1996         // Remove stale "recent" chat messages from previous connections
1997         chat_backend->clearRecentChat();
1998
1999         // Chat backend and console
2000         gui_chat_console = new GUIChatConsole(guienv, guienv->getRootGUIElement(),
2001                         -1, chat_backend, client, &g_menumgr);
2002         if (!gui_chat_console) {
2003                 *error_message = "Could not allocate memory for chat console";
2004                 errorstream << *error_message << std::endl;
2005                 return false;
2006         }
2007
2008         // Profiler text (size is updated when text is updated)
2009         guitext_profiler = addStaticText(guienv,
2010                         L"<Profiler>",
2011                         core::rect<s32>(0, 0, 0, 0),
2012                         false, false, guiroot);
2013         guitext_profiler->setBackgroundColor(video::SColor(120, 0, 0, 0));
2014         guitext_profiler->setVisible(false);
2015         guitext_profiler->setWordWrap(true);
2016
2017 #ifdef HAVE_TOUCHSCREENGUI
2018
2019         if (g_touchscreengui)
2020                 g_touchscreengui->init(texture_src);
2021
2022 #endif
2023
2024         return true;
2025 }
2026
2027 bool Game::connectToServer(const std::string &playername,
2028                 const std::string &password, std::string *address, u16 port,
2029                 bool *connect_ok, bool *aborted)
2030 {
2031         *connect_ok = false;    // Let's not be overly optimistic
2032         *aborted = false;
2033         bool local_server_mode = false;
2034
2035         showOverlayMessage(wgettext("Resolving address..."), 0, 15);
2036
2037         Address connect_address(0, 0, 0, 0, port);
2038
2039         try {
2040                 connect_address.Resolve(address->c_str());
2041
2042                 if (connect_address.isZero()) { // i.e. INADDR_ANY, IN6ADDR_ANY
2043                         //connect_address.Resolve("localhost");
2044                         if (connect_address.isIPv6()) {
2045                                 IPv6AddressBytes addr_bytes;
2046                                 addr_bytes.bytes[15] = 1;
2047                                 connect_address.setAddress(&addr_bytes);
2048                         } else {
2049                                 connect_address.setAddress(127, 0, 0, 1);
2050                         }
2051                         local_server_mode = true;
2052                 }
2053         } catch (ResolveError &e) {
2054                 *error_message = std::string("Couldn't resolve address: ") + e.what();
2055                 errorstream << *error_message << std::endl;
2056                 return false;
2057         }
2058
2059         if (connect_address.isIPv6() && !g_settings->getBool("enable_ipv6")) {
2060                 *error_message = "Unable to connect to " +
2061                                 connect_address.serializeString() +
2062                                 " because IPv6 is disabled";
2063                 errorstream << *error_message << std::endl;
2064                 return false;
2065         }
2066
2067         client = new Client(device,
2068                         playername.c_str(), password, *address,
2069                         *draw_control, texture_src, shader_src,
2070                         itemdef_manager, nodedef_manager, sound, eventmgr,
2071                         connect_address.isIPv6(), &flags);
2072
2073         if (!client)
2074                 return false;
2075
2076         infostream << "Connecting to server at ";
2077         connect_address.print(&infostream);
2078         infostream << std::endl;
2079
2080         client->connect(connect_address,
2081                 simple_singleplayer_mode || local_server_mode);
2082
2083         /*
2084                 Wait for server to accept connection
2085         */
2086
2087         try {
2088                 input->clear();
2089
2090                 FpsControl fps_control = { 0 };
2091                 f32 dtime;
2092                 f32 wait_time = 0; // in seconds
2093
2094                 fps_control.last_time = device->getTimer()->getTime();
2095
2096                 client->initMods();
2097
2098                 while (device->run()) {
2099
2100                         limitFps(&fps_control, &dtime);
2101
2102                         // Update client and server
2103                         client->step(dtime);
2104
2105                         if (server != NULL)
2106                                 server->step(dtime);
2107
2108                         // End condition
2109                         if (client->getState() == LC_Init) {
2110                                 *connect_ok = true;
2111                                 break;
2112                         }
2113
2114                         // Break conditions
2115                         if (client->accessDenied()) {
2116                                 *error_message = "Access denied. Reason: "
2117                                                 + client->accessDeniedReason();
2118                                 *reconnect_requested = client->reconnectRequested();
2119                                 errorstream << *error_message << std::endl;
2120                                 break;
2121                         }
2122
2123                         if (wasKeyDown(KeyType::ESC) || input->wasKeyDown(CancelKey)) {
2124                                 *aborted = true;
2125                                 infostream << "Connect aborted [Escape]" << std::endl;
2126                                 break;
2127                         }
2128
2129                         wait_time += dtime;
2130                         // Only time out if we aren't waiting for the server we started
2131                         if ((*address != "") && (wait_time > 10)) {
2132                                 bool sent_old_init = g_settings->getFlag("send_pre_v25_init");
2133                                 // If no pre v25 init was sent, and no answer was received,
2134                                 // but the low level connection could be established
2135                                 // (meaning that we have a peer id), then we probably wanted
2136                                 // to connect to a legacy server. In this case, tell the user
2137                                 // to enable the option to be able to connect.
2138                                 if (!sent_old_init &&
2139                                                 (client->getProtoVersion() == 0) &&
2140                                                 client->connectedToServer()) {
2141                                         *error_message = "Connection failure: init packet not "
2142                                         "recognized by server.\n"
2143                                         "Most likely the server uses an old protocol version (<v25).\n"
2144                                         "Please ask the server owner to update to 0.4.13 or later.\n"
2145                                         "To still connect to the server in the meantime,\n"
2146                                         "you can enable the 'send_pre_v25_init' setting by editing minetest.conf,\n"
2147                                         "or by enabling the 'Client -> Network -> Support older Servers'\n"
2148                                         "entry in the advanced settings menu.";
2149                                 } else {
2150                                         *error_message = "Connection timed out.";
2151                                 }
2152                                 errorstream << *error_message << std::endl;
2153                                 break;
2154                         }
2155
2156                         // Update status
2157                         showOverlayMessage(wgettext("Connecting to server..."), dtime, 20);
2158                 }
2159         } catch (con::PeerNotFoundException &e) {
2160                 // TODO: Should something be done here? At least an info/error
2161                 // message?
2162                 return false;
2163         }
2164
2165         return true;
2166 }
2167
2168 bool Game::getServerContent(bool *aborted)
2169 {
2170         input->clear();
2171
2172         FpsControl fps_control = { 0 };
2173         f32 dtime; // in seconds
2174
2175         fps_control.last_time = device->getTimer()->getTime();
2176
2177         while (device->run()) {
2178
2179                 limitFps(&fps_control, &dtime);
2180
2181                 // Update client and server
2182                 client->step(dtime);
2183
2184                 if (server != NULL)
2185                         server->step(dtime);
2186
2187                 // End condition
2188                 if (client->mediaReceived() && client->itemdefReceived() &&
2189                                 client->nodedefReceived()) {
2190                         break;
2191                 }
2192
2193                 // Error conditions
2194                 if (!checkConnection())
2195                         return false;
2196
2197                 if (client->getState() < LC_Init) {
2198                         *error_message = "Client disconnected";
2199                         errorstream << *error_message << std::endl;
2200                         return false;
2201                 }
2202
2203                 if (wasKeyDown(KeyType::ESC) || input->wasKeyDown(CancelKey)) {
2204                         *aborted = true;
2205                         infostream << "Connect aborted [Escape]" << std::endl;
2206                         return false;
2207                 }
2208
2209                 // Display status
2210                 int progress = 25;
2211
2212                 if (!client->itemdefReceived()) {
2213                         const wchar_t *text = wgettext("Item definitions...");
2214                         progress = 25;
2215                         draw_load_screen(text, device, guienv, texture_src,
2216                                 dtime, progress);
2217                         delete[] text;
2218                 } else if (!client->nodedefReceived()) {
2219                         const wchar_t *text = wgettext("Node definitions...");
2220                         progress = 30;
2221                         draw_load_screen(text, device, guienv, texture_src,
2222                                 dtime, progress);
2223                         delete[] text;
2224                 } else {
2225                         std::stringstream message;
2226                         std::fixed(message);
2227                         message.precision(0);
2228                         message << gettext("Media...") << " " << (client->mediaReceiveProgress()*100) << "%";
2229                         message.precision(2);
2230
2231                         if ((USE_CURL == 0) ||
2232                                         (!g_settings->getBool("enable_remote_media_server"))) {
2233                                 float cur = client->getCurRate();
2234                                 std::string cur_unit = gettext("KiB/s");
2235
2236                                 if (cur > 900) {
2237                                         cur /= 1024.0;
2238                                         cur_unit = gettext("MiB/s");
2239                                 }
2240
2241                                 message << " (" << cur << ' ' << cur_unit << ")";
2242                         }
2243
2244                         progress = 30 + client->mediaReceiveProgress() * 35 + 0.5;
2245                         draw_load_screen(utf8_to_wide(message.str()), device,
2246                                         guienv, texture_src, dtime, progress);
2247                 }
2248         }
2249
2250         return true;
2251 }
2252
2253
2254 /****************************************************************************/
2255 /****************************************************************************
2256  Run
2257  ****************************************************************************/
2258 /****************************************************************************/
2259
2260 inline void Game::updateInteractTimers(f32 dtime)
2261 {
2262         if (runData.nodig_delay_timer >= 0)
2263                 runData.nodig_delay_timer -= dtime;
2264
2265         if (runData.object_hit_delay_timer >= 0)
2266                 runData.object_hit_delay_timer -= dtime;
2267
2268         runData.time_from_last_punch += dtime;
2269 }
2270
2271
2272 /* returns false if game should exit, otherwise true
2273  */
2274 inline bool Game::checkConnection()
2275 {
2276         if (client->accessDenied()) {
2277                 *error_message = "Access denied. Reason: "
2278                                 + client->accessDeniedReason();
2279                 *reconnect_requested = client->reconnectRequested();
2280                 errorstream << *error_message << std::endl;
2281                 return false;
2282         }
2283
2284         return true;
2285 }
2286
2287
2288 /* returns false if game should exit, otherwise true
2289  */
2290 inline bool Game::handleCallbacks()
2291 {
2292         if (g_gamecallback->disconnect_requested) {
2293                 g_gamecallback->disconnect_requested = false;
2294                 return false;
2295         }
2296
2297         if (g_gamecallback->changepassword_requested) {
2298                 (new GUIPasswordChange(guienv, guiroot, -1,
2299                                        &g_menumgr, client))->drop();
2300                 g_gamecallback->changepassword_requested = false;
2301         }
2302
2303         if (g_gamecallback->changevolume_requested) {
2304                 (new GUIVolumeChange(guienv, guiroot, -1,
2305                                      &g_menumgr))->drop();
2306                 g_gamecallback->changevolume_requested = false;
2307         }
2308
2309         if (g_gamecallback->keyconfig_requested) {
2310                 (new GUIKeyChangeMenu(guienv, guiroot, -1,
2311                                       &g_menumgr))->drop();
2312                 g_gamecallback->keyconfig_requested = false;
2313         }
2314
2315         if (g_gamecallback->keyconfig_changed) {
2316                 keycache.populate(); // update the cache with new settings
2317                 g_gamecallback->keyconfig_changed = false;
2318         }
2319
2320         return true;
2321 }
2322
2323
2324 void Game::processQueues()
2325 {
2326         texture_src->processQueue();
2327         itemdef_manager->processQueue(client);
2328         shader_src->processQueue();
2329 }
2330
2331
2332 void Game::updateProfilers(const RunStats &stats, const FpsControl &draw_times, f32 dtime)
2333 {
2334         float profiler_print_interval =
2335                         g_settings->getFloat("profiler_print_interval");
2336         bool print_to_log = true;
2337
2338         if (profiler_print_interval == 0) {
2339                 print_to_log = false;
2340                 profiler_print_interval = 5;
2341         }
2342
2343         if (profiler_interval.step(dtime, profiler_print_interval)) {
2344                 if (print_to_log) {
2345                         infostream << "Profiler:" << std::endl;
2346                         g_profiler->print(infostream);
2347                 }
2348
2349                 update_profiler_gui(guitext_profiler, g_fontengine,
2350                                 runData.profiler_current_page, runData.profiler_max_page,
2351                                 driver->getScreenSize().Height);
2352
2353                 g_profiler->clear();
2354         }
2355
2356         addProfilerGraphs(stats, draw_times, dtime);
2357 }
2358
2359
2360 void Game::addProfilerGraphs(const RunStats &stats,
2361                 const FpsControl &draw_times, f32 dtime)
2362 {
2363         g_profiler->graphAdd("mainloop_other",
2364                         draw_times.busy_time / 1000.0f - stats.drawtime / 1000.0f);
2365
2366         if (draw_times.sleep_time != 0)
2367                 g_profiler->graphAdd("mainloop_sleep", draw_times.sleep_time / 1000.0f);
2368         g_profiler->graphAdd("mainloop_dtime", dtime);
2369
2370         g_profiler->add("Elapsed time", dtime);
2371         g_profiler->avg("FPS", 1. / dtime);
2372 }
2373
2374
2375 void Game::updateStats(RunStats *stats, const FpsControl &draw_times,
2376                 f32 dtime)
2377 {
2378
2379         f32 jitter;
2380         Jitter *jp;
2381
2382         /* Time average and jitter calculation
2383          */
2384         jp = &stats->dtime_jitter;
2385         jp->avg = jp->avg * 0.96 + dtime * 0.04;
2386
2387         jitter = dtime - jp->avg;
2388
2389         if (jitter > jp->max)
2390                 jp->max = jitter;
2391
2392         jp->counter += dtime;
2393
2394         if (jp->counter > 0.0) {
2395                 jp->counter -= 3.0;
2396                 jp->max_sample = jp->max;
2397                 jp->max_fraction = jp->max_sample / (jp->avg + 0.001);
2398                 jp->max = 0.0;
2399         }
2400
2401         /* Busytime average and jitter calculation
2402          */
2403         jp = &stats->busy_time_jitter;
2404         jp->avg = jp->avg + draw_times.busy_time * 0.02;
2405
2406         jitter = draw_times.busy_time - jp->avg;
2407
2408         if (jitter > jp->max)
2409                 jp->max = jitter;
2410         if (jitter < jp->min)
2411                 jp->min = jitter;
2412
2413         jp->counter += dtime;
2414
2415         if (jp->counter > 0.0) {
2416                 jp->counter -= 3.0;
2417                 jp->max_sample = jp->max;
2418                 jp->min_sample = jp->min;
2419                 jp->max = 0.0;
2420                 jp->min = 0.0;
2421         }
2422 }
2423
2424
2425
2426 /****************************************************************************
2427  Input handling
2428  ****************************************************************************/
2429
2430 void Game::processUserInput(f32 dtime)
2431 {
2432         // Reset input if window not active or some menu is active
2433         if (!device->isWindowActive() || isMenuActive() || guienv->hasFocus(gui_chat_console)) {
2434                 input->clear();
2435 #ifdef HAVE_TOUCHSCREENGUI
2436                 g_touchscreengui->hide();
2437 #endif
2438         }
2439 #ifdef HAVE_TOUCHSCREENGUI
2440         else if (g_touchscreengui) {
2441                 /* on touchscreengui step may generate own input events which ain't
2442                  * what we want in case we just did clear them */
2443                 g_touchscreengui->step(dtime);
2444         }
2445 #endif
2446
2447         if (!guienv->hasFocus(gui_chat_console) && gui_chat_console->isOpen()) {
2448                 gui_chat_console->closeConsoleAtOnce();
2449         }
2450
2451         // Input handler step() (used by the random input generator)
2452         input->step(dtime);
2453
2454 #ifdef __ANDROID__
2455         if (current_formspec != NULL)
2456                 current_formspec->getAndroidUIInput();
2457         else
2458                 handleAndroidChatInput();
2459 #endif
2460
2461         // Increase timer for double tap of "keymap_jump"
2462         if (m_cache_doubletap_jump && runData.jump_timer <= 0.2f)
2463                 runData.jump_timer += dtime;
2464
2465         processKeyInput();
2466         processItemSelection(&runData.new_playeritem);
2467 }
2468
2469
2470 void Game::processKeyInput()
2471 {
2472         if (wasKeyDown(KeyType::DROP)) {
2473                 dropSelectedItem();
2474         } else if (wasKeyDown(KeyType::AUTORUN)) {
2475                 toggleAutorun();
2476         } else if (wasKeyDown(KeyType::INVENTORY)) {
2477                 openInventory();
2478         } else if (wasKeyDown(KeyType::ESC) || input->wasKeyDown(CancelKey)) {
2479                 if (!gui_chat_console->isOpenInhibited()) {
2480                         showPauseMenu();
2481                 }
2482         } else if (wasKeyDown(KeyType::CHAT)) {
2483                 openConsole(0.2, L"");
2484         } else if (wasKeyDown(KeyType::CMD)) {
2485                 openConsole(0.2, L"/");
2486         } else if (wasKeyDown(KeyType::CMD_LOCAL)) {
2487                 openConsole(0.2, L".");
2488         } else if (wasKeyDown(KeyType::CONSOLE)) {
2489                 openConsole(core::clamp(g_settings->getFloat("console_height"), 0.1f, 1.0f));
2490         } else if (wasKeyDown(KeyType::FREEMOVE)) {
2491                 toggleFreeMove();
2492         } else if (wasKeyDown(KeyType::JUMP)) {
2493                 toggleFreeMoveAlt();
2494         } else if (wasKeyDown(KeyType::FASTMOVE)) {
2495                 toggleFast();
2496         } else if (wasKeyDown(KeyType::NOCLIP)) {
2497                 toggleNoClip();
2498         } else if (wasKeyDown(KeyType::MUTE)) {
2499                 float volume = g_settings->getFloat("sound_volume");
2500                 if (volume < 0.001f) {
2501                         g_settings->setFloat("sound_volume", 1.0f);
2502                         m_statustext = narrow_to_wide(gettext("Volume changed to 100%"));
2503                 } else {
2504                         g_settings->setFloat("sound_volume", 0.0f);
2505                         m_statustext = narrow_to_wide(gettext("Volume changed to 0%"));
2506                 }
2507                 runData.statustext_time = 0;
2508         } else if (wasKeyDown(KeyType::INC_VOLUME)) {
2509                 float new_volume = rangelim(g_settings->getFloat("sound_volume") + 0.1f, 0.0f, 1.0f);
2510                 char buf[100];
2511                 g_settings->setFloat("sound_volume", new_volume);
2512                 snprintf(buf, sizeof(buf), gettext("Volume changed to %d%%"), myround(new_volume * 100));
2513                 m_statustext = narrow_to_wide(buf);
2514                 runData.statustext_time = 0;
2515         } else if (wasKeyDown(KeyType::DEC_VOLUME)) {
2516                 float new_volume = rangelim(g_settings->getFloat("sound_volume") - 0.1f, 0.0f, 1.0f);
2517                 char buf[100];
2518                 g_settings->setFloat("sound_volume", new_volume);
2519                 snprintf(buf, sizeof(buf), gettext("Volume changed to %d%%"), myround(new_volume * 100));
2520                 m_statustext = narrow_to_wide(buf);
2521                 runData.statustext_time = 0;
2522         } else if (wasKeyDown(KeyType::CINEMATIC)) {
2523                 toggleCinematic();
2524         } else if (wasKeyDown(KeyType::SCREENSHOT)) {
2525                 client->makeScreenshot(device);
2526         } else if (wasKeyDown(KeyType::TOGGLE_HUD)) {
2527                 toggleHud();
2528         } else if (wasKeyDown(KeyType::MINIMAP)) {
2529                 toggleMinimap(isKeyDown(KeyType::SNEAK));
2530         } else if (wasKeyDown(KeyType::TOGGLE_CHAT)) {
2531                 toggleChat();
2532         } else if (wasKeyDown(KeyType::TOGGLE_FORCE_FOG_OFF)) {
2533                 toggleFog();
2534         } else if (wasKeyDown(KeyType::TOGGLE_UPDATE_CAMERA)) {
2535                 toggleUpdateCamera();
2536         } else if (wasKeyDown(KeyType::TOGGLE_DEBUG)) {
2537                 toggleDebug();
2538         } else if (wasKeyDown(KeyType::TOGGLE_PROFILER)) {
2539                 toggleProfiler();
2540         } else if (wasKeyDown(KeyType::INCREASE_VIEWING_RANGE)) {
2541                 increaseViewRange();
2542         } else if (wasKeyDown(KeyType::DECREASE_VIEWING_RANGE)) {
2543                 decreaseViewRange();
2544         } else if (wasKeyDown(KeyType::RANGESELECT)) {
2545                 toggleFullViewRange();
2546         } else if (wasKeyDown(KeyType::QUICKTUNE_NEXT)) {
2547                 quicktune->next();
2548         } else if (wasKeyDown(KeyType::QUICKTUNE_PREV)) {
2549                 quicktune->prev();
2550         } else if (wasKeyDown(KeyType::QUICKTUNE_INC)) {
2551                 quicktune->inc();
2552         } else if (wasKeyDown(KeyType::QUICKTUNE_DEC)) {
2553                 quicktune->dec();
2554         } else if (wasKeyDown(KeyType::DEBUG_STACKS)) {
2555                 // Print debug stacks
2556                 dstream << "-----------------------------------------"
2557                         << std::endl;
2558                 dstream << "Printing debug stacks:" << std::endl;
2559                 dstream << "-----------------------------------------"
2560                         << std::endl;
2561                 debug_stacks_print();
2562         }
2563
2564         if (!isKeyDown(KeyType::JUMP) && runData.reset_jump_timer) {
2565                 runData.reset_jump_timer = false;
2566                 runData.jump_timer = 0.0f;
2567         }
2568
2569         if (quicktune->hasMessage()) {
2570                 m_statustext = utf8_to_wide(quicktune->getMessage());
2571                 runData.statustext_time = 0.0f;
2572         }
2573 }
2574
2575 void Game::processItemSelection(u16 *new_playeritem)
2576 {
2577         LocalPlayer *player = client->getEnv().getLocalPlayer();
2578
2579         /* Item selection using mouse wheel
2580          */
2581         *new_playeritem = client->getPlayerItem();
2582
2583         s32 wheel = input->getMouseWheel();
2584         u16 max_item = MYMIN(PLAYER_INVENTORY_SIZE - 1,
2585                     player->hud_hotbar_itemcount - 1);
2586
2587         s32 dir = wheel;
2588
2589         if (input->joystick.wasKeyDown(KeyType::SCROLL_DOWN) ||
2590                         wasKeyDown(KeyType::HOTBAR_NEXT)) {
2591                 dir = -1;
2592         }
2593
2594         if (input->joystick.wasKeyDown(KeyType::SCROLL_UP) ||
2595                         wasKeyDown(KeyType::HOTBAR_PREV)) {
2596                 dir = 1;
2597         }
2598
2599         if (dir < 0)
2600                 *new_playeritem = *new_playeritem < max_item ? *new_playeritem + 1 : 0;
2601         else if (dir > 0)
2602                 *new_playeritem = *new_playeritem > 0 ? *new_playeritem - 1 : max_item;
2603         // else dir == 0
2604
2605         /* Item selection using keyboard
2606          */
2607         for (u16 i = 0; i < 10; i++) {
2608                 static const KeyPress *item_keys[10] = {
2609                         NumberKey + 1, NumberKey + 2, NumberKey + 3, NumberKey + 4,
2610                         NumberKey + 5, NumberKey + 6, NumberKey + 7, NumberKey + 8,
2611                         NumberKey + 9, NumberKey + 0,
2612                 };
2613
2614                 if (input->wasKeyDown(*item_keys[i])) {
2615                         if (i < PLAYER_INVENTORY_SIZE && i < player->hud_hotbar_itemcount) {
2616                                 *new_playeritem = i;
2617                                 infostream << "Selected item: " << new_playeritem << std::endl;
2618                         }
2619                         break;
2620                 }
2621         }
2622 }
2623
2624
2625 void Game::dropSelectedItem()
2626 {
2627         IDropAction *a = new IDropAction();
2628         a->count = 0;
2629         a->from_inv.setCurrentPlayer();
2630         a->from_list = "main";
2631         a->from_i = client->getPlayerItem();
2632         client->inventoryAction(a);
2633 }
2634
2635
2636 void Game::openInventory()
2637 {
2638         /*
2639          * Don't permit to open inventory is CAO or player doesn't exists.
2640          * This prevent showing an empty inventory at player load
2641          */
2642
2643         LocalPlayer *player = client->getEnv().getLocalPlayer();
2644         if (player == NULL || player->getCAO() == NULL)
2645                 return;
2646
2647         infostream << "the_game: " << "Launching inventory" << std::endl;
2648
2649         PlayerInventoryFormSource *fs_src = new PlayerInventoryFormSource(client);
2650         TextDest *txt_dst = new TextDestPlayerInventory(client);
2651
2652         create_formspec_menu(&current_formspec, client, device, &input->joystick, fs_src, txt_dst);
2653         cur_formname = "";
2654
2655         InventoryLocation inventoryloc;
2656         inventoryloc.setCurrentPlayer();
2657         current_formspec->setFormSpec(fs_src->getForm(), inventoryloc);
2658 }
2659
2660
2661 void Game::openConsole(float scale, const wchar_t *line)
2662 {
2663         assert(scale > 0.0f && scale <= 1.0f);
2664
2665 #ifdef __ANDROID__
2666         porting::showInputDialog(gettext("ok"), "", "", 2);
2667         m_android_chat_open = true;
2668 #else
2669         if (gui_chat_console->isOpenInhibited())
2670                 return;
2671         gui_chat_console->openConsole(scale);
2672         if (line) {
2673                 gui_chat_console->setCloseOnEnter(true);
2674                 gui_chat_console->replaceAndAddToHistory(line);
2675         }
2676 #endif
2677 }
2678
2679 #ifdef __ANDROID__
2680 void Game::handleAndroidChatInput()
2681 {
2682         if (m_android_chat_open && porting::getInputDialogState() == 0) {
2683                 std::string text = porting::getInputDialogValue();
2684                 client->typeChatMessage(utf8_to_wide(text));
2685         }
2686 }
2687 #endif
2688
2689
2690 void Game::toggleFreeMove()
2691 {
2692         static const wchar_t *msg[] = { L"free_move disabled", L"free_move enabled" };
2693
2694         bool free_move = !g_settings->getBool("free_move");
2695         g_settings->set("free_move", bool_to_cstr(free_move));
2696
2697         runData.statustext_time = 0;
2698         m_statustext = msg[free_move];
2699         if (free_move && !client->checkPrivilege("fly"))
2700                 m_statustext += L" (note: no 'fly' privilege)";
2701 }
2702
2703
2704 void Game::toggleFreeMoveAlt()
2705 {
2706         if (m_cache_doubletap_jump && runData.jump_timer < 0.2f)
2707                 toggleFreeMove();
2708
2709         runData.reset_jump_timer = true;
2710 }
2711
2712
2713 void Game::toggleFast()
2714 {
2715         static const wchar_t *msg[] = { L"fast_move disabled", L"fast_move enabled" };
2716         bool fast_move = !g_settings->getBool("fast_move");
2717         g_settings->set("fast_move", bool_to_cstr(fast_move));
2718
2719         runData.statustext_time = 0;
2720         m_statustext = msg[fast_move];
2721
2722         bool has_fast_privs = client->checkPrivilege("fast");
2723
2724         if (fast_move && !has_fast_privs)
2725                 m_statustext += L" (note: no 'fast' privilege)";
2726
2727 #ifdef __ANDROID__
2728         m_cache_hold_aux1 = fast_move && has_fast_privs;
2729 #endif
2730 }
2731
2732
2733 void Game::toggleNoClip()
2734 {
2735         static const wchar_t *msg[] = { L"noclip disabled", L"noclip enabled" };
2736         bool noclip = !g_settings->getBool("noclip");
2737         g_settings->set("noclip", bool_to_cstr(noclip));
2738
2739         runData.statustext_time = 0;
2740         m_statustext = msg[noclip];
2741
2742         if (noclip && !client->checkPrivilege("noclip"))
2743                 m_statustext += L" (note: no 'noclip' privilege)";
2744 }
2745
2746 void Game::toggleCinematic()
2747 {
2748         static const wchar_t *msg[] = { L"cinematic disabled", L"cinematic enabled" };
2749         bool cinematic = !g_settings->getBool("cinematic");
2750         g_settings->set("cinematic", bool_to_cstr(cinematic));
2751
2752         runData.statustext_time = 0;
2753         m_statustext = msg[cinematic];
2754 }
2755
2756 // Add WoW-style autorun by toggling continuous forward.
2757 void Game::toggleAutorun()
2758 {
2759         static const wchar_t *msg[] = { L"autorun disabled", L"autorun enabled" };
2760         bool autorun_enabled = !g_settings->getBool("continuous_forward");
2761         g_settings->set("continuous_forward", bool_to_cstr(autorun_enabled));
2762
2763         runData.statustext_time = 0;
2764         m_statustext = msg[autorun_enabled ? 1 : 0];
2765 }
2766
2767 void Game::toggleChat()
2768 {
2769         static const wchar_t *msg[] = { L"Chat hidden", L"Chat shown" };
2770
2771         flags.show_chat = !flags.show_chat;
2772         runData.statustext_time = 0;
2773         m_statustext = msg[flags.show_chat];
2774 }
2775
2776
2777 void Game::toggleHud()
2778 {
2779         static const wchar_t *msg[] = { L"HUD hidden", L"HUD shown" };
2780
2781         flags.show_hud = !flags.show_hud;
2782         runData.statustext_time = 0;
2783         m_statustext = msg[flags.show_hud];
2784 }
2785
2786 void Game::toggleMinimap(bool shift_pressed)
2787 {
2788         if (!mapper || !flags.show_hud || !g_settings->getBool("enable_minimap"))
2789                 return;
2790
2791         if (shift_pressed) {
2792                 mapper->toggleMinimapShape();
2793                 return;
2794         }
2795
2796         u32 hud_flags = client->getEnv().getLocalPlayer()->hud_flags;
2797
2798         MinimapMode mode = MINIMAP_MODE_OFF;
2799         if (hud_flags & HUD_FLAG_MINIMAP_VISIBLE) {
2800                 mode = mapper->getMinimapMode();
2801                 mode = (MinimapMode)((int)mode + 1);
2802         }
2803
2804         flags.show_minimap = true;
2805         switch (mode) {
2806                 case MINIMAP_MODE_SURFACEx1:
2807                         m_statustext = L"Minimap in surface mode, Zoom x1";
2808                         break;
2809                 case MINIMAP_MODE_SURFACEx2:
2810                         m_statustext = L"Minimap in surface mode, Zoom x2";
2811                         break;
2812                 case MINIMAP_MODE_SURFACEx4:
2813                         m_statustext = L"Minimap in surface mode, Zoom x4";
2814                         break;
2815                 case MINIMAP_MODE_RADARx1:
2816                         m_statustext = L"Minimap in radar mode, Zoom x1";
2817                         break;
2818                 case MINIMAP_MODE_RADARx2:
2819                         m_statustext = L"Minimap in radar mode, Zoom x2";
2820                         break;
2821                 case MINIMAP_MODE_RADARx4:
2822                         m_statustext = L"Minimap in radar mode, Zoom x4";
2823                         break;
2824                 default:
2825                         mode = MINIMAP_MODE_OFF;
2826                         flags.show_minimap = false;
2827                         m_statustext = (hud_flags & HUD_FLAG_MINIMAP_VISIBLE) ?
2828                                 L"Minimap hidden" : L"Minimap disabled by server";
2829         }
2830
2831         runData.statustext_time = 0;
2832         mapper->setMinimapMode(mode);
2833 }
2834
2835 void Game::toggleFog()
2836 {
2837         static const wchar_t *msg[] = { L"Fog enabled", L"Fog disabled" };
2838
2839         flags.force_fog_off = !flags.force_fog_off;
2840         runData.statustext_time = 0;
2841         m_statustext = msg[flags.force_fog_off];
2842 }
2843
2844
2845 void Game::toggleDebug()
2846 {
2847         // Initial / 4x toggle: Chat only
2848         // 1x toggle: Debug text with chat
2849         // 2x toggle: Debug text with profiler graph
2850         // 3x toggle: Debug text and wireframe
2851         if (!flags.show_debug) {
2852                 flags.show_debug = true;
2853                 flags.show_profiler_graph = false;
2854                 draw_control->show_wireframe = false;
2855                 m_statustext = L"Debug info shown";
2856         } else if (!flags.show_profiler_graph && !draw_control->show_wireframe) {
2857                 flags.show_profiler_graph = true;
2858                 m_statustext = L"Profiler graph shown";
2859         } else if (!draw_control->show_wireframe && client->checkPrivilege("debug")) {
2860                 flags.show_profiler_graph = false;
2861                 draw_control->show_wireframe = true;
2862                 m_statustext = L"Wireframe shown";
2863         } else {
2864                 flags.show_debug = false;
2865                 flags.show_profiler_graph = false;
2866                 draw_control->show_wireframe = false;
2867                 if (client->checkPrivilege("debug")) {
2868                         m_statustext = L"Debug info, profiler graph, and wireframe hidden";
2869                 } else {
2870                         m_statustext = L"Debug info and profiler graph hidden";
2871                 }
2872         }
2873         runData.statustext_time = 0;
2874 }
2875
2876
2877 void Game::toggleUpdateCamera()
2878 {
2879         static const wchar_t *msg[] = {
2880                 L"Camera update enabled",
2881                 L"Camera update disabled"
2882         };
2883
2884         flags.disable_camera_update = !flags.disable_camera_update;
2885         runData.statustext_time = 0;
2886         m_statustext = msg[flags.disable_camera_update];
2887 }
2888
2889
2890 void Game::toggleProfiler()
2891 {
2892         runData.profiler_current_page =
2893                 (runData.profiler_current_page + 1) % (runData.profiler_max_page + 1);
2894
2895         // FIXME: This updates the profiler with incomplete values
2896         update_profiler_gui(guitext_profiler, g_fontengine, runData.profiler_current_page,
2897                 runData.profiler_max_page, driver->getScreenSize().Height);
2898
2899         if (runData.profiler_current_page != 0) {
2900                 std::wstringstream sstr;
2901                 sstr << "Profiler shown (page " << runData.profiler_current_page
2902                      << " of " << runData.profiler_max_page << ")";
2903                 m_statustext = sstr.str();
2904         } else {
2905                 m_statustext = L"Profiler hidden";
2906         }
2907         runData.statustext_time = 0;
2908 }
2909
2910
2911 void Game::increaseViewRange()
2912 {
2913         s16 range = g_settings->getS16("viewing_range");
2914         s16 range_new = range + 10;
2915
2916         if (range_new > 4000) {
2917                 range_new = 4000;
2918                 m_statustext = utf8_to_wide("Viewing range is at maximum: "
2919                                 + itos(range_new));
2920         } else {
2921                 m_statustext = utf8_to_wide("Viewing range changed to "
2922                                 + itos(range_new));
2923         }
2924         g_settings->set("viewing_range", itos(range_new));
2925         runData.statustext_time = 0;
2926 }
2927
2928
2929 void Game::decreaseViewRange()
2930 {
2931         s16 range = g_settings->getS16("viewing_range");
2932         s16 range_new = range - 10;
2933
2934         if (range_new < 20) {
2935                 range_new = 20;
2936                 m_statustext = utf8_to_wide("Viewing range is at minimum: "
2937                                 + itos(range_new));
2938         } else {
2939                 m_statustext = utf8_to_wide("Viewing range changed to "
2940                                 + itos(range_new));
2941         }
2942         g_settings->set("viewing_range", itos(range_new));
2943         runData.statustext_time = 0;
2944 }
2945
2946
2947 void Game::toggleFullViewRange()
2948 {
2949         static const wchar_t *msg[] = {
2950                 L"Disabled full viewing range",
2951                 L"Enabled full viewing range"
2952         };
2953
2954         draw_control->range_all = !draw_control->range_all;
2955         infostream << msg[draw_control->range_all] << std::endl;
2956         m_statustext = msg[draw_control->range_all];
2957         runData.statustext_time = 0;
2958 }
2959
2960
2961 void Game::updateCameraDirection(CameraOrientation *cam, float dtime)
2962 {
2963         if ((device->isWindowActive() && device->isWindowFocused()
2964                         && !isMenuActive()) || random_input) {
2965
2966 #ifndef __ANDROID__
2967                 if (!random_input) {
2968                         // Mac OSX gets upset if this is set every frame
2969                         if (device->getCursorControl()->isVisible())
2970                                 device->getCursorControl()->setVisible(false);
2971                 }
2972 #endif
2973
2974                 if (m_first_loop_after_window_activation)
2975                         m_first_loop_after_window_activation = false;
2976                 else
2977                         updateCameraOrientation(cam, dtime);
2978
2979                 input->setMousePos((driver->getScreenSize().Width / 2),
2980                                 (driver->getScreenSize().Height / 2));
2981         } else {
2982
2983 #ifndef ANDROID
2984                 // Mac OSX gets upset if this is set every frame
2985                 if (!device->getCursorControl()->isVisible())
2986                         device->getCursorControl()->setVisible(true);
2987 #endif
2988
2989                 m_first_loop_after_window_activation = true;
2990
2991         }
2992 }
2993
2994 void Game::updateCameraOrientation(CameraOrientation *cam, float dtime)
2995 {
2996 #ifdef HAVE_TOUCHSCREENGUI
2997         if (g_touchscreengui) {
2998                 cam->camera_yaw   += g_touchscreengui->getYawChange();
2999                 cam->camera_pitch  = g_touchscreengui->getPitch();
3000         } else {
3001 #endif
3002
3003                 s32 dx = input->getMousePos().X - (driver->getScreenSize().Width / 2);
3004                 s32 dy = input->getMousePos().Y - (driver->getScreenSize().Height / 2);
3005
3006                 if (m_invert_mouse || camera->getCameraMode() == CAMERA_MODE_THIRD_FRONT) {
3007                         dy = -dy;
3008                 }
3009
3010                 cam->camera_yaw   -= dx * m_cache_mouse_sensitivity;
3011                 cam->camera_pitch += dy * m_cache_mouse_sensitivity;
3012
3013 #ifdef HAVE_TOUCHSCREENGUI
3014         }
3015 #endif
3016
3017         if (m_cache_enable_joysticks) {
3018                 f32 c = m_cache_joystick_frustum_sensitivity * (1.f / 32767.f) * dtime;
3019                 cam->camera_yaw -= input->joystick.getAxisWithoutDead(JA_FRUSTUM_HORIZONTAL) * c;
3020                 cam->camera_pitch += input->joystick.getAxisWithoutDead(JA_FRUSTUM_VERTICAL) * c;
3021         }
3022
3023         cam->camera_pitch = rangelim(cam->camera_pitch, -89.5, 89.5);
3024 }
3025
3026
3027 void Game::updatePlayerControl(const CameraOrientation &cam)
3028 {
3029         //TimeTaker tt("update player control", NULL, PRECISION_NANO);
3030
3031         // DO NOT use the isKeyDown method for the forward, backward, left, right
3032         // buttons, as the code that uses the controls needs to be able to
3033         // distinguish between the two in order to know when to use joysticks.
3034
3035         PlayerControl control(
3036                 input->isKeyDown(keycache.key[KeyType::FORWARD]),
3037                 input->isKeyDown(keycache.key[KeyType::BACKWARD]),
3038                 input->isKeyDown(keycache.key[KeyType::LEFT]),
3039                 input->isKeyDown(keycache.key[KeyType::RIGHT]),
3040                 isKeyDown(KeyType::JUMP),
3041                 isKeyDown(KeyType::SPECIAL1),
3042                 isKeyDown(KeyType::SNEAK),
3043                 isKeyDown(KeyType::ZOOM),
3044                 isLeftPressed(),
3045                 isRightPressed(),
3046                 cam.camera_pitch,
3047                 cam.camera_yaw,
3048                 input->joystick.getAxisWithoutDead(JA_SIDEWARD_MOVE),
3049                 input->joystick.getAxisWithoutDead(JA_FORWARD_MOVE)
3050         );
3051
3052         u32 keypress_bits =
3053                         ( (u32)(isKeyDown(KeyType::FORWARD)                       & 0x1) << 0) |
3054                         ( (u32)(isKeyDown(KeyType::BACKWARD)                      & 0x1) << 1) |
3055                         ( (u32)(isKeyDown(KeyType::LEFT)                          & 0x1) << 2) |
3056                         ( (u32)(isKeyDown(KeyType::RIGHT)                         & 0x1) << 3) |
3057                         ( (u32)(isKeyDown(KeyType::JUMP)                          & 0x1) << 4) |
3058                         ( (u32)(isKeyDown(KeyType::SPECIAL1)                      & 0x1) << 5) |
3059                         ( (u32)(isKeyDown(KeyType::SNEAK)                         & 0x1) << 6) |
3060                         ( (u32)(isLeftPressed()                                   & 0x1) << 7) |
3061                         ( (u32)(isRightPressed()                                  & 0x1) << 8
3062                 );
3063
3064 #ifdef ANDROID
3065         /* For Android, simulate holding down AUX1 (fast move) if the user has
3066          * the fast_move setting toggled on. If there is an aux1 key defined for
3067          * Android then its meaning is inverted (i.e. holding aux1 means walk and
3068          * not fast)
3069          */
3070         if (m_cache_hold_aux1) {
3071                 control.aux1 = control.aux1 ^ true;
3072                 keypress_bits ^= ((u32)(1U << 5));
3073         }
3074 #endif
3075
3076         client->setPlayerControl(control);
3077         LocalPlayer *player = client->getEnv().getLocalPlayer();
3078         player->keyPressed = keypress_bits;
3079
3080         //tt.stop();
3081 }
3082
3083
3084 inline void Game::step(f32 *dtime)
3085 {
3086         bool can_be_and_is_paused =
3087                         (simple_singleplayer_mode && g_menumgr.pausesGame());
3088
3089         if (can_be_and_is_paused) {     // This is for a singleplayer server
3090                 *dtime = 0;             // No time passes
3091         } else {
3092                 if (server != NULL) {
3093                         //TimeTaker timer("server->step(dtime)");
3094                         server->step(*dtime);
3095                 }
3096
3097                 //TimeTaker timer("client.step(dtime)");
3098                 client->step(*dtime);
3099         }
3100 }
3101
3102
3103 void Game::processClientEvents(CameraOrientation *cam)
3104 {
3105         LocalPlayer *player = client->getEnv().getLocalPlayer();
3106
3107         while (client->hasClientEvents()) {
3108                 ClientEvent event = client->getClientEvent();
3109
3110                 switch (event.type) {
3111                 case CE_PLAYER_DAMAGE:
3112                         if (client->getHP() == 0)
3113                                 break;
3114                         if (client->moddingEnabled()) {
3115                                 client->getScript()->on_damage_taken(event.player_damage.amount);
3116                         }
3117
3118                         runData.damage_flash += 95.0 + 3.2 * event.player_damage.amount;
3119                         runData.damage_flash = MYMIN(runData.damage_flash, 127.0);
3120
3121                         player->hurt_tilt_timer = 1.5;
3122                         player->hurt_tilt_strength =
3123                                 rangelim(event.player_damage.amount / 4, 1.0, 4.0);
3124
3125                         client->event()->put(new SimpleTriggerEvent("PlayerDamage"));
3126                         break;
3127
3128                 case CE_PLAYER_FORCE_MOVE:
3129                         cam->camera_yaw = event.player_force_move.yaw;
3130                         cam->camera_pitch = event.player_force_move.pitch;
3131                         break;
3132
3133                 case CE_DEATHSCREEN:
3134                         // This should be enabled for death formspec in builtin
3135                         client->getScript()->on_death();
3136
3137                         /* Handle visualization */
3138                         runData.damage_flash = 0;
3139                         player->hurt_tilt_timer = 0;
3140                         player->hurt_tilt_strength = 0;
3141                         break;
3142
3143                 case CE_SHOW_FORMSPEC:
3144                         if (*(event.show_formspec.formspec) == "") {
3145                                 if (current_formspec && ( *(event.show_formspec.formname) == "" || *(event.show_formspec.formname) == cur_formname) ){
3146                                         current_formspec->quitMenu();
3147                                 }
3148                         } else {
3149                                 FormspecFormSource *fs_src =
3150                                         new FormspecFormSource(*(event.show_formspec.formspec));
3151                                 TextDestPlayerInventory *txt_dst =
3152                                         new TextDestPlayerInventory(client, *(event.show_formspec.formname));
3153
3154                                 create_formspec_menu(&current_formspec, client, device, &input->joystick,
3155                                         fs_src, txt_dst);
3156                                 cur_formname = *(event.show_formspec.formname);
3157                         }
3158
3159                         delete event.show_formspec.formspec;
3160                         delete event.show_formspec.formname;
3161                         break;
3162
3163                 case CE_SHOW_LOCAL_FORMSPEC:
3164                         {
3165                                 FormspecFormSource *fs_src = new FormspecFormSource(*event.show_formspec.formspec);
3166                                 LocalFormspecHandler *txt_dst = new LocalFormspecHandler(*event.show_formspec.formname, client);
3167                                 create_formspec_menu(&current_formspec, client, device, &input->joystick,
3168                                         fs_src, txt_dst);
3169                         }
3170                         delete event.show_formspec.formspec;
3171                         delete event.show_formspec.formname;
3172                         break;
3173
3174                 case CE_SPAWN_PARTICLE:
3175                 case CE_ADD_PARTICLESPAWNER:
3176                 case CE_DELETE_PARTICLESPAWNER:
3177                         client->getParticleManager()->handleParticleEvent(&event, client,
3178                                         smgr, player);
3179                         break;
3180
3181                 case CE_HUDADD:
3182                         {
3183                                 u32 id = event.hudadd.id;
3184
3185                                 HudElement *e = player->getHud(id);
3186
3187                                 if (e != NULL) {
3188                                         delete event.hudadd.pos;
3189                                         delete event.hudadd.name;
3190                                         delete event.hudadd.scale;
3191                                         delete event.hudadd.text;
3192                                         delete event.hudadd.align;
3193                                         delete event.hudadd.offset;
3194                                         delete event.hudadd.world_pos;
3195                                         delete event.hudadd.size;
3196                                         continue;
3197                                 }
3198
3199                                 e = new HudElement;
3200                                 e->type   = (HudElementType)event.hudadd.type;
3201                                 e->pos    = *event.hudadd.pos;
3202                                 e->name   = *event.hudadd.name;
3203                                 e->scale  = *event.hudadd.scale;
3204                                 e->text   = *event.hudadd.text;
3205                                 e->number = event.hudadd.number;
3206                                 e->item   = event.hudadd.item;
3207                                 e->dir    = event.hudadd.dir;
3208                                 e->align  = *event.hudadd.align;
3209                                 e->offset = *event.hudadd.offset;
3210                                 e->world_pos = *event.hudadd.world_pos;
3211                                 e->size = *event.hudadd.size;
3212
3213                                 u32 new_id = player->addHud(e);
3214                                 //if this isn't true our huds aren't consistent
3215                                 sanity_check(new_id == id);
3216                         }
3217
3218                         delete event.hudadd.pos;
3219                         delete event.hudadd.name;
3220                         delete event.hudadd.scale;
3221                         delete event.hudadd.text;
3222                         delete event.hudadd.align;
3223                         delete event.hudadd.offset;
3224                         delete event.hudadd.world_pos;
3225                         delete event.hudadd.size;
3226                         break;
3227
3228                 case CE_HUDRM:
3229                         {
3230                                 HudElement *e = player->removeHud(event.hudrm.id);
3231
3232                                 if (e != NULL)
3233                                         delete e;
3234                         }
3235                         break;
3236
3237                 case CE_HUDCHANGE:
3238                         {
3239                                 u32 id = event.hudchange.id;
3240                                 HudElement *e = player->getHud(id);
3241
3242                                 if (e == NULL) {
3243                                         delete event.hudchange.v3fdata;
3244                                         delete event.hudchange.v2fdata;
3245                                         delete event.hudchange.sdata;
3246                                         delete event.hudchange.v2s32data;
3247                                         continue;
3248                                 }
3249
3250                                 switch (event.hudchange.stat) {
3251                                 case HUD_STAT_POS:
3252                                         e->pos = *event.hudchange.v2fdata;
3253                                         break;
3254
3255                                 case HUD_STAT_NAME:
3256                                         e->name = *event.hudchange.sdata;
3257                                         break;
3258
3259                                 case HUD_STAT_SCALE:
3260                                         e->scale = *event.hudchange.v2fdata;
3261                                         break;
3262
3263                                 case HUD_STAT_TEXT:
3264                                         e->text = *event.hudchange.sdata;
3265                                         break;
3266
3267                                 case HUD_STAT_NUMBER:
3268                                         e->number = event.hudchange.data;
3269                                         break;
3270
3271                                 case HUD_STAT_ITEM:
3272                                         e->item = event.hudchange.data;
3273                                         break;
3274
3275                                 case HUD_STAT_DIR:
3276                                         e->dir = event.hudchange.data;
3277                                         break;
3278
3279                                 case HUD_STAT_ALIGN:
3280                                         e->align = *event.hudchange.v2fdata;
3281                                         break;
3282
3283                                 case HUD_STAT_OFFSET:
3284                                         e->offset = *event.hudchange.v2fdata;
3285                                         break;
3286
3287                                 case HUD_STAT_WORLD_POS:
3288                                         e->world_pos = *event.hudchange.v3fdata;
3289                                         break;
3290
3291                                 case HUD_STAT_SIZE:
3292                                         e->size = *event.hudchange.v2s32data;
3293                                         break;
3294                                 }
3295                         }
3296
3297                         delete event.hudchange.v3fdata;
3298                         delete event.hudchange.v2fdata;
3299                         delete event.hudchange.sdata;
3300                         delete event.hudchange.v2s32data;
3301                         break;
3302
3303                 case CE_SET_SKY:
3304                         sky->setVisible(false);
3305                         // Whether clouds are visible in front of a custom skybox
3306                         sky->setCloudsEnabled(event.set_sky.clouds);
3307
3308                         if (skybox) {
3309                                 skybox->remove();
3310                                 skybox = NULL;
3311                         }
3312
3313                         // Handle according to type
3314                         if (*event.set_sky.type == "regular") {
3315                                 sky->setVisible(true);
3316                                 sky->setCloudsEnabled(true);
3317                         } else if (*event.set_sky.type == "skybox" &&
3318                                         event.set_sky.params->size() == 6) {
3319                                 sky->setFallbackBgColor(*event.set_sky.bgcolor);
3320                                 skybox = smgr->addSkyBoxSceneNode(
3321                                                  texture_src->getTextureForMesh((*event.set_sky.params)[0]),
3322                                                  texture_src->getTextureForMesh((*event.set_sky.params)[1]),
3323                                                  texture_src->getTextureForMesh((*event.set_sky.params)[2]),
3324                                                  texture_src->getTextureForMesh((*event.set_sky.params)[3]),
3325                                                  texture_src->getTextureForMesh((*event.set_sky.params)[4]),
3326                                                  texture_src->getTextureForMesh((*event.set_sky.params)[5]));
3327                         }
3328                         // Handle everything else as plain color
3329                         else {
3330                                 if (*event.set_sky.type != "plain")
3331                                         infostream << "Unknown sky type: "
3332                                                    << (*event.set_sky.type) << std::endl;
3333
3334                                 sky->setFallbackBgColor(*event.set_sky.bgcolor);
3335                         }
3336
3337                         delete event.set_sky.bgcolor;
3338                         delete event.set_sky.type;
3339                         delete event.set_sky.params;
3340                         break;
3341
3342                 case CE_OVERRIDE_DAY_NIGHT_RATIO:
3343                         client->getEnv().setDayNightRatioOverride(
3344                                         event.override_day_night_ratio.do_override,
3345                                         event.override_day_night_ratio.ratio_f * 1000);
3346                         break;
3347
3348                 case CE_CLOUD_PARAMS:
3349                         if (clouds) {
3350                                 clouds->setDensity(event.cloud_params.density);
3351                                 clouds->setColorBright(video::SColor(event.cloud_params.color_bright));
3352                                 clouds->setColorAmbient(video::SColor(event.cloud_params.color_ambient));
3353                                 clouds->setHeight(event.cloud_params.height);
3354                                 clouds->setThickness(event.cloud_params.thickness);
3355                                 clouds->setSpeed(v2f(
3356                                                 event.cloud_params.speed_x,
3357                                                 event.cloud_params.speed_y));
3358                         }
3359                         break;
3360
3361                 default:
3362                         // unknown or unhandled type
3363                         break;
3364
3365                 }
3366         }
3367 }
3368
3369
3370 void Game::updateCamera(u32 busy_time, f32 dtime)
3371 {
3372         LocalPlayer *player = client->getEnv().getLocalPlayer();
3373
3374         /*
3375                 For interaction purposes, get info about the held item
3376                 - What item is it?
3377                 - Is it a usable item?
3378                 - Can it point to liquids?
3379         */
3380         ItemStack playeritem;
3381         {
3382                 InventoryList *mlist = local_inventory->getList("main");
3383
3384                 if (mlist && client->getPlayerItem() < mlist->getSize())
3385                         playeritem = mlist->getItem(client->getPlayerItem());
3386         }
3387
3388         if (playeritem.getDefinition(itemdef_manager).name.empty()) { // override the hand
3389                 InventoryList *hlist = local_inventory->getList("hand");
3390                 if (hlist)
3391                         playeritem = hlist->getItem(0);
3392         }
3393
3394
3395         ToolCapabilities playeritem_toolcap =
3396                 playeritem.getToolCapabilities(itemdef_manager);
3397
3398         v3s16 old_camera_offset = camera->getOffset();
3399
3400         if (wasKeyDown(KeyType::CAMERA_MODE)) {
3401                 GenericCAO *playercao = player->getCAO();
3402
3403                 // If playercao not loaded, don't change camera
3404                 if (playercao == NULL)
3405                         return;
3406
3407                 camera->toggleCameraMode();
3408
3409                 playercao->setVisible(camera->getCameraMode() > CAMERA_MODE_FIRST);
3410                 playercao->setChildrenVisible(camera->getCameraMode() > CAMERA_MODE_FIRST);
3411         }
3412
3413         float full_punch_interval = playeritem_toolcap.full_punch_interval;
3414         float tool_reload_ratio = runData.time_from_last_punch / full_punch_interval;
3415
3416         tool_reload_ratio = MYMIN(tool_reload_ratio, 1.0);
3417         camera->update(player, dtime, busy_time / 1000.0f, tool_reload_ratio,
3418                       client->getEnv());
3419         camera->step(dtime);
3420
3421         v3f camera_position = camera->getPosition();
3422         v3f camera_direction = camera->getDirection();
3423         f32 camera_fov = camera->getFovMax();
3424         v3s16 camera_offset = camera->getOffset();
3425
3426         m_camera_offset_changed = (camera_offset != old_camera_offset);
3427
3428         if (!flags.disable_camera_update) {
3429                 client->getEnv().getClientMap().updateCamera(camera_position,
3430                                 camera_direction, camera_fov, camera_offset);
3431
3432                 if (m_camera_offset_changed) {
3433                         client->updateCameraOffset(camera_offset);
3434                         client->getEnv().updateCameraOffset(camera_offset);
3435
3436                         if (clouds)
3437                                 clouds->updateCameraOffset(camera_offset);
3438                 }
3439         }
3440 }
3441
3442
3443 void Game::updateSound(f32 dtime)
3444 {
3445         // Update sound listener
3446         v3s16 camera_offset = camera->getOffset();
3447         sound->updateListener(camera->getCameraNode()->getPosition() + intToFloat(camera_offset, BS),
3448                               v3f(0, 0, 0), // velocity
3449                               camera->getDirection(),
3450                               camera->getCameraNode()->getUpVector());
3451
3452         // Check if volume is in the proper range, else fix it.
3453         float old_volume = g_settings->getFloat("sound_volume");
3454         float new_volume = rangelim(old_volume, 0.0f, 1.0f);
3455         sound->setListenerGain(new_volume);
3456
3457         if (old_volume != new_volume) {
3458                 g_settings->setFloat("sound_volume", new_volume);
3459         }
3460
3461         LocalPlayer *player = client->getEnv().getLocalPlayer();
3462
3463         // Tell the sound maker whether to make footstep sounds
3464         soundmaker->makes_footstep_sound = player->makes_footstep_sound;
3465
3466         //      Update sound maker
3467         if (player->makes_footstep_sound)
3468                 soundmaker->step(dtime);
3469
3470         ClientMap &map = client->getEnv().getClientMap();
3471         MapNode n = map.getNodeNoEx(player->getFootstepNodePos());
3472         soundmaker->m_player_step_sound = nodedef_manager->get(n).sound_footstep;
3473 }
3474
3475
3476 void Game::processPlayerInteraction(f32 dtime, bool show_hud, bool show_debug)
3477 {
3478         LocalPlayer *player = client->getEnv().getLocalPlayer();
3479
3480         ItemStack playeritem;
3481         {
3482                 InventoryList *mlist = local_inventory->getList("main");
3483
3484                 if (mlist && client->getPlayerItem() < mlist->getSize())
3485                         playeritem = mlist->getItem(client->getPlayerItem());
3486         }
3487
3488         const ItemDefinition &playeritem_def =
3489                         playeritem.getDefinition(itemdef_manager);
3490         InventoryList *hlist = local_inventory->getList("hand");
3491         const ItemDefinition &hand_def =
3492                 hlist ? hlist->getItem(0).getDefinition(itemdef_manager) : itemdef_manager->get("");
3493
3494         v3f player_position  = player->getPosition();
3495         v3f camera_position  = camera->getPosition();
3496         v3f camera_direction = camera->getDirection();
3497         v3s16 camera_offset  = camera->getOffset();
3498
3499
3500         /*
3501                 Calculate what block is the crosshair pointing to
3502         */
3503
3504         f32 d = playeritem_def.range; // max. distance
3505         f32 d_hand = hand_def.range;
3506
3507         if (d < 0 && d_hand >= 0)
3508                 d = d_hand;
3509         else if (d < 0)
3510                 d = 4.0;
3511
3512         core::line3d<f32> shootline;
3513
3514         if (camera->getCameraMode() != CAMERA_MODE_THIRD_FRONT) {
3515                 shootline = core::line3d<f32>(camera_position,
3516                         camera_position + camera_direction * BS * d);
3517         } else {
3518             // prevent player pointing anything in front-view
3519                 shootline = core::line3d<f32>(camera_position,camera_position);
3520         }
3521
3522 #ifdef HAVE_TOUCHSCREENGUI
3523
3524         if ((g_settings->getBool("touchtarget")) && (g_touchscreengui)) {
3525                 shootline = g_touchscreengui->getShootline();
3526                 shootline.start += intToFloat(camera_offset, BS);
3527                 shootline.end += intToFloat(camera_offset, BS);
3528         }
3529
3530 #endif
3531
3532         PointedThing pointed = updatePointedThing(shootline,
3533                         playeritem_def.liquids_pointable,
3534                         !runData.ldown_for_dig,
3535                         camera_offset);
3536
3537         if (pointed != runData.pointed_old) {
3538                 infostream << "Pointing at " << pointed.dump() << std::endl;
3539                 hud->updateSelectionMesh(camera_offset);
3540         }
3541
3542         /*
3543                 Stop digging when
3544                 - releasing left mouse button
3545                 - pointing away from node
3546         */
3547         if (runData.digging) {
3548                 if (getLeftReleased()) {
3549                         infostream << "Left button released"
3550                                    << " (stopped digging)" << std::endl;
3551                         runData.digging = false;
3552                 } else if (pointed != runData.pointed_old) {
3553                         if (pointed.type == POINTEDTHING_NODE
3554                                         && runData.pointed_old.type == POINTEDTHING_NODE
3555                                         && pointed.node_undersurface
3556                                                         == runData.pointed_old.node_undersurface) {
3557                                 // Still pointing to the same node, but a different face.
3558                                 // Don't reset.
3559                         } else {
3560                                 infostream << "Pointing away from node"
3561                                            << " (stopped digging)" << std::endl;
3562                                 runData.digging = false;
3563                                 hud->updateSelectionMesh(camera_offset);
3564                         }
3565                 }
3566
3567                 if (!runData.digging) {
3568                         client->interact(1, runData.pointed_old);
3569                         client->setCrack(-1, v3s16(0, 0, 0));
3570                         runData.dig_time = 0.0;
3571                 }
3572         } else if (runData.dig_instantly && getLeftReleased()) {
3573                 // Remove e.g. torches faster when clicking instead of holding LMB
3574                 runData.nodig_delay_timer = 0;
3575                 runData.dig_instantly = false;
3576         }
3577
3578         if (!runData.digging && runData.ldown_for_dig && !isLeftPressed()) {
3579                 runData.ldown_for_dig = false;
3580         }
3581
3582         runData.left_punch = false;
3583
3584         soundmaker->m_player_leftpunch_sound.name = "";
3585
3586         if (isRightPressed())
3587                 runData.repeat_rightclick_timer += dtime;
3588         else
3589                 runData.repeat_rightclick_timer = 0;
3590
3591         if (playeritem_def.usable && isLeftPressed()) {
3592                 if (getLeftClicked() && (!client->moddingEnabled()
3593                                 || !client->getScript()->on_item_use(playeritem, pointed)))
3594                         client->interact(4, pointed);
3595         } else if (pointed.type == POINTEDTHING_NODE) {
3596                 ToolCapabilities playeritem_toolcap =
3597                                 playeritem.getToolCapabilities(itemdef_manager);
3598                 if (playeritem.name.empty()) {
3599                         playeritem_toolcap = *hand_def.tool_capabilities;
3600                 }
3601                 handlePointingAtNode(pointed, playeritem_def, playeritem_toolcap, dtime);
3602         } else if (pointed.type == POINTEDTHING_OBJECT) {
3603                 handlePointingAtObject(pointed, playeritem, player_position, show_debug);
3604         } else if (isLeftPressed()) {
3605                 // When button is held down in air, show continuous animation
3606                 runData.left_punch = true;
3607         } else if (getRightClicked()) {
3608                 handlePointingAtNothing(playeritem);
3609         }
3610
3611         runData.pointed_old = pointed;
3612
3613         if (runData.left_punch || getLeftClicked())
3614                 camera->setDigging(0); // left click animation
3615
3616         input->resetLeftClicked();
3617         input->resetRightClicked();
3618
3619         input->joystick.clearWasKeyDown(KeyType::MOUSE_L);
3620         input->joystick.clearWasKeyDown(KeyType::MOUSE_R);
3621
3622         input->resetLeftReleased();
3623         input->resetRightReleased();
3624
3625         input->joystick.clearWasKeyReleased(KeyType::MOUSE_L);
3626         input->joystick.clearWasKeyReleased(KeyType::MOUSE_R);
3627 }
3628
3629
3630 PointedThing Game::updatePointedThing(
3631         const core::line3d<f32> &shootline,
3632         bool liquids_pointable,
3633         bool look_for_object,
3634         const v3s16 &camera_offset)
3635 {
3636         std::vector<aabb3f> *selectionboxes = hud->getSelectionBoxes();
3637         selectionboxes->clear();
3638         hud->setSelectedFaceNormal(v3f(0.0, 0.0, 0.0));
3639         static const bool show_entity_selectionbox = g_settings->getBool(
3640                 "show_entity_selectionbox");
3641
3642         ClientMap &map = client->getEnv().getClientMap();
3643         INodeDefManager *nodedef=client->getNodeDefManager();
3644
3645         runData.selected_object = NULL;
3646
3647         PointedThing result=client->getEnv().getPointedThing(
3648                 shootline, liquids_pointable, look_for_object);
3649         if (result.type == POINTEDTHING_OBJECT) {
3650                 runData.selected_object = client->getEnv().getActiveObject(result.object_id);
3651                 if (show_entity_selectionbox && runData.selected_object->doShowSelectionBox()) {
3652                         aabb3f *selection_box = runData.selected_object->getSelectionBox();
3653
3654                         // Box should exist because object was
3655                         // returned in the first place
3656
3657                         assert(selection_box);
3658
3659                         v3f pos = runData.selected_object->getPosition();
3660                         selectionboxes->push_back(aabb3f(
3661                                 selection_box->MinEdge, selection_box->MaxEdge));
3662                         selectionboxes->push_back(
3663                                 aabb3f(selection_box->MinEdge, selection_box->MaxEdge));
3664                         hud->setSelectionPos(pos, camera_offset);
3665                 }
3666         } else if (result.type == POINTEDTHING_NODE) {
3667                 // Update selection boxes
3668                 MapNode n = map.getNodeNoEx(result.node_undersurface);
3669                 std::vector<aabb3f> boxes;
3670                 n.getSelectionBoxes(nodedef, &boxes,
3671                         n.getNeighbors(result.node_undersurface, &map));
3672
3673                 f32 d = 0.002 * BS;
3674                 for (std::vector<aabb3f>::const_iterator i = boxes.begin();
3675                         i != boxes.end(); ++i) {
3676                         aabb3f box = *i;
3677                         box.MinEdge -= v3f(d, d, d);
3678                         box.MaxEdge += v3f(d, d, d);
3679                         selectionboxes->push_back(box);
3680                 }
3681                 hud->setSelectionPos(intToFloat(result.node_undersurface, BS),
3682                         camera_offset);
3683                 hud->setSelectedFaceNormal(v3f(
3684                         result.intersection_normal.X,
3685                         result.intersection_normal.Y,
3686                         result.intersection_normal.Z));
3687         }
3688
3689         // Update selection mesh light level and vertex colors
3690         if (selectionboxes->size() > 0) {
3691                 v3f pf = hud->getSelectionPos();
3692                 v3s16 p = floatToInt(pf, BS);
3693
3694                 // Get selection mesh light level
3695                 MapNode n = map.getNodeNoEx(p);
3696                 u16 node_light = getInteriorLight(n, -1, nodedef);
3697                 u16 light_level = node_light;
3698
3699                 for (u8 i = 0; i < 6; i++) {
3700                         n = map.getNodeNoEx(p + g_6dirs[i]);
3701                         node_light = getInteriorLight(n, -1, nodedef);
3702                         if (node_light > light_level)
3703                                 light_level = node_light;
3704                 }
3705
3706                 u32 daynight_ratio = client->getEnv().getDayNightRatio();
3707                 video::SColor c;
3708                 final_color_blend(&c, light_level, daynight_ratio);
3709
3710                 // Modify final color a bit with time
3711                 u32 timer = porting::getTimeMs() % 5000;
3712                 float timerf = (float) (irr::core::PI * ((timer / 2500.0) - 0.5));
3713                 float sin_r = 0.08 * sin(timerf);
3714                 float sin_g = 0.08 * sin(timerf + irr::core::PI * 0.5);
3715                 float sin_b = 0.08 * sin(timerf + irr::core::PI);
3716                 c.setRed(core::clamp(core::round32(c.getRed() * (0.8 + sin_r)), 0, 255));
3717                 c.setGreen(core::clamp(core::round32(c.getGreen() * (0.8 + sin_g)), 0, 255));
3718                 c.setBlue(core::clamp(core::round32(c.getBlue() * (0.8 + sin_b)), 0, 255));
3719
3720                 // Set mesh final color
3721                 hud->setSelectionMeshColor(c);
3722         }
3723         return result;
3724 }
3725
3726
3727 void Game::handlePointingAtNothing(const ItemStack &playerItem)
3728 {
3729         infostream << "Right Clicked in Air" << std::endl;
3730         PointedThing fauxPointed;
3731         fauxPointed.type = POINTEDTHING_NOTHING;
3732         client->interact(5, fauxPointed);
3733 }
3734
3735
3736 void Game::handlePointingAtNode(const PointedThing &pointed, const ItemDefinition &playeritem_def,
3737                 const ToolCapabilities &playeritem_toolcap, f32 dtime)
3738 {
3739         v3s16 nodepos = pointed.node_undersurface;
3740         v3s16 neighbourpos = pointed.node_abovesurface;
3741
3742         /*
3743                 Check information text of node
3744         */
3745
3746         ClientMap &map = client->getEnv().getClientMap();
3747         NodeMetadata *meta = map.getNodeMetadata(nodepos);
3748
3749         if (meta) {
3750                 infotext = unescape_enriched(utf8_to_wide(meta->getString("infotext")));
3751         } else {
3752                 MapNode n = map.getNodeNoEx(nodepos);
3753
3754                 if (nodedef_manager->get(n).tiledef[0].name == "unknown_node.png") {
3755                         infotext = L"Unknown node: ";
3756                         infotext += utf8_to_wide(nodedef_manager->get(n).name);
3757                 }
3758         }
3759
3760         if (runData.nodig_delay_timer <= 0.0 && isLeftPressed()
3761                         && client->checkPrivilege("interact")) {
3762                 handleDigging(pointed, nodepos, playeritem_toolcap, dtime);
3763         }
3764
3765         if ((getRightClicked() ||
3766                         runData.repeat_rightclick_timer >= m_repeat_right_click_time) &&
3767                         client->checkPrivilege("interact")) {
3768                 runData.repeat_rightclick_timer = 0;
3769                 infostream << "Ground right-clicked" << std::endl;
3770
3771                 if (meta && meta->getString("formspec") != "" && !random_input
3772                                 && !isKeyDown(KeyType::SNEAK)) {
3773                         infostream << "Launching custom inventory view" << std::endl;
3774
3775                         InventoryLocation inventoryloc;
3776                         inventoryloc.setNodeMeta(nodepos);
3777
3778                         NodeMetadataFormSource *fs_src = new NodeMetadataFormSource(
3779                                 &client->getEnv().getClientMap(), nodepos);
3780                         TextDest *txt_dst = new TextDestNodeMetadata(nodepos, client);
3781
3782                         create_formspec_menu(&current_formspec, client,
3783                                         device, &input->joystick, fs_src, txt_dst);
3784                         cur_formname = "";
3785
3786                         current_formspec->setFormSpec(meta->getString("formspec"), inventoryloc);
3787                 } else {
3788                         // Report right click to server
3789
3790                         camera->setDigging(1);  // right click animation (always shown for feedback)
3791
3792                         // If the wielded item has node placement prediction,
3793                         // make that happen
3794                         bool placed = nodePlacementPrediction(*client,
3795                                         playeritem_def,
3796                                         nodepos, neighbourpos);
3797
3798                         if (placed) {
3799                                 // Report to server
3800                                 client->interact(3, pointed);
3801                                 // Read the sound
3802                                 soundmaker->m_player_rightpunch_sound =
3803                                                 playeritem_def.sound_place;
3804
3805                                 if (client->moddingEnabled())
3806                                         client->getScript()->on_placenode(pointed, playeritem_def);
3807                         } else {
3808                                 soundmaker->m_player_rightpunch_sound =
3809                                                 SimpleSoundSpec();
3810
3811                                 if (playeritem_def.node_placement_prediction == "" ||
3812                                                 nodedef_manager->get(map.getNodeNoEx(nodepos)).rightclickable) {
3813                                         client->interact(3, pointed); // Report to server
3814                                 } else {
3815                                         soundmaker->m_player_rightpunch_sound =
3816                                                 playeritem_def.sound_place_failed;
3817                                 }
3818                         }
3819                 }
3820         }
3821 }
3822
3823
3824 void Game::handlePointingAtObject(const PointedThing &pointed, const ItemStack &playeritem,
3825                 const v3f &player_position, bool show_debug)
3826 {
3827         infotext = unescape_enriched(
3828                 utf8_to_wide(runData.selected_object->infoText()));
3829
3830         if (show_debug) {
3831                 if (infotext != L"") {
3832                         infotext += L"\n";
3833                 }
3834                 infotext += unescape_enriched(utf8_to_wide(
3835                         runData.selected_object->debugInfoText()));
3836         }
3837
3838         if (isLeftPressed()) {
3839                 bool do_punch = false;
3840                 bool do_punch_damage = false;
3841
3842                 if (runData.object_hit_delay_timer <= 0.0) {
3843                         do_punch = true;
3844                         do_punch_damage = true;
3845                         runData.object_hit_delay_timer = object_hit_delay;
3846                 }
3847
3848                 if (getLeftClicked())
3849                         do_punch = true;
3850
3851                 if (do_punch) {
3852                         infostream << "Left-clicked object" << std::endl;
3853                         runData.left_punch = true;
3854                 }
3855
3856                 if (do_punch_damage) {
3857                         // Report direct punch
3858                         v3f objpos = runData.selected_object->getPosition();
3859                         v3f dir = (objpos - player_position).normalize();
3860                         ItemStack item = playeritem;
3861                         if (playeritem.name.empty()) {
3862                                 InventoryList *hlist = local_inventory->getList("hand");
3863                                 if (hlist) {
3864                                         item = hlist->getItem(0);
3865                                 }
3866                         }
3867
3868                         bool disable_send = runData.selected_object->directReportPunch(
3869                                         dir, &item, runData.time_from_last_punch);
3870                         runData.time_from_last_punch = 0;
3871
3872                         if (!disable_send)
3873                                 client->interact(0, pointed);
3874                 }
3875         } else if (getRightClicked()) {
3876                 infostream << "Right-clicked object" << std::endl;
3877                 client->interact(3, pointed);  // place
3878         }
3879 }
3880
3881
3882 void Game::handleDigging(const PointedThing &pointed, const v3s16 &nodepos,
3883                 const ToolCapabilities &playeritem_toolcap, f32 dtime)
3884 {
3885         LocalPlayer *player = client->getEnv().getLocalPlayer();
3886         ClientMap &map = client->getEnv().getClientMap();
3887         MapNode n = client->getEnv().getClientMap().getNodeNoEx(nodepos);
3888
3889         // NOTE: Similar piece of code exists on the server side for
3890         // cheat detection.
3891         // Get digging parameters
3892         DigParams params = getDigParams(nodedef_manager->get(n).groups,
3893                         &playeritem_toolcap);
3894
3895         // If can't dig, try hand
3896         if (!params.diggable) {
3897                 InventoryList *hlist = local_inventory->getList("hand");
3898                 const ItemDefinition &hand =
3899                         hlist ? hlist->getItem(0).getDefinition(itemdef_manager) : itemdef_manager->get("");
3900                 const ToolCapabilities *tp = hand.tool_capabilities;
3901
3902                 if (tp)
3903                         params = getDigParams(nodedef_manager->get(n).groups, tp);
3904         }
3905
3906         if (!runData.digging) {
3907                 infostream << "Started digging" << std::endl;
3908                 runData.dig_instantly = params.time == 0;
3909                 if (client->moddingEnabled() && client->getScript()->on_punchnode(nodepos, n))
3910                         return;
3911                 client->interact(0, pointed);
3912                 runData.digging = true;
3913                 runData.ldown_for_dig = true;
3914         }
3915
3916         if (!params.diggable) {
3917                 // I guess nobody will wait for this long
3918                 runData.dig_time_complete = 10000000.0;
3919         } else {
3920                 runData.dig_time_complete = params.time;
3921
3922                 if (m_cache_enable_particles) {
3923                         const ContentFeatures &features =
3924                                         client->getNodeDefManager()->get(n);
3925                         client->getParticleManager()->addPunchingParticles(client, smgr,
3926                                         player, nodepos, n, features);
3927                 }
3928         }
3929
3930         if (!runData.dig_instantly) {
3931                 runData.dig_index = (float)crack_animation_length
3932                                 * runData.dig_time
3933                                 / runData.dig_time_complete;
3934         } else {
3935                 // This is for e.g. torches
3936                 runData.dig_index = crack_animation_length;
3937         }
3938
3939         SimpleSoundSpec sound_dig = nodedef_manager->get(n).sound_dig;
3940
3941         if (sound_dig.exists() && params.diggable) {
3942                 if (sound_dig.name == "__group") {
3943                         if (params.main_group != "") {
3944                                 soundmaker->m_player_leftpunch_sound.gain = 0.5;
3945                                 soundmaker->m_player_leftpunch_sound.name =
3946                                                 std::string("default_dig_") +
3947                                                 params.main_group;
3948                         }
3949                 } else {
3950                         soundmaker->m_player_leftpunch_sound = sound_dig;
3951                 }
3952         }
3953
3954         // Don't show cracks if not diggable
3955         if (runData.dig_time_complete >= 100000.0) {
3956         } else if (runData.dig_index < crack_animation_length) {
3957                 //TimeTaker timer("client.setTempMod");
3958                 //infostream<<"dig_index="<<dig_index<<std::endl;
3959                 client->setCrack(runData.dig_index, nodepos);
3960         } else {
3961                 infostream << "Digging completed" << std::endl;
3962                 client->setCrack(-1, v3s16(0, 0, 0));
3963
3964                 runData.dig_time = 0;
3965                 runData.digging = false;
3966
3967                 runData.nodig_delay_timer =
3968                                 runData.dig_time_complete / (float)crack_animation_length;
3969
3970                 // We don't want a corresponding delay to very time consuming nodes
3971                 // and nodes without digging time (e.g. torches) get a fixed delay.
3972                 if (runData.nodig_delay_timer > 0.3)
3973                         runData.nodig_delay_timer = 0.3;
3974                 else if (runData.dig_instantly)
3975                         runData.nodig_delay_timer = 0.15;
3976
3977                 bool is_valid_position;
3978                 MapNode wasnode = map.getNodeNoEx(nodepos, &is_valid_position);
3979                 if (is_valid_position) {
3980                         if (client->moddingEnabled()) {
3981                                 if (client->getScript()->on_dignode(nodepos, wasnode)) {
3982                                         return;
3983                                 }
3984                         }
3985                         client->removeNode(nodepos);
3986                 }
3987
3988                 client->interact(2, pointed);
3989
3990                 if (m_cache_enable_particles) {
3991                         const ContentFeatures &features =
3992                                 client->getNodeDefManager()->get(wasnode);
3993                         client->getParticleManager()->addDiggingParticles(client, smgr,
3994                                 player, nodepos, wasnode, features);
3995                 }
3996
3997
3998                 // Send event to trigger sound
3999                 MtEvent *e = new NodeDugEvent(nodepos, wasnode);
4000                 client->event()->put(e);
4001         }
4002
4003         if (runData.dig_time_complete < 100000.0) {
4004                 runData.dig_time += dtime;
4005         } else {
4006                 runData.dig_time = 0;
4007                 client->setCrack(-1, nodepos);
4008         }
4009
4010         camera->setDigging(0);  // left click animation
4011 }
4012
4013
4014 void Game::updateFrame(ProfilerGraph *graph, RunStats *stats, f32 dtime,
4015                 const CameraOrientation &cam)
4016 {
4017         LocalPlayer *player = client->getEnv().getLocalPlayer();
4018
4019         /*
4020                 Fog range
4021         */
4022
4023         if (draw_control->range_all) {
4024                 runData.fog_range = 100000 * BS;
4025         } else {
4026                 runData.fog_range = draw_control->wanted_range * BS;
4027         }
4028
4029         /*
4030                 Calculate general brightness
4031         */
4032         u32 daynight_ratio = client->getEnv().getDayNightRatio();
4033         float time_brightness = decode_light_f((float)daynight_ratio / 1000.0);
4034         float direct_brightness;
4035         bool sunlight_seen;
4036
4037         if (m_cache_enable_noclip && m_cache_enable_free_move) {
4038                 direct_brightness = time_brightness;
4039                 sunlight_seen = true;
4040         } else {
4041                 ScopeProfiler sp(g_profiler, "Detecting background light", SPT_AVG);
4042                 float old_brightness = sky->getBrightness();
4043                 direct_brightness = client->getEnv().getClientMap()
4044                                 .getBackgroundBrightness(MYMIN(runData.fog_range * 1.2, 60 * BS),
4045                                         daynight_ratio, (int)(old_brightness * 255.5), &sunlight_seen)
4046                                     / 255.0;
4047         }
4048
4049         float time_of_day_smooth = runData.time_of_day_smooth;
4050         float time_of_day = client->getEnv().getTimeOfDayF();
4051
4052         static const float maxsm = 0.05;
4053         static const float todsm = 0.05;
4054
4055         if (fabs(time_of_day - time_of_day_smooth) > maxsm &&
4056                         fabs(time_of_day - time_of_day_smooth + 1.0) > maxsm &&
4057                         fabs(time_of_day - time_of_day_smooth - 1.0) > maxsm)
4058                 time_of_day_smooth = time_of_day;
4059
4060         if (time_of_day_smooth > 0.8 && time_of_day < 0.2)
4061                 time_of_day_smooth = time_of_day_smooth * (1.0 - todsm)
4062                                 + (time_of_day + 1.0) * todsm;
4063         else
4064                 time_of_day_smooth = time_of_day_smooth * (1.0 - todsm)
4065                                 + time_of_day * todsm;
4066
4067         runData.time_of_day = time_of_day;
4068         runData.time_of_day_smooth = time_of_day_smooth;
4069
4070         sky->update(time_of_day_smooth, time_brightness, direct_brightness,
4071                         sunlight_seen, camera->getCameraMode(), player->getYaw(),
4072                         player->getPitch());
4073
4074         /*
4075                 Update clouds
4076         */
4077         if (clouds) {
4078                 v3f player_position = player->getPosition();
4079                 if (sky->getCloudsVisible()) {
4080                         clouds->setVisible(true);
4081                         clouds->step(dtime);
4082                         clouds->update(v2f(player_position.X, player_position.Z),
4083                                        sky->getCloudColor());
4084                 } else {
4085                         clouds->setVisible(false);
4086                 }
4087         }
4088
4089         /*
4090                 Update particles
4091         */
4092         client->getParticleManager()->step(dtime);
4093
4094         /*
4095                 Fog
4096         */
4097
4098         if (m_cache_enable_fog && !flags.force_fog_off) {
4099                 driver->setFog(
4100                                 sky->getBgColor(),
4101                                 video::EFT_FOG_LINEAR,
4102                                 runData.fog_range * m_cache_fog_start,
4103                                 runData.fog_range * 1.0,
4104                                 0.01,
4105                                 false, // pixel fog
4106                                 true // range fog
4107                 );
4108         } else {
4109                 driver->setFog(
4110                                 sky->getBgColor(),
4111                                 video::EFT_FOG_LINEAR,
4112                                 100000 * BS,
4113                                 110000 * BS,
4114                                 0.01,
4115                                 false, // pixel fog
4116                                 false // range fog
4117                 );
4118         }
4119
4120         /*
4121                 Get chat messages from client
4122         */
4123
4124         v2u32 screensize = driver->getScreenSize();
4125
4126         updateChat(*client, dtime, flags.show_debug, screensize,
4127                         flags.show_chat, runData.profiler_current_page,
4128                         *chat_backend, guitext_chat);
4129
4130         /*
4131                 Inventory
4132         */
4133
4134         if (client->getPlayerItem() != runData.new_playeritem)
4135                 client->selectPlayerItem(runData.new_playeritem);
4136
4137         // Update local inventory if it has changed
4138         if (client->getLocalInventoryUpdated()) {
4139                 //infostream<<"Updating local inventory"<<std::endl;
4140                 client->getLocalInventory(*local_inventory);
4141                 runData.update_wielded_item_trigger = true;
4142         }
4143
4144         if (runData.update_wielded_item_trigger) {
4145                 // Update wielded tool
4146                 InventoryList *mlist = local_inventory->getList("main");
4147
4148                 if (mlist && (client->getPlayerItem() < mlist->getSize())) {
4149                         ItemStack item = mlist->getItem(client->getPlayerItem());
4150                         if (item.getDefinition(itemdef_manager).name.empty()) { // override the hand
4151                                 InventoryList *hlist = local_inventory->getList("hand");
4152                                 if (hlist)
4153                                         item = hlist->getItem(0);
4154                         }
4155                         camera->wield(item);
4156                 }
4157
4158                 runData.update_wielded_item_trigger = false;
4159         }
4160
4161         /*
4162                 Update block draw list every 200ms or when camera direction has
4163                 changed much
4164         */
4165         runData.update_draw_list_timer += dtime;
4166
4167         v3f camera_direction = camera->getDirection();
4168         if (runData.update_draw_list_timer >= 0.2
4169                         || runData.update_draw_list_last_cam_dir.getDistanceFrom(camera_direction) > 0.2
4170                         || m_camera_offset_changed) {
4171                 runData.update_draw_list_timer = 0;
4172                 client->getEnv().getClientMap().updateDrawList(driver);
4173                 runData.update_draw_list_last_cam_dir = camera_direction;
4174         }
4175
4176         updateGui(*stats, dtime, cam);
4177
4178         /*
4179            make sure menu is on top
4180            1. Delete formspec menu reference if menu was removed
4181            2. Else, make sure formspec menu is on top
4182         */
4183         if (current_formspec) {
4184                 if (current_formspec->getReferenceCount() == 1) {
4185                         current_formspec->drop();
4186                         current_formspec = NULL;
4187                 } else if (isMenuActive()) {
4188                         guiroot->bringToFront(current_formspec);
4189                 }
4190         }
4191
4192         /*
4193                 Drawing begins
4194         */
4195
4196         const video::SColor &skycolor = sky->getSkyColor();
4197
4198         TimeTaker tt_draw("mainloop: draw");
4199         driver->beginScene(true, true, skycolor);
4200
4201         draw_scene(driver, smgr, *camera, *client, player, *hud, mapper,
4202                         guienv, screensize, skycolor, flags.show_hud,
4203                         flags.show_minimap);
4204
4205         /*
4206                 Profiler graph
4207         */
4208         if (flags.show_profiler_graph)
4209                 graph->draw(10, screensize.Y - 10, driver, g_fontengine->getFont());
4210
4211         /*
4212                 Damage flash
4213         */
4214         if (runData.damage_flash > 0.0) {
4215                 video::SColor color(runData.damage_flash, 180, 0, 0);
4216                 driver->draw2DRectangle(color,
4217                                         core::rect<s32>(0, 0, screensize.X, screensize.Y),
4218                                         NULL);
4219
4220                 runData.damage_flash -= 100.0 * dtime;
4221         }
4222
4223         /*
4224                 Damage camera tilt
4225         */
4226         if (player->hurt_tilt_timer > 0.0) {
4227                 player->hurt_tilt_timer -= dtime * 5;
4228
4229                 if (player->hurt_tilt_timer < 0)
4230                         player->hurt_tilt_strength = 0;
4231         }
4232
4233         /*
4234                 Update minimap pos and rotation
4235         */
4236         if (mapper && flags.show_minimap && flags.show_hud) {
4237                 mapper->setPos(floatToInt(player->getPosition(), BS));
4238                 mapper->setAngle(player->getYaw());
4239         }
4240
4241         /*
4242                 End scene
4243         */
4244         driver->endScene();
4245
4246         stats->drawtime = tt_draw.stop(true);
4247         g_profiler->graphAdd("mainloop_draw", stats->drawtime / 1000.0f);
4248 }
4249
4250
4251 inline static const char *yawToDirectionString(int yaw)
4252 {
4253         static const char *direction[4] = {"North [+Z]", "West [-X]", "South [-Z]", "East [+X]"};
4254
4255         yaw = wrapDegrees_0_360(yaw);
4256         yaw = (yaw + 45) % 360 / 90;
4257
4258         return direction[yaw];
4259 }
4260
4261
4262 void Game::updateGui(const RunStats &stats, f32 dtime, const CameraOrientation &cam)
4263 {
4264         v2u32 screensize = driver->getScreenSize();
4265         LocalPlayer *player = client->getEnv().getLocalPlayer();
4266         v3f player_position = player->getPosition();
4267
4268         if (flags.show_debug) {
4269                 static float drawtime_avg = 0;
4270                 drawtime_avg = drawtime_avg * 0.95 + stats.drawtime * 0.05;
4271
4272                 u16 fps = 1.0 / stats.dtime_jitter.avg;
4273
4274                 std::ostringstream os(std::ios_base::binary);
4275                 os << std::fixed
4276                    << PROJECT_NAME_C " " << g_version_hash
4277                    << " FPS = " << fps
4278                    << " (R: range_all=" << draw_control->range_all << ")"
4279                    << std::setprecision(0)
4280                    << " drawtime = " << drawtime_avg
4281                    << std::setprecision(1)
4282                    << ", dtime_jitter = "
4283                    << (stats.dtime_jitter.max_fraction * 100.0) << " %"
4284                    << std::setprecision(1)
4285                    << ", v_range = " << draw_control->wanted_range
4286                    << std::setprecision(3)
4287                    << ", RTT = " << client->getRTT();
4288                 setStaticText(guitext, utf8_to_wide(os.str()).c_str());
4289                 guitext->setVisible(true);
4290         } else {
4291                 guitext->setVisible(false);
4292         }
4293
4294         if (guitext->isVisible()) {
4295                 core::rect<s32> rect(
4296                                 5,              5,
4297                                 screensize.X,   5 + g_fontengine->getTextHeight()
4298                 );
4299                 guitext->setRelativePosition(rect);
4300         }
4301
4302         if (flags.show_debug) {
4303                 std::ostringstream os(std::ios_base::binary);
4304                 os << std::setprecision(1) << std::fixed
4305                    << "(" << (player_position.X / BS)
4306                    << ", " << (player_position.Y / BS)
4307                    << ", " << (player_position.Z / BS)
4308                    << ") (yaw=" << (wrapDegrees_0_360(cam.camera_yaw))
4309                    << " " << yawToDirectionString(cam.camera_yaw)
4310                    << ") (seed = " << ((u64)client->getMapSeed())
4311                    << ")";
4312
4313                 if (runData.pointed_old.type == POINTEDTHING_NODE) {
4314                         ClientMap &map = client->getEnv().getClientMap();
4315                         const INodeDefManager *nodedef = client->getNodeDefManager();
4316                         MapNode n = map.getNodeNoEx(runData.pointed_old.node_undersurface);
4317                         if (n.getContent() != CONTENT_IGNORE && nodedef->get(n).name != "unknown") {
4318                                 const ContentFeatures &features = nodedef->get(n);
4319                                 os << " (pointing_at = " << nodedef->get(n).name
4320                                    << " - " << features.tiledef[0].name.c_str()
4321                                    << ")";
4322                         }
4323                 }
4324
4325                 setStaticText(guitext2, utf8_to_wide(os.str()).c_str());
4326                 guitext2->setVisible(true);
4327
4328                 core::rect<s32> rect(
4329                                 5,             5 + g_fontengine->getTextHeight(),
4330                                 screensize.X,  5 + g_fontengine->getTextHeight() * 2
4331                 );
4332                 guitext2->setRelativePosition(rect);
4333         } else {
4334                 guitext2->setVisible(false);
4335         }
4336
4337         setStaticText(guitext_info, infotext.c_str());
4338         guitext_info->setVisible(flags.show_hud && g_menumgr.menuCount() == 0);
4339
4340         float statustext_time_max = 1.5;
4341
4342         if (!m_statustext.empty()) {
4343                 runData.statustext_time += dtime;
4344
4345                 if (runData.statustext_time >= statustext_time_max) {
4346                         m_statustext = L"";
4347                         runData.statustext_time = 0;
4348                 }
4349         }
4350
4351         setStaticText(guitext_status, m_statustext.c_str());
4352         guitext_status->setVisible(!m_statustext.empty());
4353
4354         if (!m_statustext.empty()) {
4355                 s32 status_width  = guitext_status->getTextWidth();
4356                 s32 status_height = guitext_status->getTextHeight();
4357                 s32 status_y = screensize.Y - 150;
4358                 s32 status_x = (screensize.X - status_width) / 2;
4359                 core::rect<s32> rect(
4360                                 status_x , status_y - status_height,
4361                                 status_x + status_width, status_y
4362                 );
4363                 guitext_status->setRelativePosition(rect);
4364
4365                 // Fade out
4366                 video::SColor initial_color(255, 0, 0, 0);
4367
4368                 if (guienv->getSkin())
4369                         initial_color = guienv->getSkin()->getColor(gui::EGDC_BUTTON_TEXT);
4370
4371                 video::SColor final_color = initial_color;
4372                 final_color.setAlpha(0);
4373                 video::SColor fade_color = initial_color.getInterpolated_quadratic(
4374                                 initial_color, final_color,
4375                                 pow(runData.statustext_time / statustext_time_max, 2.0f));
4376                 guitext_status->setOverrideColor(fade_color);
4377                 guitext_status->enableOverrideColor(true);
4378         }
4379 }
4380
4381
4382 /* Log times and stuff for visualization */
4383 inline void Game::updateProfilerGraphs(ProfilerGraph *graph)
4384 {
4385         Profiler::GraphValues values;
4386         g_profiler->graphGet(values);
4387         graph->put(values);
4388 }
4389
4390
4391
4392 /****************************************************************************
4393  Misc
4394  ****************************************************************************/
4395
4396 /* On some computers framerate doesn't seem to be automatically limited
4397  */
4398 inline void Game::limitFps(FpsControl *fps_timings, f32 *dtime)
4399 {
4400         // not using getRealTime is necessary for wine
4401         device->getTimer()->tick(); // Maker sure device time is up-to-date
4402         u32 time = device->getTimer()->getTime();
4403         u32 last_time = fps_timings->last_time;
4404
4405         if (time > last_time)  // Make sure time hasn't overflowed
4406                 fps_timings->busy_time = time - last_time;
4407         else
4408                 fps_timings->busy_time = 0;
4409
4410         u32 frametime_min = 1000 / (g_menumgr.pausesGame()
4411                         ? g_settings->getFloat("pause_fps_max")
4412                         : g_settings->getFloat("fps_max"));
4413
4414         if (fps_timings->busy_time < frametime_min) {
4415                 fps_timings->sleep_time = frametime_min - fps_timings->busy_time;
4416                 device->sleep(fps_timings->sleep_time);
4417         } else {
4418                 fps_timings->sleep_time = 0;
4419         }
4420
4421         /* Get the new value of the device timer. Note that device->sleep() may
4422          * not sleep for the entire requested time as sleep may be interrupted and
4423          * therefore it is arguably more accurate to get the new time from the
4424          * device rather than calculating it by adding sleep_time to time.
4425          */
4426
4427         device->getTimer()->tick(); // Update device timer
4428         time = device->getTimer()->getTime();
4429
4430         if (time > last_time)  // Make sure last_time hasn't overflowed
4431                 *dtime = (time - last_time) / 1000.0;
4432         else
4433                 *dtime = 0;
4434
4435         fps_timings->last_time = time;
4436 }
4437
4438 // Note: This will free (using delete[])! \p msg. If you want to use it later,
4439 // pass a copy of it to this function
4440 // Note: \p msg must be allocated using new (not malloc())
4441 void Game::showOverlayMessage(const wchar_t *msg, float dtime,
4442                 int percent, bool draw_clouds)
4443 {
4444         draw_load_screen(msg, device, guienv, texture_src, dtime, percent,
4445                 draw_clouds);
4446         delete[] msg;
4447 }
4448
4449 void Game::settingChangedCallback(const std::string &setting_name, void *data)
4450 {
4451         ((Game *)data)->readSettings();
4452 }
4453
4454 void Game::readSettings()
4455 {
4456         m_cache_doubletap_jump               = g_settings->getBool("doubletap_jump");
4457         m_cache_enable_clouds                = g_settings->getBool("enable_clouds");
4458         m_cache_enable_joysticks             = g_settings->getBool("enable_joysticks");
4459         m_cache_enable_particles             = g_settings->getBool("enable_particles");
4460         m_cache_enable_fog                   = g_settings->getBool("enable_fog");
4461         m_cache_mouse_sensitivity            = g_settings->getFloat("mouse_sensitivity");
4462         m_cache_joystick_frustum_sensitivity = g_settings->getFloat("joystick_frustum_sensitivity");
4463         m_repeat_right_click_time            = g_settings->getFloat("repeat_rightclick_time");
4464
4465         m_cache_enable_noclip                = g_settings->getBool("noclip");
4466         m_cache_enable_free_move             = g_settings->getBool("free_move");
4467
4468         m_cache_fog_start                    = g_settings->getFloat("fog_start");
4469
4470         m_cache_cam_smoothing = 0;
4471         if (g_settings->getBool("cinematic"))
4472                 m_cache_cam_smoothing = 1 - g_settings->getFloat("cinematic_camera_smoothing");
4473         else
4474                 m_cache_cam_smoothing = 1 - g_settings->getFloat("camera_smoothing");
4475
4476         m_cache_fog_start = rangelim(m_cache_fog_start, 0.0f, 0.99f);
4477         m_cache_cam_smoothing = rangelim(m_cache_cam_smoothing, 0.01f, 1.0f);
4478         m_cache_mouse_sensitivity = rangelim(m_cache_mouse_sensitivity, 0.001, 100.0);
4479
4480 }
4481
4482 /****************************************************************************/
4483 /****************************************************************************
4484  Shutdown / cleanup
4485  ****************************************************************************/
4486 /****************************************************************************/
4487
4488 void Game::extendedResourceCleanup()
4489 {
4490         // Extended resource accounting
4491         infostream << "Irrlicht resources after cleanup:" << std::endl;
4492         infostream << "\tRemaining meshes   : "
4493                    << device->getSceneManager()->getMeshCache()->getMeshCount() << std::endl;
4494         infostream << "\tRemaining textures : "
4495                    << driver->getTextureCount() << std::endl;
4496
4497         for (unsigned int i = 0; i < driver->getTextureCount(); i++) {
4498                 irr::video::ITexture *texture = driver->getTextureByIndex(i);
4499                 infostream << "\t\t" << i << ":" << texture->getName().getPath().c_str()
4500                            << std::endl;
4501         }
4502
4503         clearTextureNameCache();
4504         infostream << "\tRemaining materials: "
4505                << driver-> getMaterialRendererCount()
4506                        << " (note: irrlicht doesn't support removing renderers)" << std::endl;
4507 }
4508
4509 #define GET_KEY_NAME(KEY) gettext(getKeySetting(#KEY).name())
4510 void Game::showPauseMenu()
4511 {
4512 #ifdef __ANDROID__
4513         static const std::string control_text = strgettext("Default Controls:\n"
4514                 "No menu visible:\n"
4515                 "- single tap: button activate\n"
4516                 "- double tap: place/use\n"
4517                 "- slide finger: look around\n"
4518                 "Menu/Inventory visible:\n"
4519                 "- double tap (outside):\n"
4520                 " -->close\n"
4521                 "- touch stack, touch slot:\n"
4522                 " --> move stack\n"
4523                 "- touch&drag, tap 2nd finger\n"
4524                 " --> place single item to slot\n"
4525                 );
4526 #else
4527         static const std::string control_text_template = strgettext("Controls:\n"
4528                 "- %s: move forwards\n"
4529                 "- %s: move backwards\n"
4530                 "- %s: move left\n"
4531                 "- %s: move right\n"
4532                 "- %s: jump/climb\n"
4533                 "- %s: sneak/go down\n"
4534                 "- %s: drop item\n"
4535                 "- %s: inventory\n"
4536                 "- Mouse: turn/look\n"
4537                 "- Mouse left: dig/punch\n"
4538                 "- Mouse right: place/use\n"
4539                 "- Mouse wheel: select item\n"
4540                 "- %s: chat\n"
4541         );
4542
4543          char control_text_buf[600];
4544
4545          snprintf(control_text_buf, ARRLEN(control_text_buf), control_text_template.c_str(),
4546                         GET_KEY_NAME(keymap_forward),
4547                         GET_KEY_NAME(keymap_backward),
4548                         GET_KEY_NAME(keymap_left),
4549                         GET_KEY_NAME(keymap_right),
4550                         GET_KEY_NAME(keymap_jump),
4551                         GET_KEY_NAME(keymap_sneak),
4552                         GET_KEY_NAME(keymap_drop),
4553                         GET_KEY_NAME(keymap_inventory),
4554                         GET_KEY_NAME(keymap_chat)
4555                         );
4556
4557         std::string control_text = std::string(control_text_buf);
4558         str_formspec_escape(control_text);
4559 #endif
4560
4561         float ypos = simple_singleplayer_mode ? 0.7f : 0.1f;
4562         std::ostringstream os;
4563
4564         os << FORMSPEC_VERSION_STRING  << SIZE_TAG
4565                 << "button_exit[4," << (ypos++) << ";3,0.5;btn_continue;"
4566                 << strgettext("Continue") << "]";
4567
4568         if (!simple_singleplayer_mode) {
4569                 os << "button_exit[4," << (ypos++) << ";3,0.5;btn_change_password;"
4570                         << strgettext("Change Password") << "]";
4571         } else {
4572                 os << "field[4.95,0;5,1.5;;" << strgettext("Game paused") << ";]";
4573         }
4574
4575 #ifndef __ANDROID__
4576         os              << "button_exit[4," << (ypos++) << ";3,0.5;btn_sound;"
4577                 << strgettext("Sound Volume") << "]";
4578         os              << "button_exit[4," << (ypos++) << ";3,0.5;btn_key_config;"
4579                 << strgettext("Change Keys")  << "]";
4580 #endif
4581         os              << "button_exit[4," << (ypos++) << ";3,0.5;btn_exit_menu;"
4582                 << strgettext("Exit to Menu") << "]";
4583         os              << "button_exit[4," << (ypos++) << ";3,0.5;btn_exit_os;"
4584                 << strgettext("Exit to OS")   << "]"
4585                 << "textarea[7.5,0.25;3.9,6.25;;" << control_text << ";]"
4586                 << "textarea[0.4,0.25;3.9,6.25;;" << PROJECT_NAME_C " " VERSION_STRING "\n"
4587                 << "\n"
4588                 <<  strgettext("Game info:") << "\n";
4589         const std::string &address = client->getAddressName();
4590         static const std::string mode = strgettext("- Mode: ");
4591         if (!simple_singleplayer_mode) {
4592                 Address serverAddress = client->getServerAddress();
4593                 if (address != "") {
4594                         os << mode << strgettext("Remote server") << "\n"
4595                                         << strgettext("- Address: ") << address;
4596                 } else {
4597                         os << mode << strgettext("Hosting server");
4598                 }
4599                 os << "\n" << strgettext("- Port: ") << serverAddress.getPort() << "\n";
4600         } else {
4601                 os << mode << strgettext("Singleplayer") << "\n";
4602         }
4603         if (simple_singleplayer_mode || address == "") {
4604                 static const std::string on = strgettext("On");
4605                 static const std::string off = strgettext("Off");
4606                 const std::string &damage = g_settings->getBool("enable_damage") ? on : off;
4607                 const std::string &creative = g_settings->getBool("creative_mode") ? on : off;
4608                 const std::string &announced = g_settings->getBool("server_announce") ? on : off;
4609                 os << strgettext("- Damage: ") << damage << "\n"
4610                                 << strgettext("- Creative Mode: ") << creative << "\n";
4611                 if (!simple_singleplayer_mode) {
4612                         const std::string &pvp = g_settings->getBool("enable_pvp") ? on : off;
4613                         os << strgettext("- PvP: ") << pvp << "\n"
4614                                         << strgettext("- Public: ") << announced << "\n";
4615                         std::string server_name = g_settings->get("server_name");
4616                         str_formspec_escape(server_name);
4617                         if (announced == on && server_name != "")
4618                                 os << strgettext("- Server Name: ") << server_name;
4619
4620                 }
4621         }
4622         os << ";]";
4623
4624         /* Create menu */
4625         /* Note: FormspecFormSource and LocalFormspecHandler  *
4626          * are deleted by guiFormSpecMenu                     */
4627         FormspecFormSource *fs_src = new FormspecFormSource(os.str());
4628         LocalFormspecHandler *txt_dst = new LocalFormspecHandler("MT_PAUSE_MENU");
4629
4630         create_formspec_menu(&current_formspec, client, device, &input->joystick, fs_src, txt_dst);
4631         current_formspec->setFocus("btn_continue");
4632         current_formspec->doPause = true;
4633 }
4634
4635 /****************************************************************************/
4636 /****************************************************************************
4637  extern function for launching the game
4638  ****************************************************************************/
4639 /****************************************************************************/
4640
4641 void the_game(bool *kill,
4642                 bool random_input,
4643                 InputHandler *input,
4644                 IrrlichtDevice *device,
4645
4646                 const std::string &map_dir,
4647                 const std::string &playername,
4648                 const std::string &password,
4649                 const std::string &address,         // If empty local server is created
4650                 u16 port,
4651
4652                 std::string &error_message,
4653                 ChatBackend &chat_backend,
4654                 bool *reconnect_requested,
4655                 const SubgameSpec &gamespec,        // Used for local game
4656                 bool simple_singleplayer_mode)
4657 {
4658         Game game;
4659
4660         /* Make a copy of the server address because if a local singleplayer server
4661          * is created then this is updated and we don't want to change the value
4662          * passed to us by the calling function
4663          */
4664         std::string server_address = address;
4665
4666         try {
4667
4668                 if (game.startup(kill, random_input, input, device, map_dir,
4669                                 playername, password, &server_address, port, error_message,
4670                                 reconnect_requested, &chat_backend, gamespec,
4671                                 simple_singleplayer_mode)) {
4672                         game.run();
4673                         game.shutdown();
4674                 }
4675
4676         } catch (SerializationError &e) {
4677                 error_message = std::string("A serialization error occurred:\n")
4678                                 + e.what() + "\n\nThe server is probably "
4679                                 " running a different version of " PROJECT_NAME_C ".";
4680                 errorstream << error_message << std::endl;
4681         } catch (ServerError &e) {
4682                 error_message = e.what();
4683                 errorstream << "ServerError: " << error_message << std::endl;
4684         } catch (ModError &e) {
4685                 error_message = e.what() + strgettext("\nCheck debug.txt for details.");
4686                 errorstream << "ModError: " << error_message << std::endl;
4687         }
4688 }