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