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