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