Exposing the zoom key to Lua API (#9903)
[oweals/minetest.git] / src / client / game.cpp
index 2b0976649ea348c6c3f7821a17cd569f8c0b36a0..069c482caae5a548347271704d1ed91138e4c7b0 100644 (file)
@@ -55,7 +55,6 @@ with this program; if not, write to the Free Software Foundation, Inc.,
 #include "particles.h"
 #include "porting.h"
 #include "profiler.h"
-#include "quicktune_shortcutter.h"
 #include "raycast.h"
 #include "server.h"
 #include "settings.h"
@@ -65,6 +64,7 @@ with this program; if not, write to the Free Software Foundation, Inc.,
 #include "util/basic_macros.h"
 #include "util/directiontables.h"
 #include "util/pointedthing.h"
+#include "util/quicktune_shortcutter.h"
 #include "irrlicht_changes/static_text.h"
 #include "version.h"
 #include "script/scripting_client.h"
@@ -266,6 +266,7 @@ class SoundMaker
 public:
        bool makes_footstep_sound;
        float m_player_step_timer;
+       float m_player_jump_timer;
 
        SimpleSoundSpec m_player_step_sound;
        SimpleSoundSpec m_player_leftpunch_sound;
@@ -275,7 +276,8 @@ public:
                m_sound(sound),
                m_ndef(ndef),
                makes_footstep_sound(true),
-               m_player_step_timer(0)
+               m_player_step_timer(0.0f),
+               m_player_jump_timer(0.0f)
        {
        }
 
@@ -288,6 +290,14 @@ public:
                }
        }
 
+       void playPlayerJump()
+       {
+               if (m_player_jump_timer <= 0.0f) {
+                       m_player_jump_timer = 0.2f;
+                       m_sound->playSound(SimpleSoundSpec("player_jump", 0.5f), false);
+               }
+       }
+
        static void viewBobbingStep(MtEvent *e, void *data)
        {
                SoundMaker *sm = (SoundMaker *)data;
@@ -302,7 +312,8 @@ public:
 
        static void playerJump(MtEvent *e, void *data)
        {
-               //SoundMaker *sm = (SoundMaker*)data;
+               SoundMaker *sm = (SoundMaker *)data;
+               sm->playPlayerJump();
        }
 
        static void cameraPunchLeft(MtEvent *e, void *data)
@@ -351,6 +362,7 @@ public:
        void step(float dtime)
        {
                m_player_step_timer -= dtime;
+               m_player_jump_timer -= dtime;
        }
 };
 
@@ -413,6 +425,8 @@ class GameGlobalShaderConstantSetter : public IShaderConstantSetter
        CachedPixelShaderSetting<float, 3> m_eye_position_pixel;
        CachedVertexShaderSetting<float, 3> m_eye_position_vertex;
        CachedPixelShaderSetting<float, 3> m_minimap_yaw;
+       CachedPixelShaderSetting<float, 3> m_camera_offset_pixel;
+       CachedPixelShaderSetting<float, 3> m_camera_offset_vertex;
        CachedPixelShaderSetting<SamplerLayer_t> m_base_texture;
        CachedPixelShaderSetting<SamplerLayer_t> m_normal_texture;
        CachedPixelShaderSetting<SamplerLayer_t> m_texture_flags;
@@ -445,6 +459,8 @@ public:
                m_eye_position_pixel("eyePosition"),
                m_eye_position_vertex("eyePosition"),
                m_minimap_yaw("yawVec"),
+               m_camera_offset_pixel("cameraOffset"),
+               m_camera_offset_vertex("cameraOffset"),
                m_base_texture("baseTexture"),
                m_normal_texture("normalTexture"),
                m_texture_flags("textureFlags"),
@@ -493,7 +509,7 @@ public:
                        sunlight.b };
                m_day_light.set(dnc, services);
 
-               u32 animation_timer = porting::getTimeMs() % 100000;
+               u32 animation_timer = porting::getTimeMs() % 1000000;
                float animation_timer_f = (float)animation_timer / 100000.f;
                m_animation_timer_vertex.set(&animation_timer_f, services);
                m_animation_timer_pixel.set(&animation_timer_f, services);
@@ -523,6 +539,18 @@ public:
                        m_minimap_yaw.set(minimap_yaw_array, services);
                }
 
+               float camera_offset_array[3];
+               v3f offset = intToFloat(m_client->getCamera()->getOffset(), BS);
+#if (IRRLICHT_VERSION_MAJOR == 1 && IRRLICHT_VERSION_MINOR < 8)
+               camera_offset_array[0] = offset.X;
+               camera_offset_array[1] = offset.Y;
+               camera_offset_array[2] = offset.Z;
+#else
+               offset.getAs3Values(camera_offset_array);
+#endif
+               m_camera_offset_pixel.set(camera_offset_array, services);
+               m_camera_offset_vertex.set(camera_offset_array, services);
+
                SamplerLayer_t base_tex = 0,
                                normal_tex = 1,
                                flags_tex = 2;
