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