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