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