@@ -795,14 +823,18 @@ private:
        void handleClientEvent_HudRemove(ClientEvent *event, CameraOrientation *cam);
        void handleClientEvent_HudChange(ClientEvent *event, CameraOrientation *cam);
        void handleClientEvent_SetSky(ClientEvent *event, CameraOrientation *cam);
+       void handleClientEvent_SetSun(ClientEvent *event, CameraOrientation *cam);
+       void handleClientEvent_SetMoon(ClientEvent *event, CameraOrientation *cam);
+       void handleClientEvent_SetStars(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 &selected_def,
-               const ItemStack &selected_item, const v3s16 &nodepos, const v3s16 &neighbourpos);
+       bool nodePlacement(const ItemDefinition &selected_def, const ItemStack &selected_item,
+               const v3s16 &nodepos, const v3s16 &neighbourpos, const PointedThing &pointed,
+               const NodeMetadata *meta);
        static const ClientEventHandler clientEventHandler[CLIENTEVENT_MAX];
 
        InputHandler *input = nullptr;
@@ -823,6 +855,7 @@ private:
        SoundMaker *soundmaker = nullptr;
 
        ChatBackend *chat_backend = nullptr;
+       LogOutputBuffer m_chat_log_buf;
 
        EventManager *eventmgr = nullptr;
        QuicktuneShortcutter *quicktune = nullptr;
@@ -894,6 +927,7 @@ private:
 };
 
 Game::Game() :
+       m_chat_log_buf(g_logger),
        m_game_ui(new GameUI())
 {
        g_settings->registerChangedCallback("doubletap_jump",
@@ -1023,7 +1057,7 @@ bool Game::startup(bool *kill,
        m_invert_mouse = g_settings->getBool("invert_mouse");
        m_first_loop_after_window_activation = true;
 
-       g_translations->clear();
+       g_client_translations->clear();
 
        if (!init(map_dir, address, port, gamespec))
                return false;
@@ -1083,7 +1117,7 @@ void Game::run()
                //    RenderingEngine::run() from this iteration
                //  + Sleep time until the wanted FPS are reached
                limitFps(&draw_times, &dtime);
-               
+
                // Prepare render data for next iteration
 
                updateStats(&stats, draw_times, dtime);
@@ -1139,6 +1173,10 @@ void Game::shutdown()
        if (formspec)
                formspec->quitMenu();
 
+#ifdef HAVE_TOUCHSCREENGUI
+       g_touchscreengui->hide();
+#endif
+
        showOverlayMessage(N_("Shutting down..."), 0, 0, false);
 
        if (clouds)
@@ -1160,6 +1198,7 @@ void Game::shutdown()
 
        chat_backend->addMessage(L"", L"# Disconnected.");
        chat_backend->addMessage(L"", L"");
+       m_chat_log_buf.clear();
 
        if (client) {
                client->Stop();
@@ -1217,7 +1256,7 @@ bool Game::init(
 bool Game::initSound()
 {
 #if USE_SOUND
-       if (g_settings->getBool("enable_sound")) {
+       if (g_settings->getBool("enable_sound") && g_sound_manager_singleton.get()) {
                infostream << "Attempting to use OpenAL audio" << std::endl;
                sound = createOpenALSoundManager(g_sound_manager_singleton.get(), &soundfetcher);
                if (!sound)
@@ -1270,7 +1309,6 @@ bool Game::createSingleplayerServer(const std::string &map_dir,
        }
 
        server = new Server(map_dir, gamespec, simple_singleplayer_mode, bind_addr, false);
-       server->init();
        server->start();
 
        return true;
@@ -1387,8 +1425,11 @@ bool Game::createClient(const std::string &playername,
        }
 
        mapper = client->getMinimap();
-       if (mapper)
+       if (mapper) {
                mapper->setMinimapMode(MINIMAP_MODE_OFF);
+               if (client->modsLoaded())
+                       client->getScript()->on_minimap_ready(mapper);
+       }
 
        return true;
 }
@@ -1533,7 +1574,8 @@ bool Game::connectToServer(const std::string &playername,
                                } else {
                                        registration_confirmation_shown = true;
                                        (new GUIConfirmRegistration(guienv, guienv->getRootGUIElement(), -1,
-                                                  &g_menumgr, client, playername, password, connection_aborted))->drop();
+                                                  &g_menumgr, client, playername, password,
+                                                  connection_aborted, texture_src))->drop();
                                }
                        } else {
                                wait_time += dtime;
@@ -1688,19 +1730,19 @@ inline bool Game::handleCallbacks()
 
        if (g_gamecallback->changepassword_requested) {
                (new GUIPasswordChange(guienv, guiroot, -1,
-                                      &g_menumgr, client))->drop();
+                                      &g_menumgr, client, texture_src))->drop();
                g_gamecallback->changepassword_requested = false;
        }
 
        if (g_gamecallback->changevolume_requested) {
                (new GUIVolumeChange(guienv, guiroot, -1,
-                                    &g_menumgr))->drop();
+                                    &g_menumgr, texture_src))->drop();
                g_gamecallback->changevolume_requested = false;
        }
 
        if (g_gamecallback->keyconfig_requested) {
                (new GUIKeyChangeMenu(guienv, guiroot, -1,
-                                     &g_menumgr))->drop();
+                                     &g_menumgr, texture_src))->drop();
                g_gamecallback->keyconfig_requested = false;
        }
 
