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