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