3 Copyright (C) 2010-2013 celeron55, Perttu Ahola <celeron55@gmail.com>
5 This program is free software; you can redistribute it and/or modify
6 it under the terms of the GNU Lesser General Public License as published by
7 the Free Software Foundation; either version 2.1 of the License, or
8 (at your option) any later version.
10 This program is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 GNU Lesser General Public License for more details.
15 You should have received a copy of the GNU Lesser General Public License along
16 with this program; if not, write to the Free Software Foundation, Inc.,
17 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
24 #include "client/renderingengine.h"
27 #include "client/clientevent.h"
28 #include "client/gameui.h"
29 #include "client/inputhandler.h"
30 #include "client/tile.h" // For TextureSource
31 #include "client/keys.h"
32 #include "client/joystick_controller.h"
33 #include "clientmap.h"
36 #include "content_cao.h"
37 #include "client/event_manager.h"
38 #include "fontengine.h"
43 #include "gui/guiChatConsole.h"
44 #include "gui/guiConfirmRegistration.h"
45 #include "gui/guiFormSpecMenu.h"
46 #include "gui/guiKeyChangeMenu.h"
47 #include "gui/guiPasswordChange.h"
48 #include "gui/guiVolumeChange.h"
49 #include "gui/mainmenumanager.h"
50 #include "gui/profilergraph.h"
53 #include "nodedef.h" // Needed for determining pointing to nodes
54 #include "nodemetadata.h"
55 #include "particles.h"
58 #include "quicktune_shortcutter.h"
64 #include "translation.h"
65 #include "util/basic_macros.h"
66 #include "util/directiontables.h"
67 #include "util/pointedthing.h"
68 #include "irrlicht_changes/static_text.h"
70 #include "script/scripting_client.h"
74 #include "client/sound_openal.h"
76 #include "client/sound.h"
82 struct TextDestNodeMetadata : public TextDest
84 TextDestNodeMetadata(v3s16 p, Client *client)
89 // This is deprecated I guess? -celeron55
90 void gotText(const std::wstring &text)
92 std::string ntext = wide_to_utf8(text);
93 infostream << "Submitting 'text' field of node at (" << m_p.X << ","
94 << m_p.Y << "," << m_p.Z << "): " << ntext << std::endl;
96 fields["text"] = ntext;
97 m_client->sendNodemetaFields(m_p, "", fields);
99 void gotText(const StringMap &fields)
101 m_client->sendNodemetaFields(m_p, "", fields);
108 struct TextDestPlayerInventory : public TextDest
110 TextDestPlayerInventory(Client *client)
115 TextDestPlayerInventory(Client *client, const std::string &formname)
118 m_formname = formname;
120 void gotText(const StringMap &fields)
122 m_client->sendInventoryFields(m_formname, fields);
128 struct LocalFormspecHandler : public TextDest
130 LocalFormspecHandler(const std::string &formname)
132 m_formname = formname;
135 LocalFormspecHandler(const std::string &formname, Client *client):
138 m_formname = formname;
141 void gotText(const StringMap &fields)
143 if (m_formname == "MT_PAUSE_MENU") {
144 if (fields.find("btn_sound") != fields.end()) {
145 g_gamecallback->changeVolume();
149 if (fields.find("btn_key_config") != fields.end()) {
150 g_gamecallback->keyConfig();
154 if (fields.find("btn_exit_menu") != fields.end()) {
155 g_gamecallback->disconnect();
159 if (fields.find("btn_exit_os") != fields.end()) {
160 g_gamecallback->exitToOS();
162 RenderingEngine::get_raw_device()->closeDevice();
167 if (fields.find("btn_change_password") != fields.end()) {
168 g_gamecallback->changePassword();
172 if (fields.find("quit") != fields.end()) {
176 if (fields.find("btn_continue") != fields.end()) {
181 if (m_formname == "MT_DEATH_SCREEN") {
182 assert(m_client != 0);
183 m_client->sendRespawn();
187 if (m_client && m_client->moddingEnabled())
188 m_client->getScript()->on_formspec_input(m_formname, fields);
191 Client *m_client = nullptr;
194 /* Form update callback */
196 class NodeMetadataFormSource: public IFormSource
199 NodeMetadataFormSource(ClientMap *map, v3s16 p):
204 const std::string &getForm() const
206 static const std::string empty_string = "";
207 NodeMetadata *meta = m_map->getNodeMetadata(m_p);
212 return meta->getString("formspec");
215 virtual std::string resolveText(const std::string &str)
217 NodeMetadata *meta = m_map->getNodeMetadata(m_p);
222 return meta->resolveString(str);
229 class PlayerInventoryFormSource: public IFormSource
232 PlayerInventoryFormSource(Client *client):
237 const std::string &getForm() const
239 LocalPlayer *player = m_client->getEnv().getLocalPlayer();
240 return player->inventory_formspec;
246 class NodeDugEvent: public MtEvent
252 NodeDugEvent(v3s16 p, MapNode n):
256 MtEvent::Type getType() const
258 return MtEvent::NODE_DUG;
264 ISoundManager *m_sound;
265 const NodeDefManager *m_ndef;
267 bool makes_footstep_sound;
268 float m_player_step_timer;
270 SimpleSoundSpec m_player_step_sound;
271 SimpleSoundSpec m_player_leftpunch_sound;
272 SimpleSoundSpec m_player_rightpunch_sound;
274 SoundMaker(ISoundManager *sound, const NodeDefManager *ndef):
277 makes_footstep_sound(true),
278 m_player_step_timer(0)
282 void playPlayerStep()
284 if (m_player_step_timer <= 0 && m_player_step_sound.exists()) {
285 m_player_step_timer = 0.03;
286 if (makes_footstep_sound)
287 m_sound->playSound(m_player_step_sound, false);
291 static void viewBobbingStep(MtEvent *e, void *data)
293 SoundMaker *sm = (SoundMaker *)data;
294 sm->playPlayerStep();
297 static void playerRegainGround(MtEvent *e, void *data)
299 SoundMaker *sm = (SoundMaker *)data;
300 sm->playPlayerStep();
303 static void playerJump(MtEvent *e, void *data)
305 //SoundMaker *sm = (SoundMaker*)data;
308 static void cameraPunchLeft(MtEvent *e, void *data)
310 SoundMaker *sm = (SoundMaker *)data;
311 sm->m_sound->playSound(sm->m_player_leftpunch_sound, false);
314 static void cameraPunchRight(MtEvent *e, void *data)
316 SoundMaker *sm = (SoundMaker *)data;
317 sm->m_sound->playSound(sm->m_player_rightpunch_sound, false);
320 static void nodeDug(MtEvent *e, void *data)
322 SoundMaker *sm = (SoundMaker *)data;
323 NodeDugEvent *nde = (NodeDugEvent *)e;
324 sm->m_sound->playSound(sm->m_ndef->get(nde->n).sound_dug, false);
327 static void playerDamage(MtEvent *e, void *data)
329 SoundMaker *sm = (SoundMaker *)data;
330 sm->m_sound->playSound(SimpleSoundSpec("player_damage", 0.5), false);
333 static void playerFallingDamage(MtEvent *e, void *data)
335 SoundMaker *sm = (SoundMaker *)data;
336 sm->m_sound->playSound(SimpleSoundSpec("player_falling_damage", 0.5), false);
339 void registerReceiver(MtEventManager *mgr)
341 mgr->reg(MtEvent::VIEW_BOBBING_STEP, SoundMaker::viewBobbingStep, this);
342 mgr->reg(MtEvent::PLAYER_REGAIN_GROUND, SoundMaker::playerRegainGround, this);
343 mgr->reg(MtEvent::PLAYER_JUMP, SoundMaker::playerJump, this);
344 mgr->reg(MtEvent::CAMERA_PUNCH_LEFT, SoundMaker::cameraPunchLeft, this);
345 mgr->reg(MtEvent::CAMERA_PUNCH_RIGHT, SoundMaker::cameraPunchRight, this);
346 mgr->reg(MtEvent::NODE_DUG, SoundMaker::nodeDug, this);
347 mgr->reg(MtEvent::PLAYER_DAMAGE, SoundMaker::playerDamage, this);
348 mgr->reg(MtEvent::PLAYER_FALLING_DAMAGE, SoundMaker::playerFallingDamage, this);
351 void step(float dtime)
353 m_player_step_timer -= dtime;
357 // Locally stored sounds don't need to be preloaded because of this
358 class GameOnDemandSoundFetcher: public OnDemandSoundFetcher
360 std::set<std::string> m_fetched;
362 void paths_insert(std::set<std::string> &dst_paths,
363 const std::string &base,
364 const std::string &name)
366 dst_paths.insert(base + DIR_DELIM + "sounds" + DIR_DELIM + name + ".ogg");
367 dst_paths.insert(base + DIR_DELIM + "sounds" + DIR_DELIM + name + ".0.ogg");
368 dst_paths.insert(base + DIR_DELIM + "sounds" + DIR_DELIM + name + ".1.ogg");
369 dst_paths.insert(base + DIR_DELIM + "sounds" + DIR_DELIM + name + ".2.ogg");
370 dst_paths.insert(base + DIR_DELIM + "sounds" + DIR_DELIM + name + ".3.ogg");
371 dst_paths.insert(base + DIR_DELIM + "sounds" + DIR_DELIM + name + ".4.ogg");
372 dst_paths.insert(base + DIR_DELIM + "sounds" + DIR_DELIM + name + ".5.ogg");
373 dst_paths.insert(base + DIR_DELIM + "sounds" + DIR_DELIM + name + ".6.ogg");
374 dst_paths.insert(base + DIR_DELIM + "sounds" + DIR_DELIM + name + ".7.ogg");
375 dst_paths.insert(base + DIR_DELIM + "sounds" + DIR_DELIM + name + ".8.ogg");
376 dst_paths.insert(base + DIR_DELIM + "sounds" + DIR_DELIM + name + ".9.ogg");
379 void fetchSounds(const std::string &name,
380 std::set<std::string> &dst_paths,
381 std::set<std::string> &dst_datas)
383 if (m_fetched.count(name))
386 m_fetched.insert(name);
388 paths_insert(dst_paths, porting::path_share, name);
389 paths_insert(dst_paths, porting::path_user, name);
394 // before 1.8 there isn't a "integer interface", only float
395 #if (IRRLICHT_VERSION_MAJOR == 1 && IRRLICHT_VERSION_MINOR < 8)
396 typedef f32 SamplerLayer_t;
398 typedef s32 SamplerLayer_t;
402 class GameGlobalShaderConstantSetter : public IShaderConstantSetter
405 bool *m_force_fog_off;
408 CachedPixelShaderSetting<float, 4> m_sky_bg_color;
409 CachedPixelShaderSetting<float> m_fog_distance;
410 CachedVertexShaderSetting<float> m_animation_timer_vertex;
411 CachedPixelShaderSetting<float> m_animation_timer_pixel;
412 CachedPixelShaderSetting<float, 3> m_day_light;
413 CachedPixelShaderSetting<float, 3> m_eye_position_pixel;
414 CachedVertexShaderSetting<float, 3> m_eye_position_vertex;
415 CachedPixelShaderSetting<float, 3> m_minimap_yaw;
416 CachedPixelShaderSetting<SamplerLayer_t> m_base_texture;
417 CachedPixelShaderSetting<SamplerLayer_t> m_normal_texture;
418 CachedPixelShaderSetting<SamplerLayer_t> m_texture_flags;
422 void onSettingsChange(const std::string &name)
424 if (name == "enable_fog")
425 m_fog_enabled = g_settings->getBool("enable_fog");
428 static void settingsCallback(const std::string &name, void *userdata)
430 reinterpret_cast<GameGlobalShaderConstantSetter*>(userdata)->onSettingsChange(name);
433 void setSky(Sky *sky) { m_sky = sky; }
435 GameGlobalShaderConstantSetter(Sky *sky, bool *force_fog_off,
436 f32 *fog_range, Client *client) :
438 m_force_fog_off(force_fog_off),
439 m_fog_range(fog_range),
440 m_sky_bg_color("skyBgColor"),
441 m_fog_distance("fogDistance"),
442 m_animation_timer_vertex("animationTimer"),
443 m_animation_timer_pixel("animationTimer"),
444 m_day_light("dayLight"),
445 m_eye_position_pixel("eyePosition"),
446 m_eye_position_vertex("eyePosition"),
447 m_minimap_yaw("yawVec"),
448 m_base_texture("baseTexture"),
449 m_normal_texture("normalTexture"),
450 m_texture_flags("textureFlags"),
453 g_settings->registerChangedCallback("enable_fog", settingsCallback, this);
454 m_fog_enabled = g_settings->getBool("enable_fog");
457 ~GameGlobalShaderConstantSetter()
459 g_settings->deregisterChangedCallback("enable_fog", settingsCallback, this);
462 virtual void onSetConstants(video::IMaterialRendererServices *services,
469 video::SColor bgcolor = m_sky->getBgColor();
470 video::SColorf bgcolorf(bgcolor);
471 float bgcolorfa[4] = {
477 m_sky_bg_color.set(bgcolorfa, services);
480 float fog_distance = 10000 * BS;
482 if (m_fog_enabled && !*m_force_fog_off)
483 fog_distance = *m_fog_range;
485 m_fog_distance.set(&fog_distance, services);
487 u32 daynight_ratio = (float)m_client->getEnv().getDayNightRatio();
488 video::SColorf sunlight;
489 get_sunlight_color(&sunlight, daynight_ratio);
494 m_day_light.set(dnc, services);
496 u32 animation_timer = porting::getTimeMs() % 100000;
497 float animation_timer_f = (float)animation_timer / 100000.f;
498 m_animation_timer_vertex.set(&animation_timer_f, services);
499 m_animation_timer_pixel.set(&animation_timer_f, services);
501 float eye_position_array[3];
502 v3f epos = m_client->getEnv().getLocalPlayer()->getEyePosition();
503 #if (IRRLICHT_VERSION_MAJOR == 1 && IRRLICHT_VERSION_MINOR < 8)
504 eye_position_array[0] = epos.X;
505 eye_position_array[1] = epos.Y;
506 eye_position_array[2] = epos.Z;
508 epos.getAs3Values(eye_position_array);
510 m_eye_position_pixel.set(eye_position_array, services);
511 m_eye_position_vertex.set(eye_position_array, services);
513 if (m_client->getMinimap()) {
514 float minimap_yaw_array[3];
515 v3f minimap_yaw = m_client->getMinimap()->getYawVec();
516 #if (IRRLICHT_VERSION_MAJOR == 1 && IRRLICHT_VERSION_MINOR < 8)
517 minimap_yaw_array[0] = minimap_yaw.X;
518 minimap_yaw_array[1] = minimap_yaw.Y;
519 minimap_yaw_array[2] = minimap_yaw.Z;
521 minimap_yaw.getAs3Values(minimap_yaw_array);
523 m_minimap_yaw.set(minimap_yaw_array, services);
526 SamplerLayer_t base_tex = 0,
529 m_base_texture.set(&base_tex, services);
530 m_normal_texture.set(&normal_tex, services);
531 m_texture_flags.set(&flags_tex, services);
536 class GameGlobalShaderConstantSetterFactory : public IShaderConstantSetterFactory
539 bool *m_force_fog_off;
542 std::vector<GameGlobalShaderConstantSetter *> created_nosky;
544 GameGlobalShaderConstantSetterFactory(bool *force_fog_off,
545 f32 *fog_range, Client *client) :
547 m_force_fog_off(force_fog_off),
548 m_fog_range(fog_range),
552 void setSky(Sky *sky) {
554 for (GameGlobalShaderConstantSetter *ggscs : created_nosky) {
555 ggscs->setSky(m_sky);
557 created_nosky.clear();
560 virtual IShaderConstantSetter* create()
562 GameGlobalShaderConstantSetter *scs = new GameGlobalShaderConstantSetter(
563 m_sky, m_force_fog_off, m_fog_range, m_client);
565 created_nosky.push_back(scs);
571 #define SIZE_TAG "size[11,5.5]"
573 #define SIZE_TAG "size[11,5.5,true]" // Fixed size on desktop
576 /****************************************************************************
578 ****************************************************************************/
580 const float object_hit_delay = 0.2;
583 u32 last_time, busy_time, sleep_time;
587 /* The reason the following structs are not anonymous structs within the
588 * class is that they are not used by the majority of member functions and
589 * many functions that do require objects of thse types do not modify them
590 * (so they can be passed as a const qualified parameter)
596 PointedThing pointed_old;
600 bool digging_blocked;
602 bool update_wielded_item_trigger;
603 bool reset_jump_timer;
604 float nodig_delay_timer;
606 float dig_time_complete;
607 float repeat_rightclick_timer;
608 float object_hit_delay_timer;
609 float time_from_last_punch;
610 ClientActiveObject *selected_object;
614 float update_draw_list_timer;
618 v3f update_draw_list_last_cam_dir;
620 float time_of_day_smooth;
625 struct ClientEventHandler
627 void (Game::*handler)(ClientEvent *, CameraOrientation *);
630 /****************************************************************************
632 ****************************************************************************/
634 /* This is not intended to be a public class. If a public class becomes
635 * desirable then it may be better to create another 'wrapper' class that
636 * hides most of the stuff in this class (nothing in this class is required
637 * by any other file) but exposes the public methods/data only.
644 bool startup(bool *kill,
647 const std::string &map_dir,
648 const std::string &playername,
649 const std::string &password,
650 // If address is "", local server is used and address is updated
651 std::string *address,
653 std::string &error_message,
655 ChatBackend *chat_backend,
656 const SubgameSpec &gamespec, // Used for local game
657 bool simple_singleplayer_mode);
664 void extendedResourceCleanup();
666 // Basic initialisation
667 bool init(const std::string &map_dir, std::string *address,
669 const SubgameSpec &gamespec);
671 bool createSingleplayerServer(const std::string &map_dir,
672 const SubgameSpec &gamespec, u16 port, std::string *address);
675 bool createClient(const std::string &playername,
676 const std::string &password, std::string *address, u16 port);
680 bool connectToServer(const std::string &playername,
681 const std::string &password, std::string *address, u16 port,
682 bool *connect_ok, bool *aborted);
683 bool getServerContent(bool *aborted);
687 void updateInteractTimers(f32 dtime);
688 bool checkConnection();
689 bool handleCallbacks();
690 void processQueues();
691 void updateProfilers(const RunStats &stats, const FpsControl &draw_times, f32 dtime);
692 void updateStats(RunStats *stats, const FpsControl &draw_times, f32 dtime);
693 void updateProfilerGraphs(ProfilerGraph *graph);
696 void processUserInput(f32 dtime);
697 void processKeyInput();
698 void processItemSelection(u16 *new_playeritem);
700 void dropSelectedItem(bool single_item = false);
701 void openInventory();
702 void openConsole(float scale, const wchar_t *line=NULL);
703 void toggleFreeMove();
704 void toggleFreeMoveAlt();
705 void togglePitchMove();
708 void toggleCinematic();
709 void toggleAutoforward();
711 void toggleMinimap(bool shift_pressed);
714 void toggleUpdateCamera();
716 void increaseViewRange();
717 void decreaseViewRange();
718 void toggleFullViewRange();
719 void checkZoomEnabled();
721 void updateCameraDirection(CameraOrientation *cam, float dtime);
722 void updateCameraOrientation(CameraOrientation *cam, float dtime);
723 void updatePlayerControl(const CameraOrientation &cam);
724 void step(f32 *dtime);
725 void processClientEvents(CameraOrientation *cam);
726 void updateCamera(u32 busy_time, f32 dtime);
727 void updateSound(f32 dtime);
728 void processPlayerInteraction(f32 dtime, bool show_hud, bool show_debug);
730 * Returns the object or node the player is pointing at.
731 * Also updates the selected thing in the Hud.
733 * @param[in] shootline the shootline, starting from
734 * the camera position. This also gives the maximal distance
736 * @param[in] liquids_pointable if false, liquids are ignored
737 * @param[in] look_for_object if false, objects are ignored
738 * @param[in] camera_offset offset of the camera
739 * @param[out] selected_object the selected object or
742 PointedThing updatePointedThing(
743 const core::line3d<f32> &shootline, bool liquids_pointable,
744 bool look_for_object, const v3s16 &camera_offset);
745 void handlePointingAtNothing(const ItemStack &playerItem);
746 void handlePointingAtNode(const PointedThing &pointed,
747 const ItemStack &selected_item, const ItemStack &hand_item, f32 dtime);
748 void handlePointingAtObject(const PointedThing &pointed, const ItemStack &playeritem,
749 const v3f &player_position, bool show_debug);
750 void handleDigging(const PointedThing &pointed, const v3s16 &nodepos,
751 const ItemStack &selected_item, const ItemStack &hand_item, f32 dtime);
752 void updateFrame(ProfilerGraph *graph, RunStats *stats, f32 dtime,
753 const CameraOrientation &cam);
756 void limitFps(FpsControl *fps_timings, f32 *dtime);
758 void showOverlayMessage(const char *msg, float dtime, int percent,
759 bool draw_clouds = true);
761 static void settingChangedCallback(const std::string &setting_name, void *data);
764 inline bool isKeyDown(GameKeyType k)
766 return input->isKeyDown(k);
768 inline bool wasKeyDown(GameKeyType k)
770 return input->wasKeyDown(k);
774 void handleAndroidChatInput();
779 bool force_fog_off = false;
780 bool disable_camera_update = false;
783 void showDeathFormspec();
784 void showPauseMenu();
786 // ClientEvent handlers
787 void handleClientEvent_None(ClientEvent *event, CameraOrientation *cam);
788 void handleClientEvent_PlayerDamage(ClientEvent *event, CameraOrientation *cam);
789 void handleClientEvent_PlayerForceMove(ClientEvent *event, CameraOrientation *cam);
790 void handleClientEvent_Deathscreen(ClientEvent *event, CameraOrientation *cam);
791 void handleClientEvent_ShowFormSpec(ClientEvent *event, CameraOrientation *cam);
792 void handleClientEvent_ShowLocalFormSpec(ClientEvent *event, CameraOrientation *cam);
793 void handleClientEvent_HandleParticleEvent(ClientEvent *event,
794 CameraOrientation *cam);
795 void handleClientEvent_HudAdd(ClientEvent *event, CameraOrientation *cam);
796 void handleClientEvent_HudRemove(ClientEvent *event, CameraOrientation *cam);
797 void handleClientEvent_HudChange(ClientEvent *event, CameraOrientation *cam);
798 void handleClientEvent_SetSky(ClientEvent *event, CameraOrientation *cam);
799 void handleClientEvent_OverrideDayNigthRatio(ClientEvent *event,
800 CameraOrientation *cam);
801 void handleClientEvent_CloudParams(ClientEvent *event, CameraOrientation *cam);
803 void updateChat(f32 dtime, const v2u32 &screensize);
805 bool nodePlacementPrediction(const ItemDefinition &selected_def,
806 const ItemStack &selected_item, const v3s16 &nodepos, const v3s16 &neighbourpos);
807 static const ClientEventHandler clientEventHandler[CLIENTEVENT_MAX];
809 InputHandler *input = nullptr;
811 Client *client = nullptr;
812 Server *server = nullptr;
814 IWritableTextureSource *texture_src = nullptr;
815 IWritableShaderSource *shader_src = nullptr;
817 // When created, these will be filled with data received from the server
818 IWritableItemDefManager *itemdef_manager = nullptr;
819 NodeDefManager *nodedef_manager = nullptr;
821 GameOnDemandSoundFetcher soundfetcher; // useful when testing
822 ISoundManager *sound = nullptr;
823 bool sound_is_dummy = false;
824 SoundMaker *soundmaker = nullptr;
826 ChatBackend *chat_backend = nullptr;
828 EventManager *eventmgr = nullptr;
829 QuicktuneShortcutter *quicktune = nullptr;
830 bool registration_confirmation_shown = false;
832 std::unique_ptr<GameUI> m_game_ui;
833 GUIChatConsole *gui_chat_console = nullptr; // Free using ->Drop()
834 MapDrawControl *draw_control = nullptr;
835 Camera *camera = nullptr;
836 Clouds *clouds = nullptr; // Free using ->Drop()
837 Sky *sky = nullptr; // Free using ->Drop()
839 Minimap *mapper = nullptr;
845 This class does take ownership/responsibily for cleaning up etc of any of
846 these items (e.g. device)
848 IrrlichtDevice *device;
849 video::IVideoDriver *driver;
850 scene::ISceneManager *smgr;
852 std::string *error_message;
853 bool *reconnect_requested;
854 scene::ISceneNode *skybox;
857 bool simple_singleplayer_mode;
860 /* Pre-calculated values
862 int crack_animation_length;
864 IntervalLimiter profiler_interval;
867 * TODO: Local caching of settings is not optimal and should at some stage
868 * be updated to use a global settings object for getting thse values
869 * (as opposed to the this local caching). This can be addressed in
872 bool m_cache_doubletap_jump;
873 bool m_cache_enable_clouds;
874 bool m_cache_enable_joysticks;
875 bool m_cache_enable_particles;
876 bool m_cache_enable_fog;
877 bool m_cache_enable_noclip;
878 bool m_cache_enable_free_move;
879 f32 m_cache_mouse_sensitivity;
880 f32 m_cache_joystick_frustum_sensitivity;
881 f32 m_repeat_right_click_time;
882 f32 m_cache_cam_smoothing;
883 f32 m_cache_fog_start;
885 bool m_invert_mouse = false;
886 bool m_first_loop_after_window_activation = false;
887 bool m_camera_offset_changed = false;
889 bool m_does_lost_focus_pause_game = false;
892 bool m_cache_hold_aux1;
893 bool m_android_chat_open;
898 m_game_ui(new GameUI())
900 g_settings->registerChangedCallback("doubletap_jump",
901 &settingChangedCallback, this);
902 g_settings->registerChangedCallback("enable_clouds",
903 &settingChangedCallback, this);
904 g_settings->registerChangedCallback("doubletap_joysticks",
905 &settingChangedCallback, this);
906 g_settings->registerChangedCallback("enable_particles",
907 &settingChangedCallback, this);
908 g_settings->registerChangedCallback("enable_fog",
909 &settingChangedCallback, this);
910 g_settings->registerChangedCallback("mouse_sensitivity",
911 &settingChangedCallback, this);
912 g_settings->registerChangedCallback("joystick_frustum_sensitivity",
913 &settingChangedCallback, this);
914 g_settings->registerChangedCallback("repeat_rightclick_time",
915 &settingChangedCallback, this);
916 g_settings->registerChangedCallback("noclip",
917 &settingChangedCallback, this);
918 g_settings->registerChangedCallback("free_move",
919 &settingChangedCallback, this);
920 g_settings->registerChangedCallback("cinematic",
921 &settingChangedCallback, this);
922 g_settings->registerChangedCallback("cinematic_camera_smoothing",
923 &settingChangedCallback, this);
924 g_settings->registerChangedCallback("camera_smoothing",
925 &settingChangedCallback, this);
930 m_cache_hold_aux1 = false; // This is initialised properly later
937 /****************************************************************************
939 ****************************************************************************/
948 delete server; // deleted first to stop all server threads
956 delete nodedef_manager;
957 delete itemdef_manager;
960 extendedResourceCleanup();
962 g_settings->deregisterChangedCallback("doubletap_jump",
963 &settingChangedCallback, this);
964 g_settings->deregisterChangedCallback("enable_clouds",
965 &settingChangedCallback, this);
966 g_settings->deregisterChangedCallback("enable_particles",
967 &settingChangedCallback, this);
968 g_settings->deregisterChangedCallback("enable_fog",
969 &settingChangedCallback, this);
970 g_settings->deregisterChangedCallback("mouse_sensitivity",
971 &settingChangedCallback, this);
972 g_settings->deregisterChangedCallback("repeat_rightclick_time",
973 &settingChangedCallback, this);
974 g_settings->deregisterChangedCallback("noclip",
975 &settingChangedCallback, this);
976 g_settings->deregisterChangedCallback("free_move",
977 &settingChangedCallback, this);
978 g_settings->deregisterChangedCallback("cinematic",
979 &settingChangedCallback, this);
980 g_settings->deregisterChangedCallback("cinematic_camera_smoothing",
981 &settingChangedCallback, this);
982 g_settings->deregisterChangedCallback("camera_smoothing",
983 &settingChangedCallback, this);
986 bool Game::startup(bool *kill,
989 const std::string &map_dir,
990 const std::string &playername,
991 const std::string &password,
992 std::string *address, // can change if simple_singleplayer_mode
994 std::string &error_message,
996 ChatBackend *chat_backend,
997 const SubgameSpec &gamespec,
998 bool simple_singleplayer_mode)
1001 this->device = RenderingEngine::get_raw_device();
1003 this->error_message = &error_message;
1004 this->reconnect_requested = reconnect;
1005 this->random_input = random_input;
1006 this->input = input;
1007 this->chat_backend = chat_backend;
1008 this->simple_singleplayer_mode = simple_singleplayer_mode;
1010 input->keycache.populate();
1012 driver = device->getVideoDriver();
1013 smgr = RenderingEngine::get_scene_manager();
1015 RenderingEngine::get_scene_manager()->getParameters()->
1016 setAttribute(scene::OBJ_LOADER_IGNORE_MATERIAL_FILES, true);
1019 runData = GameRunData();
1020 runData.time_from_last_punch = 10.0;
1021 runData.update_wielded_item_trigger = true;
1023 m_game_ui->initFlags();
1025 m_invert_mouse = g_settings->getBool("invert_mouse");
1026 m_first_loop_after_window_activation = true;
1028 g_translations->clear();
1030 if (!init(map_dir, address, port, gamespec))
1033 if (!createClient(playername, password, address, port))
1036 RenderingEngine::initialize(client, hud);
1044 ProfilerGraph graph;
1045 RunStats stats = { 0 };
1046 CameraOrientation cam_view_target = { 0 };
1047 CameraOrientation cam_view = { 0 };
1048 FpsControl draw_times = { 0 };
1049 f32 dtime; // in seconds
1051 /* Clear the profiler */
1052 Profiler::GraphValues dummyvalues;
1053 g_profiler->graphGet(dummyvalues);
1055 draw_times.last_time = RenderingEngine::get_timer_time();
1057 set_light_table(g_settings->getFloat("display_gamma"));
1060 m_cache_hold_aux1 = g_settings->getBool("fast_move")
1061 && client->checkPrivilege("fast");
1064 irr::core::dimension2d<u32> previous_screen_size(g_settings->getU16("screen_w"),
1065 g_settings->getU16("screen_h"));
1067 while (RenderingEngine::run()
1068 && !(*kill || g_gamecallback->shutdown_requested
1069 || (server && server->isShutdownRequested()))) {
1071 const irr::core::dimension2d<u32> ¤t_screen_size =
1072 RenderingEngine::get_video_driver()->getScreenSize();
1073 // Verify if window size has changed and save it if it's the case
1074 // Ensure evaluating settings->getBool after verifying screensize
1075 // First condition is cheaper
1076 if (previous_screen_size != current_screen_size &&
1077 current_screen_size != irr::core::dimension2d<u32>(0,0) &&
1078 g_settings->getBool("autosave_screensize")) {
1079 g_settings->setU16("screen_w", current_screen_size.Width);
1080 g_settings->setU16("screen_h", current_screen_size.Height);
1081 previous_screen_size = current_screen_size;
1084 // Calculate dtime =
1085 // RenderingEngine::run() from this iteration
1086 // + Sleep time until the wanted FPS are reached
1087 limitFps(&draw_times, &dtime);
1089 // Prepare render data for next iteration
1091 updateStats(&stats, draw_times, dtime);
1092 updateInteractTimers(dtime);
1094 if (!checkConnection())
1096 if (!handleCallbacks())
1101 m_game_ui->clearInfoText();
1102 hud->resizeHotbar();
1104 updateProfilers(stats, draw_times, dtime);
1105 processUserInput(dtime);
1106 // Update camera before player movement to avoid camera lag of one frame
1107 updateCameraDirection(&cam_view_target, dtime);
1108 cam_view.camera_yaw += (cam_view_target.camera_yaw -
1109 cam_view.camera_yaw) * m_cache_cam_smoothing;
1110 cam_view.camera_pitch += (cam_view_target.camera_pitch -
1111 cam_view.camera_pitch) * m_cache_cam_smoothing;
1112 updatePlayerControl(cam_view);
1114 processClientEvents(&cam_view_target);
1115 updateCamera(draw_times.busy_time, dtime);
1117 processPlayerInteraction(dtime, m_game_ui->m_flags.show_hud,
1118 m_game_ui->m_flags.show_debug);
1119 updateFrame(&graph, &stats, dtime, cam_view);
1120 updateProfilerGraphs(&graph);
1122 // Update if minimap has been disabled by the server
1123 m_game_ui->m_flags.show_minimap &= client->shouldShowMinimap();
1125 if (m_does_lost_focus_pause_game && !device->isWindowFocused() && !isMenuActive()) {
1132 void Game::shutdown()
1134 RenderingEngine::finalize();
1135 #if IRRLICHT_VERSION_MAJOR == 1 && IRRLICHT_VERSION_MINOR <= 8
1136 if (g_settings->get("3d_mode") == "pageflip") {
1137 driver->setRenderTarget(irr::video::ERT_STEREO_BOTH_BUFFERS);
1140 auto formspec = m_game_ui->getFormspecGUI();
1142 formspec->quitMenu();
1144 showOverlayMessage(N_("Shutting down..."), 0, 0, false);
1149 if (gui_chat_console)
1150 gui_chat_console->drop();
1156 while (g_menumgr.menuCount() > 0) {
1157 g_menumgr.m_stack.front()->setVisible(false);
1158 g_menumgr.deletingMenu(g_menumgr.m_stack.front());
1161 m_game_ui->deleteFormspec();
1163 chat_backend->addMessage(L"", L"# Disconnected.");
1164 chat_backend->addMessage(L"", L"");
1168 while (!client->isShutdown()) {
1169 assert(texture_src != NULL);
1170 assert(shader_src != NULL);
1171 texture_src->processQueue();
1172 shader_src->processQueue();
1179 /****************************************************************************/
1180 /****************************************************************************
1182 ****************************************************************************/
1183 /****************************************************************************/
1186 const std::string &map_dir,
1187 std::string *address,
1189 const SubgameSpec &gamespec)
1191 texture_src = createTextureSource();
1193 showOverlayMessage(N_("Loading..."), 0, 0);
1195 shader_src = createShaderSource();
1197 itemdef_manager = createItemDefManager();
1198 nodedef_manager = createNodeDefManager();
1200 eventmgr = new EventManager();
1201 quicktune = new QuicktuneShortcutter();
1203 if (!(texture_src && shader_src && itemdef_manager && nodedef_manager
1204 && eventmgr && quicktune))
1210 // Create a server if not connecting to an existing one
1211 if (address->empty()) {
1212 if (!createSingleplayerServer(map_dir, gamespec, port, address))
1219 bool Game::initSound()
1222 if (g_settings->getBool("enable_sound")) {
1223 infostream << "Attempting to use OpenAL audio" << std::endl;
1224 sound = createOpenALSoundManager(g_sound_manager_singleton.get(), &soundfetcher);
1226 infostream << "Failed to initialize OpenAL audio" << std::endl;
1228 infostream << "Sound disabled." << std::endl;
1232 infostream << "Using dummy audio." << std::endl;
1233 sound = &dummySoundManager;
1234 sound_is_dummy = true;
1237 soundmaker = new SoundMaker(sound, nodedef_manager);
1241 soundmaker->registerReceiver(eventmgr);
1246 bool Game::createSingleplayerServer(const std::string &map_dir,
1247 const SubgameSpec &gamespec, u16 port, std::string *address)
1249 showOverlayMessage(N_("Creating server..."), 0, 5);
1251 std::string bind_str = g_settings->get("bind_address");
1252 Address bind_addr(0, 0, 0, 0, port);
1254 if (g_settings->getBool("ipv6_server")) {
1255 bind_addr.setAddress((IPv6AddressBytes *) NULL);
1259 bind_addr.Resolve(bind_str.c_str());
1260 } catch (ResolveError &e) {
1261 infostream << "Resolving bind address \"" << bind_str
1262 << "\" failed: " << e.what()
1263 << " -- Listening on all addresses." << std::endl;
1266 if (bind_addr.isIPv6() && !g_settings->getBool("enable_ipv6")) {
1267 *error_message = "Unable to listen on " +
1268 bind_addr.serializeString() +
1269 " because IPv6 is disabled";
1270 errorstream << *error_message << std::endl;
1274 server = new Server(map_dir, gamespec, simple_singleplayer_mode, bind_addr, false);
1281 bool Game::createClient(const std::string &playername,
1282 const std::string &password, std::string *address, u16 port)
1284 showOverlayMessage(N_("Creating client..."), 0, 10);
1286 draw_control = new MapDrawControl;
1290 bool could_connect, connect_aborted;
1291 #ifdef HAVE_TOUCHSCREENGUI
1292 if (g_touchscreengui) {
1293 g_touchscreengui->init(texture_src);
1294 g_touchscreengui->hide();
1297 if (!connectToServer(playername, password, address, port,
1298 &could_connect, &connect_aborted))
1301 if (!could_connect) {
1302 if (error_message->empty() && !connect_aborted) {
1303 // Should not happen if error messages are set properly
1304 *error_message = "Connection failed for unknown reason";
1305 errorstream << *error_message << std::endl;
1310 if (!getServerContent(&connect_aborted)) {
1311 if (error_message->empty() && !connect_aborted) {
1312 // Should not happen if error messages are set properly
1313 *error_message = "Connection failed for unknown reason";
1314 errorstream << *error_message << std::endl;
1319 GameGlobalShaderConstantSetterFactory *scsf = new GameGlobalShaderConstantSetterFactory(
1320 &m_flags.force_fog_off, &runData.fog_range, client);
1321 shader_src->addShaderConstantSetterFactory(scsf);
1323 // Update cached textures, meshes and materials
1324 client->afterContentReceived();
1328 camera = new Camera(*draw_control, client);
1329 if (!camera || !camera->successfullyCreated(*error_message))
1331 client->setCamera(camera);
1335 if (m_cache_enable_clouds) {
1336 clouds = new Clouds(smgr, -1, time(0));
1338 *error_message = "Memory allocation error (clouds)";
1339 errorstream << *error_message << std::endl;
1346 sky = new Sky(-1, texture_src);
1348 skybox = NULL; // This is used/set later on in the main run loop
1351 *error_message = "Memory allocation error sky";
1352 errorstream << *error_message << std::endl;
1356 /* Pre-calculated values
1358 video::ITexture *t = texture_src->getTexture("crack_anylength.png");
1360 v2u32 size = t->getOriginalSize();
1361 crack_animation_length = size.Y / size.X;
1363 crack_animation_length = 5;
1369 /* Set window caption
1371 std::wstring str = utf8_to_wide(PROJECT_NAME_C);
1373 str += utf8_to_wide(g_version_hash);
1375 str += driver->getName();
1377 device->setWindowCaption(str.c_str());
1379 LocalPlayer *player = client->getEnv().getLocalPlayer();
1380 player->hurt_tilt_timer = 0;
1381 player->hurt_tilt_strength = 0;
1383 hud = new Hud(guienv, client, player, &player->inventory);
1386 *error_message = "Memory error: could not create HUD";
1387 errorstream << *error_message << std::endl;
1391 mapper = client->getMinimap();
1393 mapper->setMinimapMode(MINIMAP_MODE_OFF);
1398 bool Game::initGui()
1402 // Remove stale "recent" chat messages from previous connections
1403 chat_backend->clearRecentChat();
1405 // Make sure the size of the recent messages buffer is right
1406 chat_backend->applySettings();
1408 // Chat backend and console
1409 gui_chat_console = new GUIChatConsole(guienv, guienv->getRootGUIElement(),
1410 -1, chat_backend, client, &g_menumgr);
1411 if (!gui_chat_console) {
1412 *error_message = "Could not allocate memory for chat console";
1413 errorstream << *error_message << std::endl;
1417 #ifdef HAVE_TOUCHSCREENGUI
1419 if (g_touchscreengui)
1420 g_touchscreengui->show();
1427 bool Game::connectToServer(const std::string &playername,
1428 const std::string &password, std::string *address, u16 port,
1429 bool *connect_ok, bool *connection_aborted)
1431 *connect_ok = false; // Let's not be overly optimistic
1432 *connection_aborted = false;
1433 bool local_server_mode = false;
1435 showOverlayMessage(N_("Resolving address..."), 0, 15);
1437 Address connect_address(0, 0, 0, 0, port);
1440 connect_address.Resolve(address->c_str());
1442 if (connect_address.isZero()) { // i.e. INADDR_ANY, IN6ADDR_ANY
1443 //connect_address.Resolve("localhost");
1444 if (connect_address.isIPv6()) {
1445 IPv6AddressBytes addr_bytes;
1446 addr_bytes.bytes[15] = 1;
1447 connect_address.setAddress(&addr_bytes);
1449 connect_address.setAddress(127, 0, 0, 1);
1451 local_server_mode = true;
1453 } catch (ResolveError &e) {
1454 *error_message = std::string("Couldn't resolve address: ") + e.what();
1455 errorstream << *error_message << std::endl;
1459 if (connect_address.isIPv6() && !g_settings->getBool("enable_ipv6")) {
1460 *error_message = "Unable to connect to " +
1461 connect_address.serializeString() +
1462 " because IPv6 is disabled";
1463 errorstream << *error_message << std::endl;
1467 client = new Client(playername.c_str(), password, *address,
1468 *draw_control, texture_src, shader_src,
1469 itemdef_manager, nodedef_manager, sound, eventmgr,
1470 connect_address.isIPv6(), m_game_ui.get());
1475 client->m_simple_singleplayer_mode = simple_singleplayer_mode;
1477 infostream << "Connecting to server at ";
1478 connect_address.print(&infostream);
1479 infostream << std::endl;
1481 client->connect(connect_address,
1482 simple_singleplayer_mode || local_server_mode);
1485 Wait for server to accept connection
1491 FpsControl fps_control = { 0 };
1493 f32 wait_time = 0; // in seconds
1495 fps_control.last_time = RenderingEngine::get_timer_time();
1497 while (RenderingEngine::run()) {
1499 limitFps(&fps_control, &dtime);
1501 // Update client and server
1502 client->step(dtime);
1505 server->step(dtime);
1508 if (client->getState() == LC_Init) {
1514 if (*connection_aborted)
1517 if (client->accessDenied()) {
1518 *error_message = "Access denied. Reason: "
1519 + client->accessDeniedReason();
1520 *reconnect_requested = client->reconnectRequested();
1521 errorstream << *error_message << std::endl;
1525 if (input->cancelPressed()) {
1526 *connection_aborted = true;
1527 infostream << "Connect aborted [Escape]" << std::endl;
1531 if (client->m_is_registration_confirmation_state) {
1532 if (registration_confirmation_shown) {
1533 // Keep drawing the GUI
1534 RenderingEngine::draw_menu_scene(guienv, dtime, true);
1536 registration_confirmation_shown = true;
1537 (new GUIConfirmRegistration(guienv, guienv->getRootGUIElement(), -1,
1538 &g_menumgr, client, playername, password, connection_aborted))->drop();
1542 // Only time out if we aren't waiting for the server we started
1543 if (!address->empty() && wait_time > 10) {
1544 *error_message = "Connection timed out.";
1545 errorstream << *error_message << std::endl;
1550 showOverlayMessage(N_("Connecting to server..."), dtime, 20);
1553 } catch (con::PeerNotFoundException &e) {
1554 // TODO: Should something be done here? At least an info/error
1562 bool Game::getServerContent(bool *aborted)
1566 FpsControl fps_control = { 0 };
1567 f32 dtime; // in seconds
1569 fps_control.last_time = RenderingEngine::get_timer_time();
1571 while (RenderingEngine::run()) {
1573 limitFps(&fps_control, &dtime);
1575 // Update client and server
1576 client->step(dtime);
1579 server->step(dtime);
1582 if (client->mediaReceived() && client->itemdefReceived() &&
1583 client->nodedefReceived()) {
1588 if (!checkConnection())
1591 if (client->getState() < LC_Init) {
1592 *error_message = "Client disconnected";
1593 errorstream << *error_message << std::endl;
1597 if (input->cancelPressed()) {
1599 infostream << "Connect aborted [Escape]" << std::endl;
1606 if (!client->itemdefReceived()) {
1607 const wchar_t *text = wgettext("Item definitions...");
1609 RenderingEngine::draw_load_screen(text, guienv, texture_src,
1612 } else if (!client->nodedefReceived()) {
1613 const wchar_t *text = wgettext("Node definitions...");
1615 RenderingEngine::draw_load_screen(text, guienv, texture_src,
1619 std::stringstream message;
1620 std::fixed(message);
1621 message.precision(0);
1622 message << gettext("Media...") << " " << (client->mediaReceiveProgress()*100) << "%";
1623 message.precision(2);
1625 if ((USE_CURL == 0) ||
1626 (!g_settings->getBool("enable_remote_media_server"))) {
1627 float cur = client->getCurRate();
1628 std::string cur_unit = gettext("KiB/s");
1632 cur_unit = gettext("MiB/s");
1635 message << " (" << cur << ' ' << cur_unit << ")";
1638 progress = 30 + client->mediaReceiveProgress() * 35 + 0.5;
1639 RenderingEngine::draw_load_screen(utf8_to_wide(message.str()), guienv,
1640 texture_src, dtime, progress);
1648 /****************************************************************************/
1649 /****************************************************************************
1651 ****************************************************************************/
1652 /****************************************************************************/
1654 inline void Game::updateInteractTimers(f32 dtime)
1656 if (runData.nodig_delay_timer >= 0)
1657 runData.nodig_delay_timer -= dtime;
1659 if (runData.object_hit_delay_timer >= 0)
1660 runData.object_hit_delay_timer -= dtime;
1662 runData.time_from_last_punch += dtime;
1666 /* returns false if game should exit, otherwise true
1668 inline bool Game::checkConnection()
1670 if (client->accessDenied()) {
1671 *error_message = "Access denied. Reason: "
1672 + client->accessDeniedReason();
1673 *reconnect_requested = client->reconnectRequested();
1674 errorstream << *error_message << std::endl;
1682 /* returns false if game should exit, otherwise true
1684 inline bool Game::handleCallbacks()
1686 if (g_gamecallback->disconnect_requested) {
1687 g_gamecallback->disconnect_requested = false;
1691 if (g_gamecallback->changepassword_requested) {
1692 (new GUIPasswordChange(guienv, guiroot, -1,
1693 &g_menumgr, client))->drop();
1694 g_gamecallback->changepassword_requested = false;
1697 if (g_gamecallback->changevolume_requested) {
1698 (new GUIVolumeChange(guienv, guiroot, -1,
1699 &g_menumgr))->drop();
1700 g_gamecallback->changevolume_requested = false;
1703 if (g_gamecallback->keyconfig_requested) {
1704 (new GUIKeyChangeMenu(guienv, guiroot, -1,
1705 &g_menumgr))->drop();
1706 g_gamecallback->keyconfig_requested = false;
1709 if (g_gamecallback->keyconfig_changed) {
1710 input->keycache.populate(); // update the cache with new settings
1711 g_gamecallback->keyconfig_changed = false;
1718 void Game::processQueues()
1720 texture_src->processQueue();
1721 itemdef_manager->processQueue(client);
1722 shader_src->processQueue();
1726 void Game::updateProfilers(const RunStats &stats, const FpsControl &draw_times,
1729 float profiler_print_interval =
1730 g_settings->getFloat("profiler_print_interval");
1731 bool print_to_log = true;
1733 if (profiler_print_interval == 0) {
1734 print_to_log = false;
1735 profiler_print_interval = 3;
1738 if (profiler_interval.step(dtime, profiler_print_interval)) {
1740 infostream << "Profiler:" << std::endl;
1741 g_profiler->print(infostream);
1744 m_game_ui->updateProfiler();
1745 g_profiler->clear();
1748 // Update update graphs
1749 g_profiler->graphAdd("Time non-rendering [ms]",
1750 draw_times.busy_time - stats.drawtime);
1752 g_profiler->graphAdd("Sleep [ms]", draw_times.sleep_time);
1753 g_profiler->graphAdd("FPS", 1.0f / dtime);
1756 void Game::updateStats(RunStats *stats, const FpsControl &draw_times,
1763 /* Time average and jitter calculation
1765 jp = &stats->dtime_jitter;
1766 jp->avg = jp->avg * 0.96 + dtime * 0.04;
1768 jitter = dtime - jp->avg;
1770 if (jitter > jp->max)
1773 jp->counter += dtime;
1775 if (jp->counter > 0.0) {
1777 jp->max_sample = jp->max;
1778 jp->max_fraction = jp->max_sample / (jp->avg + 0.001);
1782 /* Busytime average and jitter calculation
1784 jp = &stats->busy_time_jitter;
1785 jp->avg = jp->avg + draw_times.busy_time * 0.02;
1787 jitter = draw_times.busy_time - jp->avg;
1789 if (jitter > jp->max)
1791 if (jitter < jp->min)
1794 jp->counter += dtime;
1796 if (jp->counter > 0.0) {
1798 jp->max_sample = jp->max;
1799 jp->min_sample = jp->min;
1807 /****************************************************************************
1809 ****************************************************************************/
1811 void Game::processUserInput(f32 dtime)
1813 // Reset input if window not active or some menu is active
1814 if (!device->isWindowActive() || isMenuActive() || guienv->hasFocus(gui_chat_console)) {
1816 #ifdef HAVE_TOUCHSCREENGUI
1817 g_touchscreengui->hide();
1820 #ifdef HAVE_TOUCHSCREENGUI
1821 else if (g_touchscreengui) {
1822 /* on touchscreengui step may generate own input events which ain't
1823 * what we want in case we just did clear them */
1824 g_touchscreengui->step(dtime);
1828 if (!guienv->hasFocus(gui_chat_console) && gui_chat_console->isOpen()) {
1829 gui_chat_console->closeConsoleAtOnce();
1832 // Input handler step() (used by the random input generator)
1836 auto formspec = m_game_ui->getFormspecGUI();
1838 formspec->getAndroidUIInput();
1840 handleAndroidChatInput();
1843 // Increase timer for double tap of "keymap_jump"
1844 if (m_cache_doubletap_jump && runData.jump_timer <= 0.2f)
1845 runData.jump_timer += dtime;
1848 processItemSelection(&runData.new_playeritem);
1852 void Game::processKeyInput()
1854 if (wasKeyDown(KeyType::DROP)) {
1855 dropSelectedItem(isKeyDown(KeyType::SNEAK));
1856 } else if (wasKeyDown(KeyType::AUTOFORWARD)) {
1857 toggleAutoforward();
1858 } else if (wasKeyDown(KeyType::BACKWARD)) {
1859 if (g_settings->getBool("continuous_forward"))
1860 toggleAutoforward();
1861 } else if (wasKeyDown(KeyType::INVENTORY)) {
1863 } else if (input->cancelPressed()) {
1865 m_android_chat_open = false;
1867 if (!gui_chat_console->isOpenInhibited()) {
1870 } else if (wasKeyDown(KeyType::CHAT)) {
1871 openConsole(0.2, L"");
1872 } else if (wasKeyDown(KeyType::CMD)) {
1873 openConsole(0.2, L"/");
1874 } else if (wasKeyDown(KeyType::CMD_LOCAL)) {
1875 if (client->moddingEnabled())
1876 openConsole(0.2, L".");
1878 m_game_ui->showStatusText(wgettext("Client side scripting is disabled"));
1879 } else if (wasKeyDown(KeyType::CONSOLE)) {
1880 openConsole(core::clamp(g_settings->getFloat("console_height"), 0.1f, 1.0f));
1881 } else if (wasKeyDown(KeyType::FREEMOVE)) {
1883 } else if (wasKeyDown(KeyType::JUMP)) {
1884 toggleFreeMoveAlt();
1885 } else if (wasKeyDown(KeyType::PITCHMOVE)) {
1887 } else if (wasKeyDown(KeyType::FASTMOVE)) {
1889 } else if (wasKeyDown(KeyType::NOCLIP)) {
1891 } else if (wasKeyDown(KeyType::MUTE)) {
1892 bool new_mute_sound = !g_settings->getBool("mute_sound");
1893 g_settings->setBool("mute_sound", new_mute_sound);
1895 m_game_ui->showTranslatedStatusText("Sound muted");
1897 m_game_ui->showTranslatedStatusText("Sound unmuted");
1898 } else if (wasKeyDown(KeyType::INC_VOLUME)) {
1899 float new_volume = rangelim(g_settings->getFloat("sound_volume") + 0.1f, 0.0f, 1.0f);
1901 g_settings->setFloat("sound_volume", new_volume);
1902 const wchar_t *str = wgettext("Volume changed to %d%%");
1903 swprintf(buf, sizeof(buf) / sizeof(wchar_t), str, myround(new_volume * 100));
1905 m_game_ui->showStatusText(buf);
1906 } else if (wasKeyDown(KeyType::DEC_VOLUME)) {
1907 float new_volume = rangelim(g_settings->getFloat("sound_volume") - 0.1f, 0.0f, 1.0f);
1909 g_settings->setFloat("sound_volume", new_volume);
1910 const wchar_t *str = wgettext("Volume changed to %d%%");
1911 swprintf(buf, sizeof(buf) / sizeof(wchar_t), str, myround(new_volume * 100));
1913 m_game_ui->showStatusText(buf);
1914 } else if (wasKeyDown(KeyType::CINEMATIC)) {
1916 } else if (wasKeyDown(KeyType::SCREENSHOT)) {
1917 client->makeScreenshot();
1918 } else if (wasKeyDown(KeyType::TOGGLE_HUD)) {
1919 m_game_ui->toggleHud();
1920 } else if (wasKeyDown(KeyType::MINIMAP)) {
1921 toggleMinimap(isKeyDown(KeyType::SNEAK));
1922 } else if (wasKeyDown(KeyType::TOGGLE_CHAT)) {
1923 m_game_ui->toggleChat();
1924 } else if (wasKeyDown(KeyType::TOGGLE_FOG)) {
1926 } else if (wasKeyDown(KeyType::TOGGLE_UPDATE_CAMERA)) {
1927 toggleUpdateCamera();
1928 } else if (wasKeyDown(KeyType::TOGGLE_DEBUG)) {
1930 } else if (wasKeyDown(KeyType::TOGGLE_PROFILER)) {
1931 m_game_ui->toggleProfiler();
1932 } else if (wasKeyDown(KeyType::INCREASE_VIEWING_RANGE)) {
1933 increaseViewRange();
1934 } else if (wasKeyDown(KeyType::DECREASE_VIEWING_RANGE)) {
1935 decreaseViewRange();
1936 } else if (wasKeyDown(KeyType::RANGESELECT)) {
1937 toggleFullViewRange();
1938 } else if (wasKeyDown(KeyType::ZOOM)) {
1940 } else if (wasKeyDown(KeyType::QUICKTUNE_NEXT)) {
1942 } else if (wasKeyDown(KeyType::QUICKTUNE_PREV)) {
1944 } else if (wasKeyDown(KeyType::QUICKTUNE_INC)) {
1946 } else if (wasKeyDown(KeyType::QUICKTUNE_DEC)) {
1950 if (!isKeyDown(KeyType::JUMP) && runData.reset_jump_timer) {
1951 runData.reset_jump_timer = false;
1952 runData.jump_timer = 0.0f;
1955 if (quicktune->hasMessage()) {
1956 m_game_ui->showStatusText(utf8_to_wide(quicktune->getMessage()));
1960 void Game::processItemSelection(u16 *new_playeritem)
1962 LocalPlayer *player = client->getEnv().getLocalPlayer();
1964 /* Item selection using mouse wheel
1966 *new_playeritem = player->getWieldIndex();
1968 s32 wheel = input->getMouseWheel();
1969 u16 max_item = MYMIN(PLAYER_INVENTORY_SIZE - 1,
1970 player->hud_hotbar_itemcount - 1);
1974 if (input->joystick.wasKeyDown(KeyType::SCROLL_DOWN) ||
1975 wasKeyDown(KeyType::HOTBAR_NEXT)) {
1979 if (input->joystick.wasKeyDown(KeyType::SCROLL_UP) ||
1980 wasKeyDown(KeyType::HOTBAR_PREV)) {
1985 *new_playeritem = *new_playeritem < max_item ? *new_playeritem + 1 : 0;
1987 *new_playeritem = *new_playeritem > 0 ? *new_playeritem - 1 : max_item;
1990 /* Item selection using hotbar slot keys
1992 for (u16 i = 0; i <= max_item; i++) {
1993 if (wasKeyDown((GameKeyType) (KeyType::SLOT_1 + i))) {
1994 *new_playeritem = i;
1995 infostream << "Selected item: " << new_playeritem << std::endl;
2002 void Game::dropSelectedItem(bool single_item)
2004 IDropAction *a = new IDropAction();
2005 a->count = single_item ? 1 : 0;
2006 a->from_inv.setCurrentPlayer();
2007 a->from_list = "main";
2008 a->from_i = client->getEnv().getLocalPlayer()->getWieldIndex();
2009 client->inventoryAction(a);
2013 void Game::openInventory()
2016 * Don't permit to open inventory is CAO or player doesn't exists.
2017 * This prevent showing an empty inventory at player load
2020 LocalPlayer *player = client->getEnv().getLocalPlayer();
2021 if (!player || !player->getCAO())
2024 infostream << "the_game: " << "Launching inventory" << std::endl;
2026 PlayerInventoryFormSource *fs_src = new PlayerInventoryFormSource(client);
2028 InventoryLocation inventoryloc;
2029 inventoryloc.setCurrentPlayer();
2031 if (!client->moddingEnabled()
2032 || !client->getScript()->on_inventory_open(fs_src->m_client->getInventory(inventoryloc))) {
2033 TextDest *txt_dst = new TextDestPlayerInventory(client);
2034 auto *&formspec = m_game_ui->updateFormspec("");
2035 GUIFormSpecMenu::create(formspec, client, &input->joystick, fs_src,
2036 txt_dst, client->getFormspecPrepend());
2038 formspec->setFormSpec(fs_src->getForm(), inventoryloc);
2043 void Game::openConsole(float scale, const wchar_t *line)
2045 assert(scale > 0.0f && scale <= 1.0f);
2048 porting::showInputDialog(gettext("ok"), "", "", 2);
2049 m_android_chat_open = true;
2051 if (gui_chat_console->isOpenInhibited())
2053 gui_chat_console->openConsole(scale);
2055 gui_chat_console->setCloseOnEnter(true);
2056 gui_chat_console->replaceAndAddToHistory(line);
2062 void Game::handleAndroidChatInput()
2064 if (m_android_chat_open && porting::getInputDialogState() == 0) {
2065 std::string text = porting::getInputDialogValue();
2066 client->typeChatMessage(utf8_to_wide(text));
2067 m_android_chat_open = false;
2073 void Game::toggleFreeMove()
2075 bool free_move = !g_settings->getBool("free_move");
2076 g_settings->set("free_move", bool_to_cstr(free_move));
2079 if (client->checkPrivilege("fly")) {
2080 m_game_ui->showTranslatedStatusText("Fly mode enabled");
2082 m_game_ui->showTranslatedStatusText("Fly mode enabled (note: no 'fly' privilege)");
2085 m_game_ui->showTranslatedStatusText("Fly mode disabled");
2089 void Game::toggleFreeMoveAlt()
2091 if (m_cache_doubletap_jump && runData.jump_timer < 0.2f)
2094 runData.reset_jump_timer = true;
2098 void Game::togglePitchMove()
2100 bool pitch_move = !g_settings->getBool("pitch_move");
2101 g_settings->set("pitch_move", bool_to_cstr(pitch_move));
2104 m_game_ui->showTranslatedStatusText("Pitch move mode enabled");
2106 m_game_ui->showTranslatedStatusText("Pitch move mode disabled");
2111 void Game::toggleFast()
2113 bool fast_move = !g_settings->getBool("fast_move");
2114 bool has_fast_privs = client->checkPrivilege("fast");
2115 g_settings->set("fast_move", bool_to_cstr(fast_move));
2118 if (has_fast_privs) {
2119 m_game_ui->showTranslatedStatusText("Fast mode enabled");
2121 m_game_ui->showTranslatedStatusText("Fast mode enabled (note: no 'fast' privilege)");
2124 m_game_ui->showTranslatedStatusText("Fast mode disabled");
2128 m_cache_hold_aux1 = fast_move && has_fast_privs;
2133 void Game::toggleNoClip()
2135 bool noclip = !g_settings->getBool("noclip");
2136 g_settings->set("noclip", bool_to_cstr(noclip));
2139 if (client->checkPrivilege("noclip")) {
2140 m_game_ui->showTranslatedStatusText("Noclip mode enabled");
2142 m_game_ui->showTranslatedStatusText("Noclip mode enabled (note: no 'noclip' privilege)");
2145 m_game_ui->showTranslatedStatusText("Noclip mode disabled");
2149 void Game::toggleCinematic()
2151 bool cinematic = !g_settings->getBool("cinematic");
2152 g_settings->set("cinematic", bool_to_cstr(cinematic));
2155 m_game_ui->showTranslatedStatusText("Cinematic mode enabled");
2157 m_game_ui->showTranslatedStatusText("Cinematic mode disabled");
2160 // Autoforward by toggling continuous forward.
2161 void Game::toggleAutoforward()
2163 bool autorun_enabled = !g_settings->getBool("continuous_forward");
2164 g_settings->set("continuous_forward", bool_to_cstr(autorun_enabled));
2166 if (autorun_enabled)
2167 m_game_ui->showTranslatedStatusText("Automatic forward enabled");
2169 m_game_ui->showTranslatedStatusText("Automatic forward disabled");
2172 void Game::toggleMinimap(bool shift_pressed)
2174 if (!mapper || !m_game_ui->m_flags.show_hud || !g_settings->getBool("enable_minimap"))
2177 if (shift_pressed) {
2178 mapper->toggleMinimapShape();
2182 u32 hud_flags = client->getEnv().getLocalPlayer()->hud_flags;
2184 MinimapMode mode = MINIMAP_MODE_OFF;
2185 if (hud_flags & HUD_FLAG_MINIMAP_VISIBLE) {
2186 mode = mapper->getMinimapMode();
2187 mode = (MinimapMode)((int)mode + 1);
2188 // If radar is disabled and in, or switching to, radar mode
2189 if (!(hud_flags & HUD_FLAG_MINIMAP_RADAR_VISIBLE) && mode > 3)
2190 mode = MINIMAP_MODE_OFF;
2193 m_game_ui->m_flags.show_minimap = true;
2195 case MINIMAP_MODE_SURFACEx1:
2196 m_game_ui->showTranslatedStatusText("Minimap in surface mode, Zoom x1");
2198 case MINIMAP_MODE_SURFACEx2:
2199 m_game_ui->showTranslatedStatusText("Minimap in surface mode, Zoom x2");
2201 case MINIMAP_MODE_SURFACEx4:
2202 m_game_ui->showTranslatedStatusText("Minimap in surface mode, Zoom x4");
2204 case MINIMAP_MODE_RADARx1:
2205 m_game_ui->showTranslatedStatusText("Minimap in radar mode, Zoom x1");
2207 case MINIMAP_MODE_RADARx2:
2208 m_game_ui->showTranslatedStatusText("Minimap in radar mode, Zoom x2");
2210 case MINIMAP_MODE_RADARx4:
2211 m_game_ui->showTranslatedStatusText("Minimap in radar mode, Zoom x4");
2214 mode = MINIMAP_MODE_OFF;
2215 m_game_ui->m_flags.show_minimap = false;
2216 if (hud_flags & HUD_FLAG_MINIMAP_VISIBLE)
2217 m_game_ui->showTranslatedStatusText("Minimap hidden");
2219 m_game_ui->showTranslatedStatusText("Minimap currently disabled by game or mod");
2222 mapper->setMinimapMode(mode);
2225 void Game::toggleFog()
2227 bool fog_enabled = g_settings->getBool("enable_fog");
2228 g_settings->setBool("enable_fog", !fog_enabled);
2230 m_game_ui->showTranslatedStatusText("Fog disabled");
2232 m_game_ui->showTranslatedStatusText("Fog enabled");
2236 void Game::toggleDebug()
2238 // Initial / 4x toggle: Chat only
2239 // 1x toggle: Debug text with chat
2240 // 2x toggle: Debug text with profiler graph
2241 // 3x toggle: Debug text and wireframe
2242 if (!m_game_ui->m_flags.show_debug) {
2243 m_game_ui->m_flags.show_debug = true;
2244 m_game_ui->m_flags.show_profiler_graph = false;
2245 draw_control->show_wireframe = false;
2246 m_game_ui->showTranslatedStatusText("Debug info shown");
2247 } else if (!m_game_ui->m_flags.show_profiler_graph && !draw_control->show_wireframe) {
2248 m_game_ui->m_flags.show_profiler_graph = true;
2249 m_game_ui->showTranslatedStatusText("Profiler graph shown");
2250 } else if (!draw_control->show_wireframe && client->checkPrivilege("debug")) {
2251 m_game_ui->m_flags.show_profiler_graph = false;
2252 draw_control->show_wireframe = true;
2253 m_game_ui->showTranslatedStatusText("Wireframe shown");
2255 m_game_ui->m_flags.show_debug = false;
2256 m_game_ui->m_flags.show_profiler_graph = false;
2257 draw_control->show_wireframe = false;
2258 if (client->checkPrivilege("debug")) {
2259 m_game_ui->showTranslatedStatusText("Debug info, profiler graph, and wireframe hidden");
2261 m_game_ui->showTranslatedStatusText("Debug info and profiler graph hidden");
2267 void Game::toggleUpdateCamera()
2269 m_flags.disable_camera_update = !m_flags.disable_camera_update;
2270 if (m_flags.disable_camera_update)
2271 m_game_ui->showTranslatedStatusText("Camera update disabled");
2273 m_game_ui->showTranslatedStatusText("Camera update enabled");
2277 void Game::increaseViewRange()
2279 s16 range = g_settings->getS16("viewing_range");
2280 s16 range_new = range + 10;
2284 if (range_new > 4000) {
2286 str = wgettext("Viewing range is at maximum: %d");
2287 swprintf(buf, sizeof(buf) / sizeof(wchar_t), str, range_new);
2289 m_game_ui->showStatusText(buf);
2292 str = wgettext("Viewing range changed to %d");
2293 swprintf(buf, sizeof(buf) / sizeof(wchar_t), str, range_new);
2295 m_game_ui->showStatusText(buf);
2297 g_settings->set("viewing_range", itos(range_new));
2301 void Game::decreaseViewRange()
2303 s16 range = g_settings->getS16("viewing_range");
2304 s16 range_new = range - 10;
2308 if (range_new < 20) {
2310 str = wgettext("Viewing range is at minimum: %d");
2311 swprintf(buf, sizeof(buf) / sizeof(wchar_t), str, range_new);
2313 m_game_ui->showStatusText(buf);
2315 str = wgettext("Viewing range changed to %d");
2316 swprintf(buf, sizeof(buf) / sizeof(wchar_t), str, range_new);
2318 m_game_ui->showStatusText(buf);
2320 g_settings->set("viewing_range", itos(range_new));
2324 void Game::toggleFullViewRange()
2326 draw_control->range_all = !draw_control->range_all;
2327 if (draw_control->range_all)
2328 m_game_ui->showTranslatedStatusText("Enabled unlimited viewing range");
2330 m_game_ui->showTranslatedStatusText("Disabled unlimited viewing range");
2334 void Game::checkZoomEnabled()
2336 LocalPlayer *player = client->getEnv().getLocalPlayer();
2337 if (player->getZoomFOV() < 0.001f)
2338 m_game_ui->showTranslatedStatusText("Zoom currently disabled by game or mod");
2342 void Game::updateCameraDirection(CameraOrientation *cam, float dtime)
2344 if ((device->isWindowActive() && device->isWindowFocused()
2345 && !isMenuActive()) || random_input) {
2348 if (!random_input) {
2349 // Mac OSX gets upset if this is set every frame
2350 if (device->getCursorControl()->isVisible())
2351 device->getCursorControl()->setVisible(false);
2355 if (m_first_loop_after_window_activation) {
2356 m_first_loop_after_window_activation = false;
2358 input->setMousePos(driver->getScreenSize().Width / 2,
2359 driver->getScreenSize().Height / 2);
2361 updateCameraOrientation(cam, dtime);
2367 // Mac OSX gets upset if this is set every frame
2368 if (!device->getCursorControl()->isVisible())
2369 device->getCursorControl()->setVisible(true);
2372 m_first_loop_after_window_activation = true;
2377 void Game::updateCameraOrientation(CameraOrientation *cam, float dtime)
2379 #ifdef HAVE_TOUCHSCREENGUI
2380 if (g_touchscreengui) {
2381 cam->camera_yaw += g_touchscreengui->getYawChange();
2382 cam->camera_pitch = g_touchscreengui->getPitch();
2385 v2s32 center(driver->getScreenSize().Width / 2, driver->getScreenSize().Height / 2);
2386 v2s32 dist = input->getMousePos() - center;
2388 if (m_invert_mouse || camera->getCameraMode() == CAMERA_MODE_THIRD_FRONT) {
2392 cam->camera_yaw -= dist.X * m_cache_mouse_sensitivity;
2393 cam->camera_pitch += dist.Y * m_cache_mouse_sensitivity;
2395 if (dist.X != 0 || dist.Y != 0)
2396 input->setMousePos(center.X, center.Y);
2397 #ifdef HAVE_TOUCHSCREENGUI
2401 if (m_cache_enable_joysticks) {
2402 f32 c = m_cache_joystick_frustum_sensitivity * (1.f / 32767.f) * dtime;
2403 cam->camera_yaw -= input->joystick.getAxisWithoutDead(JA_FRUSTUM_HORIZONTAL) * c;
2404 cam->camera_pitch += input->joystick.getAxisWithoutDead(JA_FRUSTUM_VERTICAL) * c;
2407 cam->camera_pitch = rangelim(cam->camera_pitch, -89.5, 89.5);
2411 void Game::updatePlayerControl(const CameraOrientation &cam)
2413 //TimeTaker tt("update player control", NULL, PRECISION_NANO);
2415 // DO NOT use the isKeyDown method for the forward, backward, left, right
2416 // buttons, as the code that uses the controls needs to be able to
2417 // distinguish between the two in order to know when to use joysticks.
2419 PlayerControl control(
2420 input->isKeyDown(KeyType::FORWARD),
2421 input->isKeyDown(KeyType::BACKWARD),
2422 input->isKeyDown(KeyType::LEFT),
2423 input->isKeyDown(KeyType::RIGHT),
2424 isKeyDown(KeyType::JUMP),
2425 isKeyDown(KeyType::SPECIAL1),
2426 isKeyDown(KeyType::SNEAK),
2427 isKeyDown(KeyType::ZOOM),
2428 input->getLeftState(),
2429 input->getRightState(),
2432 input->joystick.getAxisWithoutDead(JA_SIDEWARD_MOVE),
2433 input->joystick.getAxisWithoutDead(JA_FORWARD_MOVE)
2437 ( (u32)(isKeyDown(KeyType::FORWARD) & 0x1) << 0) |
2438 ( (u32)(isKeyDown(KeyType::BACKWARD) & 0x1) << 1) |
2439 ( (u32)(isKeyDown(KeyType::LEFT) & 0x1) << 2) |
2440 ( (u32)(isKeyDown(KeyType::RIGHT) & 0x1) << 3) |
2441 ( (u32)(isKeyDown(KeyType::JUMP) & 0x1) << 4) |
2442 ( (u32)(isKeyDown(KeyType::SPECIAL1) & 0x1) << 5) |
2443 ( (u32)(isKeyDown(KeyType::SNEAK) & 0x1) << 6) |
2444 ( (u32)(input->getLeftState() & 0x1) << 7) |
2445 ( (u32)(input->getRightState() & 0x1) << 8
2449 /* For Android, simulate holding down AUX1 (fast move) if the user has
2450 * the fast_move setting toggled on. If there is an aux1 key defined for
2451 * Android then its meaning is inverted (i.e. holding aux1 means walk and
2454 if (m_cache_hold_aux1) {
2455 control.aux1 = control.aux1 ^ true;
2456 keypress_bits ^= ((u32)(1U << 5));
2460 LocalPlayer *player = client->getEnv().getLocalPlayer();
2462 // autojump if set: simulate "jump" key
2463 if (player->getAutojump()) {
2464 control.jump = true;
2465 keypress_bits |= 1U << 4;
2468 // autoforward if set: simulate "up" key
2469 if (player->getPlayerSettings().continuous_forward && !player->isDead()) {
2471 keypress_bits |= 1U << 0;
2474 client->setPlayerControl(control);
2475 player->keyPressed = keypress_bits;
2481 inline void Game::step(f32 *dtime)
2483 bool can_be_and_is_paused =
2484 (simple_singleplayer_mode && g_menumgr.pausesGame());
2486 if (can_be_and_is_paused) { // This is for a singleplayer server
2487 *dtime = 0; // No time passes
2490 server->step(*dtime);
2492 client->step(*dtime);
2496 const ClientEventHandler Game::clientEventHandler[CLIENTEVENT_MAX] = {
2497 {&Game::handleClientEvent_None},
2498 {&Game::handleClientEvent_PlayerDamage},
2499 {&Game::handleClientEvent_PlayerForceMove},
2500 {&Game::handleClientEvent_Deathscreen},
2501 {&Game::handleClientEvent_ShowFormSpec},
2502 {&Game::handleClientEvent_ShowLocalFormSpec},
2503 {&Game::handleClientEvent_HandleParticleEvent},
2504 {&Game::handleClientEvent_HandleParticleEvent},
2505 {&Game::handleClientEvent_HandleParticleEvent},
2506 {&Game::handleClientEvent_HudAdd},
2507 {&Game::handleClientEvent_HudRemove},
2508 {&Game::handleClientEvent_HudChange},
2509 {&Game::handleClientEvent_SetSky},
2510 {&Game::handleClientEvent_OverrideDayNigthRatio},
2511 {&Game::handleClientEvent_CloudParams},
2514 void Game::handleClientEvent_None(ClientEvent *event, CameraOrientation *cam)
2516 FATAL_ERROR("ClientEvent type None received");
2519 void Game::handleClientEvent_PlayerDamage(ClientEvent *event, CameraOrientation *cam)
2521 if (client->moddingEnabled()) {
2522 client->getScript()->on_damage_taken(event->player_damage.amount);
2525 // Damage flash and hurt tilt are not used at death
2526 if (client->getHP() > 0) {
2527 runData.damage_flash += 95.0f + 3.2f * event->player_damage.amount;
2528 runData.damage_flash = MYMIN(runData.damage_flash, 127.0f);
2530 LocalPlayer *player = client->getEnv().getLocalPlayer();
2532 player->hurt_tilt_timer = 1.5f;
2533 player->hurt_tilt_strength =
2534 rangelim(event->player_damage.amount / 4.0f, 1.0f, 4.0f);
2537 // Play damage sound
2538 client->getEventManager()->put(new SimpleTriggerEvent(MtEvent::PLAYER_DAMAGE));
2541 void Game::handleClientEvent_PlayerForceMove(ClientEvent *event, CameraOrientation *cam)
2543 cam->camera_yaw = event->player_force_move.yaw;
2544 cam->camera_pitch = event->player_force_move.pitch;
2547 void Game::handleClientEvent_Deathscreen(ClientEvent *event, CameraOrientation *cam)
2549 // If client scripting is enabled, deathscreen is handled by CSM code in
2550 // builtin/client/init.lua
2551 if (client->moddingEnabled())
2552 client->getScript()->on_death();
2554 showDeathFormspec();
2556 /* Handle visualization */
2557 LocalPlayer *player = client->getEnv().getLocalPlayer();
2558 runData.damage_flash = 0;
2559 player->hurt_tilt_timer = 0;
2560 player->hurt_tilt_strength = 0;
2563 void Game::handleClientEvent_ShowFormSpec(ClientEvent *event, CameraOrientation *cam)
2565 if (event->show_formspec.formspec->empty()) {
2566 auto formspec = m_game_ui->getFormspecGUI();
2567 if (formspec && (event->show_formspec.formname->empty()
2568 || *(event->show_formspec.formname) == m_game_ui->getFormspecName())) {
2569 formspec->quitMenu();
2572 FormspecFormSource *fs_src =
2573 new FormspecFormSource(*(event->show_formspec.formspec));
2574 TextDestPlayerInventory *txt_dst =
2575 new TextDestPlayerInventory(client, *(event->show_formspec.formname));
2577 auto *&formspec = m_game_ui->updateFormspec(*(event->show_formspec.formname));
2578 GUIFormSpecMenu::create(formspec, client, &input->joystick,
2579 fs_src, txt_dst, client->getFormspecPrepend());
2582 delete event->show_formspec.formspec;
2583 delete event->show_formspec.formname;
2586 void Game::handleClientEvent_ShowLocalFormSpec(ClientEvent *event, CameraOrientation *cam)
2588 FormspecFormSource *fs_src = new FormspecFormSource(*event->show_formspec.formspec);
2589 LocalFormspecHandler *txt_dst =
2590 new LocalFormspecHandler(*event->show_formspec.formname, client);
2591 GUIFormSpecMenu::create(m_game_ui->getFormspecGUI(), client, &input->joystick,
2592 fs_src, txt_dst, client->getFormspecPrepend());
2594 delete event->show_formspec.formspec;
2595 delete event->show_formspec.formname;
2598 void Game::handleClientEvent_HandleParticleEvent(ClientEvent *event,
2599 CameraOrientation *cam)
2601 LocalPlayer *player = client->getEnv().getLocalPlayer();
2602 client->getParticleManager()->handleParticleEvent(event, client, player);
2605 void Game::handleClientEvent_HudAdd(ClientEvent *event, CameraOrientation *cam)
2607 LocalPlayer *player = client->getEnv().getLocalPlayer();
2608 auto &hud_server_to_client = client->getHUDTranslationMap();
2610 u32 server_id = event->hudadd.server_id;
2611 // ignore if we already have a HUD with that ID
2612 auto i = hud_server_to_client.find(server_id);
2613 if (i != hud_server_to_client.end()) {
2614 delete event->hudadd.pos;
2615 delete event->hudadd.name;
2616 delete event->hudadd.scale;
2617 delete event->hudadd.text;
2618 delete event->hudadd.align;
2619 delete event->hudadd.offset;
2620 delete event->hudadd.world_pos;
2621 delete event->hudadd.size;
2625 HudElement *e = new HudElement;
2626 e->type = (HudElementType)event->hudadd.type;
2627 e->pos = *event->hudadd.pos;
2628 e->name = *event->hudadd.name;
2629 e->scale = *event->hudadd.scale;
2630 e->text = *event->hudadd.text;
2631 e->number = event->hudadd.number;
2632 e->item = event->hudadd.item;
2633 e->dir = event->hudadd.dir;
2634 e->align = *event->hudadd.align;
2635 e->offset = *event->hudadd.offset;
2636 e->world_pos = *event->hudadd.world_pos;
2637 e->size = *event->hudadd.size;
2638 hud_server_to_client[server_id] = player->addHud(e);
2640 delete event->hudadd.pos;
2641 delete event->hudadd.name;
2642 delete event->hudadd.scale;
2643 delete event->hudadd.text;
2644 delete event->hudadd.align;
2645 delete event->hudadd.offset;
2646 delete event->hudadd.world_pos;
2647 delete event->hudadd.size;
2650 void Game::handleClientEvent_HudRemove(ClientEvent *event, CameraOrientation *cam)
2652 LocalPlayer *player = client->getEnv().getLocalPlayer();
2653 HudElement *e = player->removeHud(event->hudrm.id);
2657 void Game::handleClientEvent_HudChange(ClientEvent *event, CameraOrientation *cam)
2659 LocalPlayer *player = client->getEnv().getLocalPlayer();
2661 u32 id = event->hudchange.id;
2662 HudElement *e = player->getHud(id);
2665 delete event->hudchange.v3fdata;
2666 delete event->hudchange.v2fdata;
2667 delete event->hudchange.sdata;
2668 delete event->hudchange.v2s32data;
2672 switch (event->hudchange.stat) {
2674 e->pos = *event->hudchange.v2fdata;
2678 e->name = *event->hudchange.sdata;
2681 case HUD_STAT_SCALE:
2682 e->scale = *event->hudchange.v2fdata;
2686 e->text = *event->hudchange.sdata;
2689 case HUD_STAT_NUMBER:
2690 e->number = event->hudchange.data;
2694 e->item = event->hudchange.data;
2698 e->dir = event->hudchange.data;
2701 case HUD_STAT_ALIGN:
2702 e->align = *event->hudchange.v2fdata;
2705 case HUD_STAT_OFFSET:
2706 e->offset = *event->hudchange.v2fdata;
2709 case HUD_STAT_WORLD_POS:
2710 e->world_pos = *event->hudchange.v3fdata;
2714 e->size = *event->hudchange.v2s32data;
2718 delete event->hudchange.v3fdata;
2719 delete event->hudchange.v2fdata;
2720 delete event->hudchange.sdata;
2721 delete event->hudchange.v2s32data;
2724 void Game::handleClientEvent_SetSky(ClientEvent *event, CameraOrientation *cam)
2726 sky->setVisible(false);
2727 // Whether clouds are visible in front of a custom skybox
2728 sky->setCloudsEnabled(event->set_sky.clouds);
2735 // Handle according to type
2736 if (*event->set_sky.type == "regular") {
2737 sky->setVisible(true);
2738 sky->setCloudsEnabled(true);
2739 } else if (*event->set_sky.type == "skybox" &&
2740 event->set_sky.params->size() == 6) {
2741 sky->setFallbackBgColor(*event->set_sky.bgcolor);
2742 skybox = RenderingEngine::get_scene_manager()->addSkyBoxSceneNode(
2743 texture_src->getTextureForMesh((*event->set_sky.params)[0]),
2744 texture_src->getTextureForMesh((*event->set_sky.params)[1]),
2745 texture_src->getTextureForMesh((*event->set_sky.params)[2]),
2746 texture_src->getTextureForMesh((*event->set_sky.params)[3]),
2747 texture_src->getTextureForMesh((*event->set_sky.params)[4]),
2748 texture_src->getTextureForMesh((*event->set_sky.params)[5]));
2750 // Handle everything else as plain color
2752 if (*event->set_sky.type != "plain")
2753 infostream << "Unknown sky type: "
2754 << (*event->set_sky.type) << std::endl;
2756 sky->setFallbackBgColor(*event->set_sky.bgcolor);
2759 delete event->set_sky.bgcolor;
2760 delete event->set_sky.type;
2761 delete event->set_sky.params;
2764 void Game::handleClientEvent_OverrideDayNigthRatio(ClientEvent *event,
2765 CameraOrientation *cam)
2767 client->getEnv().setDayNightRatioOverride(
2768 event->override_day_night_ratio.do_override,
2769 event->override_day_night_ratio.ratio_f * 1000.0f);
2772 void Game::handleClientEvent_CloudParams(ClientEvent *event, CameraOrientation *cam)
2777 clouds->setDensity(event->cloud_params.density);
2778 clouds->setColorBright(video::SColor(event->cloud_params.color_bright));
2779 clouds->setColorAmbient(video::SColor(event->cloud_params.color_ambient));
2780 clouds->setHeight(event->cloud_params.height);
2781 clouds->setThickness(event->cloud_params.thickness);
2782 clouds->setSpeed(v2f(event->cloud_params.speed_x, event->cloud_params.speed_y));
2785 void Game::processClientEvents(CameraOrientation *cam)
2787 while (client->hasClientEvents()) {
2788 std::unique_ptr<ClientEvent> event(client->getClientEvent());
2789 FATAL_ERROR_IF(event->type >= CLIENTEVENT_MAX, "Invalid clientevent type");
2790 const ClientEventHandler& evHandler = clientEventHandler[event->type];
2791 (this->*evHandler.handler)(event.get(), cam);
2795 void Game::updateChat(f32 dtime, const v2u32 &screensize)
2797 // Add chat log output for errors to be shown in chat
2798 static LogOutputBuffer chat_log_error_buf(g_logger, LL_ERROR);
2800 // Get new messages from error log buffer
2801 while (!chat_log_error_buf.empty()) {
2802 std::wstring error_message = utf8_to_wide(chat_log_error_buf.get());
2803 if (!g_settings->getBool("disable_escape_sequences")) {
2804 error_message.insert(0, L"\x1b(c@red)");
2805 error_message.append(L"\x1b(c@white)");
2807 chat_backend->addMessage(L"", error_message);
2810 // Get new messages from client
2811 std::wstring message;
2812 while (client->getChatMessage(message)) {
2813 chat_backend->addUnparsedMessage(message);
2816 // Remove old messages
2817 chat_backend->step(dtime);
2819 // Display all messages in a static text element
2820 m_game_ui->setChatText(chat_backend->getRecentChat(),
2821 chat_backend->getRecentBuffer().getLineCount());
2824 void Game::updateCamera(u32 busy_time, f32 dtime)
2826 LocalPlayer *player = client->getEnv().getLocalPlayer();
2829 For interaction purposes, get info about the held item
2831 - Is it a usable item?
2832 - Can it point to liquids?
2834 ItemStack playeritem;
2836 ItemStack selected, hand;
2837 playeritem = player->getWieldedItem(&selected, &hand);
2840 ToolCapabilities playeritem_toolcap =
2841 playeritem.getToolCapabilities(itemdef_manager);
2843 v3s16 old_camera_offset = camera->getOffset();
2845 if (wasKeyDown(KeyType::CAMERA_MODE)) {
2846 GenericCAO *playercao = player->getCAO();
2848 // If playercao not loaded, don't change camera
2852 camera->toggleCameraMode();
2854 playercao->setVisible(camera->getCameraMode() > CAMERA_MODE_FIRST);
2855 playercao->setChildrenVisible(camera->getCameraMode() > CAMERA_MODE_FIRST);
2858 float full_punch_interval = playeritem_toolcap.full_punch_interval;
2859 float tool_reload_ratio = runData.time_from_last_punch / full_punch_interval;
2861 tool_reload_ratio = MYMIN(tool_reload_ratio, 1.0);
2862 camera->update(player, dtime, busy_time / 1000.0f, tool_reload_ratio);
2863 camera->step(dtime);
2865 v3f camera_position = camera->getPosition();
2866 v3f camera_direction = camera->getDirection();
2867 f32 camera_fov = camera->getFovMax();
2868 v3s16 camera_offset = camera->getOffset();
2870 m_camera_offset_changed = (camera_offset != old_camera_offset);
2872 if (!m_flags.disable_camera_update) {
2873 client->getEnv().getClientMap().updateCamera(camera_position,
2874 camera_direction, camera_fov, camera_offset);
2876 if (m_camera_offset_changed) {
2877 client->updateCameraOffset(camera_offset);
2878 client->getEnv().updateCameraOffset(camera_offset);
2881 clouds->updateCameraOffset(camera_offset);
2887 void Game::updateSound(f32 dtime)
2889 // Update sound listener
2890 v3s16 camera_offset = camera->getOffset();
2891 sound->updateListener(camera->getCameraNode()->getPosition() + intToFloat(camera_offset, BS),
2892 v3f(0, 0, 0), // velocity
2893 camera->getDirection(),
2894 camera->getCameraNode()->getUpVector());
2896 bool mute_sound = g_settings->getBool("mute_sound");
2898 sound->setListenerGain(0.0f);
2900 // Check if volume is in the proper range, else fix it.
2901 float old_volume = g_settings->getFloat("sound_volume");
2902 float new_volume = rangelim(old_volume, 0.0f, 1.0f);
2903 sound->setListenerGain(new_volume);
2905 if (old_volume != new_volume) {
2906 g_settings->setFloat("sound_volume", new_volume);
2910 LocalPlayer *player = client->getEnv().getLocalPlayer();
2912 // Tell the sound maker whether to make footstep sounds
2913 soundmaker->makes_footstep_sound = player->makes_footstep_sound;
2915 // Update sound maker
2916 if (player->makes_footstep_sound)
2917 soundmaker->step(dtime);
2919 ClientMap &map = client->getEnv().getClientMap();
2920 MapNode n = map.getNode(player->getFootstepNodePos());
2921 soundmaker->m_player_step_sound = nodedef_manager->get(n).sound_footstep;
2925 void Game::processPlayerInteraction(f32 dtime, bool show_hud, bool show_debug)
2927 LocalPlayer *player = client->getEnv().getLocalPlayer();
2929 v3f player_position = player->getPosition();
2930 v3f player_eye_position = player->getEyePosition();
2931 v3f camera_position = camera->getPosition();
2932 v3f camera_direction = camera->getDirection();
2933 v3s16 camera_offset = camera->getOffset();
2935 if (camera->getCameraMode() == CAMERA_MODE_FIRST)
2936 player_eye_position += player->eye_offset_first;
2938 player_eye_position += player->eye_offset_third;
2941 Calculate what block is the crosshair pointing to
2944 ItemStack selected_item, hand_item;
2945 const ItemStack &tool_item = player->getWieldedItem(&selected_item, &hand_item);
2947 const ItemDefinition &selected_def = selected_item.getDefinition(itemdef_manager);
2948 f32 d = getToolRange(selected_def, hand_item.getDefinition(itemdef_manager));
2950 core::line3d<f32> shootline;
2952 if (camera->getCameraMode() != CAMERA_MODE_THIRD_FRONT) {
2953 shootline = core::line3d<f32>(player_eye_position,
2954 player_eye_position + camera_direction * BS * d);
2956 // prevent player pointing anything in front-view
2957 shootline = core::line3d<f32>(camera_position, camera_position);
2960 #ifdef HAVE_TOUCHSCREENGUI
2962 if ((g_settings->getBool("touchtarget")) && (g_touchscreengui)) {
2963 shootline = g_touchscreengui->getShootline();
2964 // Scale shootline to the acual distance the player can reach
2965 shootline.end = shootline.start
2966 + shootline.getVector().normalize() * BS * d;
2967 shootline.start += intToFloat(camera_offset, BS);
2968 shootline.end += intToFloat(camera_offset, BS);
2973 PointedThing pointed = updatePointedThing(shootline,
2974 selected_def.liquids_pointable,
2975 !runData.ldown_for_dig,
2978 if (pointed != runData.pointed_old) {
2979 infostream << "Pointing at " << pointed.dump() << std::endl;
2980 hud->updateSelectionMesh(camera_offset);
2983 if (runData.digging_blocked && !input->getLeftState()) {
2984 // allow digging again if button is not pressed
2985 runData.digging_blocked = false;
2990 - releasing left mouse button
2991 - pointing away from node
2993 if (runData.digging) {
2994 if (input->getLeftReleased()) {
2995 infostream << "Left button released"
2996 << " (stopped digging)" << std::endl;
2997 runData.digging = false;
2998 } else if (pointed != runData.pointed_old) {
2999 if (pointed.type == POINTEDTHING_NODE
3000 && runData.pointed_old.type == POINTEDTHING_NODE
3001 && pointed.node_undersurface
3002 == runData.pointed_old.node_undersurface) {
3003 // Still pointing to the same node, but a different face.
3006 infostream << "Pointing away from node"
3007 << " (stopped digging)" << std::endl;
3008 runData.digging = false;
3009 hud->updateSelectionMesh(camera_offset);
3013 if (!runData.digging) {
3014 client->interact(INTERACT_STOP_DIGGING, runData.pointed_old);
3015 client->setCrack(-1, v3s16(0, 0, 0));
3016 runData.dig_time = 0.0;
3018 } else if (runData.dig_instantly && input->getLeftReleased()) {
3019 // Remove e.g. torches faster when clicking instead of holding LMB
3020 runData.nodig_delay_timer = 0;
3021 runData.dig_instantly = false;
3024 if (!runData.digging && runData.ldown_for_dig && !input->getLeftState()) {
3025 runData.ldown_for_dig = false;
3028 runData.left_punch = false;
3030 soundmaker->m_player_leftpunch_sound.name = "";
3032 // Prepare for repeating, unless we're not supposed to
3033 if (input->getRightState() && !g_settings->getBool("safe_dig_and_place"))
3034 runData.repeat_rightclick_timer += dtime;
3036 runData.repeat_rightclick_timer = 0;
3039 if (selected_def.usable && input->getLeftState()) {
3040 if (input->getLeftClicked() && (!client->moddingEnabled()
3041 || !client->getScript()->on_item_use(selected_item, pointed)))
3042 client->interact(INTERACT_USE, pointed);
3043 } else if (pointed.type == POINTEDTHING_NODE) {
3044 handlePointingAtNode(pointed, selected_item, hand_item, dtime);
3045 } else if (pointed.type == POINTEDTHING_OBJECT) {
3046 handlePointingAtObject(pointed, tool_item, player_position, show_debug);
3047 } else if (input->getLeftState()) {
3048 // When button is held down in air, show continuous animation
3049 runData.left_punch = true;
3050 } else if (input->getRightClicked()) {
3051 handlePointingAtNothing(selected_item);
3054 runData.pointed_old = pointed;
3056 if (runData.left_punch || input->getLeftClicked())
3057 camera->setDigging(0); // left click animation
3059 input->resetLeftClicked();
3060 input->resetRightClicked();
3062 input->resetLeftReleased();
3063 input->resetRightReleased();
3067 PointedThing Game::updatePointedThing(
3068 const core::line3d<f32> &shootline,
3069 bool liquids_pointable,
3070 bool look_for_object,
3071 const v3s16 &camera_offset)
3073 std::vector<aabb3f> *selectionboxes = hud->getSelectionBoxes();
3074 selectionboxes->clear();
3075 hud->setSelectedFaceNormal(v3f(0.0, 0.0, 0.0));
3076 static thread_local const bool show_entity_selectionbox = g_settings->getBool(
3077 "show_entity_selectionbox");
3079 ClientEnvironment &env = client->getEnv();
3080 ClientMap &map = env.getClientMap();
3081 const NodeDefManager *nodedef = map.getNodeDefManager();
3083 runData.selected_object = NULL;
3085 RaycastState s(shootline, look_for_object, liquids_pointable);
3086 PointedThing result;
3087 env.continueRaycast(&s, &result);
3088 if (result.type == POINTEDTHING_OBJECT) {
3089 runData.selected_object = client->getEnv().getActiveObject(result.object_id);
3090 aabb3f selection_box;
3091 if (show_entity_selectionbox && runData.selected_object->doShowSelectionBox() &&
3092 runData.selected_object->getSelectionBox(&selection_box)) {
3093 v3f pos = runData.selected_object->getPosition();
3094 selectionboxes->push_back(aabb3f(selection_box));
3095 hud->setSelectionPos(pos, camera_offset);
3097 } else if (result.type == POINTEDTHING_NODE) {
3098 // Update selection boxes
3099 MapNode n = map.getNode(result.node_undersurface);
3100 std::vector<aabb3f> boxes;
3101 n.getSelectionBoxes(nodedef, &boxes,
3102 n.getNeighbors(result.node_undersurface, &map));
3105 for (std::vector<aabb3f>::const_iterator i = boxes.begin();
3106 i != boxes.end(); ++i) {
3108 box.MinEdge -= v3f(d, d, d);
3109 box.MaxEdge += v3f(d, d, d);
3110 selectionboxes->push_back(box);
3112 hud->setSelectionPos(intToFloat(result.node_undersurface, BS),
3114 hud->setSelectedFaceNormal(v3f(
3115 result.intersection_normal.X,
3116 result.intersection_normal.Y,
3117 result.intersection_normal.Z));
3120 // Update selection mesh light level and vertex colors
3121 if (!selectionboxes->empty()) {
3122 v3f pf = hud->getSelectionPos();
3123 v3s16 p = floatToInt(pf, BS);
3125 // Get selection mesh light level
3126 MapNode n = map.getNode(p);
3127 u16 node_light = getInteriorLight(n, -1, nodedef);
3128 u16 light_level = node_light;
3130 for (const v3s16 &dir : g_6dirs) {
3131 n = map.getNode(p + dir);
3132 node_light = getInteriorLight(n, -1, nodedef);
3133 if (node_light > light_level)
3134 light_level = node_light;
3137 u32 daynight_ratio = client->getEnv().getDayNightRatio();
3139 final_color_blend(&c, light_level, daynight_ratio);
3141 // Modify final color a bit with time
3142 u32 timer = porting::getTimeMs() % 5000;
3143 float timerf = (float) (irr::core::PI * ((timer / 2500.0) - 0.5));
3144 float sin_r = 0.08f * std::sin(timerf);
3145 float sin_g = 0.08f * std::sin(timerf + irr::core::PI * 0.5f);
3146 float sin_b = 0.08f * std::sin(timerf + irr::core::PI);
3147 c.setRed(core::clamp(core::round32(c.getRed() * (0.8 + sin_r)), 0, 255));
3148 c.setGreen(core::clamp(core::round32(c.getGreen() * (0.8 + sin_g)), 0, 255));
3149 c.setBlue(core::clamp(core::round32(c.getBlue() * (0.8 + sin_b)), 0, 255));
3151 // Set mesh final color
3152 hud->setSelectionMeshColor(c);
3158 void Game::handlePointingAtNothing(const ItemStack &playerItem)
3160 infostream << "Right Clicked in Air" << std::endl;
3161 PointedThing fauxPointed;
3162 fauxPointed.type = POINTEDTHING_NOTHING;
3163 client->interact(INTERACT_ACTIVATE, fauxPointed);
3167 void Game::handlePointingAtNode(const PointedThing &pointed,
3168 const ItemStack &selected_item, const ItemStack &hand_item, f32 dtime)
3170 v3s16 nodepos = pointed.node_undersurface;
3171 v3s16 neighbourpos = pointed.node_abovesurface;
3174 Check information text of node
3177 ClientMap &map = client->getEnv().getClientMap();
3179 if (runData.nodig_delay_timer <= 0.0 && input->getLeftState()
3180 && !runData.digging_blocked
3181 && client->checkPrivilege("interact")) {
3182 handleDigging(pointed, nodepos, selected_item, hand_item, dtime);
3185 // This should be done after digging handling
3186 NodeMetadata *meta = map.getNodeMetadata(nodepos);
3189 m_game_ui->setInfoText(unescape_translate(utf8_to_wide(
3190 meta->getString("infotext"))));
3192 MapNode n = map.getNode(nodepos);
3194 if (nodedef_manager->get(n).tiledef[0].name == "unknown_node.png") {
3195 m_game_ui->setInfoText(L"Unknown node: " +
3196 utf8_to_wide(nodedef_manager->get(n).name));
3200 if ((input->getRightClicked() ||
3201 runData.repeat_rightclick_timer >= m_repeat_right_click_time) &&
3202 client->checkPrivilege("interact")) {
3203 runData.repeat_rightclick_timer = 0;
3204 infostream << "Ground right-clicked" << std::endl;
3206 if (meta && !meta->getString("formspec").empty() && !random_input
3207 && !isKeyDown(KeyType::SNEAK)) {
3208 // Report right click to server
3209 if (nodedef_manager->get(map.getNode(nodepos)).rightclickable) {
3210 client->interact(INTERACT_PLACE, pointed);
3213 infostream << "Launching custom inventory view" << std::endl;
3215 InventoryLocation inventoryloc;
3216 inventoryloc.setNodeMeta(nodepos);
3218 NodeMetadataFormSource *fs_src = new NodeMetadataFormSource(
3219 &client->getEnv().getClientMap(), nodepos);
3220 TextDest *txt_dst = new TextDestNodeMetadata(nodepos, client);
3222 auto *&formspec = m_game_ui->updateFormspec("");
3223 GUIFormSpecMenu::create(formspec, client, &input->joystick, fs_src,
3224 txt_dst, client->getFormspecPrepend());
3226 formspec->setFormSpec(meta->getString("formspec"), inventoryloc);
3228 // Report right click to server
3230 camera->setDigging(1); // right click animation (always shown for feedback)
3232 // If the wielded item has node placement prediction,
3234 auto &def = selected_item.getDefinition(itemdef_manager);
3235 bool placed = nodePlacementPrediction(def, selected_item, nodepos,
3240 client->interact(INTERACT_PLACE, pointed);
3242 soundmaker->m_player_rightpunch_sound =
3245 if (client->moddingEnabled())
3246 client->getScript()->on_placenode(pointed, def);
3248 soundmaker->m_player_rightpunch_sound =
3251 if (def.node_placement_prediction.empty() ||
3252 nodedef_manager->get(map.getNode(nodepos)).rightclickable) {
3253 client->interact(INTERACT_PLACE, pointed); // Report to server
3255 soundmaker->m_player_rightpunch_sound =
3256 def.sound_place_failed;
3263 bool Game::nodePlacementPrediction(const ItemDefinition &selected_def,
3264 const ItemStack &selected_item, const v3s16 &nodepos, const v3s16 &neighbourpos)
3266 std::string prediction = selected_def.node_placement_prediction;
3267 const NodeDefManager *nodedef = client->ndef();
3268 ClientMap &map = client->getEnv().getClientMap();
3270 bool is_valid_position;
3272 node = map.getNode(nodepos, &is_valid_position);
3273 if (!is_valid_position)
3276 if (!prediction.empty() && !(nodedef->get(node).rightclickable &&
3277 !isKeyDown(KeyType::SNEAK))) {
3278 verbosestream << "Node placement prediction for "
3279 << selected_item.name << " is "
3280 << prediction << std::endl;
3281 v3s16 p = neighbourpos;
3283 // Place inside node itself if buildable_to
3284 MapNode n_under = map.getNode(nodepos, &is_valid_position);
3285 if (is_valid_position)
3287 if (nodedef->get(n_under).buildable_to)
3290 node = map.getNode(p, &is_valid_position);
3291 if (is_valid_position &&!nodedef->get(node).buildable_to)
3296 // Find id of predicted node
3298 bool found = nodedef->getId(prediction, id);
3301 errorstream << "Node placement prediction failed for "
3302 << selected_item.name << " (places "
3304 << ") - Name not known" << std::endl;
3308 const ContentFeatures &predicted_f = nodedef->get(id);
3310 // Predict param2 for facedir and wallmounted nodes
3313 if (predicted_f.param_type_2 == CPT2_WALLMOUNTED ||
3314 predicted_f.param_type_2 == CPT2_COLORED_WALLMOUNTED) {
3315 v3s16 dir = nodepos - neighbourpos;
3317 if (abs(dir.Y) > MYMAX(abs(dir.X), abs(dir.Z))) {
3318 param2 = dir.Y < 0 ? 1 : 0;
3319 } else if (abs(dir.X) > abs(dir.Z)) {
3320 param2 = dir.X < 0 ? 3 : 2;
3322 param2 = dir.Z < 0 ? 5 : 4;
3326 if (predicted_f.param_type_2 == CPT2_FACEDIR ||
3327 predicted_f.param_type_2 == CPT2_COLORED_FACEDIR) {
3328 v3s16 dir = nodepos - floatToInt(client->getEnv().getLocalPlayer()->getPosition(), BS);
3330 if (abs(dir.X) > abs(dir.Z)) {
3331 param2 = dir.X < 0 ? 3 : 1;
3333 param2 = dir.Z < 0 ? 2 : 0;
3337 assert(param2 <= 5);
3339 //Check attachment if node is in group attached_node
3340 if (((ItemGroupList) predicted_f.groups)["attached_node"] != 0) {
3341 static v3s16 wallmounted_dirs[8] = {
3351 if (predicted_f.param_type_2 == CPT2_WALLMOUNTED ||
3352 predicted_f.param_type_2 == CPT2_COLORED_WALLMOUNTED)
3353 pp = p + wallmounted_dirs[param2];
3355 pp = p + v3s16(0, -1, 0);
3357 if (!nodedef->get(map.getNode(pp)).walkable)
3362 if ((predicted_f.param_type_2 == CPT2_COLOR
3363 || predicted_f.param_type_2 == CPT2_COLORED_FACEDIR
3364 || predicted_f.param_type_2 == CPT2_COLORED_WALLMOUNTED)) {
3365 const std::string &indexstr = selected_item.metadata.getString(
3366 "palette_index", 0);
3367 if (!indexstr.empty()) {
3368 s32 index = mystoi(indexstr);
3369 if (predicted_f.param_type_2 == CPT2_COLOR) {
3371 } else if (predicted_f.param_type_2
3372 == CPT2_COLORED_WALLMOUNTED) {
3373 // param2 = pure palette index + other
3374 param2 = (index & 0xf8) | (param2 & 0x07);
3375 } else if (predicted_f.param_type_2
3376 == CPT2_COLORED_FACEDIR) {
3377 // param2 = pure palette index + other
3378 param2 = (index & 0xe0) | (param2 & 0x1f);
3383 // Add node to client map
3384 MapNode n(id, 0, param2);
3387 LocalPlayer *player = client->getEnv().getLocalPlayer();
3389 // Dont place node when player would be inside new node
3390 // NOTE: This is to be eventually implemented by a mod as client-side Lua
3391 if (!nodedef->get(n).walkable ||
3392 g_settings->getBool("enable_build_where_you_stand") ||
3393 (client->checkPrivilege("noclip") && g_settings->getBool("noclip")) ||
3394 (nodedef->get(n).walkable &&
3395 neighbourpos != player->getStandingNodePos() + v3s16(0, 1, 0) &&
3396 neighbourpos != player->getStandingNodePos() + v3s16(0, 2, 0))) {
3398 // This triggers the required mesh update too
3399 client->addNode(p, n);
3402 } catch (InvalidPositionException &e) {
3403 errorstream << "Node placement prediction failed for "
3404 << selected_item.name << " (places "
3406 << ") - Position not loaded" << std::endl;
3413 void Game::handlePointingAtObject(const PointedThing &pointed,
3414 const ItemStack &tool_item, const v3f &player_position, bool show_debug)
3416 std::wstring infotext = unescape_translate(
3417 utf8_to_wide(runData.selected_object->infoText()));
3420 if (!infotext.empty()) {
3423 infotext += utf8_to_wide(runData.selected_object->debugInfoText());
3426 m_game_ui->setInfoText(infotext);
3428 if (input->getLeftState()) {
3429 bool do_punch = false;
3430 bool do_punch_damage = false;
3432 if (runData.object_hit_delay_timer <= 0.0) {
3434 do_punch_damage = true;
3435 runData.object_hit_delay_timer = object_hit_delay;
3438 if (input->getLeftClicked())
3442 infostream << "Left-clicked object" << std::endl;
3443 runData.left_punch = true;
3446 if (do_punch_damage) {
3447 // Report direct punch
3448 v3f objpos = runData.selected_object->getPosition();
3449 v3f dir = (objpos - player_position).normalize();
3451 bool disable_send = runData.selected_object->directReportPunch(
3452 dir, &tool_item, runData.time_from_last_punch);
3453 runData.time_from_last_punch = 0;
3456 client->interact(INTERACT_START_DIGGING, pointed);
3458 } else if (input->getRightClicked()) {
3459 infostream << "Right-clicked object" << std::endl;
3460 client->interact(INTERACT_PLACE, pointed); // place
3465 void Game::handleDigging(const PointedThing &pointed, const v3s16 &nodepos,
3466 const ItemStack &selected_item, const ItemStack &hand_item, f32 dtime)
3468 // See also: serverpackethandle.cpp, action == 2
3469 LocalPlayer *player = client->getEnv().getLocalPlayer();
3470 ClientMap &map = client->getEnv().getClientMap();
3471 MapNode n = client->getEnv().getClientMap().getNode(nodepos);
3473 // NOTE: Similar piece of code exists on the server side for
3475 // Get digging parameters
3476 DigParams params = getDigParams(nodedef_manager->get(n).groups,
3477 &selected_item.getToolCapabilities(itemdef_manager));
3479 // If can't dig, try hand
3480 if (!params.diggable) {
3481 params = getDigParams(nodedef_manager->get(n).groups,
3482 &hand_item.getToolCapabilities(itemdef_manager));
3485 if (!params.diggable) {
3486 // I guess nobody will wait for this long
3487 runData.dig_time_complete = 10000000.0;
3489 runData.dig_time_complete = params.time;
3491 if (m_cache_enable_particles) {
3492 const ContentFeatures &features = client->getNodeDefManager()->get(n);
3493 client->getParticleManager()->addNodeParticle(client,
3494 player, nodepos, n, features);
3498 if (!runData.digging) {
3499 infostream << "Started digging" << std::endl;
3500 runData.dig_instantly = runData.dig_time_complete == 0;
3501 if (client->moddingEnabled() && client->getScript()->on_punchnode(nodepos, n))
3503 client->interact(INTERACT_START_DIGGING, pointed);
3504 runData.digging = true;
3505 runData.ldown_for_dig = true;
3508 if (!runData.dig_instantly) {
3509 runData.dig_index = (float)crack_animation_length
3511 / runData.dig_time_complete;
3513 // This is for e.g. torches
3514 runData.dig_index = crack_animation_length;
3517 SimpleSoundSpec sound_dig = nodedef_manager->get(n).sound_dig;
3519 if (sound_dig.exists() && params.diggable) {
3520 if (sound_dig.name == "__group") {
3521 if (!params.main_group.empty()) {
3522 soundmaker->m_player_leftpunch_sound.gain = 0.5;
3523 soundmaker->m_player_leftpunch_sound.name =
3524 std::string("default_dig_") +
3528 soundmaker->m_player_leftpunch_sound = sound_dig;
3532 // Don't show cracks if not diggable
3533 if (runData.dig_time_complete >= 100000.0) {
3534 } else if (runData.dig_index < crack_animation_length) {
3535 //TimeTaker timer("client.setTempMod");
3536 //infostream<<"dig_index="<<dig_index<<std::endl;
3537 client->setCrack(runData.dig_index, nodepos);
3539 infostream << "Digging completed" << std::endl;
3540 client->setCrack(-1, v3s16(0, 0, 0));
3542 runData.dig_time = 0;
3543 runData.digging = false;
3544 // we successfully dug, now block it from repeating if we want to be safe
3545 if (g_settings->getBool("safe_dig_and_place"))
3546 runData.digging_blocked = true;
3548 runData.nodig_delay_timer =
3549 runData.dig_time_complete / (float)crack_animation_length;
3551 // We don't want a corresponding delay to very time consuming nodes
3552 // and nodes without digging time (e.g. torches) get a fixed delay.
3553 if (runData.nodig_delay_timer > 0.3)
3554 runData.nodig_delay_timer = 0.3;
3555 else if (runData.dig_instantly)
3556 runData.nodig_delay_timer = 0.15;
3558 bool is_valid_position;
3559 MapNode wasnode = map.getNode(nodepos, &is_valid_position);
3560 if (is_valid_position) {
3561 if (client->moddingEnabled() &&
3562 client->getScript()->on_dignode(nodepos, wasnode)) {
3566 const ContentFeatures &f = client->ndef()->get(wasnode);
3567 if (f.node_dig_prediction == "air") {
3568 client->removeNode(nodepos);
3569 } else if (!f.node_dig_prediction.empty()) {
3571 bool found = client->ndef()->getId(f.node_dig_prediction, id);
3573 client->addNode(nodepos, id, true);
3575 // implicit else: no prediction
3578 client->interact(INTERACT_DIGGING_COMPLETED, pointed);
3580 if (m_cache_enable_particles) {
3581 const ContentFeatures &features =
3582 client->getNodeDefManager()->get(wasnode);
3583 client->getParticleManager()->addDiggingParticles(client,
3584 player, nodepos, wasnode, features);
3588 // Send event to trigger sound
3589 client->getEventManager()->put(new NodeDugEvent(nodepos, wasnode));
3592 if (runData.dig_time_complete < 100000.0) {
3593 runData.dig_time += dtime;
3595 runData.dig_time = 0;
3596 client->setCrack(-1, nodepos);
3599 camera->setDigging(0); // left click animation
3603 void Game::updateFrame(ProfilerGraph *graph, RunStats *stats, f32 dtime,
3604 const CameraOrientation &cam)
3606 TimeTaker tt_update("Game::updateFrame()");
3607 LocalPlayer *player = client->getEnv().getLocalPlayer();
3613 if (draw_control->range_all) {
3614 runData.fog_range = 100000 * BS;
3616 runData.fog_range = draw_control->wanted_range * BS;
3620 Calculate general brightness
3622 u32 daynight_ratio = client->getEnv().getDayNightRatio();
3623 float time_brightness = decode_light_f((float)daynight_ratio / 1000.0);
3624 float direct_brightness;
3627 if (m_cache_enable_noclip && m_cache_enable_free_move) {
3628 direct_brightness = time_brightness;
3629 sunlight_seen = true;
3631 float old_brightness = sky->getBrightness();
3632 direct_brightness = client->getEnv().getClientMap()
3633 .getBackgroundBrightness(MYMIN(runData.fog_range * 1.2, 60 * BS),
3634 daynight_ratio, (int)(old_brightness * 255.5), &sunlight_seen)
3638 float time_of_day_smooth = runData.time_of_day_smooth;
3639 float time_of_day = client->getEnv().getTimeOfDayF();
3641 static const float maxsm = 0.05f;
3642 static const float todsm = 0.05f;
3644 if (std::fabs(time_of_day - time_of_day_smooth) > maxsm &&
3645 std::fabs(time_of_day - time_of_day_smooth + 1.0) > maxsm &&
3646 std::fabs(time_of_day - time_of_day_smooth - 1.0) > maxsm)
3647 time_of_day_smooth = time_of_day;
3649 if (time_of_day_smooth > 0.8 && time_of_day < 0.2)
3650 time_of_day_smooth = time_of_day_smooth * (1.0 - todsm)
3651 + (time_of_day + 1.0) * todsm;
3653 time_of_day_smooth = time_of_day_smooth * (1.0 - todsm)
3654 + time_of_day * todsm;
3656 runData.time_of_day_smooth = time_of_day_smooth;
3658 sky->update(time_of_day_smooth, time_brightness, direct_brightness,
3659 sunlight_seen, camera->getCameraMode(), player->getYaw(),
3660 player->getPitch());
3666 if (sky->getCloudsVisible()) {
3667 clouds->setVisible(true);
3668 clouds->step(dtime);
3669 // camera->getPosition is not enough for 3rd person views
3670 v3f camera_node_position = camera->getCameraNode()->getPosition();
3671 v3s16 camera_offset = camera->getOffset();
3672 camera_node_position.X = camera_node_position.X + camera_offset.X * BS;
3673 camera_node_position.Y = camera_node_position.Y + camera_offset.Y * BS;
3674 camera_node_position.Z = camera_node_position.Z + camera_offset.Z * BS;
3675 clouds->update(camera_node_position,
3676 sky->getCloudColor());
3677 if (clouds->isCameraInsideCloud() && m_cache_enable_fog) {
3678 // if inside clouds, and fog enabled, use that as sky
3680 video::SColor clouds_dark = clouds->getColor()
3681 .getInterpolated(video::SColor(255, 0, 0, 0), 0.9);
3682 sky->overrideColors(clouds_dark, clouds->getColor());
3683 sky->setBodiesVisible(false);
3684 runData.fog_range = std::fmin(runData.fog_range * 0.5f, 32.0f * BS);
3685 // do not draw clouds after all
3686 clouds->setVisible(false);
3689 clouds->setVisible(false);
3696 client->getParticleManager()->step(dtime);
3702 if (m_cache_enable_fog) {
3705 video::EFT_FOG_LINEAR,
3706 runData.fog_range * m_cache_fog_start,
3707 runData.fog_range * 1.0,
3715 video::EFT_FOG_LINEAR,
3725 Get chat messages from client
3728 v2u32 screensize = driver->getScreenSize();
3730 updateChat(dtime, screensize);
3736 if (player->getWieldIndex() != runData.new_playeritem)
3737 client->setPlayerItem(runData.new_playeritem);
3739 // Update local inventory if it has changed
3740 if (client->getLocalInventoryUpdated()) {
3741 //infostream<<"Updating local inventory"<<std::endl;
3742 runData.update_wielded_item_trigger = true;
3745 if (runData.update_wielded_item_trigger) {
3746 // Update wielded tool
3747 ItemStack selected_item, hand_item;
3748 ItemStack &tool_item = player->getWieldedItem(&selected_item, &hand_item);
3749 camera->wield(tool_item);
3751 runData.update_wielded_item_trigger = false;
3755 Update block draw list every 200ms or when camera direction has
3758 runData.update_draw_list_timer += dtime;
3760 v3f camera_direction = camera->getDirection();
3761 if (runData.update_draw_list_timer >= 0.2
3762 || runData.update_draw_list_last_cam_dir.getDistanceFrom(camera_direction) > 0.2
3763 || m_camera_offset_changed) {
3764 runData.update_draw_list_timer = 0;
3765 client->getEnv().getClientMap().updateDrawList();
3766 runData.update_draw_list_last_cam_dir = camera_direction;
3769 m_game_ui->update(*stats, client, draw_control, cam, runData.pointed_old, gui_chat_console, dtime);
3772 make sure menu is on top
3773 1. Delete formspec menu reference if menu was removed
3774 2. Else, make sure formspec menu is on top
3776 auto formspec = m_game_ui->getFormspecGUI();
3777 do { // breakable. only runs for one iteration
3781 if (formspec->getReferenceCount() == 1) {
3782 m_game_ui->deleteFormspec();
3786 auto &loc = formspec->getFormspecLocation();
3787 if (loc.type == InventoryLocation::NODEMETA) {
3788 NodeMetadata *meta = client->getEnv().getClientMap().getNodeMetadata(loc.p);
3789 if (!meta || meta->getString("formspec").empty()) {
3790 formspec->quitMenu();
3796 guiroot->bringToFront(formspec);
3802 const video::SColor &skycolor = sky->getSkyColor();
3804 TimeTaker tt_draw("Draw scene");
3805 driver->beginScene(true, true, skycolor);
3807 bool draw_wield_tool = (m_game_ui->m_flags.show_hud &&
3808 (player->hud_flags & HUD_FLAG_WIELDITEM_VISIBLE) &&
3809 (camera->getCameraMode() == CAMERA_MODE_FIRST));
3810 bool draw_crosshair = (
3811 (player->hud_flags & HUD_FLAG_CROSSHAIR_VISIBLE) &&
3812 (camera->getCameraMode() != CAMERA_MODE_THIRD_FRONT));
3813 #ifdef HAVE_TOUCHSCREENGUI
3815 draw_crosshair = !g_settings->getBool("touchtarget");
3816 } catch (SettingNotFoundException) {
3819 RenderingEngine::draw_scene(skycolor, m_game_ui->m_flags.show_hud,
3820 m_game_ui->m_flags.show_minimap, draw_wield_tool, draw_crosshair);
3825 if (m_game_ui->m_flags.show_profiler_graph)
3826 graph->draw(10, screensize.Y - 10, driver, g_fontengine->getFont());
3831 if (runData.damage_flash > 0.0f) {
3832 video::SColor color(runData.damage_flash, 180, 0, 0);
3833 driver->draw2DRectangle(color,
3834 core::rect<s32>(0, 0, screensize.X, screensize.Y),
3837 runData.damage_flash -= 384.0f * dtime;
3843 if (player->hurt_tilt_timer > 0.0f) {
3844 player->hurt_tilt_timer -= dtime * 6.0f;
3846 if (player->hurt_tilt_timer < 0.0f)
3847 player->hurt_tilt_strength = 0.0f;
3851 Update minimap pos and rotation
3853 if (mapper && m_game_ui->m_flags.show_minimap && m_game_ui->m_flags.show_hud) {
3854 mapper->setPos(floatToInt(player->getPosition(), BS));
3855 mapper->setAngle(player->getYaw());
3863 stats->drawtime = tt_draw.stop(true);
3864 g_profiler->avg("Game::updateFrame(): draw scene [ms]", stats->drawtime);
3865 g_profiler->graphAdd("Update frame [ms]", tt_update.stop(true));
3868 /* Log times and stuff for visualization */
3869 inline void Game::updateProfilerGraphs(ProfilerGraph *graph)
3871 Profiler::GraphValues values;
3872 g_profiler->graphGet(values);
3878 /****************************************************************************
3880 ****************************************************************************/
3882 /* On some computers framerate doesn't seem to be automatically limited
3884 inline void Game::limitFps(FpsControl *fps_timings, f32 *dtime)
3886 // not using getRealTime is necessary for wine
3887 device->getTimer()->tick(); // Maker sure device time is up-to-date
3888 u32 time = device->getTimer()->getTime();
3889 u32 last_time = fps_timings->last_time;
3891 if (time > last_time) // Make sure time hasn't overflowed
3892 fps_timings->busy_time = time - last_time;
3894 fps_timings->busy_time = 0;
3896 u32 frametime_min = 1000 / (g_menumgr.pausesGame()
3897 ? g_settings->getFloat("pause_fps_max")
3898 : g_settings->getFloat("fps_max"));
3900 if (fps_timings->busy_time < frametime_min) {
3901 fps_timings->sleep_time = frametime_min - fps_timings->busy_time;
3902 device->sleep(fps_timings->sleep_time);
3904 fps_timings->sleep_time = 0;
3907 /* Get the new value of the device timer. Note that device->sleep() may
3908 * not sleep for the entire requested time as sleep may be interrupted and
3909 * therefore it is arguably more accurate to get the new time from the
3910 * device rather than calculating it by adding sleep_time to time.
3913 device->getTimer()->tick(); // Update device timer
3914 time = device->getTimer()->getTime();
3916 if (time > last_time) // Make sure last_time hasn't overflowed
3917 *dtime = (time - last_time) / 1000.0;
3921 fps_timings->last_time = time;
3924 void Game::showOverlayMessage(const char *msg, float dtime, int percent, bool draw_clouds)
3926 const wchar_t *wmsg = wgettext(msg);
3927 RenderingEngine::draw_load_screen(wmsg, guienv, texture_src, dtime, percent,
3932 void Game::settingChangedCallback(const std::string &setting_name, void *data)
3934 ((Game *)data)->readSettings();
3937 void Game::readSettings()
3939 m_cache_doubletap_jump = g_settings->getBool("doubletap_jump");
3940 m_cache_enable_clouds = g_settings->getBool("enable_clouds");
3941 m_cache_enable_joysticks = g_settings->getBool("enable_joysticks");
3942 m_cache_enable_particles = g_settings->getBool("enable_particles");
3943 m_cache_enable_fog = g_settings->getBool("enable_fog");
3944 m_cache_mouse_sensitivity = g_settings->getFloat("mouse_sensitivity");
3945 m_cache_joystick_frustum_sensitivity = g_settings->getFloat("joystick_frustum_sensitivity");
3946 m_repeat_right_click_time = g_settings->getFloat("repeat_rightclick_time");
3948 m_cache_enable_noclip = g_settings->getBool("noclip");
3949 m_cache_enable_free_move = g_settings->getBool("free_move");
3951 m_cache_fog_start = g_settings->getFloat("fog_start");
3953 m_cache_cam_smoothing = 0;
3954 if (g_settings->getBool("cinematic"))
3955 m_cache_cam_smoothing = 1 - g_settings->getFloat("cinematic_camera_smoothing");
3957 m_cache_cam_smoothing = 1 - g_settings->getFloat("camera_smoothing");
3959 m_cache_fog_start = rangelim(m_cache_fog_start, 0.0f, 0.99f);
3960 m_cache_cam_smoothing = rangelim(m_cache_cam_smoothing, 0.01f, 1.0f);
3961 m_cache_mouse_sensitivity = rangelim(m_cache_mouse_sensitivity, 0.001, 100.0);
3963 m_does_lost_focus_pause_game = g_settings->getBool("pause_on_lost_focus");
3966 /****************************************************************************/
3967 /****************************************************************************
3969 ****************************************************************************/
3970 /****************************************************************************/
3972 void Game::extendedResourceCleanup()
3974 // Extended resource accounting
3975 infostream << "Irrlicht resources after cleanup:" << std::endl;
3976 infostream << "\tRemaining meshes : "
3977 << RenderingEngine::get_mesh_cache()->getMeshCount() << std::endl;
3978 infostream << "\tRemaining textures : "
3979 << driver->getTextureCount() << std::endl;
3981 for (unsigned int i = 0; i < driver->getTextureCount(); i++) {
3982 irr::video::ITexture *texture = driver->getTextureByIndex(i);
3983 infostream << "\t\t" << i << ":" << texture->getName().getPath().c_str()
3987 clearTextureNameCache();
3988 infostream << "\tRemaining materials: "
3989 << driver-> getMaterialRendererCount()
3990 << " (note: irrlicht doesn't support removing renderers)" << std::endl;
3993 void Game::showDeathFormspec()
3995 static std::string formspec_str =
3996 std::string(FORMSPEC_VERSION_STRING) +
3998 "bgcolor[#320000b4;true]"
3999 "label[4.85,1.35;" + gettext("You died") + "]"
4000 "button_exit[4,3;3,0.5;btn_respawn;" + gettext("Respawn") + "]"
4004 /* Note: FormspecFormSource and LocalFormspecHandler *
4005 * are deleted by guiFormSpecMenu */
4006 FormspecFormSource *fs_src = new FormspecFormSource(formspec_str);
4007 LocalFormspecHandler *txt_dst = new LocalFormspecHandler("MT_DEATH_SCREEN", client);
4009 auto *&formspec = m_game_ui->getFormspecGUI();
4010 GUIFormSpecMenu::create(formspec, client, &input->joystick,
4011 fs_src, txt_dst, client->getFormspecPrepend());
4012 formspec->setFocus("btn_respawn");
4015 #define GET_KEY_NAME(KEY) gettext(getKeySetting(#KEY).name())
4016 void Game::showPauseMenu()
4019 static const std::string control_text = strgettext("Default Controls:\n"
4020 "No menu visible:\n"
4021 "- single tap: button activate\n"
4022 "- double tap: place/use\n"
4023 "- slide finger: look around\n"
4024 "Menu/Inventory visible:\n"
4025 "- double tap (outside):\n"
4027 "- touch stack, touch slot:\n"
4029 "- touch&drag, tap 2nd finger\n"
4030 " --> place single item to slot\n"
4033 static const std::string control_text_template = strgettext("Controls:\n"
4034 "- %s: move forwards\n"
4035 "- %s: move backwards\n"
4037 "- %s: move right\n"
4038 "- %s: jump/climb\n"
4039 "- %s: sneak/go down\n"
4042 "- Mouse: turn/look\n"
4043 "- Mouse left: dig/punch\n"
4044 "- Mouse right: place/use\n"
4045 "- Mouse wheel: select item\n"
4049 char control_text_buf[600];
4051 porting::mt_snprintf(control_text_buf, sizeof(control_text_buf), control_text_template.c_str(),
4052 GET_KEY_NAME(keymap_forward),
4053 GET_KEY_NAME(keymap_backward),
4054 GET_KEY_NAME(keymap_left),
4055 GET_KEY_NAME(keymap_right),
4056 GET_KEY_NAME(keymap_jump),
4057 GET_KEY_NAME(keymap_sneak),
4058 GET_KEY_NAME(keymap_drop),
4059 GET_KEY_NAME(keymap_inventory),
4060 GET_KEY_NAME(keymap_chat)
4063 std::string control_text = std::string(control_text_buf);
4064 str_formspec_escape(control_text);
4067 float ypos = simple_singleplayer_mode ? 0.7f : 0.1f;
4068 std::ostringstream os;
4070 os << FORMSPEC_VERSION_STRING << SIZE_TAG
4071 << "button_exit[4," << (ypos++) << ";3,0.5;btn_continue;"
4072 << strgettext("Continue") << "]";
4074 if (!simple_singleplayer_mode) {
4075 os << "button_exit[4," << (ypos++) << ";3,0.5;btn_change_password;"
4076 << strgettext("Change Password") << "]";
4078 os << "field[4.95,0;5,1.5;;" << strgettext("Game paused") << ";]";
4082 os << "button_exit[4," << (ypos++) << ";3,0.5;btn_sound;"
4083 << strgettext("Sound Volume") << "]";
4084 os << "button_exit[4," << (ypos++) << ";3,0.5;btn_key_config;"
4085 << strgettext("Change Keys") << "]";
4087 os << "button_exit[4," << (ypos++) << ";3,0.5;btn_exit_menu;"
4088 << strgettext("Exit to Menu") << "]";
4089 os << "button_exit[4," << (ypos++) << ";3,0.5;btn_exit_os;"
4090 << strgettext("Exit to OS") << "]"
4091 << "textarea[7.5,0.25;3.9,6.25;;" << control_text << ";]"
4092 << "textarea[0.4,0.25;3.9,6.25;;" << PROJECT_NAME_C " " VERSION_STRING "\n"
4094 << strgettext("Game info:") << "\n";
4095 const std::string &address = client->getAddressName();
4096 static const std::string mode = strgettext("- Mode: ");
4097 if (!simple_singleplayer_mode) {
4098 Address serverAddress = client->getServerAddress();
4099 if (!address.empty()) {
4100 os << mode << strgettext("Remote server") << "\n"
4101 << strgettext("- Address: ") << address;
4103 os << mode << strgettext("Hosting server");
4105 os << "\n" << strgettext("- Port: ") << serverAddress.getPort() << "\n";
4107 os << mode << strgettext("Singleplayer") << "\n";
4109 if (simple_singleplayer_mode || address.empty()) {
4110 static const std::string on = strgettext("On");
4111 static const std::string off = strgettext("Off");
4112 const std::string &damage = g_settings->getBool("enable_damage") ? on : off;
4113 const std::string &creative = g_settings->getBool("creative_mode") ? on : off;
4114 const std::string &announced = g_settings->getBool("server_announce") ? on : off;
4115 os << strgettext("- Damage: ") << damage << "\n"
4116 << strgettext("- Creative Mode: ") << creative << "\n";
4117 if (!simple_singleplayer_mode) {
4118 const std::string &pvp = g_settings->getBool("enable_pvp") ? on : off;
4119 os << strgettext("- PvP: ") << pvp << "\n"
4120 << strgettext("- Public: ") << announced << "\n";
4121 std::string server_name = g_settings->get("server_name");
4122 str_formspec_escape(server_name);
4123 if (announced == on && !server_name.empty())
4124 os << strgettext("- Server Name: ") << server_name;
4131 /* Note: FormspecFormSource and LocalFormspecHandler *
4132 * are deleted by guiFormSpecMenu */
4133 FormspecFormSource *fs_src = new FormspecFormSource(os.str());
4134 LocalFormspecHandler *txt_dst = new LocalFormspecHandler("MT_PAUSE_MENU");
4136 auto *&formspec = m_game_ui->getFormspecGUI();
4137 GUIFormSpecMenu::create(formspec, client, &input->joystick,
4138 fs_src, txt_dst, client->getFormspecPrepend());
4139 formspec->setFocus("btn_continue");
4140 formspec->doPause = true;
4143 /****************************************************************************/
4144 /****************************************************************************
4145 extern function for launching the game
4146 ****************************************************************************/
4147 /****************************************************************************/
4149 void the_game(bool *kill,
4151 InputHandler *input,
4152 const std::string &map_dir,
4153 const std::string &playername,
4154 const std::string &password,
4155 const std::string &address, // If empty local server is created
4158 std::string &error_message,
4159 ChatBackend &chat_backend,
4160 bool *reconnect_requested,
4161 const SubgameSpec &gamespec, // Used for local game
4162 bool simple_singleplayer_mode)
4166 /* Make a copy of the server address because if a local singleplayer server
4167 * is created then this is updated and we don't want to change the value
4168 * passed to us by the calling function
4170 std::string server_address = address;
4174 if (game.startup(kill, random_input, input, map_dir,
4175 playername, password, &server_address, port, error_message,
4176 reconnect_requested, &chat_backend, gamespec,
4177 simple_singleplayer_mode)) {
4182 } catch (SerializationError &e) {
4183 error_message = std::string("A serialization error occurred:\n")
4184 + e.what() + "\n\nThe server is probably "
4185 " running a different version of " PROJECT_NAME_C ".";
4186 errorstream << error_message << std::endl;
4187 } catch (ServerError &e) {
4188 error_message = e.what();
4189 errorstream << "ServerError: " << error_message << std::endl;
4190 } catch (ModError &e) {
4191 error_message = std::string("ModError: ") + e.what() +
4192 strgettext("\nCheck debug.txt for details.");
4193 errorstream << error_message << std::endl;