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