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