@@ -1886,29 +1928,47 @@ void Game::processKeyInput()
                toggleFast();
        } else if (wasKeyDown(KeyType::NOCLIP)) {
                toggleNoClip();
+#if USE_SOUND
        } else if (wasKeyDown(KeyType::MUTE)) {
-               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");
+               if (g_settings->getBool("enable_sound")) {
+                       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 {
+                       m_game_ui->showTranslatedStatusText("Sound system is disabled");
+               }
        } else if (wasKeyDown(KeyType::INC_VOLUME)) {
-               float new_volume = rangelim(g_settings->getFloat("sound_volume") + 0.1f, 0.0f, 1.0f);
-               wchar_t buf[100];
-               g_settings->setFloat("sound_volume", new_volume);
-               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);
+               if (g_settings->getBool("enable_sound")) {
+                       float new_volume = rangelim(g_settings->getFloat("sound_volume") + 0.1f, 0.0f, 1.0f);
+                       wchar_t buf[100];
+                       g_settings->setFloat("sound_volume", new_volume);
+                       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 {
+                       m_game_ui->showTranslatedStatusText("Sound system is disabled");
+               }
        } else if (wasKeyDown(KeyType::DEC_VOLUME)) {
-               float new_volume = rangelim(g_settings->getFloat("sound_volume") - 0.1f, 0.0f, 1.0f);
-               wchar_t buf[100];
-               g_settings->setFloat("sound_volume", new_volume);
-               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);
+               if (g_settings->getBool("enable_sound")) {
+                       float new_volume = rangelim(g_settings->getFloat("sound_volume") - 0.1f, 0.0f, 1.0f);
+                       wchar_t buf[100];
+                       g_settings->setFloat("sound_volume", new_volume);
+                       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 {
+                       m_game_ui->showTranslatedStatusText("Sound system is disabled");
+               }
+#else
+       } else if (wasKeyDown(KeyType::MUTE) || wasKeyDown(KeyType::INC_VOLUME)
+                       || wasKeyDown(KeyType::DEC_VOLUME)) {
+               m_game_ui->showTranslatedStatusText("Sound system is not supported on this build");
+#endif
        } else if (wasKeyDown(KeyType::CINEMATIC)) {
                toggleCinematic();
        } else if (wasKeyDown(KeyType::SCREENSHOT)) {
@@ -1990,7 +2050,6 @@ void Game::processItemSelection(u16 *new_playeritem)
        for (u16 i = 0; i <= max_item; i++) {
                if (wasKeyDown((GameKeyType) (KeyType::SLOT_1 + i))) {
                        *new_playeritem = i;
-                       infostream << "Selected item: " << new_playeritem << std::endl;
                        break;
                }
        }
@@ -2019,7 +2078,7 @@ void Game::openInventory()
        if (!player || !player->getCAO())
                return;
 
-       infostream << "the_game: " << "Launching inventory" << std::endl;
+       infostream << "Game: Launching inventory" << std::endl;
 
        PlayerInventoryFormSource *fs_src = new PlayerInventoryFormSource(client);
 
@@ -2332,7 +2391,7 @@ void Game::toggleFullViewRange()
 void Game::checkZoomEnabled()
 {
        LocalPlayer *player = client->getEnv().getLocalPlayer();
-       if (player->getZoomFOV() < 0.001f)
+       if (player->getZoomFOV() < 0.001f || player->getFov().fov > 0.0f)
                m_game_ui->showTranslatedStatusText("Zoom currently disabled by game or mod");
 }
 
@@ -2431,7 +2490,7 @@ void Game::updatePlayerControl(const CameraOrientation &cam)
                input->joystick.getAxisWithoutDead(JA_FORWARD_MOVE)
        );
 
-       u32 keypress_bits =
+       u32 keypress_bits = (
                        ( (u32)(isKeyDown(KeyType::FORWARD)                       & 0x1) << 0) |
                        ( (u32)(isKeyDown(KeyType::BACKWARD)                      & 0x1) << 1) |
                        ( (u32)(isKeyDown(KeyType::LEFT)                          & 0x1) << 2) |
@@ -2440,7 +2499,8 @@ void Game::updatePlayerControl(const CameraOrientation &cam)
                        ( (u32)(isKeyDown(KeyType::SPECIAL1)                      & 0x1) << 5) |
                        ( (u32)(isKeyDown(KeyType::SNEAK)                         & 0x1) << 6) |
                        ( (u32)(input->getLeftState()                             & 0x1) << 7) |
-                       ( (u32)(input->getRightState()                            & 0x1) << 8
+                       ( (u32)(input->getRightState()                            & 0x1) << 8) |
+                       ( (u32)(isKeyDown(KeyType::ZOOM)                          & 0x1) << 9)
                );
 
 #ifdef ANDROID
@@ -2464,7 +2524,8 @@ void Game::updatePlayerControl(const CameraOrientation &cam)
        }
 
        // autoforward if set: simulate "up" key
-       if (player->getPlayerSettings().continuous_forward && !player->isDead()) {
+       if (player->getPlayerSettings().continuous_forward &&
+                       client->activeObjectsReceived() && !player->isDead()) {
                control.up = true;
                keypress_bits |= 1U << 0;
        }
@@ -2505,6 +2566,9 @@ const ClientEventHandler Game::clientEventHandler[CLIENTEVENT_MAX] = {
        {&Game::handleClientEvent_HudRemove},
        {&Game::handleClientEvent_HudChange},
        {&Game::handleClientEvent_SetSky},
+       {&Game::handleClientEvent_SetSun},
+       {&Game::handleClientEvent_SetMoon},
+       {&Game::handleClientEvent_SetStars},
        {&Game::handleClientEvent_OverrideDayNigthRatio},
        {&Game::handleClientEvent_CloudParams},
 };
@@ -2616,6 +2680,7 @@ void Game::handleClientEvent_HudAdd(ClientEvent *event, CameraOrientation *cam)
                delete event->hudadd.offset;
                delete event->hudadd.world_pos;
                delete event->hudadd.size;
+               delete event->hudadd.text2;
                return;
        }
 
@@ -2632,6 +2697,8 @@ void Game::handleClientEvent_HudAdd(ClientEvent *event, CameraOrientation *cam)
        e->offset = *event->hudadd.offset;
        e->world_pos = *event->hudadd.world_pos;
        e->size = *event->hudadd.size;
+       e->z_index = event->hudadd.z_index;
+       e->text2  = *event->hudadd.text2;
        hud_server_to_client[server_id] = player->addHud(e);
 
        delete event->hudadd.pos;
@@ -2642,6 +2709,7 @@ void Game::handleClientEvent_HudAdd(ClientEvent *event, CameraOrientation *cam)
        delete event->hudadd.offset;
        delete event->hudadd.world_pos;
        delete event->hudadd.size;
+       delete event->hudadd.text2;
 }
 
 void Game::handleClientEvent_HudRemove(ClientEvent *event, CameraOrientation *cam)
