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