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