@@ -2710,6 +2778,14 @@ void Game::handleClientEvent_HudChange(ClientEvent *event, CameraOrientation *ca
                case HUD_STAT_SIZE:
                        e->size = *event->hudchange.v2s32data;
                        break;
+
+               case HUD_STAT_Z_INDEX:
+                       e->z_index = event->hudchange.data;
+                       break;
+
+               case HUD_STAT_TEXT2:
+                       e->text2 = *event->hudchange.sdata;
+                       break;
        }
 
        delete event->hudchange.v3fdata;
@@ -2721,41 +2797,85 @@ void Game::handleClientEvent_HudChange(ClientEvent *event, CameraOrientation *ca
 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);
+       // Whether clouds are visible in front of a custom skybox.
+       sky->setCloudsEnabled(event->set_sky->clouds);
 
        if (skybox) {
                skybox->remove();
                skybox = NULL;
        }
-
+       // Clear the old textures out in case we switch rendering type.
+       sky->clearSkyboxTextures();
        // Handle according to type
-       if (*event->set_sky.type == "regular") {
+       if (event->set_sky->type == "regular") {
+               // Shows the mesh skybox
                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")
+               // Update mesh based skybox colours if applicable.
+               sky->setSkyColors(event->set_sky->sky_color);
+               sky->setHorizonTint(
+                       event->set_sky->fog_sun_tint,
+                       event->set_sky->fog_moon_tint,
+                       event->set_sky->fog_tint_type
+               );
+       } else if (event->set_sky->type == "skybox" &&
+                       event->set_sky->textures.size() == 6) {
+               // Disable the dyanmic mesh skybox:
+               sky->setVisible(false);
+               // Set fog colors:
+               sky->setFallbackBgColor(event->set_sky->bgcolor);
+               // Set sunrise and sunset fog tinting:
+               sky->setHorizonTint(
+                       event->set_sky->fog_sun_tint,
+                       event->set_sky->fog_moon_tint,
+                       event->set_sky->fog_tint_type
+               );
+               // Add textures to skybox.
+               for (int i = 0; i < 6; i++)
+                       sky->addTextureToSkybox(event->set_sky->textures[i], i, texture_src);
+       } else {
+               // Handle everything else as plain color.
+               if (event->set_sky->type != "plain")
                        infostream << "Unknown sky type: "
-                               << (*event->set_sky.type) << std::endl;
-
-               sky->setFallbackBgColor(*event->set_sky.bgcolor);
+                               << (event->set_sky->type) << std::endl;
+               sky->setVisible(false);
+               sky->setFallbackBgColor(event->set_sky->bgcolor);
+               // Disable directional sun/moon tinting on plain or invalid skyboxes.
+               sky->setHorizonTint(
+                       event->set_sky->bgcolor,
+                       event->set_sky->bgcolor,
+                       "custom"
+               );
        }
+       delete event->set_sky;
+}
+
+void Game::handleClientEvent_SetSun(ClientEvent *event, CameraOrientation *cam)
+{
+       sky->setSunVisible(event->sun_params->visible);
+       sky->setSunTexture(event->sun_params->texture,
+               event->sun_params->tonemap, texture_src);
+       sky->setSunScale(event->sun_params->scale);
+       sky->setSunriseVisible(event->sun_params->sunrise_visible);
+       sky->setSunriseTexture(event->sun_params->sunrise, texture_src);
+       delete event->sun_params;
+}
 
