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