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