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