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