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