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