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