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