]> git.lizzy.rs Git - dragonfireclient.git/blobdiff - src/game.cpp
Getv3intfield: Fix logic of return bool
[dragonfireclient.git] / src / game.cpp
index ae5efa964662f128c1f70ad873bb8b5a606ab7a4..2145d565da0430013894d4669ecd88fe2aefc45a 100644 (file)
@@ -20,8 +20,13 @@ with this program; if not, write to the Free Software Foundation, Inc.,
 #include "game.h"
 
 #include <iomanip>
+#include <cmath>
+#include "client/renderingengine.h"
 #include "camera.h"
 #include "client.h"
+#include "client/clientevent.h"
+#include "client/gameui.h"
+#include "client/inputhandler.h"
 #include "client/tile.h"     // For TextureSource
 #include "client/keys.h"
 #include "client/joystick_controller.h"
@@ -29,52 +34,44 @@ with this program; if not, write to the Free Software Foundation, Inc.,
 #include "clouds.h"
 #include "config.h"
 #include "content_cao.h"
-#include "drawscene.h"
 #include "event_manager.h"
 #include "fontengine.h"
 #include "itemdef.h"
 #include "log.h"
 #include "filesys.h"
 #include "gettext.h"
-#include "guiChatConsole.h"
-#include "guiFormSpecMenu.h"
-#include "guiKeyChangeMenu.h"
-#include "guiPasswordChange.h"
-#include "guiVolumeChange.h"
-#include "mainmenumanager.h"
+#include "gui/guiChatConsole.h"
+#include "gui/guiConfirmRegistration.h"
+#include "gui/guiFormSpecMenu.h"
+#include "gui/guiKeyChangeMenu.h"
+#include "gui/guiPasswordChange.h"
+#include "gui/guiVolumeChange.h"
+#include "gui/mainmenumanager.h"
+#include "gui/profilergraph.h"
 #include "mapblock.h"
+#include "minimap.h"
 #include "nodedef.h"         // Needed for determining pointing to nodes
 #include "nodemetadata.h"
 #include "particles.h"
 #include "profiler.h"
 #include "quicktune_shortcutter.h"
+#include "raycast.h"
 #include "server.h"
 #include "settings.h"
-#include "shader.h"          // For ShaderSource
+#include "shader.h"
 #include "sky.h"
-#include "subgame.h"
-#include "tool.h"
+#include "translation.h"
 #include "util/basic_macros.h"
 #include "util/directiontables.h"
 #include "util/pointedthing.h"
 #include "irrlicht_changes/static_text.h"
 #include "version.h"
-#include "minimap.h"
-#include "mapblock_mesh.h"
 #include "script/scripting_client.h"
 
-#include "sound.h"
-
 #if USE_SOUND
        #include "sound_openal.h"
 #endif
 
-#ifdef HAVE_TOUCHSCREENGUI
-       #include "touchscreengui.h"
-#endif
-
-extern Settings *g_settings;
-extern Profiler *g_profiler;
 
 /*
        Text input system
@@ -128,8 +125,7 @@ struct TextDestPlayerInventory : public TextDest
 
 struct LocalFormspecHandler : public TextDest
 {
-       LocalFormspecHandler(const std::string &formname):
-               m_client(NULL)
+       LocalFormspecHandler(const std::string &formname)
        {
                m_formname = formname;
        }
@@ -160,6 +156,9 @@ struct LocalFormspecHandler : public TextDest
 
                        if (fields.find("btn_exit_os") != fields.end()) {
                                g_gamecallback->exitToOS();
+#ifndef __ANDROID__
+                               RenderingEngine::get_raw_device()->closeDevice();
+#endif
                                return;
                        }
 
@@ -178,10 +177,11 @@ struct LocalFormspecHandler : public TextDest
                }
 
                // Don't disable this part when modding is disabled, it's used in builtin
-               m_client->getScript()->on_formspec_input(m_formname, fields);
+               if (m_client && m_client->getScript())
+                       m_client->getScript()->on_formspec_input(m_formname, fields);
        }
 
-       Client *m_client;
+       Client *m_client = nullptr;
 };
 
 /* Form update callback */
@@ -194,12 +194,13 @@ class NodeMetadataFormSource: public IFormSource
                m_p(p)
        {
        }
-       std::string getForm()
+       const std::string &getForm() const
        {
+               static const std::string empty_string = "";
                NodeMetadata *meta = m_map->getNodeMetadata(m_p);
 
                if (!meta)
-                       return "";
+                       return empty_string;
 
                return meta->getString("formspec");
        }
@@ -225,7 +226,8 @@ class PlayerInventoryFormSource: public IFormSource
                m_client(client)
        {
        }
-       std::string getForm()
+
+       const std::string &getForm() const
        {
                LocalPlayer *player = m_client->getEnv().getLocalPlayer();
                return player->inventory_formspec;
@@ -234,228 +236,6 @@ class PlayerInventoryFormSource: public IFormSource
        Client *m_client;
 };
 
