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