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