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