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