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