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