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