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