-/* Profiler display */
-
-void update_profiler_gui(gui::IGUIStaticText *guitext_profiler, FontEngine *fe,
-               u32 show_profiler, u32 show_profiler_max, s32 screen_height)
-{
-       if (show_profiler == 0) {
-               guitext_profiler->setVisible(false);
-       } else {
-
-               std::ostringstream os(std::ios_base::binary);
-               g_profiler->printPage(os, show_profiler, show_profiler_max);
-               std::wstring text = utf8_to_wide(os.str());
-               setStaticText(guitext_profiler, text.c_str());
-               guitext_profiler->setVisible(true);
-
-               s32 w = fe->getTextWidth(text.c_str());
-
-               if (w < 400)
-                       w = 400;
-
-               unsigned text_height = fe->getTextHeight();
-
-               core::position2di upper_left, lower_right;
-
-               upper_left.X  = 6;
-               upper_left.Y  = (text_height + 5) * 2;
-               lower_right.X = 12 + w;
-               lower_right.Y = upper_left.Y + (text_height + 1) * MAX_PROFILER_TEXT_ROWS;
-
-               if (lower_right.Y > screen_height * 2 / 3)
-                       lower_right.Y = screen_height * 2 / 3;
-
-               core::rect<s32> rect(upper_left, lower_right);
-
-               guitext_profiler->setRelativePosition(rect);
-               guitext_profiler->setVisible(true);
-       }
-}
-
-class ProfilerGraph
-{
-private:
-       struct Piece {
-               Profiler::GraphValues values;
-       };
-       struct Meta {
-               float min;
-               float max;
-               video::SColor color;
-               Meta(float initial = 0,
-                       video::SColor color = video::SColor(255, 255, 255, 255)):
-                       min(initial),
-                       max(initial),
-                       color(color)
-               {}
-       };
-       std::deque<Piece> m_log;
-public:
-       u32 m_log_max_size;
-
-       ProfilerGraph():
-               m_log_max_size(200)
-       {}
-
-       void put(const Profiler::GraphValues &values)
-       {
-               Piece piece;
-               piece.values = values;
-               m_log.push_back(piece);
-
-               while (m_log.size() > m_log_max_size)
-                       m_log.erase(m_log.begin());
-       }
-
-       void draw(s32 x_left, s32 y_bottom, video::IVideoDriver *driver,
-                 gui::IGUIFont *font) const
-       {
-               // Do *not* use UNORDERED_MAP here as the order needs
-               // to be the same for each call to prevent flickering
-               std::map<std::string, Meta> m_meta;
-
-               for (std::deque<Piece>::const_iterator k = m_log.begin();
-                               k != m_log.end(); ++k) {
-                       const Piece &piece = *k;
-
-                       for (Profiler::GraphValues::const_iterator i = piece.values.begin();
-                                       i != piece.values.end(); ++i) {
-                               const std::string &id = i->first;
-                               const float &value = i->second;
-                               std::map<std::string, Meta>::iterator j = m_meta.find(id);
-
-                               if (j == m_meta.end()) {
-                                       m_meta[id] = Meta(value);
-                                       continue;
-                               }
-
-                               if (value < j->second.min)
-                                       j->second.min = value;
-
-                               if (value > j->second.max)
-                                       j->second.max = value;
-                       }
-               }
-
-               // Assign colors
-               static const video::SColor usable_colors[] = {
-                       video::SColor(255, 255, 100, 100),
-                       video::SColor(255, 90, 225, 90),
-                       video::SColor(255, 100, 100, 255),
-                       video::SColor(255, 255, 150, 50),
-                       video::SColor(255, 220, 220, 100)
-               };
-               static const u32 usable_colors_count =
-                       sizeof(usable_colors) / sizeof(*usable_colors);
-               u32 next_color_i = 0;
-
-               for (std::map<std::string, Meta>::iterator i = m_meta.begin();
-                               i != m_meta.end(); ++i) {
-                       Meta &meta = i->second;
-                       video::SColor color(255, 200, 200, 200);
-
-                       if (next_color_i < usable_colors_count)
-                               color = usable_colors[next_color_i++];
-
-                       meta.color = color;
-               }
-
-               s32 graphh = 50;
-               s32 textx = x_left + m_log_max_size + 15;
-               s32 textx2 = textx + 200 - 15;
-               s32 meta_i = 0;
-
-               for (std::map<std::string, Meta>::const_iterator i = m_meta.begin();
-                               i != m_meta.end(); ++i) {
-                       const std::string &id = i->first;
-                       const Meta &meta = i->second;
-                       s32 x = x_left;
-                       s32 y = y_bottom - meta_i * 50;
-                       float show_min = meta.min;
-                       float show_max = meta.max;
-
-                       if (show_min >= -0.0001 && show_max >= -0.0001) {
-                               if (show_min <= show_max * 0.5)
-                                       show_min = 0;
-                       }
-
-                       s32 texth = 15;
-                       char buf[10];
-                       snprintf(buf, 10, "%.3g", show_max);
-                       font->draw(utf8_to_wide(buf).c_str(),
-                                       core::rect<s32>(textx, y - graphh,
-                                                  textx2, y - graphh + texth),
-                                       meta.color);
-                       snprintf(buf, 10, "%.3g", show_min);
-                       font->draw(utf8_to_wide(buf).c_str(),
-                                       core::rect<s32>(textx, y - texth,
-                                                  textx2, y),
-                                       meta.color);
-                       font->draw(utf8_to_wide(id).c_str(),
-                                       core::rect<s32>(textx, y - graphh / 2 - texth / 2,
-                                                  textx2, y - graphh / 2 + texth / 2),
-                                       meta.color);
-                       s32 graph1y = y;
-                       s32 graph1h = graphh;
-                       bool relativegraph = (show_min != 0 && show_min != show_max);
-                       float lastscaledvalue = 0.0;
-                       bool lastscaledvalue_exists = false;
-
-                       for (std::deque<Piece>::const_iterator j = m_log.begin();
-                                       j != m_log.end(); ++j) {
-                               const Piece &piece = *j;
-                               float value = 0;
-                               bool value_exists = false;
-                               Profiler::GraphValues::const_iterator k =
-                                       piece.values.find(id);
-
-                               if (k != piece.values.end()) {
-                                       value = k->second;
-                                       value_exists = true;
-                               }
-
-                               if (!value_exists) {
-                                       x++;
-                                       lastscaledvalue_exists = false;
-                                       continue;
-                               }
-
-                               float scaledvalue = 1.0;
-
-                               if (show_max != show_min)
-                                       scaledvalue = (value - show_min) / (show_max - show_min);
-
-                               if (scaledvalue == 1.0 && value == 0) {
-                                       x++;
-                                       lastscaledvalue_exists = false;
-                                       continue;
-                               }
-
-                               if (relativegraph) {
-                                       if (lastscaledvalue_exists) {
-                                               s32 ivalue1 = lastscaledvalue * graph1h;
-                                               s32 ivalue2 = scaledvalue * graph1h;
-                                               driver->draw2DLine(v2s32(x - 1, graph1y - ivalue1),
-                                                                  v2s32(x, graph1y - ivalue2), meta.color);
-                                       }
-
-                                       lastscaledvalue = scaledvalue;
-                                       lastscaledvalue_exists = true;
-                               } else {
-                                       s32 ivalue = scaledvalue * graph1h;
-                                       driver->draw2DLine(v2s32(x, graph1y),
-                                                          v2s32(x, graph1y - ivalue), meta.color);
-                               }
-
-                               x++;
-                       }
-
-                       meta_i++;
-               }
-       }
-};
-
 class NodeDugEvent: public MtEvent
 {
 public:
@@ -475,7 +255,7 @@ class NodeDugEvent: public MtEvent
 class SoundMaker
 {
        ISoundManager *m_sound;
-       INodeDefManager *m_ndef;
+       const NodeDefManager *m_ndef;
 public:
        bool makes_footstep_sound;
        float m_player_step_timer;
@@ -484,7 +264,7 @@ class SoundMaker
        SimpleSoundSpec m_player_leftpunch_sound;
        SimpleSoundSpec m_player_rightpunch_sound;
 
-       SoundMaker(ISoundManager *sound, INodeDefManager *ndef):
+       SoundMaker(ISoundManager *sound, const NodeDefManager *ndef):
                m_sound(sound),
                m_ndef(ndef),
                makes_footstep_sound(true),
@@ -723,16 +503,18 @@ class GameGlobalShaderConstantSetter : public IShaderConstantSetter
                m_eye_position_pixel.set(eye_position_array, services);
                m_eye_position_vertex.set(eye_position_array, services);
 
-               float minimap_yaw_array[3];
-               v3f minimap_yaw = m_client->getMinimap()->getYawVec();
+               if (m_client->getMinimap()) {
+                       float minimap_yaw_array[3];
+                       v3f minimap_yaw = m_client->getMinimap()->getYawVec();
 #if (IRRLICHT_VERSION_MAJOR == 1 && IRRLICHT_VERSION_MINOR < 8)
-               minimap_yaw_array[0] = minimap_yaw.X;
-               minimap_yaw_array[1] = minimap_yaw.Y;
-               minimap_yaw_array[2] = minimap_yaw.Z;
+                       minimap_yaw_array[0] = minimap_yaw.X;
+                       minimap_yaw_array[1] = minimap_yaw.Y;
+                       minimap_yaw_array[2] = minimap_yaw.Z;
 #else
-               minimap_yaw.getAs3Values(minimap_yaw_array);
+                       minimap_yaw.getAs3Values(minimap_yaw_array);
 #endif
-               m_minimap_yaw.set(minimap_yaw_array, services);
+                       m_minimap_yaw.set(minimap_yaw_array, services);
+               }
 
                SamplerLayer_t base_tex = 0,
                                normal_tex = 1,
@@ -762,8 +544,8 @@ class GameGlobalShaderConstantSetterFactory : public IShaderConstantSetterFactor
 
        void setSky(Sky *sky) {
                m_sky = sky;
-               for (size_t i = 0; i < created_nosky.size(); ++i) {
-                       created_nosky[i]->setSky(m_sky);
+               for (GameGlobalShaderConstantSetter *ggscs : created_nosky) {
+                       ggscs->setSky(m_sky);
                }
                created_nosky.clear();
        }
@@ -778,327 +560,12 @@ class GameGlobalShaderConstantSetterFactory : public IShaderConstantSetterFactor
        }
 };
 
-
-bool nodePlacementPrediction(Client &client,
-               const ItemDefinition &playeritem_def, v3s16 nodepos, v3s16 neighbourpos)
-{
-       std::string prediction = playeritem_def.node_placement_prediction;
-       INodeDefManager *nodedef = client.ndef();
-       ClientMap &map = client.getEnv().getClientMap();
-       MapNode node;
-       bool is_valid_position;
-
-       node = map.getNodeNoEx(nodepos, &is_valid_position);
-       if (!is_valid_position)
-               return false;
-
-       if (prediction != "" && !nodedef->get(node).rightclickable) {
-               verbosestream << "Node placement prediction for "
-                             << playeritem_def.name << " is "
-                             << prediction << std::endl;
-               v3s16 p = neighbourpos;
-
-               // Place inside node itself if buildable_to
-               MapNode n_under = map.getNodeNoEx(nodepos, &is_valid_position);
-               if (is_valid_position)
-               {
-                       if (nodedef->get(n_under).buildable_to)
-                               p = nodepos;
-                       else {
-                               node = map.getNodeNoEx(p, &is_valid_position);
-                               if (is_valid_position &&!nodedef->get(node).buildable_to)
-                                       return false;
-                       }
-               }
-
-               // Find id of predicted node
-               content_t id;
-               bool found = nodedef->getId(prediction, id);
-
-               if (!found) {
-                       errorstream << "Node placement prediction failed for "
-                                   << playeritem_def.name << " (places "
-                                   << prediction
-                                   << ") - Name not known" << std::endl;
-                       return false;
-               }
-
-               // Predict param2 for facedir and wallmounted nodes
-               u8 param2 = 0;
-
-               if (nodedef->get(id).param_type_2 == CPT2_WALLMOUNTED ||
-                               nodedef->get(id).param_type_2 == CPT2_COLORED_WALLMOUNTED) {
-                       v3s16 dir = nodepos - neighbourpos;
-
-                       if (abs(dir.Y) > MYMAX(abs(dir.X), abs(dir.Z))) {
-                               param2 = dir.Y < 0 ? 1 : 0;
-                       } else if (abs(dir.X) > abs(dir.Z)) {
-                               param2 = dir.X < 0 ? 3 : 2;
-                       } else {
-                               param2 = dir.Z < 0 ? 5 : 4;
-                       }
-               }
-
-               if (nodedef->get(id).param_type_2 == CPT2_FACEDIR ||
-                               nodedef->get(id).param_type_2 == CPT2_COLORED_FACEDIR) {
-                       v3s16 dir = nodepos - floatToInt(client.getEnv().getLocalPlayer()->getPosition(), BS);
-
-                       if (abs(dir.X) > abs(dir.Z)) {
-                               param2 = dir.X < 0 ? 3 : 1;
-                       } else {
-                               param2 = dir.Z < 0 ? 2 : 0;
-                       }
-               }
-
-               assert(param2 <= 5);
-
-               //Check attachment if node is in group attached_node
-               if (((ItemGroupList) nodedef->get(id).groups)["attached_node"] != 0) {
-                       static v3s16 wallmounted_dirs[8] = {
-                               v3s16(0, 1, 0),
-                               v3s16(0, -1, 0),
-                               v3s16(1, 0, 0),
-                               v3s16(-1, 0, 0),
-                               v3s16(0, 0, 1),
-                               v3s16(0, 0, -1),
-                       };
-                       v3s16 pp;
-
-                       if (nodedef->get(id).param_type_2 == CPT2_WALLMOUNTED ||
-                                       nodedef->get(id).param_type_2 == CPT2_COLORED_WALLMOUNTED)
-                               pp = p + wallmounted_dirs[param2];
-                       else
-                               pp = p + v3s16(0, -1, 0);
-
-                       if (!nodedef->get(map.getNodeNoEx(pp)).walkable)
-                               return false;
-               }
-
-               // Add node to client map
-               MapNode n(id, 0, param2);
-
-               try {
-                       LocalPlayer *player = client.getEnv().getLocalPlayer();
-
-                       // Dont place node when player would be inside new node
-                       // NOTE: This is to be eventually implemented by a mod as client-side Lua
-                       if (!nodedef->get(n).walkable ||
-                                       g_settings->getBool("enable_build_where_you_stand") ||
-                                       (client.checkPrivilege("noclip") && g_settings->getBool("noclip")) ||
-                                       (nodedef->get(n).walkable &&
-                                        neighbourpos != player->getStandingNodePos() + v3s16(0, 1, 0) &&
-                                        neighbourpos != player->getStandingNodePos() + v3s16(0, 2, 0))) {
-
-                               // This triggers the required mesh update too
-                               client.addNode(p, n);
-                               return true;
-                       }
-               } catch (InvalidPositionException &e) {
-                       errorstream << "Node placement prediction failed for "
-                                   << playeritem_def.name << " (places "
-                                   << prediction
-                                   << ") - Position not loaded" << std::endl;
-               }
-       }
-
-       return false;
-}
-
-static inline void create_formspec_menu(GUIFormSpecMenu **cur_formspec,
-               Client *client, IrrlichtDevice *device, JoystickController *joystick,
-               IFormSource *fs_src, TextDest *txt_dest)
-{
-
-       if (*cur_formspec == 0) {
-               *cur_formspec = new GUIFormSpecMenu(device, joystick,
-                       guiroot, -1, &g_menumgr, client, client->getTextureSource(),
-                       fs_src, txt_dest);
-               (*cur_formspec)->doPause = false;
-
-               /*
-                       Caution: do not call (*cur_formspec)->drop() here --
-                       the reference might outlive the menu, so we will
-                       periodically check if *cur_formspec is the only
-                       remaining reference (i.e. the menu was removed)
-                       and delete it in that case.
-               */
-
-       } else {
-               (*cur_formspec)->setFormSource(fs_src);
-               (*cur_formspec)->setTextDest(txt_dest);
-       }
-
-}
-
 #ifdef __ANDROID__
 #define SIZE_TAG "size[11,5.5]"
 #else
 #define SIZE_TAG "size[11,5.5,true]" // Fixed size on desktop
 #endif
 
-/******************************************************************************/
-static void updateChat(Client &client, f32 dtime, bool show_debug,
-               const v2u32 &screensize, bool show_chat, u32 show_profiler,
-               ChatBackend &chat_backend, gui::IGUIStaticText *guitext_chat)
-{
-       // Add chat log output for errors to be shown in chat
-       static LogOutputBuffer chat_log_error_buf(g_logger, LL_ERROR);
-
-       // Get new messages from error log buffer
-       while (!chat_log_error_buf.empty()) {
-               std::wstring error_message = utf8_to_wide(chat_log_error_buf.get());
-               if (!g_settings->getBool("disable_escape_sequences")) {
-                       error_message = L"\x1b(c@red)" + error_message + L"\x1b(c@white)";
-               }
-               chat_backend.addMessage(L"", error_message);
-       }
-
-       // Get new messages from client
-       std::wstring message;
-
-       while (client.getChatMessage(message)) {
-               chat_backend.addUnparsedMessage(message);
-       }
-
-       // Remove old messages
-       chat_backend.step(dtime);
-
-       // Display all messages in a static text element
-       unsigned int recent_chat_count = chat_backend.getRecentBuffer().getLineCount();
-       EnrichedString recent_chat     = chat_backend.getRecentChat();
-       unsigned int line_height       = g_fontengine->getLineHeight();
-
-       setStaticText(guitext_chat, recent_chat);
-
-       // Update gui element size and position
-       s32 chat_y = 5;
-
-       if (show_debug)
-               chat_y += 2 * line_height;
-
-       // first pass to calculate height of text to be set
-       s32 width = std::min(g_fontengine->getTextWidth(recent_chat.c_str()) + 10,
-                            porting::getWindowSize().X - 20);
-       core::rect<s32> rect(10, chat_y, width, chat_y + porting::getWindowSize().Y);
-       guitext_chat->setRelativePosition(rect);
-
-       //now use real height of text and adjust rect according to this size
-       rect = core::rect<s32>(10, chat_y, width,
-                              chat_y + guitext_chat->getTextHeight());
-
-
-       guitext_chat->setRelativePosition(rect);
-       // Don't show chat if disabled or empty or profiler is enabled
-       guitext_chat->setVisible(
-               show_chat && recent_chat_count != 0 && !show_profiler);
-}
-
-
-/****************************************************************************
- Fast key cache for main game loop
- ****************************************************************************/
-
-/* This is faster than using getKeySetting with the tradeoff that functions
- * using it must make sure that it's initialised before using it and there is
- * no error handling (for example bounds checking). This is really intended for
- * use only in the main running loop of the client (the_game()) where the faster
- * (up to 10x faster) key lookup is an asset. Other parts of the codebase
- * (e.g. formspecs) should continue using getKeySetting().
- */
-struct KeyCache {
-
-       KeyCache()
-       {
-               handler = NULL;
-               populate();
-               populate_nonchanging();
-       }
-
-       void populate();
-
-       // Keys that are not settings dependent
-       void populate_nonchanging();
-
-       KeyPress key[KeyType::INTERNAL_ENUM_COUNT];
-       InputHandler *handler;
-};
-
-void KeyCache::populate_nonchanging()
-{
-       key[KeyType::ESC] = EscapeKey;
-}
-
-void KeyCache::populate()
-{
-       key[KeyType::FORWARD]      = getKeySetting("keymap_forward");
-       key[KeyType::BACKWARD]     = getKeySetting("keymap_backward");
-       key[KeyType::LEFT]         = getKeySetting("keymap_left");
-       key[KeyType::RIGHT]        = getKeySetting("keymap_right");
-       key[KeyType::JUMP]         = getKeySetting("keymap_jump");
-       key[KeyType::SPECIAL1]     = getKeySetting("keymap_special1");
-       key[KeyType::SNEAK]        = getKeySetting("keymap_sneak");
-
-       key[KeyType::AUTORUN]      = getKeySetting("keymap_autorun");
-
-       key[KeyType::DROP]         = getKeySetting("keymap_drop");
-       key[KeyType::INVENTORY]    = getKeySetting("keymap_inventory");
-       key[KeyType::CHAT]         = getKeySetting("keymap_chat");
-       key[KeyType::CMD]          = getKeySetting("keymap_cmd");
-       key[KeyType::CMD_LOCAL]    = getKeySetting("keymap_cmd_local");
-       key[KeyType::CONSOLE]      = getKeySetting("keymap_console");
-       key[KeyType::MINIMAP]      = getKeySetting("keymap_minimap");
-       key[KeyType::FREEMOVE]     = getKeySetting("keymap_freemove");
-       key[KeyType::FASTMOVE]     = getKeySetting("keymap_fastmove");
-       key[KeyType::NOCLIP]       = getKeySetting("keymap_noclip");
-       key[KeyType::HOTBAR_PREV]  = getKeySetting("keymap_hotbar_previous");
-       key[KeyType::HOTBAR_NEXT]  = getKeySetting("keymap_hotbar_next");
-       key[KeyType::MUTE]         = getKeySetting("keymap_mute");
-       key[KeyType::INC_VOLUME]   = getKeySetting("keymap_increase_volume");
-       key[KeyType::DEC_VOLUME]   = getKeySetting("keymap_decrease_volume");
-       key[KeyType::CINEMATIC]    = getKeySetting("keymap_cinematic");
-       key[KeyType::SCREENSHOT]   = getKeySetting("keymap_screenshot");
-       key[KeyType::TOGGLE_HUD]   = getKeySetting("keymap_toggle_hud");
-       key[KeyType::TOGGLE_CHAT]  = getKeySetting("keymap_toggle_chat");
-       key[KeyType::TOGGLE_FORCE_FOG_OFF]
-                       = getKeySetting("keymap_toggle_force_fog_off");
-       key[KeyType::TOGGLE_UPDATE_CAMERA]
-                       = getKeySetting("keymap_toggle_update_camera");
-       key[KeyType::TOGGLE_DEBUG]
-                       = getKeySetting("keymap_toggle_debug");
-       key[KeyType::TOGGLE_PROFILER]
-                       = getKeySetting("keymap_toggle_profiler");
-       key[KeyType::CAMERA_MODE]
-                       = getKeySetting("keymap_camera_mode");
-       key[KeyType::INCREASE_VIEWING_RANGE]
-                       = getKeySetting("keymap_increase_viewing_range_min");
-       key[KeyType::DECREASE_VIEWING_RANGE]
-                       = getKeySetting("keymap_decrease_viewing_range_min");
-       key[KeyType::RANGESELECT]
-                       = getKeySetting("keymap_rangeselect");
-       key[KeyType::ZOOM] = getKeySetting("keymap_zoom");
-
-       key[KeyType::QUICKTUNE_NEXT] = getKeySetting("keymap_quicktune_next");
-       key[KeyType::QUICKTUNE_PREV] = getKeySetting("keymap_quicktune_prev");
-       key[KeyType::QUICKTUNE_INC]  = getKeySetting("keymap_quicktune_inc");
-       key[KeyType::QUICKTUNE_DEC]  = getKeySetting("keymap_quicktune_dec");
-
-       key[KeyType::DEBUG_STACKS]   = getKeySetting("keymap_print_debug_stacks");
-
-       if (handler) {
-               // First clear all keys, then re-add the ones we listen for
-               handler->dontListenForKeys();
-               for (size_t i = 0; i < KeyType::INTERNAL_ENUM_COUNT; i++) {
-                       handler->listenForKey(key[i]);
-               }
-               handler->listenForKey(EscapeKey);
-               handler->listenForKey(CancelKey);
-               for (size_t i = 0; i < 10; i++) {
-                       handler->listenForKey(NumberKey[i]);
-               }
-       }
-}
-
-
 /****************************************************************************
 
  ****************************************************************************/
@@ -1115,10 +582,6 @@ struct FpsControl {
  * many functions that do require objects of thse types do not modify them
  * (so they can be passed as a const qualified parameter)
  */
-struct CameraOrientation {
-       f32 camera_yaw;    // "right/left"
-       f32 camera_pitch;  // "up/down"
-};
 
 struct GameRunData {
        u16 dig_index;
@@ -1127,6 +590,7 @@ struct GameRunData {
        bool digging;
        bool ldown_for_dig;
        bool dig_instantly;
+       bool digging_blocked;
        bool left_punch;
        bool update_wielded_item_trigger;
        bool reset_jump_timer;
@@ -1141,27 +605,19 @@ struct GameRunData {
        float jump_timer;
        float damage_flash;
        float update_draw_list_timer;
-       float statustext_time;
 
        f32 fog_range;
 
        v3f update_draw_list_last_cam_dir;
 
-       u32 profiler_current_page;
-       u32 profiler_max_page;     // Number of pages
-
-       float time_of_day;
        float time_of_day_smooth;
 };
 
-struct Jitter {
-       f32 max, min, avg, counter, max_sample, min_sample, max_fraction;
-};
-
-struct RunStats {
-       u32 drawtime;
+class Game;
 
-       Jitter dtime_jitter, busy_time_jitter;
+struct ClientEventHandler
+{
+       void (Game::*handler)(ClientEvent *, CameraOrientation *);
 };
 
 /****************************************************************************
@@ -1181,7 +637,6 @@ class Game {
        bool startup(bool *kill,
                        bool random_input,
                        InputHandler *input,
-                       IrrlichtDevice *device,
                        const std::string &map_dir,
                        const std::string &playername,
                        const std::string &password,
@@ -1235,7 +690,7 @@ class Game {
        void processKeyInput();
        void processItemSelection(u16 *new_playeritem);
 
-       void dropSelectedItem();
+       void dropSelectedItem(bool single_item = false);
        void openInventory();
        void openConsole(float scale, const wchar_t *line=NULL);
        void toggleFreeMove();
@@ -1243,19 +698,17 @@ class Game {
        void toggleFast();
        void toggleNoClip();
        void toggleCinematic();
-       void toggleAutorun();
+       void toggleAutoforward();
 
-       void toggleChat();
-       void toggleHud();
        void toggleMinimap(bool shift_pressed);
        void toggleFog();
        void toggleDebug();
        void toggleUpdateCamera();
-       void toggleProfiler();
 
        void increaseViewRange();
        void decreaseViewRange();
        void toggleFullViewRange();
+       void checkZoomEnabled();
 
        void updateCameraDirection(CameraOrientation *cam, float dtime);
        void updateCameraOrientation(CameraOrientation *cam, float dtime);
@@ -1282,59 +735,33 @@ class Game {
                        const core::line3d<f32> &shootline, bool liquids_pointable,
                        bool look_for_object, const v3s16 &camera_offset);
        void handlePointingAtNothing(const ItemStack &playerItem);
-       void handlePointingAtNode(const PointedThing &pointed, const ItemDefinition &playeritem_def,
-                       const ToolCapabilities &playeritem_toolcap, f32 dtime);
+       void handlePointingAtNode(const PointedThing &pointed,
+               const ItemDefinition &playeritem_def, const ItemStack &playeritem,
+               const ToolCapabilities &playeritem_toolcap, f32 dtime);
        void handlePointingAtObject(const PointedThing &pointed, const ItemStack &playeritem,
                        const v3f &player_position, bool show_debug);
        void handleDigging(const PointedThing &pointed, const v3s16 &nodepos,
                        const ToolCapabilities &playeritem_toolcap, f32 dtime);
        void updateFrame(ProfilerGraph *graph, RunStats *stats, f32 dtime,
                        const CameraOrientation &cam);
-       void updateGui(const RunStats &stats, f32 dtime, const CameraOrientation &cam);
        void updateProfilerGraphs(ProfilerGraph *graph);
 
        // Misc
        void limitFps(FpsControl *fps_timings, f32 *dtime);
 
-       void showOverlayMessage(const wchar_t *msg, float dtime, int percent,
+       void showOverlayMessage(const char *msg, float dtime, int percent,
                        bool draw_clouds = true);
 
        static void settingChangedCallback(const std::string &setting_name, void *data);
        void readSettings();
 
-       inline bool getLeftClicked()
-       {
-               return input->getLeftClicked() ||
-                       input->joystick.getWasKeyDown(KeyType::MOUSE_L);
-       }
-       inline bool getRightClicked()
-       {
-               return input->getRightClicked() ||
-                       input->joystick.getWasKeyDown(KeyType::MOUSE_R);
-       }
-       inline bool isLeftPressed()
-       {
-               return input->getLeftState() ||
-                       input->joystick.isKeyDown(KeyType::MOUSE_L);
-       }
-       inline bool isRightPressed()
-       {
-               return input->getRightState() ||
-                       input->joystick.isKeyDown(KeyType::MOUSE_R);
-       }
-       inline bool getLeftReleased()
-       {
-               return input->getLeftReleased() ||
-                       input->joystick.wasKeyReleased(KeyType::MOUSE_L);
-       }
-
        inline bool isKeyDown(GameKeyType k)
        {
-               return input->isKeyDown(keycache.key[k]) || input->joystick.isKeyDown(k);
+               return input->isKeyDown(k);
        }
        inline bool wasKeyDown(GameKeyType k)
        {
-               return input->wasKeyDown(keycache.key[k]) || input->joystick.wasKeyDown(k);
+               return input->wasKeyDown(k);
        }
 
 #ifdef __ANDROID__
@@ -1342,45 +769,75 @@ class Game {
 #endif
 
 private:
-       void showPauseMenu();
-
-       InputHandler *input;
+       struct Flags {
+               bool force_fog_off = false;
+               bool disable_camera_update = false;
+       };
 
-       Client *client;
-       Server *server;
+       void showPauseMenu();
 
-       IWritableTextureSource *texture_src;
-       IWritableShaderSource *shader_src;
+       // ClientEvent handlers
+       void handleClientEvent_None(ClientEvent *event, CameraOrientation *cam);
+       void handleClientEvent_PlayerDamage(ClientEvent *event, CameraOrientation *cam);
+       void handleClientEvent_PlayerForceMove(ClientEvent *event, CameraOrientation *cam);
+       void handleClientEvent_Deathscreen(ClientEvent *event, CameraOrientation *cam);
+       void handleClientEvent_ShowFormSpec(ClientEvent *event, CameraOrientation *cam);
+       void handleClientEvent_ShowLocalFormSpec(ClientEvent *event, CameraOrientation *cam);
+       void handleClientEvent_HandleParticleEvent(ClientEvent *event,
+               CameraOrientation *cam);
+       void handleClientEvent_HudAdd(ClientEvent *event, CameraOrientation *cam);
+       void handleClientEvent_HudRemove(ClientEvent *event, CameraOrientation *cam);
+       void handleClientEvent_HudChange(ClientEvent *event, CameraOrientation *cam);
+       void handleClientEvent_SetSky(ClientEvent *event, CameraOrientation *cam);
+       void handleClientEvent_OverrideDayNigthRatio(ClientEvent *event,
+               CameraOrientation *cam);
+       void handleClientEvent_CloudParams(ClientEvent *event, CameraOrientation *cam);
+
+       void updateChat(f32 dtime, const v2u32 &screensize);
+
+       bool nodePlacementPrediction(const ItemDefinition &playeritem_def,
+               const ItemStack &playeritem, const v3s16 &nodepos, const v3s16 &neighbourpos);
+       static const ClientEventHandler clientEventHandler[CLIENTEVENT_MAX];
+
+       InputHandler *input = nullptr;
+
+       Client *client = nullptr;
+       Server *server = nullptr;
+
+       IWritableTextureSource *texture_src = nullptr;
+       IWritableShaderSource *shader_src = nullptr;
 
        // When created, these will be filled with data received from the server
-       IWritableItemDefManager *itemdef_manager;
-       IWritableNodeDefManager *nodedef_manager;
+       IWritableItemDefManager *itemdef_manager = nullptr;
+       NodeDefManager *nodedef_manager = nullptr;
 
        GameOnDemandSoundFetcher soundfetcher; // useful when testing
-       ISoundManager *sound;
-       bool sound_is_dummy;
-       SoundMaker *soundmaker;
+       ISoundManager *sound = nullptr;
+       bool sound_is_dummy = false;
+       SoundMaker *soundmaker = nullptr;
 
-       ChatBackend *chat_backend;
+       ChatBackend *chat_backend = nullptr;
 
-       GUIFormSpecMenu *current_formspec;
+       GUIFormSpecMenu *current_formspec = nullptr;
        //default: "". If other than "", empty show_formspec packets will only close the formspec when the formname matches
        std::string cur_formname;
 
-       EventManager *eventmgr;
-       QuicktuneShortcutter *quicktune;
+       EventManager *eventmgr = nullptr;
+       QuicktuneShortcutter *quicktune = nullptr;
+       bool registration_confirmation_shown = false;
 
-       GUIChatConsole *gui_chat_console; // Free using ->Drop()
-       MapDrawControl *draw_control;
-       Camera *camera;
-       Clouds *clouds;                   // Free using ->Drop()
-       Sky *sky;                         // Free using ->Drop()
-       Inventory *local_inventory;
-       Hud *hud;
-       Minimap *mapper;
+       std::unique_ptr<GameUI> m_game_ui;
+       GUIChatConsole *gui_chat_console = nullptr; // Free using ->Drop()
+       MapDrawControl *draw_control = nullptr;
+       Camera *camera = nullptr;
+       Clouds *clouds = nullptr;                         // Free using ->Drop()
+       Sky *sky = nullptr;                         // Free using ->Drop()
+       Inventory *local_inventory = nullptr;
+       Hud *hud = nullptr;
+       Minimap *mapper = nullptr;
 
        GameRunData runData;
-       GameUIFlags flags;
+       Flags m_flags;
 
        /* 'cache'
           This class does take ownership/responsibily for cleaning up etc of any of
@@ -1402,20 +859,6 @@ class Game {
         */
        int crack_animation_length;
 
-       /* GUI stuff
-        */
-       gui::IGUIStaticText *guitext;          // First line of debug text
-       gui::IGUIStaticText *guitext2;         // Second line of debug text
-       gui::IGUIStaticText *guitext_info;     // At the middle of the screen
-       gui::IGUIStaticText *guitext_status;
-       gui::IGUIStaticText *guitext_chat;         // Chat text
-       gui::IGUIStaticText *guitext_profiler; // Profiler text
-
-       std::wstring infotext;
-       std::wstring m_statustext;
-
-       KeyCache keycache;
-
        IntervalLimiter profiler_interval;
 
        /*
@@ -1437,9 +880,11 @@ class Game {
        f32  m_cache_cam_smoothing;
        f32  m_cache_fog_start;
 
-       bool m_invert_mouse;
-       bool m_first_loop_after_window_activation;
-       bool m_camera_offset_changed;
+       bool m_invert_mouse = false;
+       bool m_first_loop_after_window_activation = false;
+       bool m_camera_offset_changed = false;
+
+       bool m_does_lost_focus_pause_game = false;
 
 #ifdef __ANDROID__
        bool m_cache_hold_aux1;
@@ -1448,31 +893,7 @@ class Game {
 };
 
 Game::Game() :
-       client(NULL),
-       server(NULL),
-       texture_src(NULL),
-       shader_src(NULL),
-       itemdef_manager(NULL),
-       nodedef_manager(NULL),
-       sound(NULL),
-       sound_is_dummy(false),
-       soundmaker(NULL),
-       chat_backend(NULL),
-       current_formspec(NULL),
-       cur_formname(""),
-       eventmgr(NULL),
-       quicktune(NULL),
-       gui_chat_console(NULL),
-       draw_control(NULL),
-       camera(NULL),
-       clouds(NULL),
-       sky(NULL),
-       local_inventory(NULL),
-       hud(NULL),
-       mapper(NULL),
-       m_invert_mouse(false),
-       m_first_loop_after_window_activation(false),
-       m_camera_offset_changed(false)
+       m_game_ui(new GameUI())
 {
        g_settings->registerChangedCallback("doubletap_jump",
                &settingChangedCallback, this);
@@ -1564,7 +985,6 @@ Game::~Game()
 bool Game::startup(bool *kill,
                bool random_input,
                InputHandler *input,
-               IrrlichtDevice *device,
                const std::string &map_dir,
                const std::string &playername,
                const std::string &password,
@@ -1577,7 +997,7 @@ bool Game::startup(bool *kill,
                bool simple_singleplayer_mode)
 {
        // "cache"
-       this->device              = device;
+       this->device              = RenderingEngine::get_raw_device();
        this->kill                = kill;
        this->error_message       = &error_message;
        this->reconnect_requested = reconnect;
@@ -1586,32 +1006,33 @@ bool Game::startup(bool *kill,
        this->chat_backend        = chat_backend;
        this->simple_singleplayer_mode = simple_singleplayer_mode;
 
-       keycache.handler = input;
-       keycache.populate();
+       input->keycache.populate();
 
-       driver              = device->getVideoDriver();
-       smgr                = device->getSceneManager();
+       driver = device->getVideoDriver();
+       smgr = RenderingEngine::get_scene_manager();
 
-       smgr->getParameters()->setAttribute(scene::OBJ_LOADER_IGNORE_MATERIAL_FILES, true);
+       RenderingEngine::get_scene_manager()->getParameters()->
+               setAttribute(scene::OBJ_LOADER_IGNORE_MATERIAL_FILES, true);
 
        memset(&runData, 0, sizeof(runData));
        runData.time_from_last_punch = 10.0;
-       runData.profiler_max_page = 3;
        runData.update_wielded_item_trigger = true;
 
-       memset(&flags, 0, sizeof(flags));
-       flags.show_chat = true;
-       flags.show_hud = true;
-       flags.show_debug = g_settings->getBool("show_debug");
+       m_game_ui->initFlags();
+
        m_invert_mouse = g_settings->getBool("invert_mouse");
        m_first_loop_after_window_activation = true;
 
+       g_translations->clear();
+
        if (!init(map_dir, address, port, gamespec))
                return false;
 
        if (!createClient(playername, password, address, port))
                return false;
 
+       RenderingEngine::initialize(client, hud);
+
        return true;
 }
 
@@ -1629,7 +1050,7 @@ void Game::run()
        Profiler::GraphValues dummyvalues;
        g_profiler->graphGet(dummyvalues);
 
-       draw_times.last_time = device->getTimer()->getTime();
+       draw_times.last_time = RenderingEngine::get_timer_time();
 
        set_light_table(g_settings->getFloat("display_gamma"));
 
@@ -1638,23 +1059,23 @@ void Game::run()
                        && client->checkPrivilege("fast");
 #endif
 
-       irr::core::dimension2d<u32> previous_screen_size(g_settings->getU16("screenW"),
-               g_settings->getU16("screenH"));
+       irr::core::dimension2d<u32> previous_screen_size(g_settings->getU16("screen_w"),
+               g_settings->getU16("screen_h"));
 
-       while (device->run()
+       while (RenderingEngine::run()
                        && !(*kill || g_gamecallback->shutdown_requested
                        || (server && server->getShutdownRequested()))) {
 
                const irr::core::dimension2d<u32> &current_screen_size =
-                       device->getVideoDriver()->getScreenSize();
+                       RenderingEngine::get_video_driver()->getScreenSize();
                // Verify if window size has changed and save it if it's the case
                // Ensure evaluating settings->getBool after verifying screensize
                // First condition is cheaper
                if (previous_screen_size != current_screen_size &&
                                current_screen_size != irr::core::dimension2d<u32>(0,0) &&
                                g_settings->getBool("autosave_screensize")) {
-                       g_settings->setU16("screenW", current_screen_size.Width);
-                       g_settings->setU16("screenH", current_screen_size.Height);
+                       g_settings->setU16("screen_w", current_screen_size.Width);
+                       g_settings->setU16("screen_h", current_screen_size.Height);
                        previous_screen_size = current_screen_size;
                }
 
@@ -1673,7 +1094,7 @@ void Game::run()
 
                processQueues();
 
-               infotext = L"";
+               m_game_ui->clearInfoText();
                hud->resizeHotbar();
 
                updateProfilers(stats, draw_times, dtime);
@@ -1689,25 +1110,33 @@ void Game::run()
                processClientEvents(&cam_view_target);
                updateCamera(draw_times.busy_time, dtime);
                updateSound(dtime);
-               processPlayerInteraction(dtime, flags.show_hud, flags.show_debug);
+               processPlayerInteraction(dtime, m_game_ui->m_flags.show_hud,
+                       m_game_ui->m_flags.show_debug);
                updateFrame(&graph, &stats, dtime, cam_view);
                updateProfilerGraphs(&graph);
 
                // Update if minimap has been disabled by the server
-               flags.show_minimap &= client->shouldShowMinimap();
+               m_game_ui->m_flags.show_minimap &= client->shouldShowMinimap();
+
+               if (m_does_lost_focus_pause_game && !device->isWindowFocused() && !isMenuActive()) {
+                       showPauseMenu();
+               }
        }
 }
 
 
 void Game::shutdown()
 {
+       RenderingEngine::finalize();
 #if IRRLICHT_VERSION_MAJOR == 1 && IRRLICHT_VERSION_MINOR <= 8
        if (g_settings->get("3d_mode") == "pageflip") {
                driver->setRenderTarget(irr::video::ERT_STEREO_BOTH_BUFFERS);
        }
 #endif
+       if (current_formspec)
+               current_formspec->quitMenu();
 
-       showOverlayMessage(wgettext("Shutting down..."), 0, 0, false);
+       showOverlayMessage("Shutting down...", 0, 0, false);
 
        if (clouds)
                clouds->drop();
@@ -1757,11 +1186,11 @@ bool Game::init(
                u16 port,
                const SubgameSpec &gamespec)
 {
-       texture_src = createTextureSource(device);
+       texture_src = createTextureSource();
 
-       showOverlayMessage(wgettext("Loading..."), 0, 0);
+       showOverlayMessage("Loading...", 0, 0);
 
-       shader_src = createShaderSource(device);
+       shader_src = createShaderSource();
 
        itemdef_manager = createItemDefManager();
        nodedef_manager = createNodeDefManager();
@@ -1777,7 +1206,7 @@ bool Game::init(
                return false;
 
        // Create a server if not connecting to an existing one
-       if (*address == "") {
+       if (address->empty()) {
                if (!createSingleplayerServer(map_dir, gamespec, port, address))
                        return false;
        }
@@ -1815,7 +1244,7 @@ bool Game::initSound()
 bool Game::createSingleplayerServer(const std::string &map_dir,
                const SubgameSpec &gamespec, u16 port, std::string *address)
 {
-       showOverlayMessage(wgettext("Creating server..."), 0, 5);
+       showOverlayMessage("Creating server...", 0, 5);
 
        std::string bind_str = g_settings->get("bind_address");
        Address bind_addr(0, 0, 0, 0, port);
@@ -1840,10 +1269,8 @@ bool Game::createSingleplayerServer(const std::string &map_dir,
                return false;
        }
 
-       server = new Server(map_dir, gamespec, simple_singleplayer_mode,
-                           bind_addr.isIPv6(), false);
-
-       server->start(bind_addr);
+       server = new Server(map_dir, gamespec, simple_singleplayer_mode, bind_addr, false);
+       server->start();
 
        return true;
 }
@@ -1851,7 +1278,7 @@ bool Game::createSingleplayerServer(const std::string &map_dir,
 bool Game::createClient(const std::string &playername,
                const std::string &password, std::string *address, u16 port)
 {
-       showOverlayMessage(wgettext("Creating client..."), 0, 10);
+       showOverlayMessage("Creating client...", 0, 10);
 
        draw_control = new MapDrawControl;
        if (!draw_control)
@@ -1882,15 +1309,15 @@ bool Game::createClient(const std::string &playername,
        }
 
        GameGlobalShaderConstantSetterFactory *scsf = new GameGlobalShaderConstantSetterFactory(
-                       &flags.force_fog_off, &runData.fog_range, client);
+                       &m_flags.force_fog_off, &runData.fog_range, client);
        shader_src->addShaderConstantSetterFactory(scsf);
 
        // Update cached textures, meshes and materials
-       client->afterContentReceived(device);
+       client->afterContentReceived();
 
        /* Camera
         */
-       camera = new Camera(smgr, *draw_control, client);
+       camera = new Camera(*draw_control, client);
        if (!camera || !camera->successfullyCreated(*error_message))
                return false;
        client->setCamera(camera);
@@ -1898,7 +1325,7 @@ bool Game::createClient(const std::string &playername,
        /* Clouds
         */
        if (m_cache_enable_clouds) {
-               clouds = new Clouds(smgr->getRootSceneNode(), smgr, -1, time(0));
+               clouds = new Clouds(smgr, -1, time(0));
                if (!clouds) {
                        *error_message = "Memory allocation error (clouds)";
                        errorstream << *error_message << std::endl;
@@ -1908,7 +1335,7 @@ bool Game::createClient(const std::string &playername,
 
        /* Skybox
         */
-       sky = new Sky(smgr->getRootSceneNode(), smgr, -1, texture_src);
+       sky = new Sky(-1, texture_src);
        scsf->setSky(sky);
        skybox = NULL;  // This is used/set later on in the main run loop
 
@@ -1947,7 +1374,7 @@ bool Game::createClient(const std::string &playername,
        player->hurt_tilt_timer = 0;
        player->hurt_tilt_strength = 0;
 
-       hud = new Hud(driver, smgr, guienv, client, player, local_inventory);
+       hud = new Hud(guienv, client, player, local_inventory);
 
        if (!hud) {
                *error_message = "Memory error: could not create HUD";
@@ -1956,50 +1383,22 @@ bool Game::createClient(const std::string &playername,
        }
 
        mapper = client->getMinimap();
-       mapper->setMinimapMode(MINIMAP_MODE_OFF);
+       if (mapper)
+               mapper->setMinimapMode(MINIMAP_MODE_OFF);
 
        return true;
 }
 
 bool Game::initGui()
 {
-       // First line of debug text
-       guitext = addStaticText(guienv,
-                       utf8_to_wide(PROJECT_NAME_C).c_str(),
-                       core::rect<s32>(0, 0, 0, 0),
-                       false, false, guiroot);
-
-       // Second line of debug text
-       guitext2 = addStaticText(guienv,
-                       L"",
-                       core::rect<s32>(0, 0, 0, 0),
-                       false, false, guiroot);
-
-       // At the middle of the screen
-       // Object infos are shown in this
-       guitext_info = addStaticText(guienv,
-                       L"",
-                       core::rect<s32>(0, 0, 400, g_fontengine->getTextHeight() * 5 + 5) + v2s32(100, 200),
-                       false, true, guiroot);
-
-       // Status text (displays info when showing and hiding GUI stuff, etc.)
-       guitext_status = addStaticText(guienv,
-                       L"<Status>",
-                       core::rect<s32>(0, 0, 0, 0),
-                       false, false, guiroot);
-       guitext_status->setVisible(false);
-
-       // Chat text
-       guitext_chat = addStaticText(
-                       guienv,
-                       L"",
-                       core::rect<s32>(0, 0, 0, 0),
-                       //false, false); // Disable word wrap as of now
-                       false, true, guiroot);
+       m_game_ui->init();
 
        // Remove stale "recent" chat messages from previous connections
        chat_backend->clearRecentChat();
 
+       // Make sure the size of the recent messages buffer is right
+       chat_backend->applySettings();
+
        // Chat backend and console
        gui_chat_console = new GUIChatConsole(guienv, guienv->getRootGUIElement(),
                        -1, chat_backend, client, &g_menumgr);
@@ -2009,15 +1408,6 @@ bool Game::initGui()
                return false;
        }
 
-       // Profiler text (size is updated when text is updated)
-       guitext_profiler = addStaticText(guienv,
-                       L"<Profiler>",
-                       core::rect<s32>(0, 0, 0, 0),
-                       false, false, guiroot);
-       guitext_profiler->setBackgroundColor(video::SColor(120, 0, 0, 0));
-       guitext_profiler->setVisible(false);
-       guitext_profiler->setWordWrap(true);
-
 #ifdef HAVE_TOUCHSCREENGUI
 
        if (g_touchscreengui)
@@ -2030,13 +1420,13 @@ bool Game::initGui()
 
 bool Game::connectToServer(const std::string &playername,
                const std::string &password, std::string *address, u16 port,
-               bool *connect_ok, bool *aborted)
+               bool *connect_ok, bool *connection_aborted)
 {
        *connect_ok = false;    // Let's not be overly optimistic
-       *aborted = false;
+       *connection_aborted = false;
        bool local_server_mode = false;
 
-       showOverlayMessage(wgettext("Resolving address..."), 0, 15);
+       showOverlayMessage("Resolving address...", 0, 15);
 
        Address connect_address(0, 0, 0, 0, port);
 
@@ -2068,15 +1458,16 @@ bool Game::connectToServer(const std::string &playername,
                return false;
        }
 
-       client = new Client(device,
-                       playername.c_str(), password, *address,
+       client = new Client(playername.c_str(), password, *address,
                        *draw_control, texture_src, shader_src,
                        itemdef_manager, nodedef_manager, sound, eventmgr,
-                       connect_address.isIPv6(), &flags);
+                       connect_address.isIPv6(), m_game_ui.get());
 
        if (!client)
                return false;
 
+       client->m_simple_singleplayer_mode = simple_singleplayer_mode;
+
        infostream << "Connecting to server at ";
        connect_address.print(&infostream);
        infostream << std::endl;
@@ -2095,11 +1486,11 @@ bool Game::connectToServer(const std::string &playername,
                f32 dtime;
                f32 wait_time = 0; // in seconds
 
-               fps_control.last_time = device->getTimer()->getTime();
+               fps_control.last_time = RenderingEngine::get_timer_time();
 
-               client->initMods();
+               client->loadBuiltin();
 
-               while (device->run()) {
+               while (RenderingEngine::run()) {
 
                        limitFps(&fps_control, &dtime);
 
@@ -2116,6 +1507,9 @@ bool Game::connectToServer(const std::string &playername,
                        }
 
                        // Break conditions
+                       if (*connection_aborted)
+                               break;
+
                        if (client->accessDenied()) {
                                *error_message = "Access denied. Reason: "
                                                + client->accessDeniedReason();
@@ -2124,41 +1518,33 @@ bool Game::connectToServer(const std::string &playername,
                                break;
                        }
 
-                       if (wasKeyDown(KeyType::ESC) || input->wasKeyDown(CancelKey)) {
-                               *aborted = true;
+                       if (input->cancelPressed()) {
+                               *connection_aborted = true;
                                infostream << "Connect aborted [Escape]" << std::endl;
                                break;
                        }
 
-                       wait_time += dtime;
-                       // Only time out if we aren't waiting for the server we started
-                       if ((*address != "") && (wait_time > 10)) {
-                               bool sent_old_init = g_settings->getFlag("send_pre_v25_init");
-                               // If no pre v25 init was sent, and no answer was received,
-                               // but the low level connection could be established
-                               // (meaning that we have a peer id), then we probably wanted
-                               // to connect to a legacy server. In this case, tell the user
-                               // to enable the option to be able to connect.
-                               if (!sent_old_init &&
-                                               (client->getProtoVersion() == 0) &&
-                                               client->connectedToServer()) {
-                                       *error_message = "Connection failure: init packet not "
-                                       "recognized by server.\n"
-                                       "Most likely the server uses an old protocol version (<v25).\n"
-                                       "Please ask the server owner to update to 0.4.13 or later.\n"
-                                       "To still connect to the server in the meantime,\n"
-                                       "you can enable the 'send_pre_v25_init' setting by editing minetest.conf,\n"
-                                       "or by enabling the 'Client -> Network -> Support older Servers'\n"
-                                       "entry in the advanced settings menu.";
+                       if (client->m_is_registration_confirmation_state) {
+                               if (registration_confirmation_shown) {
+                                       // Keep drawing the GUI
+                                       RenderingEngine::draw_menu_scene(guienv, dtime, true);
                                } else {
+                                       registration_confirmation_shown = true;
+                                       (new GUIConfirmRegistration(guienv, guienv->getRootGUIElement(), -1,
+                                                  &g_menumgr, client, playername, password, *address, connection_aborted))->drop();
+                               }
+                       } else {
+                               wait_time += dtime;
+                               // Only time out if we aren't waiting for the server we started
+                               if (!address->empty() && wait_time > 10) {
                                        *error_message = "Connection timed out.";
+                                       errorstream << *error_message << std::endl;
+                                       break;
                                }
-                               errorstream << *error_message << std::endl;
-                               break;
-                       }
 
-                       // Update status
-                       showOverlayMessage(wgettext("Connecting to server..."), dtime, 20);
+                               // Update status
+                               showOverlayMessage("Connecting to server...", dtime, 20);
+                       }
                }
        } catch (con::PeerNotFoundException &e) {
                // TODO: Should something be done here? At least an info/error
@@ -2176,9 +1562,9 @@ bool Game::getServerContent(bool *aborted)
        FpsControl fps_control = { 0 };
        f32 dtime; // in seconds
 
-       fps_control.last_time = device->getTimer()->getTime();
+       fps_control.last_time = RenderingEngine::get_timer_time();
 
-       while (device->run()) {
+       while (RenderingEngine::run()) {
 
                limitFps(&fps_control, &dtime);
 
@@ -2204,7 +1590,7 @@ bool Game::getServerContent(bool *aborted)
                        return false;
                }
 
-               if (wasKeyDown(KeyType::ESC) || input->wasKeyDown(CancelKey)) {
+               if (input->cancelPressed()) {
                        *aborted = true;
                        infostream << "Connect aborted [Escape]" << std::endl;
                        return false;
@@ -2216,13 +1602,13 @@ bool Game::getServerContent(bool *aborted)
                if (!client->itemdefReceived()) {
                        const wchar_t *text = wgettext("Item definitions...");
                        progress = 25;
-                       draw_load_screen(text, device, guienv, texture_src,
+                       RenderingEngine::draw_load_screen(text, guienv, texture_src,
                                dtime, progress);
                        delete[] text;
                } else if (!client->nodedefReceived()) {
                        const wchar_t *text = wgettext("Node definitions...");
                        progress = 30;
-                       draw_load_screen(text, device, guienv, texture_src,
+                       RenderingEngine::draw_load_screen(text, guienv, texture_src,
                                dtime, progress);
                        delete[] text;
                } else {
@@ -2246,8 +1632,8 @@ bool Game::getServerContent(bool *aborted)
                        }
 
                        progress = 30 + client->mediaReceiveProgress() * 35 + 0.5;
-                       draw_load_screen(utf8_to_wide(message.str()), device,
-                                       guienv, texture_src, dtime, progress);
+                       RenderingEngine::draw_load_screen(utf8_to_wide(message.str()), guienv,
+                               texture_src, dtime, progress);
                }
        }
 
@@ -2317,7 +1703,7 @@ inline bool Game::handleCallbacks()
        }
 
        if (g_gamecallback->keyconfig_changed) {
-               keycache.populate(); // update the cache with new settings
+               input->keycache.populate(); // update the cache with new settings
                g_gamecallback->keyconfig_changed = false;
        }
 
@@ -2350,10 +1736,7 @@ void Game::updateProfilers(const RunStats &stats, const FpsControl &draw_times,
                        g_profiler->print(infostream);
                }
 
-               update_profiler_gui(guitext_profiler, g_fontengine,
-                               runData.profiler_current_page, runData.profiler_max_page,
-                               driver->getScreenSize().Height);
-
+               m_game_ui->updateProfiler();
                g_profiler->clear();
        }
 
@@ -2434,7 +1817,7 @@ void Game::updateStats(RunStats *stats, const FpsControl &draw_times,
 void Game::processUserInput(f32 dtime)
 {
        // Reset input if window not active or some menu is active
-       if (!device->isWindowActive() || !noMenuActive() || guienv->hasFocus(gui_chat_console)) {
+       if (!device->isWindowActive() || isMenuActive() || guienv->hasFocus(gui_chat_console)) {
                input->clear();
 #ifdef HAVE_TOUCHSCREENGUI
                g_touchscreengui->hide();
@@ -2474,12 +1857,12 @@ void Game::processUserInput(f32 dtime)
 void Game::processKeyInput()
 {
        if (wasKeyDown(KeyType::DROP)) {
-               dropSelectedItem();
-       } else if (wasKeyDown(KeyType::AUTORUN)) {
-               toggleAutorun();
+               dropSelectedItem(isKeyDown(KeyType::SNEAK));
+       } else if (wasKeyDown(KeyType::AUTOFORWARD)) {
+               toggleAutoforward();
        } else if (wasKeyDown(KeyType::INVENTORY)) {
                openInventory();
-       } else if (wasKeyDown(KeyType::ESC) || input->wasKeyDown(CancelKey)) {
+       } else if (input->cancelPressed()) {
                if (!gui_chat_console->isOpenInhibited()) {
                        showPauseMenu();
                }
@@ -2500,53 +1883,54 @@ void Game::processKeyInput()
        } else if (wasKeyDown(KeyType::NOCLIP)) {
                toggleNoClip();
        } else if (wasKeyDown(KeyType::MUTE)) {
-               float volume = g_settings->getFloat("sound_volume");
-               if (volume < 0.001f) {
-                       g_settings->setFloat("sound_volume", 1.0f);
-                       m_statustext = narrow_to_wide(gettext("Volume changed to 100%"));
-               } else {
-                       g_settings->setFloat("sound_volume", 0.0f);
-                       m_statustext = narrow_to_wide(gettext("Volume changed to 0%"));
-               }
-               runData.statustext_time = 0;
+               bool new_mute_sound = !g_settings->getBool("mute_sound");
+               g_settings->setBool("mute_sound", new_mute_sound);
+               if (new_mute_sound)
+                       m_game_ui->showTranslatedStatusText("Sound muted");
+               else
+                       m_game_ui->showTranslatedStatusText("Sound unmuted");
        } else if (wasKeyDown(KeyType::INC_VOLUME)) {
                float new_volume = rangelim(g_settings->getFloat("sound_volume") + 0.1f, 0.0f, 1.0f);
-               char buf[100];
+               wchar_t buf[100];
                g_settings->setFloat("sound_volume", new_volume);
-               snprintf(buf, sizeof(buf), gettext("Volume changed to %d%%"), myround(new_volume * 100));
-               m_statustext = narrow_to_wide(buf);
-               runData.statustext_time = 0;
+               const wchar_t *str = wgettext("Volume changed to %d%%");
+               swprintf(buf, sizeof(buf) / sizeof(wchar_t), str, myround(new_volume * 100));
+               delete[] str;
+               m_game_ui->showStatusText(buf);
        } else if (wasKeyDown(KeyType::DEC_VOLUME)) {
                float new_volume = rangelim(g_settings->getFloat("sound_volume") - 0.1f, 0.0f, 1.0f);
-               char buf[100];
+               wchar_t buf[100];
                g_settings->setFloat("sound_volume", new_volume);
-               snprintf(buf, sizeof(buf), gettext("Volume changed to %d%%"), myround(new_volume * 100));
-               m_statustext = narrow_to_wide(buf);
-               runData.statustext_time = 0;
+               const wchar_t *str = wgettext("Volume changed to %d%%");
+               swprintf(buf, sizeof(buf) / sizeof(wchar_t), str, myround(new_volume * 100));
+               delete[] str;
+               m_game_ui->showStatusText(buf);
        } else if (wasKeyDown(KeyType::CINEMATIC)) {
                toggleCinematic();
        } else if (wasKeyDown(KeyType::SCREENSHOT)) {
-               client->makeScreenshot(device);
+               client->makeScreenshot();
        } else if (wasKeyDown(KeyType::TOGGLE_HUD)) {
-               toggleHud();
+               m_game_ui->toggleHud();
        } else if (wasKeyDown(KeyType::MINIMAP)) {
                toggleMinimap(isKeyDown(KeyType::SNEAK));
        } else if (wasKeyDown(KeyType::TOGGLE_CHAT)) {
-               toggleChat();
-       } else if (wasKeyDown(KeyType::TOGGLE_FORCE_FOG_OFF)) {
+               m_game_ui->toggleChat();
+       } else if (wasKeyDown(KeyType::TOGGLE_FOG)) {
                toggleFog();
        } else if (wasKeyDown(KeyType::TOGGLE_UPDATE_CAMERA)) {
                toggleUpdateCamera();
        } else if (wasKeyDown(KeyType::TOGGLE_DEBUG)) {
                toggleDebug();
        } else if (wasKeyDown(KeyType::TOGGLE_PROFILER)) {
-               toggleProfiler();
+               m_game_ui->toggleProfiler();
        } else if (wasKeyDown(KeyType::INCREASE_VIEWING_RANGE)) {
                increaseViewRange();
        } else if (wasKeyDown(KeyType::DECREASE_VIEWING_RANGE)) {
                decreaseViewRange();
        } else if (wasKeyDown(KeyType::RANGESELECT)) {
                toggleFullViewRange();
+       } else if (wasKeyDown(KeyType::ZOOM)) {
+               checkZoomEnabled();
        } else if (wasKeyDown(KeyType::QUICKTUNE_NEXT)) {
                quicktune->next();
        } else if (wasKeyDown(KeyType::QUICKTUNE_PREV)) {
@@ -2555,14 +1939,6 @@ void Game::processKeyInput()
                quicktune->inc();
        } else if (wasKeyDown(KeyType::QUICKTUNE_DEC)) {
                quicktune->dec();
-       } else if (wasKeyDown(KeyType::DEBUG_STACKS)) {
-               // Print debug stacks
-               dstream << "-----------------------------------------"
-                       << std::endl;
-               dstream << "Printing debug stacks:" << std::endl;
-               dstream << "-----------------------------------------"
-                       << std::endl;
-               debug_stacks_print();
        }
 
        if (!isKeyDown(KeyType::JUMP) && runData.reset_jump_timer) {
@@ -2571,8 +1947,7 @@ void Game::processKeyInput()
        }
 
        if (quicktune->hasMessage()) {
-               m_statustext = utf8_to_wide(quicktune->getMessage());
-               runData.statustext_time = 0.0f;
+               m_game_ui->showStatusText(utf8_to_wide(quicktune->getMessage()));
        }
 }
 
@@ -2606,16 +1981,10 @@ void Game::processItemSelection(u16 *new_playeritem)
                *new_playeritem = *new_playeritem > 0 ? *new_playeritem - 1 : max_item;
        // else dir == 0
 
-       /* Item selection using keyboard
+       /* Item selection using hotbar slot keys
         */
-       for (u16 i = 0; i < 10; i++) {
-               static const KeyPress *item_keys[10] = {
-                       NumberKey + 1, NumberKey + 2, NumberKey + 3, NumberKey + 4,
-                       NumberKey + 5, NumberKey + 6, NumberKey + 7, NumberKey + 8,
-                       NumberKey + 9, NumberKey + 0,
-               };
-
-               if (input->wasKeyDown(*item_keys[i])) {
+       for (u16 i = 0; i < 23; i++) {
+               if (wasKeyDown((GameKeyType) (KeyType::SLOT_1 + i))) {
                        if (i < PLAYER_INVENTORY_SIZE && i < player->hud_hotbar_itemcount) {
                                *new_playeritem = i;
                                infostream << "Selected item: " << new_playeritem << std::endl;
@@ -2626,10 +1995,10 @@ void Game::processItemSelection(u16 *new_playeritem)
 }
 
 
-void Game::dropSelectedItem()
+void Game::dropSelectedItem(bool single_item)
 {
        IDropAction *a = new IDropAction();
-       a->count = 0;
+       a->count = single_item ? 1 : 0;
        a->from_inv.setCurrentPlayer();
        a->from_list = "main";
        a->from_i = client->getPlayerItem();
@@ -2645,20 +2014,24 @@ void Game::openInventory()
         */
 
        LocalPlayer *player = client->getEnv().getLocalPlayer();
-       if (player == NULL || player->getCAO() == NULL)
+       if (!player || !player->getCAO())
                return;
 
        infostream << "the_game: " << "Launching inventory" << std::endl;
 
        PlayerInventoryFormSource *fs_src = new PlayerInventoryFormSource(client);
-       TextDest *txt_dst = new TextDestPlayerInventory(client);
-
-       create_formspec_menu(&current_formspec, client, device, &input->joystick, fs_src, txt_dst);
-       cur_formname = "";
 
        InventoryLocation inventoryloc;
        inventoryloc.setCurrentPlayer();
-       current_formspec->setFormSpec(fs_src->getForm(), inventoryloc);
+
+       if (!client->moddingEnabled()
+                       || !client->getScript()->on_inventory_open(fs_src->m_client->getInventory(inventoryloc))) {
+               TextDest *txt_dst = new TextDestPlayerInventory(client);
+               GUIFormSpecMenu::create(current_formspec, client, &input->joystick, fs_src,
+                       txt_dst);
+               cur_formname = "";
+               current_formspec->setFormSpec(fs_src->getForm(), inventoryloc);
+       }
 }
 
 
@@ -2693,18 +2066,20 @@ void Game::handleAndroidChatInput()
 
 void Game::toggleFreeMove()
 {
-       static const wchar_t *msg[] = { L"free_move disabled", L"free_move enabled" };
-
        bool free_move = !g_settings->getBool("free_move");
        g_settings->set("free_move", bool_to_cstr(free_move));
 
-       runData.statustext_time = 0;
-       m_statustext = msg[free_move];
-       if (free_move && !client->checkPrivilege("fly"))
-               m_statustext += L" (note: no 'fly' privilege)";
+       if (free_move) {
+               if (client->checkPrivilege("fly")) {
+                       m_game_ui->showTranslatedStatusText("Fly mode enabled");
+               } else {
+                       m_game_ui->showTranslatedStatusText("Fly mode enabled (note: no 'fly' privilege)");
+               }
+       } else {
+               m_game_ui->showTranslatedStatusText("Fly mode disabled");
+       }
 }
 
-
 void Game::toggleFreeMoveAlt()
 {
        if (m_cache_doubletap_jump && runData.jump_timer < 0.2f)
@@ -2716,17 +2091,18 @@ void Game::toggleFreeMoveAlt()
 
 void Game::toggleFast()
 {
-       static const wchar_t *msg[] = { L"fast_move disabled", L"fast_move enabled" };
        bool fast_move = !g_settings->getBool("fast_move");
        g_settings->set("fast_move", bool_to_cstr(fast_move));
 
-       runData.statustext_time = 0;
-       m_statustext = msg[fast_move];
-
-       bool has_fast_privs = client->checkPrivilege("fast");
-
-       if (fast_move && !has_fast_privs)
-               m_statustext += L" (note: no 'fast' privilege)";
+       if (fast_move) {
+               if (client->checkPrivilege("fast")) {
+                       m_game_ui->showTranslatedStatusText("Fast mode enabled");
+               } else {
+                       m_game_ui->showTranslatedStatusText("Fast mode enabled (note: no 'fast' privilege)");
+               }
+       } else {
+               m_game_ui->showTranslatedStatusText("Fast mode disabled");
+       }
 
 #ifdef __ANDROID__
        m_cache_hold_aux1 = fast_move && has_fast_privs;
@@ -2736,60 +2112,46 @@ void Game::toggleFast()
 
 void Game::toggleNoClip()
 {
-       static const wchar_t *msg[] = { L"noclip disabled", L"noclip enabled" };
        bool noclip = !g_settings->getBool("noclip");
        g_settings->set("noclip", bool_to_cstr(noclip));
 
-       runData.statustext_time = 0;
-       m_statustext = msg[noclip];
-
-       if (noclip && !client->checkPrivilege("noclip"))
-               m_statustext += L" (note: no 'noclip' privilege)";
+       if (noclip) {
+               if (client->checkPrivilege("noclip")) {
+                       m_game_ui->showTranslatedStatusText("Noclip mode enabled");
+               } else {
+                       m_game_ui->showTranslatedStatusText("Noclip mode enabled (note: no 'noclip' privilege)");
+               }
+       } else {
+               m_game_ui->showTranslatedStatusText("Noclip mode disabled");
+       }
 }
 
 void Game::toggleCinematic()
 {
-       static const wchar_t *msg[] = { L"cinematic disabled", L"cinematic enabled" };
        bool cinematic = !g_settings->getBool("cinematic");
        g_settings->set("cinematic", bool_to_cstr(cinematic));
 
-       runData.statustext_time = 0;
-       m_statustext = msg[cinematic];
+       if (cinematic)
+               m_game_ui->showTranslatedStatusText("Cinematic mode enabled");
+       else
+               m_game_ui->showTranslatedStatusText("Cinematic mode disabled");
 }
 
-// Add WoW-style autorun by toggling continuous forward.
-void Game::toggleAutorun()
+// Autoforward by toggling continuous forward.
+void Game::toggleAutoforward()
 {
-       static const wchar_t *msg[] = { L"autorun disabled", L"autorun enabled" };
        bool autorun_enabled = !g_settings->getBool("continuous_forward");
        g_settings->set("continuous_forward", bool_to_cstr(autorun_enabled));
 
-       runData.statustext_time = 0;
-       m_statustext = msg[autorun_enabled ? 1 : 0];
-}
-
-void Game::toggleChat()
-{
-       static const wchar_t *msg[] = { L"Chat hidden", L"Chat shown" };
-
-       flags.show_chat = !flags.show_chat;
-       runData.statustext_time = 0;
-       m_statustext = msg[flags.show_chat];
-}
-
-
-void Game::toggleHud()
-{
-       static const wchar_t *msg[] = { L"HUD hidden", L"HUD shown" };
-
-       flags.show_hud = !flags.show_hud;
-       runData.statustext_time = 0;
-       m_statustext = msg[flags.show_hud];
+       if (autorun_enabled)
+               m_game_ui->showTranslatedStatusText("Automatic forwards enabled");
+       else
+               m_game_ui->showTranslatedStatusText("Automatic forwards disabled");
 }
 
 void Game::toggleMinimap(bool shift_pressed)
 {
-       if (!flags.show_hud || !g_settings->getBool("enable_minimap"))
+       if (!mapper || !m_game_ui->m_flags.show_hud || !g_settings->getBool("enable_minimap"))
                return;
 
        if (shift_pressed) {
@@ -2803,46 +2165,51 @@ void Game::toggleMinimap(bool shift_pressed)
        if (hud_flags & HUD_FLAG_MINIMAP_VISIBLE) {
                mode = mapper->getMinimapMode();
                mode = (MinimapMode)((int)mode + 1);
+               // If radar is disabled and in, or switching to, radar mode
+               if (!(hud_flags & HUD_FLAG_MINIMAP_RADAR_VISIBLE) && mode > 3)
+                       mode = MINIMAP_MODE_OFF;
        }
 
-       flags.show_minimap = true;
+       m_game_ui->m_flags.show_minimap = true;
        switch (mode) {
                case MINIMAP_MODE_SURFACEx1:
-                       m_statustext = L"Minimap in surface mode, Zoom x1";
+                       m_game_ui->showTranslatedStatusText("Minimap in surface mode, Zoom x1");
                        break;
                case MINIMAP_MODE_SURFACEx2:
-                       m_statustext = L"Minimap in surface mode, Zoom x2";
+                       m_game_ui->showTranslatedStatusText("Minimap in surface mode, Zoom x2");
                        break;
                case MINIMAP_MODE_SURFACEx4:
-                       m_statustext = L"Minimap in surface mode, Zoom x4";
+                       m_game_ui->showTranslatedStatusText("Minimap in surface mode, Zoom x4");
                        break;
                case MINIMAP_MODE_RADARx1:
-                       m_statustext = L"Minimap in radar mode, Zoom x1";
+                       m_game_ui->showTranslatedStatusText("Minimap in radar mode, Zoom x1");
                        break;
                case MINIMAP_MODE_RADARx2:
-                       m_statustext = L"Minimap in radar mode, Zoom x2";
+                       m_game_ui->showTranslatedStatusText("Minimap in radar mode, Zoom x2");
                        break;
                case MINIMAP_MODE_RADARx4:
-                       m_statustext = L"Minimap in radar mode, Zoom x4";
+                       m_game_ui->showTranslatedStatusText("Minimap in radar mode, Zoom x4");
                        break;
                default:
                        mode = MINIMAP_MODE_OFF;
-                       flags.show_minimap = false;
-                       m_statustext = (hud_flags & HUD_FLAG_MINIMAP_VISIBLE) ?
-                               L"Minimap hidden" : L"Minimap disabled by server";
+                       m_game_ui->m_flags.show_minimap = false;
+                       if (hud_flags & HUD_FLAG_MINIMAP_VISIBLE)
+                               m_game_ui->showTranslatedStatusText("Minimap hidden");
+                       else
+                               m_game_ui->showTranslatedStatusText("Minimap currently disabled by game or mod");
        }
 
-       runData.statustext_time = 0;
        mapper->setMinimapMode(mode);
 }
 
 void Game::toggleFog()
 {
-       static const wchar_t *msg[] = { L"Fog enabled", L"Fog disabled" };
-
-       flags.force_fog_off = !flags.force_fog_off;
-       runData.statustext_time = 0;
-       m_statustext = msg[flags.force_fog_off];
+       bool fog_enabled = g_settings->getBool("enable_fog");
+       g_settings->setBool("enable_fog", !fog_enabled);
+       if (fog_enabled)
+               m_game_ui->showTranslatedStatusText("Fog disabled");
+       else
+               m_game_ui->showTranslatedStatusText("Fog enabled");
 }
 
 
@@ -2852,63 +2219,38 @@ void Game::toggleDebug()
        // 1x toggle: Debug text with chat
        // 2x toggle: Debug text with profiler graph
        // 3x toggle: Debug text and wireframe
-       if (!flags.show_debug) {
-               flags.show_debug = true;
-               flags.show_profiler_graph = false;
+       if (!m_game_ui->m_flags.show_debug) {
+               m_game_ui->m_flags.show_debug = true;
+               m_game_ui->m_flags.show_profiler_graph = false;
                draw_control->show_wireframe = false;
-               m_statustext = L"Debug info shown";
-       } else if (!flags.show_profiler_graph && !draw_control->show_wireframe) {
-               flags.show_profiler_graph = true;
-               m_statustext = L"Profiler graph shown";
+               m_game_ui->showTranslatedStatusText("Debug info shown");
+       } else if (!m_game_ui->m_flags.show_profiler_graph && !draw_control->show_wireframe) {
+               m_game_ui->m_flags.show_profiler_graph = true;
+               m_game_ui->showTranslatedStatusText("Profiler graph shown");
        } else if (!draw_control->show_wireframe && client->checkPrivilege("debug")) {
-               flags.show_profiler_graph = false;
+               m_game_ui->m_flags.show_profiler_graph = false;
                draw_control->show_wireframe = true;
-               m_statustext = L"Wireframe shown";
+               m_game_ui->showTranslatedStatusText("Wireframe shown");
        } else {
-               flags.show_debug = false;
-               flags.show_profiler_graph = false;
+               m_game_ui->m_flags.show_debug = false;
+               m_game_ui->m_flags.show_profiler_graph = false;
                draw_control->show_wireframe = false;
                if (client->checkPrivilege("debug")) {
-                       m_statustext = L"Debug info, profiler graph, and wireframe hidden";
+                       m_game_ui->showTranslatedStatusText("Debug info, profiler graph, and wireframe hidden");
                } else {
-                       m_statustext = L"Debug info and profiler graph hidden";
+                       m_game_ui->showTranslatedStatusText("Debug info and profiler graph hidden");
                }
        }
-       runData.statustext_time = 0;
 }
 
 
 void Game::toggleUpdateCamera()
 {
-       static const wchar_t *msg[] = {
-               L"Camera update enabled",
-               L"Camera update disabled"
-       };
-
-       flags.disable_camera_update = !flags.disable_camera_update;
-       runData.statustext_time = 0;
-       m_statustext = msg[flags.disable_camera_update];
-}
-
-
-void Game::toggleProfiler()
-{
-       runData.profiler_current_page =
-               (runData.profiler_current_page + 1) % (runData.profiler_max_page + 1);
-
-       // FIXME: This updates the profiler with incomplete values
-       update_profiler_gui(guitext_profiler, g_fontengine, runData.profiler_current_page,
-               runData.profiler_max_page, driver->getScreenSize().Height);
-
-       if (runData.profiler_current_page != 0) {
-               std::wstringstream sstr;
-               sstr << "Profiler shown (page " << runData.profiler_current_page
-                    << " of " << runData.profiler_max_page << ")";
-               m_statustext = sstr.str();
-       } else {
-               m_statustext = L"Profiler hidden";
-       }
-       runData.statustext_time = 0;
+       m_flags.disable_camera_update = !m_flags.disable_camera_update;
+       if (m_flags.disable_camera_update)
+               m_game_ui->showTranslatedStatusText("Camera update disabled");
+       else
+               m_game_ui->showTranslatedStatusText("Camera update enabled");
 }
 
 
@@ -2917,16 +2259,22 @@ void Game::increaseViewRange()
        s16 range = g_settings->getS16("viewing_range");
        s16 range_new = range + 10;
 
+       wchar_t buf[255];
+       const wchar_t *str;
        if (range_new > 4000) {
                range_new = 4000;
-               m_statustext = utf8_to_wide("Viewing range is at maximum: "
-                               + itos(range_new));
+               str = wgettext("Viewing range is at maximum: %d");
+               swprintf(buf, sizeof(buf) / sizeof(wchar_t), str, range_new);
+               delete[] str;
+               m_game_ui->showStatusText(buf);
+
        } else {
-               m_statustext = utf8_to_wide("Viewing range changed to "
-                               + itos(range_new));
+               str = wgettext("Viewing range changed to %d");
+               swprintf(buf, sizeof(buf) / sizeof(wchar_t), str, range_new);
+               delete[] str;
+               m_game_ui->showStatusText(buf);
        }
        g_settings->set("viewing_range", itos(range_new));
-       runData.statustext_time = 0;
 }
 
 
@@ -2935,36 +2283,46 @@ void Game::decreaseViewRange()
        s16 range = g_settings->getS16("viewing_range");
        s16 range_new = range - 10;
 
+       wchar_t buf[255];
+       const wchar_t *str;
        if (range_new < 20) {
                range_new = 20;
-               m_statustext = utf8_to_wide("Viewing range is at minimum: "
-                               + itos(range_new));
+               str = wgettext("Viewing range is at minimum: %d");
+               swprintf(buf, sizeof(buf) / sizeof(wchar_t), str, range_new);
+               delete[] str;
+               m_game_ui->showStatusText(buf);
        } else {
-               m_statustext = utf8_to_wide("Viewing range changed to "
-                               + itos(range_new));
+               str = wgettext("Viewing range changed to %d");
+               swprintf(buf, sizeof(buf) / sizeof(wchar_t), str, range_new);
+               delete[] str;
+               m_game_ui->showStatusText(buf);
        }
        g_settings->set("viewing_range", itos(range_new));
-       runData.statustext_time = 0;
 }
 
 
 void Game::toggleFullViewRange()
 {
-       static const wchar_t *msg[] = {
-               L"Disabled full viewing range",
-               L"Enabled full viewing range"
-       };
-
        draw_control->range_all = !draw_control->range_all;
-       infostream << msg[draw_control->range_all] << std::endl;
-       m_statustext = msg[draw_control->range_all];
-       runData.statustext_time = 0;
+       if (draw_control->range_all)
+               m_game_ui->showTranslatedStatusText("Enabled unlimited viewing range");
+       else
+               m_game_ui->showTranslatedStatusText("Disabled unlimited viewing range");
+}
+
+
+void Game::checkZoomEnabled()
+{
+       LocalPlayer *player = client->getEnv().getLocalPlayer();
+       if (player->getZoomFOV() < 0.001f)
+               m_game_ui->showTranslatedStatusText("Zoom currently disabled by game or mod");
 }
 
 
 void Game::updateCameraDirection(CameraOrientation *cam, float dtime)
 {
-       if ((device->isWindowActive() && noMenuActive()) || random_input) {
+       if ((device->isWindowActive() && device->isWindowFocused()
+                       && !isMenuActive()) || random_input) {
 
 #ifndef __ANDROID__
                if (!random_input) {
@@ -2989,8 +2347,7 @@ void Game::updateCameraDirection(CameraOrientation *cam, float dtime)
                        device->getCursorControl()->setVisible(true);
 #endif
 
-               if (!m_first_loop_after_window_activation)
-                       m_first_loop_after_window_activation = true;
+               m_first_loop_after_window_activation = true;
 
        }
 }
@@ -3037,16 +2394,16 @@ void Game::updatePlayerControl(const CameraOrientation &cam)
        // distinguish between the two in order to know when to use joysticks.
 
        PlayerControl control(
-               input->isKeyDown(keycache.key[KeyType::FORWARD]),
-               input->isKeyDown(keycache.key[KeyType::BACKWARD]),
-               input->isKeyDown(keycache.key[KeyType::LEFT]),
-               input->isKeyDown(keycache.key[KeyType::RIGHT]),
+               input->isKeyDown(KeyType::FORWARD),
+               input->isKeyDown(KeyType::BACKWARD),
+               input->isKeyDown(KeyType::LEFT),
+               input->isKeyDown(KeyType::RIGHT),
                isKeyDown(KeyType::JUMP),
                isKeyDown(KeyType::SPECIAL1),
                isKeyDown(KeyType::SNEAK),
                isKeyDown(KeyType::ZOOM),
-               isLeftPressed(),
-               isRightPressed(),
+               input->getLeftState(),
+               input->getRightState(),
                cam.camera_pitch,
                cam.camera_yaw,
                input->joystick.getAxisWithoutDead(JA_SIDEWARD_MOVE),
@@ -3061,8 +2418,8 @@ void Game::updatePlayerControl(const CameraOrientation &cam)
                        ( (u32)(isKeyDown(KeyType::JUMP)                          & 0x1) << 4) |
                        ( (u32)(isKeyDown(KeyType::SPECIAL1)                      & 0x1) << 5) |
                        ( (u32)(isKeyDown(KeyType::SNEAK)                         & 0x1) << 6) |
-                       ( (u32)(isLeftPressed()                                   & 0x1) << 7) |
-                       ( (u32)(isRightPressed()                                  & 0x1) << 8
+                       ( (u32)(input->getLeftState()                             & 0x1) << 7) |
+                       ( (u32)(input->getRightState()                            & 0x1) << 8
                );
 
 #ifdef ANDROID
@@ -3093,283 +2450,334 @@ inline void Game::step(f32 *dtime)
        if (can_be_and_is_paused) {     // This is for a singleplayer server
                *dtime = 0;             // No time passes
        } else {
-               if (server != NULL) {
-                       //TimeTaker timer("server->step(dtime)");
+               if (server)
                        server->step(*dtime);
-               }
 
-               //TimeTaker timer("client.step(dtime)");
                client->step(*dtime);
        }
 }
 
+const ClientEventHandler Game::clientEventHandler[CLIENTEVENT_MAX] = {
+       {&Game::handleClientEvent_None},
+       {&Game::handleClientEvent_PlayerDamage},
+       {&Game::handleClientEvent_PlayerForceMove},
+       {&Game::handleClientEvent_Deathscreen},
+       {&Game::handleClientEvent_ShowFormSpec},
+       {&Game::handleClientEvent_ShowLocalFormSpec},
+       {&Game::handleClientEvent_HandleParticleEvent},
+       {&Game::handleClientEvent_HandleParticleEvent},
+       {&Game::handleClientEvent_HandleParticleEvent},
+       {&Game::handleClientEvent_HudAdd},
+       {&Game::handleClientEvent_HudRemove},
+       {&Game::handleClientEvent_HudChange},
+       {&Game::handleClientEvent_SetSky},
+       {&Game::handleClientEvent_OverrideDayNigthRatio},
+       {&Game::handleClientEvent_CloudParams},
+};
 
-void Game::processClientEvents(CameraOrientation *cam)
+void Game::handleClientEvent_None(ClientEvent *event, CameraOrientation *cam)
 {
-       LocalPlayer *player = client->getEnv().getLocalPlayer();
-
-       while (client->hasClientEvents()) {
-               ClientEvent event = client->getClientEvent();
-
-               switch (event.type) {
-               case CE_PLAYER_DAMAGE:
-                       if (client->getHP() == 0)
-                               break;
-                       if (client->moddingEnabled()) {
-                               client->getScript()->on_damage_taken(event.player_damage.amount);
-                       }
-
-                       runData.damage_flash += 95.0 + 3.2 * event.player_damage.amount;
-                       runData.damage_flash = MYMIN(runData.damage_flash, 127.0);
-
-                       player->hurt_tilt_timer = 1.5;
-                       player->hurt_tilt_strength =
-                               rangelim(event.player_damage.amount / 4, 1.0, 4.0);
-
-                       client->event()->put(new SimpleTriggerEvent("PlayerDamage"));
-                       break;
+       FATAL_ERROR("ClientEvent type None received");
+}
 
-               case CE_PLAYER_FORCE_MOVE:
-                       cam->camera_yaw = event.player_force_move.yaw;
-                       cam->camera_pitch = event.player_force_move.pitch;
-                       break;
+void Game::handleClientEvent_PlayerDamage(ClientEvent *event, CameraOrientation *cam)
+{
+       if (client->getHP() == 0)
+               return;
 
-               case CE_DEATHSCREEN:
-                       // This should be enabled for death formspec in builtin
-                       client->getScript()->on_death();
+       if (client->moddingEnabled()) {
+               client->getScript()->on_damage_taken(event->player_damage.amount);
+       }
 
-                       /* Handle visualization */
-                       runData.damage_flash = 0;
-                       player->hurt_tilt_timer = 0;
-                       player->hurt_tilt_strength = 0;
-                       break;
+       runData.damage_flash += 95.0 + 3.2 * event->player_damage.amount;
+       runData.damage_flash = MYMIN(runData.damage_flash, 127.0);
 
-               case CE_SHOW_FORMSPEC:
-                       if (*(event.show_formspec.formspec) == "") {
-                               if (current_formspec && ( *(event.show_formspec.formname) == "" || *(event.show_formspec.formname) == cur_formname) ){
-                                       current_formspec->quitMenu();
-                               }
-                       } else {
-                               FormspecFormSource *fs_src =
-                                       new FormspecFormSource(*(event.show_formspec.formspec));
-                               TextDestPlayerInventory *txt_dst =
-                                       new TextDestPlayerInventory(client, *(event.show_formspec.formname));
-
-                               create_formspec_menu(&current_formspec, client, device, &input->joystick,
-                                       fs_src, txt_dst);
-                               cur_formname = *(event.show_formspec.formname);
-                       }
+       LocalPlayer *player = client->getEnv().getLocalPlayer();
 
-                       delete event.show_formspec.formspec;
-                       delete event.show_formspec.formname;
-                       break;
+       player->hurt_tilt_timer = 1.5;
+       player->hurt_tilt_strength =
+               rangelim(event->player_damage.amount / 4, 1.0, 4.0);
 
-               case CE_SHOW_LOCAL_FORMSPEC:
-                       {
-                               FormspecFormSource *fs_src = new FormspecFormSource(*event.show_formspec.formspec);
-                               LocalFormspecHandler *txt_dst = new LocalFormspecHandler(*event.show_formspec.formname, client);
-                               create_formspec_menu(&current_formspec, client, device, &input->joystick,
-                                       fs_src, txt_dst);
-                       }
-                       delete event.show_formspec.formspec;
-                       delete event.show_formspec.formname;
-                       break;
+       client->event()->put(new SimpleTriggerEvent("PlayerDamage"));
+}
 
-               case CE_SPAWN_PARTICLE:
-               case CE_ADD_PARTICLESPAWNER:
-               case CE_DELETE_PARTICLESPAWNER:
-                       client->getParticleManager()->handleParticleEvent(&event, client,
-                                       smgr, player);
-                       break;
+void Game::handleClientEvent_PlayerForceMove(ClientEvent *event, CameraOrientation *cam)
+{
+       cam->camera_yaw = event->player_force_move.yaw;
+       cam->camera_pitch = event->player_force_move.pitch;
+}
 
-               case CE_HUDADD:
-                       {
-                               u32 id = event.hudadd.id;
-
-                               HudElement *e = player->getHud(id);
-
-                               if (e != NULL) {
-                                       delete event.hudadd.pos;
-                                       delete event.hudadd.name;
-                                       delete event.hudadd.scale;
-                                       delete event.hudadd.text;
-                                       delete event.hudadd.align;
-                                       delete event.hudadd.offset;
-                                       delete event.hudadd.world_pos;
-                                       delete event.hudadd.size;
-                                       continue;
-                               }
+void Game::handleClientEvent_Deathscreen(ClientEvent *event, CameraOrientation *cam)
+{
+       // This should be enabled for death formspec in builtin
+       client->getScript()->on_death();
 
-                               e = new HudElement;
-                               e->type   = (HudElementType)event.hudadd.type;
-                               e->pos    = *event.hudadd.pos;
-                               e->name   = *event.hudadd.name;
-                               e->scale  = *event.hudadd.scale;
-                               e->text   = *event.hudadd.text;
-                               e->number = event.hudadd.number;
-                               e->item   = event.hudadd.item;
-                               e->dir    = event.hudadd.dir;
-                               e->align  = *event.hudadd.align;
-                               e->offset = *event.hudadd.offset;
-                               e->world_pos = *event.hudadd.world_pos;
-                               e->size = *event.hudadd.size;
-
-                               u32 new_id = player->addHud(e);
-                               //if this isn't true our huds aren't consistent
-                               sanity_check(new_id == id);
-                       }
+       LocalPlayer *player = client->getEnv().getLocalPlayer();
 
-                       delete event.hudadd.pos;
-                       delete event.hudadd.name;
-                       delete event.hudadd.scale;
-                       delete event.hudadd.text;
-                       delete event.hudadd.align;
-                       delete event.hudadd.offset;
-                       delete event.hudadd.world_pos;
-                       delete event.hudadd.size;
-                       break;
+       /* Handle visualization */
+       runData.damage_flash = 0;
+       player->hurt_tilt_timer = 0;
+       player->hurt_tilt_strength = 0;
+}
 
-               case CE_HUDRM:
-                       {
-                               HudElement *e = player->removeHud(event.hudrm.id);
+void Game::handleClientEvent_ShowFormSpec(ClientEvent *event, CameraOrientation *cam)
+{
+       if (event->show_formspec.formspec->empty()) {
+               if (current_formspec && (event->show_formspec.formname->empty()
+                       || *(event->show_formspec.formname) == cur_formname)) {
+                       current_formspec->quitMenu();
+               }
+       } else {
+               FormspecFormSource *fs_src =
+                       new FormspecFormSource(*(event->show_formspec.formspec));
+               TextDestPlayerInventory *txt_dst =
+                       new TextDestPlayerInventory(client, *(event->show_formspec.formname));
 
-                               if (e != NULL)
-                                       delete e;
-                       }
-                       break;
+               GUIFormSpecMenu::create(current_formspec, client, &input->joystick,
+                       fs_src, txt_dst);
+               cur_formname = *(event->show_formspec.formname);
+       }
 
-               case CE_HUDCHANGE:
-                       {
-                               u32 id = event.hudchange.id;
-                               HudElement *e = player->getHud(id);
-
-                               if (e == NULL) {
-                                       delete event.hudchange.v3fdata;
-                                       delete event.hudchange.v2fdata;
-                                       delete event.hudchange.sdata;
-                                       delete event.hudchange.v2s32data;
-                                       continue;
-                               }
+       delete event->show_formspec.formspec;
+       delete event->show_formspec.formname;
+}
 
-                               switch (event.hudchange.stat) {
-                               case HUD_STAT_POS:
-                                       e->pos = *event.hudchange.v2fdata;
-                                       break;
+void Game::handleClientEvent_ShowLocalFormSpec(ClientEvent *event, CameraOrientation *cam)
+{
+       FormspecFormSource *fs_src = new FormspecFormSource(*event->show_formspec.formspec);
+       LocalFormspecHandler *txt_dst =
+               new LocalFormspecHandler(*event->show_formspec.formname, client);
+       GUIFormSpecMenu::create(current_formspec, client, &input->joystick, fs_src, txt_dst);
 
-                               case HUD_STAT_NAME:
-                                       e->name = *event.hudchange.sdata;
-                                       break;
+       delete event->show_formspec.formspec;
+       delete event->show_formspec.formname;
+}
 
-                               case HUD_STAT_SCALE:
-                                       e->scale = *event.hudchange.v2fdata;
-                                       break;
+void Game::handleClientEvent_HandleParticleEvent(ClientEvent *event,
+               CameraOrientation *cam)
+{
+       LocalPlayer *player = client->getEnv().getLocalPlayer();
+       client->getParticleManager()->handleParticleEvent(event, client, player);
+}
 
-                               case HUD_STAT_TEXT:
-                                       e->text = *event.hudchange.sdata;
-                                       break;
+void Game::handleClientEvent_HudAdd(ClientEvent *event, CameraOrientation *cam)
+{
+       LocalPlayer *player = client->getEnv().getLocalPlayer();
+       auto &hud_server_to_client = client->getHUDTranslationMap();
+
+       u32 server_id = event->hudadd.server_id;
+       // ignore if we already have a HUD with that ID
+       auto i = hud_server_to_client.find(server_id);
+       if (i != hud_server_to_client.end()) {
+               delete event->hudadd.pos;
+               delete event->hudadd.name;
+               delete event->hudadd.scale;
+               delete event->hudadd.text;
+               delete event->hudadd.align;
+               delete event->hudadd.offset;
+               delete event->hudadd.world_pos;
+               delete event->hudadd.size;
+               return;
+       }
 
-                               case HUD_STAT_NUMBER:
-                                       e->number = event.hudchange.data;
-                                       break;
+       HudElement *e = new HudElement;
+       e->type   = (HudElementType)event->hudadd.type;
+       e->pos    = *event->hudadd.pos;
+       e->name   = *event->hudadd.name;
+       e->scale  = *event->hudadd.scale;
+       e->text   = *event->hudadd.text;
+       e->number = event->hudadd.number;
+       e->item   = event->hudadd.item;
+       e->dir    = event->hudadd.dir;
+       e->align  = *event->hudadd.align;
+       e->offset = *event->hudadd.offset;
+       e->world_pos = *event->hudadd.world_pos;
+       e->size = *event->hudadd.size;
+       hud_server_to_client[server_id] = player->addHud(e);
+
+       delete event->hudadd.pos;
+       delete event->hudadd.name;
+       delete event->hudadd.scale;
+       delete event->hudadd.text;
+       delete event->hudadd.align;
+       delete event->hudadd.offset;
+       delete event->hudadd.world_pos;
+       delete event->hudadd.size;
+}
 
-                               case HUD_STAT_ITEM:
-                                       e->item = event.hudchange.data;
-                                       break;
+void Game::handleClientEvent_HudRemove(ClientEvent *event, CameraOrientation *cam)
+{
+       LocalPlayer *player = client->getEnv().getLocalPlayer();
+       HudElement *e = player->removeHud(event->hudrm.id);
+       delete e;
+}
 
-                               case HUD_STAT_DIR:
-                                       e->dir = event.hudchange.data;
-                                       break;
+void Game::handleClientEvent_HudChange(ClientEvent *event, CameraOrientation *cam)
+{
+       LocalPlayer *player = client->getEnv().getLocalPlayer();
 
-                               case HUD_STAT_ALIGN:
-                                       e->align = *event.hudchange.v2fdata;
-                                       break;
+       u32 id = event->hudchange.id;
+       HudElement *e = player->getHud(id);
 
-                               case HUD_STAT_OFFSET:
-                                       e->offset = *event.hudchange.v2fdata;
-                                       break;
+       if (e == NULL) {
+               delete event->hudchange.v3fdata;
+               delete event->hudchange.v2fdata;
+               delete event->hudchange.sdata;
+               delete event->hudchange.v2s32data;
+               return;
+       }
 
-                               case HUD_STAT_WORLD_POS:
-                                       e->world_pos = *event.hudchange.v3fdata;
-                                       break;
+       switch (event->hudchange.stat) {
+               case HUD_STAT_POS:
+                       e->pos = *event->hudchange.v2fdata;
+                       break;
 
-                               case HUD_STAT_SIZE:
-                                       e->size = *event.hudchange.v2s32data;
-                                       break;
-                               }
-                       }
+               case HUD_STAT_NAME:
+                       e->name = *event->hudchange.sdata;
+                       break;
 
-                       delete event.hudchange.v3fdata;
-                       delete event.hudchange.v2fdata;
-                       delete event.hudchange.sdata;
-                       delete event.hudchange.v2s32data;
+               case HUD_STAT_SCALE:
+                       e->scale = *event->hudchange.v2fdata;
                        break;
 
-               case CE_SET_SKY:
-                       sky->setVisible(false);
-                       // Whether clouds are visible in front of a custom skybox
-                       sky->setCloudsEnabled(event.set_sky.clouds);
+               case HUD_STAT_TEXT:
+                       e->text = *event->hudchange.sdata;
+                       break;
 
-                       if (skybox) {
-                               skybox->remove();
-                               skybox = NULL;
-                       }
+               case HUD_STAT_NUMBER:
+                       e->number = event->hudchange.data;
+                       break;
 
-                       // Handle according to type
-                       if (*event.set_sky.type == "regular") {
-                               sky->setVisible(true);
-                               sky->setCloudsEnabled(true);
-                       } else if (*event.set_sky.type == "skybox" &&
-                                       event.set_sky.params->size() == 6) {
-                               sky->setFallbackBgColor(*event.set_sky.bgcolor);
-                               skybox = smgr->addSkyBoxSceneNode(
-                                                texture_src->getTextureForMesh((*event.set_sky.params)[0]),
-                                                texture_src->getTextureForMesh((*event.set_sky.params)[1]),
-                                                texture_src->getTextureForMesh((*event.set_sky.params)[2]),
-                                                texture_src->getTextureForMesh((*event.set_sky.params)[3]),
-                                                texture_src->getTextureForMesh((*event.set_sky.params)[4]),
-                                                texture_src->getTextureForMesh((*event.set_sky.params)[5]));
-                       }
-                       // Handle everything else as plain color
-                       else {
-                               if (*event.set_sky.type != "plain")
-                                       infostream << "Unknown sky type: "
-                                                  << (*event.set_sky.type) << std::endl;
+               case HUD_STAT_ITEM:
+                       e->item = event->hudchange.data;
+                       break;
 
-                               sky->setFallbackBgColor(*event.set_sky.bgcolor);
-                       }
+               case HUD_STAT_DIR:
+                       e->dir = event->hudchange.data;
+                       break;
 
-                       delete event.set_sky.bgcolor;
-                       delete event.set_sky.type;
-                       delete event.set_sky.params;
+               case HUD_STAT_ALIGN:
+                       e->align = *event->hudchange.v2fdata;
                        break;
 
-               case CE_OVERRIDE_DAY_NIGHT_RATIO:
-                       client->getEnv().setDayNightRatioOverride(
-                                       event.override_day_night_ratio.do_override,
-                                       event.override_day_night_ratio.ratio_f * 1000);
+               case HUD_STAT_OFFSET:
+                       e->offset = *event->hudchange.v2fdata;
                        break;
 
-               case CE_CLOUD_PARAMS:
-                       if (clouds) {
-                               clouds->setDensity(event.cloud_params.density);
-                               clouds->setColorBright(video::SColor(event.cloud_params.color_bright));
-                               clouds->setColorAmbient(video::SColor(event.cloud_params.color_ambient));
-                               clouds->setHeight(event.cloud_params.height);
-                               clouds->setThickness(event.cloud_params.thickness);
-                               clouds->setSpeed(v2f(
-                                               event.cloud_params.speed_x,
-                                               event.cloud_params.speed_y));
-                       }
+               case HUD_STAT_WORLD_POS:
+                       e->world_pos = *event->hudchange.v3fdata;
                        break;
 
-               default:
-                       // unknown or unhandled type
+               case HUD_STAT_SIZE:
+                       e->size = *event->hudchange.v2s32data;
                        break;
+       }
 
-               }
+       delete event->hudchange.v3fdata;
+       delete event->hudchange.v2fdata;
+       delete event->hudchange.sdata;
+       delete event->hudchange.v2s32data;
+}
+
+void Game::handleClientEvent_SetSky(ClientEvent *event, CameraOrientation *cam)
+{
+       sky->setVisible(false);
+       // Whether clouds are visible in front of a custom skybox
+       sky->setCloudsEnabled(event->set_sky.clouds);
+
+       if (skybox) {
+               skybox->remove();
+               skybox = NULL;
+       }
+
+       // Handle according to type
+       if (*event->set_sky.type == "regular") {
+               sky->setVisible(true);
+               sky->setCloudsEnabled(true);
+       } else if (*event->set_sky.type == "skybox" &&
+               event->set_sky.params->size() == 6) {
+               sky->setFallbackBgColor(*event->set_sky.bgcolor);
+               skybox = RenderingEngine::get_scene_manager()->addSkyBoxSceneNode(
+                       texture_src->getTextureForMesh((*event->set_sky.params)[0]),
+                       texture_src->getTextureForMesh((*event->set_sky.params)[1]),
+                       texture_src->getTextureForMesh((*event->set_sky.params)[2]),
+                       texture_src->getTextureForMesh((*event->set_sky.params)[3]),
+                       texture_src->getTextureForMesh((*event->set_sky.params)[4]),
+                       texture_src->getTextureForMesh((*event->set_sky.params)[5]));
+       }
+               // Handle everything else as plain color
+       else {
+               if (*event->set_sky.type != "plain")
+                       infostream << "Unknown sky type: "
+                               << (*event->set_sky.type) << std::endl;
+
+               sky->setFallbackBgColor(*event->set_sky.bgcolor);
+       }
+
+       delete event->set_sky.bgcolor;
+       delete event->set_sky.type;
+       delete event->set_sky.params;
+}
+
+void Game::handleClientEvent_OverrideDayNigthRatio(ClientEvent *event,
+               CameraOrientation *cam)
+{
+       client->getEnv().setDayNightRatioOverride(
+               event->override_day_night_ratio.do_override,
+               event->override_day_night_ratio.ratio_f * 1000.0f);
+}
+
+void Game::handleClientEvent_CloudParams(ClientEvent *event, CameraOrientation *cam)
+{
+       if (!clouds)
+               return;
+
+       clouds->setDensity(event->cloud_params.density);
+       clouds->setColorBright(video::SColor(event->cloud_params.color_bright));
+       clouds->setColorAmbient(video::SColor(event->cloud_params.color_ambient));
+       clouds->setHeight(event->cloud_params.height);
+       clouds->setThickness(event->cloud_params.thickness);
+       clouds->setSpeed(v2f(event->cloud_params.speed_x, event->cloud_params.speed_y));
+}
+
+void Game::processClientEvents(CameraOrientation *cam)
+{
+       while (client->hasClientEvents()) {
+               std::unique_ptr<ClientEvent> event(client->getClientEvent());
+               FATAL_ERROR_IF(event->type >= CLIENTEVENT_MAX, "Invalid clientevent type");
+               const ClientEventHandler& evHandler = clientEventHandler[event->type];
+               (this->*evHandler.handler)(event.get(), cam);
        }
 }
 
+void Game::updateChat(f32 dtime, const v2u32 &screensize)
+{
+       // Add chat log output for errors to be shown in chat
+       static LogOutputBuffer chat_log_error_buf(g_logger, LL_ERROR);
+
+       // Get new messages from error log buffer
+       while (!chat_log_error_buf.empty()) {
+               std::wstring error_message = utf8_to_wide(chat_log_error_buf.get());
+               if (!g_settings->getBool("disable_escape_sequences")) {
+                       error_message = L"\x1b(c@red)";
+                       error_message.append(error_message).append(L"\x1b(c@white)");
+               }
+               chat_backend->addMessage(L"", error_message);
+       }
+
+       // Get new messages from client
+       std::wstring message;
+       while (client->getChatMessage(message)) {
+               chat_backend->addUnparsedMessage(message);
+       }
+
+       // Remove old messages
+       chat_backend->step(dtime);
+
+       // Display all messages in a static text element
+       m_game_ui->setChatText(chat_backend->getRecentChat(),
+               chat_backend->getRecentBuffer().getLineCount());
+}
 
 void Game::updateCamera(u32 busy_time, f32 dtime)
 {
@@ -3405,7 +2813,7 @@ void Game::updateCamera(u32 busy_time, f32 dtime)
                GenericCAO *playercao = player->getCAO();
 
                // If playercao not loaded, don't change camera
-               if (playercao == NULL)
+               if (!playercao)
                        return;
 
                camera->toggleCameraMode();
@@ -3418,8 +2826,7 @@ void Game::updateCamera(u32 busy_time, f32 dtime)
        float tool_reload_ratio = runData.time_from_last_punch / full_punch_interval;
 
        tool_reload_ratio = MYMIN(tool_reload_ratio, 1.0);
-       camera->update(player, dtime, busy_time / 1000.0f, tool_reload_ratio,
-                     client->getEnv());
+       camera->update(player, dtime, busy_time / 1000.0f, tool_reload_ratio);
        camera->step(dtime);
 
        v3f camera_position = camera->getPosition();
@@ -3429,7 +2836,7 @@ void Game::updateCamera(u32 busy_time, f32 dtime)
 
        m_camera_offset_changed = (camera_offset != old_camera_offset);
 
-       if (!flags.disable_camera_update) {
+       if (!m_flags.disable_camera_update) {
                client->getEnv().getClientMap().updateCamera(camera_position,
                                camera_direction, camera_fov, camera_offset);
 
@@ -3452,7 +2859,20 @@ void Game::updateSound(f32 dtime)
                              v3f(0, 0, 0), // velocity
                              camera->getDirection(),
                              camera->getCameraNode()->getUpVector());
-       sound->setListenerGain(g_settings->getFloat("sound_volume"));
+
+       bool mute_sound = g_settings->getBool("mute_sound");
+       if (mute_sound) {
+               sound->setListenerGain(0.0f);
+       } else {
+               // Check if volume is in the proper range, else fix it.
+               float old_volume = g_settings->getFloat("sound_volume");
+               float new_volume = rangelim(old_volume, 0.0f, 1.0f);
+               sound->setListenerGain(new_volume);
+
+               if (old_volume != new_volume) {
+                       g_settings->setFloat("sound_volume", new_volume);
+               }
+       }
 
        LocalPlayer *player = client->getEnv().getLocalPlayer();
 
@@ -3519,6 +2939,9 @@ void Game::processPlayerInteraction(f32 dtime, bool show_hud, bool show_debug)
 
        if ((g_settings->getBool("touchtarget")) && (g_touchscreengui)) {
                shootline = g_touchscreengui->getShootline();
+               // Scale shootline to the acual distance the player can reach
+               shootline.end = shootline.start
+                       + shootline.getVector().normalize() * BS * d;
                shootline.start += intToFloat(camera_offset, BS);
                shootline.end += intToFloat(camera_offset, BS);
        }
@@ -3535,13 +2958,18 @@ void Game::processPlayerInteraction(f32 dtime, bool show_hud, bool show_debug)
                hud->updateSelectionMesh(camera_offset);
        }
 
+       if (runData.digging_blocked && !input->getLeftState()) {
+               // allow digging again if button is not pressed
+               runData.digging_blocked = false;
+       }
+
        /*
                Stop digging when
                - releasing left mouse button
                - pointing away from node
        */
        if (runData.digging) {
-               if (getLeftReleased()) {
+               if (input->getLeftReleased()) {
                        infostream << "Left button released"
                                   << " (stopped digging)" << std::endl;
                        runData.digging = false;
@@ -3565,13 +2993,13 @@ void Game::processPlayerInteraction(f32 dtime, bool show_hud, bool show_debug)
                        client->setCrack(-1, v3s16(0, 0, 0));
                        runData.dig_time = 0.0;
                }
-       } else if (runData.dig_instantly && getLeftReleased()) {
+       } else if (runData.dig_instantly && input->getLeftReleased()) {
                // Remove e.g. torches faster when clicking instead of holding LMB
                runData.nodig_delay_timer = 0;
                runData.dig_instantly = false;
        }
 
-       if (!runData.digging && runData.ldown_for_dig && !isLeftPressed()) {
+       if (!runData.digging && runData.ldown_for_dig && !input->getLeftState()) {
                runData.ldown_for_dig = false;
        }
 
@@ -3579,47 +3007,48 @@ void Game::processPlayerInteraction(f32 dtime, bool show_hud, bool show_debug)
 
        soundmaker->m_player_leftpunch_sound.name = "";
 
-       if (isRightPressed())
+       // Prepare for repeating, unless we're not supposed to
+       if (input->getRightState() && !g_settings->getBool("safe_dig_and_place"))
                runData.repeat_rightclick_timer += dtime;
        else
                runData.repeat_rightclick_timer = 0;
 
-       if (playeritem_def.usable && isLeftPressed()) {
-               if (getLeftClicked() && (!client->moddingEnabled()
+       if (playeritem_def.usable && input->getLeftState()) {
+               if (input->getLeftClicked() && (!client->moddingEnabled()
                                || !client->getScript()->on_item_use(playeritem, pointed)))
                        client->interact(4, pointed);
        } else if (pointed.type == POINTEDTHING_NODE) {
                ToolCapabilities playeritem_toolcap =
                                playeritem.getToolCapabilities(itemdef_manager);
                if (playeritem.name.empty()) {
-                       playeritem_toolcap = *hand_def.tool_capabilities;
+                       const ToolCapabilities *handToolcap = hlist
+                               ? &hlist->getItem(0).getToolCapabilities(itemdef_manager)
+                               : itemdef_manager->get("").tool_capabilities;
+
+                       if (handToolcap != nullptr)
+                               playeritem_toolcap = *handToolcap;
                }
-               handlePointingAtNode(pointed, playeritem_def, playeritem_toolcap, dtime);
+               handlePointingAtNode(pointed, playeritem_def, playeritem,
+                       playeritem_toolcap, dtime);
        } else if (pointed.type == POINTEDTHING_OBJECT) {
                handlePointingAtObject(pointed, playeritem, player_position, show_debug);
-       } else if (isLeftPressed()) {
+       } else if (input->getLeftState()) {
                // When button is held down in air, show continuous animation
                runData.left_punch = true;
-       } else if (getRightClicked()) {
+       } else if (input->getRightClicked()) {
                handlePointingAtNothing(playeritem);
        }
 
        runData.pointed_old = pointed;
 
-       if (runData.left_punch || getLeftClicked())
+       if (runData.left_punch || input->getLeftClicked())
                camera->setDigging(0); // left click animation
 
        input->resetLeftClicked();
        input->resetRightClicked();
 
-       input->joystick.clearWasKeyDown(KeyType::MOUSE_L);
-       input->joystick.clearWasKeyDown(KeyType::MOUSE_R);
-
        input->resetLeftReleased();
        input->resetRightReleased();
-
-       input->joystick.clearWasKeyReleased(KeyType::MOUSE_L);
-       input->joystick.clearWasKeyReleased(KeyType::MOUSE_R);
 }
 
 
@@ -3632,31 +3061,25 @@ PointedThing Game::updatePointedThing(
        std::vector<aabb3f> *selectionboxes = hud->getSelectionBoxes();
        selectionboxes->clear();
        hud->setSelectedFaceNormal(v3f(0.0, 0.0, 0.0));
-       static const bool show_entity_selectionbox = g_settings->getBool(
+       static thread_local const bool show_entity_selectionbox = g_settings->getBool(
                "show_entity_selectionbox");
 
-       ClientMap &map = client->getEnv().getClientMap();
-       INodeDefManager *nodedef=client->getNodeDefManager();
+       ClientEnvironment &env = client->getEnv();
+       ClientMap &map = env.getClientMap();
+       const NodeDefManager *nodedef = map.getNodeDefManager();
 
        runData.selected_object = NULL;
 
-       PointedThing result=client->getEnv().getPointedThing(
-               shootline, liquids_pointable, look_for_object);
+       RaycastState s(shootline, look_for_object, liquids_pointable);
+       PointedThing result;
+       env.continueRaycast(&s, &result);
        if (result.type == POINTEDTHING_OBJECT) {
                runData.selected_object = client->getEnv().getActiveObject(result.object_id);
-               if (show_entity_selectionbox && runData.selected_object->doShowSelectionBox()) {
-                       aabb3f *selection_box = runData.selected_object->getSelectionBox();
-
-                       // Box should exist because object was
-                       // returned in the first place
-
-                       assert(selection_box);
-
+               aabb3f selection_box;
+               if (show_entity_selectionbox && runData.selected_object->doShowSelectionBox() &&
+                               runData.selected_object->getSelectionBox(&selection_box)) {
                        v3f pos = runData.selected_object->getPosition();
-                       selectionboxes->push_back(aabb3f(
-                               selection_box->MinEdge, selection_box->MaxEdge));
-                       selectionboxes->push_back(
-                               aabb3f(selection_box->MinEdge, selection_box->MaxEdge));
+                       selectionboxes->push_back(aabb3f(selection_box));
                        hud->setSelectionPos(pos, camera_offset);
                }
        } else if (result.type == POINTEDTHING_NODE) {
@@ -3683,7 +3106,7 @@ PointedThing Game::updatePointedThing(
        }
 
        // Update selection mesh light level and vertex colors
-       if (selectionboxes->size() > 0) {
+       if (!selectionboxes->empty()) {
                v3f pf = hud->getSelectionPos();
                v3s16 p = floatToInt(pf, BS);
 
@@ -3692,8 +3115,8 @@ PointedThing Game::updatePointedThing(
                u16 node_light = getInteriorLight(n, -1, nodedef);
                u16 light_level = node_light;
 
-               for (u8 i = 0; i < 6; i++) {
-                       n = map.getNodeNoEx(p + g_6dirs[i]);
+               for (const v3s16 &dir : g_6dirs) {
+                       n = map.getNodeNoEx(p + dir);
                        node_light = getInteriorLight(n, -1, nodedef);
                        if (node_light > light_level)
                                light_level = node_light;
@@ -3709,12 +3132,9 @@ PointedThing Game::updatePointedThing(
                float sin_r = 0.08 * sin(timerf);
                float sin_g = 0.08 * sin(timerf + irr::core::PI * 0.5);
                float sin_b = 0.08 * sin(timerf + irr::core::PI);
-               c.setRed(
-                       core::clamp(core::round32(c.getRed() * (0.8 + sin_r)), 0, 255));
-               c.setGreen(
-                       core::clamp(core::round32(c.getGreen() * (0.8 + sin_g)), 0, 255));
-               c.setBlue(
-                       core::clamp(core::round32(c.getBlue() * (0.8 + sin_b)), 0, 255));
+               c.setRed(core::clamp(core::round32(c.getRed() * (0.8 + sin_r)), 0, 255));
+               c.setGreen(core::clamp(core::round32(c.getGreen() * (0.8 + sin_g)), 0, 255));
+               c.setBlue(core::clamp(core::round32(c.getBlue() * (0.8 + sin_b)), 0, 255));
 
                // Set mesh final color
                hud->setSelectionMeshColor(c);
@@ -3732,8 +3152,9 @@ void Game::handlePointingAtNothing(const ItemStack &playerItem)
 }
 
 
-void Game::handlePointingAtNode(const PointedThing &pointed, const ItemDefinition &playeritem_def,
-               const ToolCapabilities &playeritem_toolcap, f32 dtime)
+void Game::handlePointingAtNode(const PointedThing &pointed,
+       const ItemDefinition &playeritem_def, const ItemStack &playeritem,
+       const ToolCapabilities &playeritem_toolcap, f32 dtime)
 {
        v3s16 nodepos = pointed.node_undersurface;
        v3s16 neighbourpos = pointed.node_abovesurface;
@@ -3743,32 +3164,41 @@ void Game::handlePointingAtNode(const PointedThing &pointed, const ItemDefinitio
        */
 
        ClientMap &map = client->getEnv().getClientMap();
+
+       if (runData.nodig_delay_timer <= 0.0 && input->getLeftState()
+                       && !runData.digging_blocked
+                       && client->checkPrivilege("interact")) {
+               handleDigging(pointed, nodepos, playeritem_toolcap, dtime);
+       }
+
+       // This should be done after digging handling
        NodeMetadata *meta = map.getNodeMetadata(nodepos);
 
        if (meta) {
-               infotext = unescape_enriched(utf8_to_wide(meta->getString("infotext")));
+               m_game_ui->setInfoText(unescape_translate(utf8_to_wide(
+                       meta->getString("infotext"))));
        } else {
                MapNode n = map.getNodeNoEx(nodepos);
 
                if (nodedef_manager->get(n).tiledef[0].name == "unknown_node.png") {
-                       infotext = L"Unknown node: ";
-                       infotext += utf8_to_wide(nodedef_manager->get(n).name);
+                       m_game_ui->setInfoText(L"Unknown node: " +
+                               utf8_to_wide(nodedef_manager->get(n).name));
                }
        }
 
-       if (runData.nodig_delay_timer <= 0.0 && isLeftPressed()
-                       && client->checkPrivilege("interact")) {
-               handleDigging(pointed, nodepos, playeritem_toolcap, dtime);
-       }
-
-       if ((getRightClicked() ||
+       if ((input->getRightClicked() ||
                        runData.repeat_rightclick_timer >= m_repeat_right_click_time) &&
                        client->checkPrivilege("interact")) {
                runData.repeat_rightclick_timer = 0;
                infostream << "Ground right-clicked" << std::endl;
 
-               if (meta && meta->getString("formspec") != "" && !random_input
+               if (meta && !meta->getString("formspec").empty() && !random_input
                                && !isKeyDown(KeyType::SNEAK)) {
+                       // Report right click to server
+                       if (nodedef_manager->get(map.getNodeNoEx(nodepos)).rightclickable) {
+                               client->interact(3, pointed);
+                       }
+
                        infostream << "Launching custom inventory view" << std::endl;
 
                        InventoryLocation inventoryloc;
@@ -3778,9 +3208,9 @@ void Game::handlePointingAtNode(const PointedThing &pointed, const ItemDefinitio
                                &client->getEnv().getClientMap(), nodepos);
                        TextDest *txt_dst = new TextDestNodeMetadata(nodepos, client);
 
-                       create_formspec_menu(&current_formspec, client,
-                                       device, &input->joystick, fs_src, txt_dst);
-                       cur_formname = "";
+                       GUIFormSpecMenu::create(current_formspec, client, &input->joystick, fs_src,
+                               txt_dst);
+                       cur_formname.clear();
 
                        current_formspec->setFormSpec(meta->getString("formspec"), inventoryloc);
                } else {
@@ -3790,9 +3220,8 @@ void Game::handlePointingAtNode(const PointedThing &pointed, const ItemDefinitio
 
                        // If the wielded item has node placement prediction,
                        // make that happen
-                       bool placed = nodePlacementPrediction(*client,
-                                       playeritem_def,
-                                       nodepos, neighbourpos);
+                       bool placed = nodePlacementPrediction(playeritem_def, playeritem, nodepos,
+                               neighbourpos);
 
                        if (placed) {
                                // Report to server
@@ -3807,7 +3236,7 @@ void Game::handlePointingAtNode(const PointedThing &pointed, const ItemDefinitio
                                soundmaker->m_player_rightpunch_sound =
                                                SimpleSoundSpec();
 
-                               if (playeritem_def.node_placement_prediction == "" ||
+                               if (playeritem_def.node_placement_prediction.empty() ||
                                                nodedef_manager->get(map.getNodeNoEx(nodepos)).rightclickable) {
                                        client->interact(3, pointed); // Report to server
                                } else {
@@ -3819,22 +3248,171 @@ void Game::handlePointingAtNode(const PointedThing &pointed, const ItemDefinitio
        }
 }
 
+bool Game::nodePlacementPrediction(const ItemDefinition &playeritem_def,
+       const ItemStack &playeritem, const v3s16 &nodepos, const v3s16 &neighbourpos)
+{
+       std::string prediction = playeritem_def.node_placement_prediction;
+       const NodeDefManager *nodedef = client->ndef();
+       ClientMap &map = client->getEnv().getClientMap();
+       MapNode node;
+       bool is_valid_position;
+
+       node = map.getNodeNoEx(nodepos, &is_valid_position);
+       if (!is_valid_position)
+               return false;
+
+       if (!prediction.empty() && !nodedef->get(node).rightclickable) {
+               verbosestream << "Node placement prediction for "
+                       << playeritem_def.name << " is "
+                       << prediction << std::endl;
+               v3s16 p = neighbourpos;
+
+               // Place inside node itself if buildable_to
+               MapNode n_under = map.getNodeNoEx(nodepos, &is_valid_position);
+               if (is_valid_position)
+               {
+                       if (nodedef->get(n_under).buildable_to)
+                               p = nodepos;
+                       else {
+                               node = map.getNodeNoEx(p, &is_valid_position);
+                               if (is_valid_position &&!nodedef->get(node).buildable_to)
+                                       return false;
+                       }
+               }
+
+               // Find id of predicted node
+               content_t id;
+               bool found = nodedef->getId(prediction, id);
+
+               if (!found) {
+                       errorstream << "Node placement prediction failed for "
+                               << playeritem_def.name << " (places "
+                               << prediction
+                               << ") - Name not known" << std::endl;
+                       return false;
+               }
+
+               const ContentFeatures &predicted_f = nodedef->get(id);
+
+               // Predict param2 for facedir and wallmounted nodes
+               u8 param2 = 0;
+
+               if (predicted_f.param_type_2 == CPT2_WALLMOUNTED ||
+                       predicted_f.param_type_2 == CPT2_COLORED_WALLMOUNTED) {
+                       v3s16 dir = nodepos - neighbourpos;
+
+                       if (abs(dir.Y) > MYMAX(abs(dir.X), abs(dir.Z))) {
+                               param2 = dir.Y < 0 ? 1 : 0;
+                       } else if (abs(dir.X) > abs(dir.Z)) {
+                               param2 = dir.X < 0 ? 3 : 2;
+                       } else {
+                               param2 = dir.Z < 0 ? 5 : 4;
+                       }
+               }
+
+               if (predicted_f.param_type_2 == CPT2_FACEDIR ||
+                       predicted_f.param_type_2 == CPT2_COLORED_FACEDIR) {
+                       v3s16 dir = nodepos - floatToInt(client->getEnv().getLocalPlayer()->getPosition(), BS);
+
+                       if (abs(dir.X) > abs(dir.Z)) {
+                               param2 = dir.X < 0 ? 3 : 1;
+                       } else {
+                               param2 = dir.Z < 0 ? 2 : 0;
+                       }
+               }
+
+               assert(param2 <= 5);
+
+               //Check attachment if node is in group attached_node
+               if (((ItemGroupList) predicted_f.groups)["attached_node"] != 0) {
+                       static v3s16 wallmounted_dirs[8] = {
+                               v3s16(0, 1, 0),
+                               v3s16(0, -1, 0),
+                               v3s16(1, 0, 0),
+                               v3s16(-1, 0, 0),
+                               v3s16(0, 0, 1),
+                               v3s16(0, 0, -1),
+                       };
+                       v3s16 pp;
+
+                       if (predicted_f.param_type_2 == CPT2_WALLMOUNTED ||
+                               predicted_f.param_type_2 == CPT2_COLORED_WALLMOUNTED)
+                               pp = p + wallmounted_dirs[param2];
+                       else
+                               pp = p + v3s16(0, -1, 0);
+
+                       if (!nodedef->get(map.getNodeNoEx(pp)).walkable)
+                               return false;
+               }
+
+               // Apply color
+               if ((predicted_f.param_type_2 == CPT2_COLOR
+                       || predicted_f.param_type_2 == CPT2_COLORED_FACEDIR
+                       || predicted_f.param_type_2 == CPT2_COLORED_WALLMOUNTED)) {
+                       const std::string &indexstr = playeritem.metadata.getString(
+                               "palette_index", 0);
+                       if (!indexstr.empty()) {
+                               s32 index = mystoi(indexstr);
+                               if (predicted_f.param_type_2 == CPT2_COLOR) {
+                                       param2 = index;
+                               } else if (predicted_f.param_type_2
+                                       == CPT2_COLORED_WALLMOUNTED) {
+                                       // param2 = pure palette index + other
+                                       param2 = (index & 0xf8) | (param2 & 0x07);
+                               } else if (predicted_f.param_type_2
+                                       == CPT2_COLORED_FACEDIR) {
+                                       // param2 = pure palette index + other
+                                       param2 = (index & 0xe0) | (param2 & 0x1f);
+                               }
+                       }
+               }
+
+               // Add node to client map
+               MapNode n(id, 0, param2);
+
+               try {
+                       LocalPlayer *player = client->getEnv().getLocalPlayer();
+
+                       // Dont place node when player would be inside new node
+                       // NOTE: This is to be eventually implemented by a mod as client-side Lua
+                       if (!nodedef->get(n).walkable ||
+                               g_settings->getBool("enable_build_where_you_stand") ||
+                               (client->checkPrivilege("noclip") && g_settings->getBool("noclip")) ||
+                               (nodedef->get(n).walkable &&
+                                       neighbourpos != player->getStandingNodePos() + v3s16(0, 1, 0) &&
+                                       neighbourpos != player->getStandingNodePos() + v3s16(0, 2, 0))) {
+
+                               // This triggers the required mesh update too
+                               client->addNode(p, n);
+                               return true;
+                       }
+               } catch (InvalidPositionException &e) {
+                       errorstream << "Node placement prediction failed for "
+                               << playeritem_def.name << " (places "
+                               << prediction
+                               << ") - Position not loaded" << std::endl;
+               }
+       }
+
+       return false;
+}
 
 void Game::handlePointingAtObject(const PointedThing &pointed, const ItemStack &playeritem,
                const v3f &player_position, bool show_debug)
 {
-       infotext = unescape_enriched(
+       std::wstring infotext = unescape_translate(
                utf8_to_wide(runData.selected_object->infoText()));
 
        if (show_debug) {
-               if (infotext != L"") {
+               if (!infotext.empty()) {
                        infotext += L"\n";
                }
-               infotext += unescape_enriched(utf8_to_wide(
-                       runData.selected_object->debugInfoText()));
+               infotext += utf8_to_wide(runData.selected_object->debugInfoText());
        }
 
-       if (isLeftPressed()) {
+       m_game_ui->setInfoText(infotext);
+
+       if (input->getLeftState()) {
                bool do_punch = false;
                bool do_punch_damage = false;
 
@@ -3844,7 +3422,7 @@ void Game::handlePointingAtObject(const PointedThing &pointed, const ItemStack &
                        runData.object_hit_delay_timer = object_hit_delay;
                }
 
-               if (getLeftClicked())
+               if (input->getLeftClicked())
                        do_punch = true;
 
                if (do_punch) {
@@ -3871,7 +3449,7 @@ void Game::handlePointingAtObject(const PointedThing &pointed, const ItemStack &
                        if (!disable_send)
                                client->interact(0, pointed);
                }
-       } else if (getRightClicked()) {
+       } else if (input->getRightClicked()) {
                infostream << "Right-clicked object" << std::endl;
                client->interact(3, pointed);  // place
        }
@@ -3894,24 +3472,14 @@ void Game::handleDigging(const PointedThing &pointed, const v3s16 &nodepos,
        // If can't dig, try hand
        if (!params.diggable) {
                InventoryList *hlist = local_inventory->getList("hand");
-               const ItemDefinition &hand =
-                       hlist ? hlist->getItem(0).getDefinition(itemdef_manager) : itemdef_manager->get("");
-               const ToolCapabilities *tp = hand.tool_capabilities;
+               const ToolCapabilities *tp = hlist
+                       ? &hlist->getItem(0).getToolCapabilities(itemdef_manager)
+                       : itemdef_manager->get("").tool_capabilities;
 
                if (tp)
                        params = getDigParams(nodedef_manager->get(n).groups, tp);
        }
 
-       if (!runData.digging) {
-               infostream << "Started digging" << std::endl;
-               runData.dig_instantly = params.time == 0;
-               if (client->moddingEnabled() && client->getScript()->on_punchnode(nodepos, n))
-                       return;
-               client->interact(0, pointed);
-               runData.digging = true;
-               runData.ldown_for_dig = true;
-       }
-
        if (!params.diggable) {
                // I guess nobody will wait for this long
                runData.dig_time_complete = 10000000.0;
@@ -3919,13 +3487,22 @@ void Game::handleDigging(const PointedThing &pointed, const v3s16 &nodepos,
                runData.dig_time_complete = params.time;
 
                if (m_cache_enable_particles) {
-                       const ContentFeatures &features =
-                                       client->getNodeDefManager()->get(n);
-                       client->getParticleManager()->addPunchingParticles(client, smgr,
+                       const ContentFeatures &features = client->getNodeDefManager()->get(n);
+                       client->getParticleManager()->addNodeParticle(client,
                                        player, nodepos, n, features);
                }
        }
 
+       if (!runData.digging) {
+               infostream << "Started digging" << std::endl;
+               runData.dig_instantly = runData.dig_time_complete == 0;
+               if (client->moddingEnabled() && client->getScript()->on_punchnode(nodepos, n))
+                       return;
+               client->interact(0, pointed);
+               runData.digging = true;
+               runData.ldown_for_dig = true;
+       }
+
        if (!runData.dig_instantly) {
                runData.dig_index = (float)crack_animation_length
                                * runData.dig_time
@@ -3939,7 +3516,7 @@ void Game::handleDigging(const PointedThing &pointed, const v3s16 &nodepos,
 
        if (sound_dig.exists() && params.diggable) {
                if (sound_dig.name == "__group") {
-                       if (params.main_group != "") {
+                       if (!params.main_group.empty()) {
                                soundmaker->m_player_leftpunch_sound.gain = 0.5;
                                soundmaker->m_player_leftpunch_sound.name =
                                                std::string("default_dig_") +
@@ -3962,6 +3539,9 @@ void Game::handleDigging(const PointedThing &pointed, const v3s16 &nodepos,
 
                runData.dig_time = 0;
                runData.digging = false;
+               // we successfully dug, now block it from repeating if we want to be safe
+               if (g_settings->getBool("safe_dig_and_place"))
+                       runData.digging_blocked = true;
 
                runData.nodig_delay_timer =
                                runData.dig_time_complete / (float)crack_animation_length;
@@ -3976,12 +3556,21 @@ void Game::handleDigging(const PointedThing &pointed, const v3s16 &nodepos,
                bool is_valid_position;
                MapNode wasnode = map.getNodeNoEx(nodepos, &is_valid_position);
                if (is_valid_position) {
-                       if (client->moddingEnabled()) {
-                               if (client->getScript()->on_dignode(nodepos, wasnode)) {
-                                       return;
-                               }
+                       if (client->moddingEnabled() &&
+                                       client->getScript()->on_dignode(nodepos, wasnode)) {
+                               return;
+                       }
+
+                       const ContentFeatures &f = client->ndef()->get(wasnode);
+                       if (f.node_dig_prediction == "air") {
+                               client->removeNode(nodepos);
+                       } else if (!f.node_dig_prediction.empty()) {
+                               content_t id;
+                               bool found = client->ndef()->getId(f.node_dig_prediction, id);
+                               if (found)
+                                       client->addNode(nodepos, id, true);
                        }
-                       client->removeNode(nodepos);
+                       // implicit else: no prediction
                }
 
                client->interact(2, pointed);
@@ -3989,7 +3578,7 @@ void Game::handleDigging(const PointedThing &pointed, const v3s16 &nodepos,
                if (m_cache_enable_particles) {
                        const ContentFeatures &features =
                                client->getNodeDefManager()->get(wasnode);
-                       client->getParticleManager()->addDiggingParticles(client, smgr,
+                       client->getParticleManager()->addDiggingParticles(client,
                                player, nodepos, wasnode, features);
                }
 
@@ -4063,7 +3652,6 @@ void Game::updateFrame(ProfilerGraph *graph, RunStats *stats, f32 dtime,
                time_of_day_smooth = time_of_day_smooth * (1.0 - todsm)
                                + time_of_day * todsm;
 
-       runData.time_of_day = time_of_day;
        runData.time_of_day_smooth = time_of_day_smooth;
 
        sky->update(time_of_day_smooth, time_brightness, direct_brightness,
@@ -4074,12 +3662,28 @@ void Game::updateFrame(ProfilerGraph *graph, RunStats *stats, f32 dtime,
                Update clouds
        */
        if (clouds) {
-               v3f player_position = player->getPosition();
                if (sky->getCloudsVisible()) {
                        clouds->setVisible(true);
                        clouds->step(dtime);
-                       clouds->update(v2f(player_position.X, player_position.Z),
-                                      sky->getCloudColor());
+                       // camera->getPosition is not enough for 3rd person views
+                       v3f camera_node_position = camera->getCameraNode()->getPosition();
+                       v3s16 camera_offset      = camera->getOffset();
+                       camera_node_position.X   = camera_node_position.X + camera_offset.X * BS;
+                       camera_node_position.Y   = camera_node_position.Y + camera_offset.Y * BS;
+                       camera_node_position.Z   = camera_node_position.Z + camera_offset.Z * BS;
+                       clouds->update(camera_node_position,
+                                       sky->getCloudColor());
+                       if (clouds->isCameraInsideCloud() && m_cache_enable_fog) {
+                               // if inside clouds, and fog enabled, use that as sky
+                               // color(s)
+                               video::SColor clouds_dark = clouds->getColor()
+                                               .getInterpolated(video::SColor(255, 0, 0, 0), 0.9);
+                               sky->overrideColors(clouds_dark, clouds->getColor());
+                               sky->setBodiesVisible(false);
+                               runData.fog_range = std::fmin(runData.fog_range * 0.5f, 32.0f * BS);
+                               // do not draw clouds after all
+                               clouds->setVisible(false);
+                       }
                } else {
                        clouds->setVisible(false);
                }
@@ -4094,7 +3698,7 @@ void Game::updateFrame(ProfilerGraph *graph, RunStats *stats, f32 dtime,
                Fog
        */
 
-       if (m_cache_enable_fog && !flags.force_fog_off) {
+       if (m_cache_enable_fog) {
                driver->setFog(
                                sky->getBgColor(),
                                video::EFT_FOG_LINEAR,
@@ -4122,9 +3726,7 @@ void Game::updateFrame(ProfilerGraph *graph, RunStats *stats, f32 dtime,
 
        v2u32 screensize = driver->getScreenSize();
 
-       updateChat(*client, dtime, flags.show_debug, screensize,
-                       flags.show_chat, runData.profiler_current_page,
-                       *chat_backend, guitext_chat);
+       updateChat(dtime, screensize);
 
        /*
                Inventory
@@ -4168,11 +3770,11 @@ void Game::updateFrame(ProfilerGraph *graph, RunStats *stats, f32 dtime,
                        || runData.update_draw_list_last_cam_dir.getDistanceFrom(camera_direction) > 0.2
                        || m_camera_offset_changed) {
                runData.update_draw_list_timer = 0;
-               client->getEnv().getClientMap().updateDrawList(driver);
+               client->getEnv().getClientMap().updateDrawList();
                runData.update_draw_list_last_cam_dir = camera_direction;
        }
 
-       updateGui(*stats, dtime, cam);
+       m_game_ui->update(*stats, client, draw_control, cam, runData.pointed_old, dtime);
 
        /*
           make sure menu is on top
@@ -4183,7 +3785,7 @@ void Game::updateFrame(ProfilerGraph *graph, RunStats *stats, f32 dtime,
                if (current_formspec->getReferenceCount() == 1) {
                        current_formspec->drop();
                        current_formspec = NULL;
-               } else if (!noMenuActive()) {
+               } else if (isMenuActive()) {
                        guiroot->bringToFront(current_formspec);
                }
        }
@@ -4191,20 +3793,30 @@ void Game::updateFrame(ProfilerGraph *graph, RunStats *stats, f32 dtime,
        /*
                Drawing begins
        */
-
        const video::SColor &skycolor = sky->getSkyColor();
 
        TimeTaker tt_draw("mainloop: draw");
        driver->beginScene(true, true, skycolor);
 
-       draw_scene(driver, smgr, *camera, *client, player, *hud, *mapper,
-                       guienv, screensize, skycolor, flags.show_hud,
-                       flags.show_minimap);
+       bool draw_wield_tool = (m_game_ui->m_flags.show_hud &&
+                       (player->hud_flags & HUD_FLAG_WIELDITEM_VISIBLE) &&
+                       (camera->getCameraMode() == CAMERA_MODE_FIRST));
+       bool draw_crosshair = (
+                       (player->hud_flags & HUD_FLAG_CROSSHAIR_VISIBLE) &&
+                       (camera->getCameraMode() != CAMERA_MODE_THIRD_FRONT));
+#ifdef HAVE_TOUCHSCREENGUI
+       try {
+               draw_crosshair = !g_settings->getBool("touchtarget");
+       } catch (SettingNotFoundException) {
+       }
+#endif
+       RenderingEngine::draw_scene(skycolor, m_game_ui->m_flags.show_hud,
+                       m_game_ui->m_flags.show_minimap, draw_wield_tool, draw_crosshair);
 
        /*
                Profiler graph
        */
-       if (flags.show_profiler_graph)
+       if (m_game_ui->m_flags.show_profiler_graph)
                graph->draw(10, screensize.Y - 10, driver, g_fontengine->getFont());
 
        /*
@@ -4232,7 +3844,7 @@ void Game::updateFrame(ProfilerGraph *graph, RunStats *stats, f32 dtime,
        /*
                Update minimap pos and rotation
        */
-       if (flags.show_minimap && flags.show_hud) {
+       if (mapper && m_game_ui->m_flags.show_minimap && m_game_ui->m_flags.show_hud) {
                mapper->setPos(floatToInt(player->getPosition(), BS));
                mapper->setAngle(player->getYaw());
        }
@@ -4246,138 +3858,6 @@ void Game::updateFrame(ProfilerGraph *graph, RunStats *stats, f32 dtime,
        g_profiler->graphAdd("mainloop_draw", stats->drawtime / 1000.0f);
 }
 
-
-inline static const char *yawToDirectionString(int yaw)
-{
-       static const char *direction[4] = {"North [+Z]", "West [-X]", "South [-Z]", "East [+X]"};
-
-       yaw = wrapDegrees_0_360(yaw);
-       yaw = (yaw + 45) % 360 / 90;
-
-       return direction[yaw];
-}
-
-
-void Game::updateGui(const RunStats &stats, f32 dtime, const CameraOrientation &cam)
-{
-       v2u32 screensize = driver->getScreenSize();
-       LocalPlayer *player = client->getEnv().getLocalPlayer();
-       v3f player_position = player->getPosition();
-
-       if (flags.show_debug) {
-               static float drawtime_avg = 0;
-               drawtime_avg = drawtime_avg * 0.95 + stats.drawtime * 0.05;
-
-               u16 fps = 1.0 / stats.dtime_jitter.avg;
-
-               std::ostringstream os(std::ios_base::binary);
-               os << std::fixed
-                  << PROJECT_NAME_C " " << g_version_hash
-                  << " FPS = " << fps
-                  << " (R: range_all=" << draw_control->range_all << ")"
-                  << std::setprecision(0)
-                  << " drawtime = " << drawtime_avg
-                  << std::setprecision(1)
-                  << ", dtime_jitter = "
-                  << (stats.dtime_jitter.max_fraction * 100.0) << " %"
-                  << std::setprecision(1)
-                  << ", v_range = " << draw_control->wanted_range
-                  << std::setprecision(3)
-                  << ", RTT = " << client->getRTT();
-               setStaticText(guitext, utf8_to_wide(os.str()).c_str());
-               guitext->setVisible(true);
-       } else {
-               guitext->setVisible(false);
-       }
-
-       if (guitext->isVisible()) {
-               core::rect<s32> rect(
-                               5,              5,
-                               screensize.X,   5 + g_fontengine->getTextHeight()
-               );
-               guitext->setRelativePosition(rect);
-       }
-
-       if (flags.show_debug) {
-               std::ostringstream os(std::ios_base::binary);
-               os << std::setprecision(1) << std::fixed
-                  << "(" << (player_position.X / BS)
-                  << ", " << (player_position.Y / BS)
-                  << ", " << (player_position.Z / BS)
-                  << ") (yaw=" << (wrapDegrees_0_360(cam.camera_yaw))
-                  << " " << yawToDirectionString(cam.camera_yaw)
-                  << ") (seed = " << ((u64)client->getMapSeed())
-                  << ")";
-
-               if (runData.pointed_old.type == POINTEDTHING_NODE) {
-                       ClientMap &map = client->getEnv().getClientMap();
-                       const INodeDefManager *nodedef = client->getNodeDefManager();
-                       MapNode n = map.getNodeNoEx(runData.pointed_old.node_undersurface);
-                       if (n.getContent() != CONTENT_IGNORE && nodedef->get(n).name != "unknown") {
-                               const ContentFeatures &features = nodedef->get(n);
-                               os << " (pointing_at = " << nodedef->get(n).name
-                                  << " - " << features.tiledef[0].name.c_str()
-                                  << ")";
-                       }
-               }
-
-               setStaticText(guitext2, utf8_to_wide(os.str()).c_str());
-               guitext2->setVisible(true);
-
-               core::rect<s32> rect(
-                               5,             5 + g_fontengine->getTextHeight(),
-                               screensize.X,  5 + g_fontengine->getTextHeight() * 2
-               );
-               guitext2->setRelativePosition(rect);
-       } else {
-               guitext2->setVisible(false);
-       }
-
-       setStaticText(guitext_info, infotext.c_str());
-       guitext_info->setVisible(flags.show_hud && g_menumgr.menuCount() == 0);
-
-       float statustext_time_max = 1.5;
-
-       if (!m_statustext.empty()) {
-               runData.statustext_time += dtime;
-
-               if (runData.statustext_time >= statustext_time_max) {
-                       m_statustext = L"";
-                       runData.statustext_time = 0;
-               }
-       }
-
-       setStaticText(guitext_status, m_statustext.c_str());
-       guitext_status->setVisible(!m_statustext.empty());
-
-       if (!m_statustext.empty()) {
-               s32 status_width  = guitext_status->getTextWidth();
-               s32 status_height = guitext_status->getTextHeight();
-               s32 status_y = screensize.Y - 150;
-               s32 status_x = (screensize.X - status_width) / 2;
-               core::rect<s32> rect(
-                               status_x , status_y - status_height,
-                               status_x + status_width, status_y
-               );
-               guitext_status->setRelativePosition(rect);
-
-               // Fade out
-               video::SColor initial_color(255, 0, 0, 0);
-
-               if (guienv->getSkin())
-                       initial_color = guienv->getSkin()->getColor(gui::EGDC_BUTTON_TEXT);
-
-               video::SColor final_color = initial_color;
-               final_color.setAlpha(0);
-               video::SColor fade_color = initial_color.getInterpolated_quadratic(
-                               initial_color, final_color,
-                               pow(runData.statustext_time / statustext_time_max, 2.0f));
-               guitext_status->setOverrideColor(fade_color);
-               guitext_status->enableOverrideColor(true);
-       }
-}
-
-
 /* Log times and stuff for visualization */
 inline void Game::updateProfilerGraphs(ProfilerGraph *graph)
 {
@@ -4434,15 +3914,12 @@ inline void Game::limitFps(FpsControl *fps_timings, f32 *dtime)
        fps_timings->last_time = time;
 }
 
-// Note: This will free (using delete[])! \p msg. If you want to use it later,
-// pass a copy of it to this function
-// Note: \p msg must be allocated using new (not malloc())
-void Game::showOverlayMessage(const wchar_t *msg, float dtime,
-               int percent, bool draw_clouds)
+void Game::showOverlayMessage(const char *msg, float dtime, int percent, bool draw_clouds)
 {
-       draw_load_screen(msg, device, guienv, texture_src, dtime, percent,
+       const wchar_t *wmsg = wgettext(msg);
+       RenderingEngine::draw_load_screen(wmsg, guienv, texture_src, dtime, percent,
                draw_clouds);
-       delete[] msg;
+       delete[] wmsg;
 }
 
 void Game::settingChangedCallback(const std::string &setting_name, void *data)
@@ -4476,6 +3953,7 @@ void Game::readSettings()
        m_cache_cam_smoothing = rangelim(m_cache_cam_smoothing, 0.01f, 1.0f);
        m_cache_mouse_sensitivity = rangelim(m_cache_mouse_sensitivity, 0.001, 100.0);
 
+       m_does_lost_focus_pause_game = g_settings->getBool("pause_on_lost_focus");
 }
 
 /****************************************************************************/
@@ -4489,7 +3967,7 @@ void Game::extendedResourceCleanup()
        // Extended resource accounting
        infostream << "Irrlicht resources after cleanup:" << std::endl;
        infostream << "\tRemaining meshes   : "
-                  << device->getSceneManager()->getMeshCache()->getMeshCount() << std::endl;
+                  << RenderingEngine::get_mesh_cache()->getMeshCount() << std::endl;
        infostream << "\tRemaining textures : "
                   << driver->getTextureCount() << std::endl;
 
@@ -4524,7 +4002,10 @@ void Game::showPauseMenu()
                );
 #else
        static const std::string control_text_template = strgettext("Controls:\n"
-               "- %s%s%s%s: move\n"
+               "- %s: move forwards\n"
+               "- %s: move backwards\n"
+               "- %s: move left\n"
+               "- %s: move right\n"
                "- %s: jump/climb\n"
                "- %s: sneak/go down\n"
                "- %s: drop item\n"
@@ -4536,24 +4017,24 @@ void Game::showPauseMenu()
                "- %s: chat\n"
        );
 
-        char control_text_buf[500];
+        char control_text_buf[600];
 
         snprintf(control_text_buf, ARRLEN(control_text_buf), control_text_template.c_str(),
-                        GET_KEY_NAME(keymap_forward),
-                        GET_KEY_NAME(keymap_left),
-                        GET_KEY_NAME(keymap_backward),
-                        GET_KEY_NAME(keymap_right),
-                        GET_KEY_NAME(keymap_jump),
-                        GET_KEY_NAME(keymap_sneak),
-                        GET_KEY_NAME(keymap_drop),
-                        GET_KEY_NAME(keymap_inventory),
-                        GET_KEY_NAME(keymap_chat)
-                        );
-
-#endif
+                       GET_KEY_NAME(keymap_forward),
+                       GET_KEY_NAME(keymap_backward),
+                       GET_KEY_NAME(keymap_left),
+                       GET_KEY_NAME(keymap_right),
+                       GET_KEY_NAME(keymap_jump),
+                       GET_KEY_NAME(keymap_sneak),
+                       GET_KEY_NAME(keymap_drop),
+                       GET_KEY_NAME(keymap_inventory),
+                       GET_KEY_NAME(keymap_chat)
+                       );
 
        std::string control_text = std::string(control_text_buf);
        str_formspec_escape(control_text);
+#endif
+
        float ypos = simple_singleplayer_mode ? 0.7f : 0.1f;
        std::ostringstream os;
 
@@ -4565,7 +4046,7 @@ void Game::showPauseMenu()
                os << "button_exit[4," << (ypos++) << ";3,0.5;btn_change_password;"
                        << strgettext("Change Password") << "]";
        } else {
-               os << "field[4.95,0;5,1.5;;" << strgettext("Game Paused") << ";]";
+               os << "field[4.95,0;5,1.5;;" << strgettext("Game paused") << ";]";
        }
 
 #ifndef __ANDROID__
@@ -4586,7 +4067,7 @@ void Game::showPauseMenu()
        static const std::string mode = strgettext("- Mode: ");
        if (!simple_singleplayer_mode) {
                Address serverAddress = client->getServerAddress();
-               if (address != "") {
+               if (!address.empty()) {
                        os << mode << strgettext("Remote server") << "\n"
                                        << strgettext("- Address: ") << address;
                } else {
@@ -4596,21 +4077,21 @@ void Game::showPauseMenu()
        } else {
                os << mode << strgettext("Singleplayer") << "\n";
        }
-       if (simple_singleplayer_mode || address == "") {
+       if (simple_singleplayer_mode || address.empty()) {
                static const std::string on = strgettext("On");
                static const std::string off = strgettext("Off");
                const std::string &damage = g_settings->getBool("enable_damage") ? on : off;
                const std::string &creative = g_settings->getBool("creative_mode") ? on : off;
                const std::string &announced = g_settings->getBool("server_announce") ? on : off;
                os << strgettext("- Damage: ") << damage << "\n"
-                               << strgettext("- Creative mode: ") << creative << "\n";
+                               << strgettext("- Creative Mode: ") << creative << "\n";
                if (!simple_singleplayer_mode) {
                        const std::string &pvp = g_settings->getBool("enable_pvp") ? on : off;
                        os << strgettext("- PvP: ") << pvp << "\n"
                                        << strgettext("- Public: ") << announced << "\n";
                        std::string server_name = g_settings->get("server_name");
                        str_formspec_escape(server_name);
-                       if (announced == on && server_name != "")
+                       if (announced == on && !server_name.empty())
                                os << strgettext("- Server Name: ") << server_name;
 
                }
@@ -4623,7 +4104,7 @@ void Game::showPauseMenu()
        FormspecFormSource *fs_src = new FormspecFormSource(os.str());
        LocalFormspecHandler *txt_dst = new LocalFormspecHandler("MT_PAUSE_MENU");
 
-       create_formspec_menu(&current_formspec, client, device, &input->joystick, fs_src, txt_dst);
+       GUIFormSpecMenu::create(current_formspec, client, &input->joystick, fs_src, txt_dst);
        current_formspec->setFocus("btn_continue");
        current_formspec->doPause = true;
 }
@@ -4637,8 +4118,6 @@ void Game::showPauseMenu()
 void the_game(bool *kill,
                bool random_input,
                InputHandler *input,
-               IrrlichtDevice *device,
-
                const std::string &map_dir,
                const std::string &playername,
                const std::string &password,
@@ -4661,7 +4140,7 @@ void the_game(bool *kill,
 
        try {
 
-               if (game.startup(kill, random_input, input, device, map_dir,
+               if (game.startup(kill, random_input, input, map_dir,
                                playername, password, &server_address, port, error_message,
                                reconnect_requested, &chat_backend, gamespec,
                                simple_singleplayer_mode)) {