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