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