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