-       delete event->set_sky.bgcolor;
-       delete event->set_sky.type;
-       delete event->set_sky.params;
+void Game::handleClientEvent_SetMoon(ClientEvent *event, CameraOrientation *cam)
+{
+       sky->setMoonVisible(event->moon_params->visible);
+       sky->setMoonTexture(event->moon_params->texture,
+               event->moon_params->tonemap, texture_src);
+       sky->setMoonScale(event->moon_params->scale);
+       delete event->moon_params;
+}
+
+void Game::handleClientEvent_SetStars(ClientEvent *event, CameraOrientation *cam)
+{
+       sky->setStarsVisible(event->star_params->visible);
+       sky->setStarCount(event->star_params->count, false);
+       sky->setStarColor(event->star_params->starcolor);
+       sky->setStarScale(event->star_params->scale);
+       delete event->star_params;
 }
 
 void Game::handleClientEvent_OverrideDayNigthRatio(ClientEvent *event,
@@ -2791,18 +2911,9 @@ void Game::processClientEvents(CameraOrientation *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.insert(0, L"\x1b(c@red)");
-                       error_message.append(L"\x1b(c@white)");
-               }
-               chat_backend->addMessage(L"", error_message);
-       }
+       while (!m_chat_log_buf.empty())
+               chat_backend->addMessage(L"", utf8_to_wide(m_chat_log_buf.get()));
 
        // Get new messages from client
        std::wstring message;
