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