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