@@ -2923,16 +3034,8 @@ void Game::processPlayerInteraction(f32 dtime, bool show_hud, bool show_debug)
 {
        LocalPlayer *player = client->getEnv().getLocalPlayer();
 
-       v3f player_position  = player->getPosition();
-       v3f player_eye_position = player->getEyePosition();
-       v3f camera_position  = camera->getPosition();
-       v3f camera_direction = camera->getDirection();
-       v3s16 camera_offset  = camera->getOffset();
-
-       if (camera->getCameraMode() == CAMERA_MODE_FIRST)
-               player_eye_position += player->eye_offset_first;
-       else
-               player_eye_position += player->eye_offset_third;
+       const v3f camera_direction = camera->getDirection();
+       const v3s16 camera_offset  = camera->getOffset();
 
        /*
                Calculate what block is the crosshair pointing to
@@ -2946,13 +3049,22 @@ void Game::processPlayerInteraction(f32 dtime, bool show_hud, bool show_debug)
 
        core::line3d<f32> shootline;
 
-       if (camera->getCameraMode() != CAMERA_MODE_THIRD_FRONT) {
-               shootline = core::line3d<f32>(player_eye_position,
-                       player_eye_position + camera_direction * BS * d);
-       } else {
+       switch (camera->getCameraMode()) {
+       case CAMERA_MODE_FIRST:
+               // Shoot from camera position, with bobbing
+               shootline.start = camera->getPosition();
+               break;
+       case CAMERA_MODE_THIRD:
+               // Shoot from player head, no bobbing
+               shootline.start = camera->getHeadPosition();
+               break;
+       case CAMERA_MODE_THIRD_FRONT:
+               shootline.start = camera->getHeadPosition();
                // prevent player pointing anything in front-view
-               shootline = core::line3d<f32>(camera_position, camera_position);
+               d = 0;
+               break;
        }
+       shootline.end = shootline.start + camera_direction * BS * d;
 
 #ifdef HAVE_TOUCHSCREENGUI
 
@@ -3039,10 +3151,14 @@ void Game::processPlayerInteraction(f32 dtime, bool show_hud, bool show_debug)
        } else if (pointed.type == POINTEDTHING_NODE) {
                handlePointingAtNode(pointed, selected_item, hand_item, dtime);
        } else if (pointed.type == POINTEDTHING_OBJECT) {
+               v3f player_position  = player->getPosition();
                handlePointingAtObject(pointed, tool_item, player_position, show_debug);
        } else if (input->getLeftState()) {
                // When button is held down in air, show continuous animation
                runData.left_punch = true;
+               // Run callback even though item is not usable
+               if (input->getLeftClicked() && client->modsLoaded())
+                       client->getScript()->on_item_use(selected_item, pointed);
        } else if (input->getRightClicked()) {
                handlePointingAtNothing(selected_item);
        }
@@ -3199,65 +3315,26 @@ void Game::handlePointingAtNode(const PointedThing &pointed,
                runData.repeat_rightclick_timer = 0;
                infostream << "Ground right-clicked" << std::endl;
 
-               if (meta && !meta->getString("formspec").empty() && !random_input
-                               && !isKeyDown(KeyType::SNEAK)) {
-                       // Report right click to server
-                       if (nodedef_manager->get(map.getNode(nodepos)).rightclickable) {
-                               client->interact(INTERACT_PLACE, pointed);
-                       }
-
-                       infostream << "Launching custom inventory view" << std::endl;
-
-                       InventoryLocation inventoryloc;
-                       inventoryloc.setNodeMeta(nodepos);
-
-                       NodeMetadataFormSource *fs_src = new NodeMetadataFormSource(
-                               &client->getEnv().getClientMap(), nodepos);
-                       TextDest *txt_dst = new TextDestNodeMetadata(nodepos, client);
-
-                       auto *&formspec = m_game_ui->updateFormspec("");
-                       GUIFormSpecMenu::create(formspec, client, &input->joystick, fs_src,
-                               txt_dst, client->getFormspecPrepend());
-
-                       formspec->setFormSpec(meta->getString("formspec"), inventoryloc);
-               } else {
-                       // Report right click to server
-
-                       camera->setDigging(1);  // right click animation (always shown for feedback)
+               camera->setDigging(1);  // right click animation (always shown for feedback)
 
-                       // If the wielded item has node placement prediction,
-                       // make that happen
-                       auto &def = selected_item.getDefinition(itemdef_manager);
-                       bool placed = nodePlacementPrediction(def, selected_item, nodepos,
-                               neighbourpos);
+               soundmaker->m_player_rightpunch_sound = SimpleSoundSpec();
 
-                       if (placed) {
-                               // Report to server
-                               client->interact(INTERACT_PLACE, pointed);
-                               // Read the sound
-                               soundmaker->m_player_rightpunch_sound =
-                                               def.sound_place;
-
-                               if (client->modsLoaded())
-                                       client->getScript()->on_placenode(pointed, def);
-                       } else {
-                               soundmaker->m_player_rightpunch_sound =
-                                               SimpleSoundSpec();
+               // If the wielded item has node placement prediction,
+               // make that happen
+               // And also set the sound and send the interact
+               // But first check for meta formspec and rightclickable
+               auto &def = selected_item.getDefinition(itemdef_manager);
+               bool placed = nodePlacement(def, selected_item, nodepos, neighbourpos,
+                       pointed, meta);
 
-                               if (def.node_placement_prediction.empty() ||
-                                               nodedef_manager->get(map.getNode(nodepos)).rightclickable) {
-                                       client->interact(INTERACT_PLACE, pointed); // Report to server
-                               } else {
-                                       soundmaker->m_player_rightpunch_sound =
-                                               def.sound_place_failed;
-                               }
-                       }
-               }
+               if (placed && client->modsLoaded())
+                       client->getScript()->on_placenode(pointed, def);
        }
 }
 
-bool Game::nodePlacementPrediction(const ItemDefinition &selected_def,
-       const ItemStack &selected_item, const v3s16 &nodepos, const v3s16 &neighbourpos)
+bool Game::nodePlacement(const ItemDefinition &selected_def,
+       const ItemStack &selected_item, const v3s16 &nodepos, const v3s16 &neighbourpos,
+       const PointedThing &pointed, const NodeMetadata *meta)
 {
        std::string prediction = selected_def.node_placement_prediction;
        const NodeDefManager *nodedef = client->ndef();
@@ -3266,144 +3343,187 @@ bool Game::nodePlacementPrediction(const ItemDefinition &selected_def,
        bool is_valid_position;
 
        node = map.getNode(nodepos, &is_valid_position);
-       if (!is_valid_position)
+       if (!is_valid_position) {
+               soundmaker->m_player_rightpunch_sound = selected_def.sound_place_failed;
                return false;
+       }
+
+       // formspec in meta
+       if (meta && !meta->getString("formspec").empty() && !random_input
+                       && !isKeyDown(KeyType::SNEAK)) {
+               // on_rightclick callbacks are called anyway
+               if (nodedef_manager->get(map.getNode(nodepos)).rightclickable)
+                       client->interact(INTERACT_PLACE, pointed);
+
+               infostream << "Launching custom inventory view" << std::endl;
+
+               InventoryLocation inventoryloc;
+               inventoryloc.setNodeMeta(nodepos);
 
-       if (!prediction.empty() && !(nodedef->get(node).rightclickable &&
+               NodeMetadataFormSource *fs_src = new NodeMetadataFormSource(
+                       &client->getEnv().getClientMap(), nodepos);
+               TextDest *txt_dst = new TextDestNodeMetadata(nodepos, client);
+
+               auto *&formspec = m_game_ui->updateFormspec("");
+               GUIFormSpecMenu::create(formspec, client, &input->joystick, fs_src,
+                       txt_dst, client->getFormspecPrepend());
+
+               formspec->setFormSpec(meta->getString("formspec"), inventoryloc);
+               return false;
+       }
+
+       // on_rightclick callback
+       if (prediction.empty() || (nodedef->get(node).rightclickable &&
                        !isKeyDown(KeyType::SNEAK))) {
-               verbosestream << "Node placement prediction for "
-                       << selected_item.name << " is "
-                       << prediction << std::endl;
-               v3s16 p = neighbourpos;
-
-               // Place inside node itself if buildable_to
-               MapNode n_under = map.getNode(nodepos, &is_valid_position);
-               if (is_valid_position)
-               {
-                       if (nodedef->get(n_under).buildable_to)
-                               p = nodepos;
-                       else {
-                               node = map.getNode(p, &is_valid_position);
-                               if (is_valid_position &&!nodedef->get(node).buildable_to)
-                                       return false;
+               // Report to server
+               client->interact(INTERACT_PLACE, pointed);
+               return false;
+       }
+
+       verbosestream << "Node placement prediction for "
+               << selected_def.name << " is "
+               << prediction << std::endl;
+       v3s16 p = neighbourpos;
+
+       // Place inside node itself if buildable_to
+       MapNode n_under = map.getNode(nodepos, &is_valid_position);
+       if (is_valid_position) {
+               if (nodedef->get(n_under).buildable_to) {
+                       p = nodepos;
+               } else {
+                       node = map.getNode(p, &is_valid_position);
+                       if (is_valid_position && !nodedef->get(node).buildable_to) {
+                               // Report to server
+                               client->interact(INTERACT_PLACE, pointed);
+                               return false;
                        }
                }
+       }
 
-               // Find id of predicted node
-               content_t id;
-               bool found = nodedef->getId(prediction, id);
+       // Find id of predicted node
+       content_t id;
+       bool found = nodedef->getId(prediction, id);
 
-               if (!found) {
-                       errorstream << "Node placement prediction failed for "
-                               << selected_item.name << " (places "
-                               << prediction
-                               << ") - Name not known" << std::endl;
-                       return false;
-               }
+       if (!found) {
+               errorstream << "Node placement prediction failed for "
+                       << selected_def.name << " (places "
+                       << prediction
+                       << ") - Name not known" << std::endl;
+               // Handle this as if prediction was empty
+               // Report to server
+               client->interact(INTERACT_PLACE, pointed);
+               return false;
+       }
 
-               const ContentFeatures &predicted_f = nodedef->get(id);
+       const ContentFeatures &predicted_f = nodedef->get(id);
 
-               // Predict param2 for facedir and wallmounted nodes
-               u8 param2 = 0;
+       // Predict param2 for facedir and wallmounted nodes
+       u8 param2 = 0;
 
-               if (predicted_f.param_type_2 == CPT2_WALLMOUNTED ||
+       if (predicted_f.param_type_2 == CPT2_WALLMOUNTED ||
                        predicted_f.param_type_2 == CPT2_COLORED_WALLMOUNTED) {
-                       v3s16 dir = nodepos - neighbourpos;
+               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 (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 ||
+       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);
+               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;
-                       }
+               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;
 
-               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 ||
+               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);
+                       pp = p + wallmounted_dirs[param2];
+               else
+                       pp = p + v3s16(0, -1, 0);
 
-                       if (!nodedef->get(map.getNode(pp)).walkable)
-                               return false;
+               if (!nodedef->get(map.getNode(pp)).walkable) {
+                       // Report to server
+                       client->interact(INTERACT_PLACE, pointed);
+                       return false;
                }
+       }
 
-               // Apply color
-               if ((predicted_f.param_type_2 == CPT2_COLOR
+       // 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 = selected_item.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);
-                               }
+               const std::string &indexstr = selected_item.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);
+       // Add node to client map
+       MapNode n(id, 0, param2);
 
-               try {
-                       LocalPlayer *player = client->getEnv().getLocalPlayer();
+       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 ||
+               // 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 "
-                               << selected_item.name << " (places "
-                               << prediction
-                               << ") - Position not loaded" << std::endl;
+                       // This triggers the required mesh update too
+                       client->addNode(p, n);
+                       // Report to server
+                       client->interact(INTERACT_PLACE, pointed);
+                       // A node is predicted, also play a sound
+                       soundmaker->m_player_rightpunch_sound = selected_def.sound_place;
+                       return true;
+               } else {
+                       soundmaker->m_player_rightpunch_sound = selected_def.sound_place_failed;
+                       return false;
                }
+       } catch (InvalidPositionException &e) {
+               errorstream << "Node placement prediction failed for "
+                       << selected_def.name << " (places "
+                       << prediction
+                       << ") - Position not loaded" << std::endl;
+               soundmaker->m_player_rightpunch_sound = selected_def.sound_place_failed;
+               return false;
        }
-
-       return false;
 }
 
 void Game::handlePointingAtObject(const PointedThing &pointed,
@@ -3676,7 +3796,7 @@ void Game::updateFrame(ProfilerGraph *graph, RunStats *stats, f32 dtime,
                                video::SColor clouds_dark = clouds->getColor()
                                                .getInterpolated(video::SColor(255, 0, 0, 0), 0.9);
                                sky->overrideColors(clouds_dark, clouds->getColor());
-                               sky->setBodiesVisible(false);
+                               sky->setInClouds(true);
                                runData.fog_range = std::fmin(runData.fog_range * 0.5f, 32.0f * BS);
                                // do not draw clouds after all
                                clouds->setVisible(false);
@@ -4067,8 +4187,12 @@ void Game::showPauseMenu()
        }
 
 #ifndef __ANDROID__
-       os              << "button_exit[4," << (ypos++) << ";3,0.5;btn_sound;"
-               << strgettext("Sound Volume") << "]";
+#if USE_SOUND
+       if (g_settings->getBool("enable_sound")) {
+               os << "button_exit[4," << (ypos++) << ";3,0.5;btn_sound;"
+                       << strgettext("Sound Volume") << "]";
+       }
+#endif
        os              << "button_exit[4," << (ypos++) << ";3,0.5;btn_key_config;"
                << strgettext("Change Keys")  << "]";
 #endif
@@ -4104,6 +4228,7 @@ void Game::showPauseMenu()
                                << strgettext("- Creative Mode: ") << creative << "\n";
                if (!simple_singleplayer_mode) {
                        const std::string &pvp = g_settings->getBool("enable_pvp") ? on : off;
+                       //~ PvP = Player versus Player
                        os << strgettext("- PvP: ") << pvp << "\n"
                                        << strgettext("- Public: ") << announced << "\n";
                        std::string server_name = g_settings->get("server_name");
@@ -4164,7 +4289,6 @@ void the_game(bool *kill,
                                reconnect_requested, &chat_backend, gamespec,
                                simple_singleplayer_mode)) {
                        game.run();
-                       game.shutdown();
                }
 
        } catch (SerializationError &e) {
@@ -4180,4 +4304,5 @@ void the_game(bool *kill,
                                strgettext("\nCheck debug.txt for details.");
                errorstream << error_message << std::endl;
        }
+       game.shutdown();
 }