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