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->modsLoaded())
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 reset_jump_timer;
603 float nodig_delay_timer;
605 float dig_time_complete;
606 float repeat_rightclick_timer;
607 float object_hit_delay_timer;
608 float time_from_last_punch;
609 ClientActiveObject *selected_object;
613 float update_draw_list_timer;
617 v3f update_draw_list_last_cam_dir;
619 float time_of_day_smooth;
624 struct ClientEventHandler
626 void (Game::*handler)(ClientEvent *, CameraOrientation *);
629 /****************************************************************************
631 ****************************************************************************/
633 /* This is not intended to be a public class. If a public class becomes
634 * desirable then it may be better to create another 'wrapper' class that
635 * hides most of the stuff in this class (nothing in this class is required
636 * by any other file) but exposes the public methods/data only.
643 bool startup(bool *kill,
646 const std::string &map_dir,
647 const std::string &playername,
648 const std::string &password,
649 // If address is "", local server is used and address is updated
650 std::string *address,
652 std::string &error_message,
654 ChatBackend *chat_backend,
655 const SubgameSpec &gamespec, // Used for local game
656 bool simple_singleplayer_mode);
663 void extendedResourceCleanup();
665 // Basic initialisation
666 bool init(const std::string &map_dir, std::string *address,
668 const SubgameSpec &gamespec);
670 bool createSingleplayerServer(const std::string &map_dir,
671 const SubgameSpec &gamespec, u16 port, std::string *address);
674 bool createClient(const std::string &playername,
675 const std::string &password, std::string *address, u16 port);
679 bool connectToServer(const std::string &playername,
680 const std::string &password, std::string *address, u16 port,
681 bool *connect_ok, bool *aborted);
682 bool getServerContent(bool *aborted);
686 void updateInteractTimers(f32 dtime);
687 bool checkConnection();
688 bool handleCallbacks();
689 void processQueues();
690 void updateProfilers(const RunStats &stats, const FpsControl &draw_times, f32 dtime);
691 void updateStats(RunStats *stats, const FpsControl &draw_times, f32 dtime);
692 void updateProfilerGraphs(ProfilerGraph *graph);
695 void processUserInput(f32 dtime);
696 void processKeyInput();
697 void processItemSelection(u16 *new_playeritem);
699 void dropSelectedItem(bool single_item = false);
700 void openInventory();
701 void openConsole(float scale, const wchar_t *line=NULL);
702 void toggleFreeMove();
703 void toggleFreeMoveAlt();
704 void togglePitchMove();
707 void toggleCinematic();
708 void toggleAutoforward();
710 void toggleMinimap(bool shift_pressed);
713 void toggleUpdateCamera();
715 void increaseViewRange();
716 void decreaseViewRange();
717 void toggleFullViewRange();
718 void checkZoomEnabled();
720 void updateCameraDirection(CameraOrientation *cam, float dtime);
721 void updateCameraOrientation(CameraOrientation *cam, float dtime);
722 void updatePlayerControl(const CameraOrientation &cam);
723 void step(f32 *dtime);
724 void processClientEvents(CameraOrientation *cam);
725 void updateCamera(u32 busy_time, f32 dtime);
726 void updateSound(f32 dtime);
727 void processPlayerInteraction(f32 dtime, bool show_hud, bool show_debug);
729 * Returns the object or node the player is pointing at.
730 * Also updates the selected thing in the Hud.
732 * @param[in] shootline the shootline, starting from
733 * the camera position. This also gives the maximal distance
735 * @param[in] liquids_pointable if false, liquids are ignored
736 * @param[in] look_for_object if false, objects are ignored
737 * @param[in] camera_offset offset of the camera
738 * @param[out] selected_object the selected object or
741 PointedThing updatePointedThing(
742 const core::line3d<f32> &shootline, bool liquids_pointable,
743 bool look_for_object, const v3s16 &camera_offset);
744 void handlePointingAtNothing(const ItemStack &playerItem);
745 void handlePointingAtNode(const PointedThing &pointed,
746 const ItemStack &selected_item, const ItemStack &hand_item, f32 dtime);
747 void handlePointingAtObject(const PointedThing &pointed, const ItemStack &playeritem,
748 const v3f &player_position, bool show_debug);
749 void handleDigging(const PointedThing &pointed, const v3s16 &nodepos,
750 const ItemStack &selected_item, const ItemStack &hand_item, f32 dtime);
751 void updateFrame(ProfilerGraph *graph, RunStats *stats, f32 dtime,
752 const CameraOrientation &cam);
755 void limitFps(FpsControl *fps_timings, f32 *dtime);
757 void showOverlayMessage(const char *msg, float dtime, int percent,
758 bool draw_clouds = true);
760 static void settingChangedCallback(const std::string &setting_name, void *data);
763 inline bool isKeyDown(GameKeyType k)
765 return input->isKeyDown(k);
767 inline bool wasKeyDown(GameKeyType k)
769 return input->wasKeyDown(k);
773 void handleAndroidChatInput();
778 bool force_fog_off = false;
779 bool disable_camera_update = false;
782 void showDeathFormspec();
783 void showPauseMenu();
785 // ClientEvent handlers
786 void handleClientEvent_None(ClientEvent *event, CameraOrientation *cam);
787 void handleClientEvent_PlayerDamage(ClientEvent *event, CameraOrientation *cam);
788 void handleClientEvent_PlayerForceMove(ClientEvent *event, CameraOrientation *cam);
789 void handleClientEvent_Deathscreen(ClientEvent *event, CameraOrientation *cam);
790 void handleClientEvent_ShowFormSpec(ClientEvent *event, CameraOrientation *cam);
791 void handleClientEvent_ShowLocalFormSpec(ClientEvent *event, CameraOrientation *cam);
792 void handleClientEvent_HandleParticleEvent(ClientEvent *event,
793 CameraOrientation *cam);
794 void handleClientEvent_HudAdd(ClientEvent *event, CameraOrientation *cam);
795 void handleClientEvent_HudRemove(ClientEvent *event, CameraOrientation *cam);
796 void handleClientEvent_HudChange(ClientEvent *event, CameraOrientation *cam);
797 void handleClientEvent_SetSky(ClientEvent *event, CameraOrientation *cam);
798 void handleClientEvent_OverrideDayNigthRatio(ClientEvent *event,
799 CameraOrientation *cam);
800 void handleClientEvent_CloudParams(ClientEvent *event, CameraOrientation *cam);
802 void updateChat(f32 dtime, const v2u32 &screensize);
804 bool nodePlacementPrediction(const ItemDefinition &selected_def,
805 const ItemStack &selected_item, const v3s16 &nodepos, const v3s16 &neighbourpos);
806 static const ClientEventHandler clientEventHandler[CLIENTEVENT_MAX];
808 InputHandler *input = nullptr;
810 Client *client = nullptr;
811 Server *server = nullptr;
813 IWritableTextureSource *texture_src = nullptr;
814 IWritableShaderSource *shader_src = nullptr;
816 // When created, these will be filled with data received from the server
817 IWritableItemDefManager *itemdef_manager = nullptr;
818 NodeDefManager *nodedef_manager = nullptr;
820 GameOnDemandSoundFetcher soundfetcher; // useful when testing
821 ISoundManager *sound = nullptr;
822 bool sound_is_dummy = false;
823 SoundMaker *soundmaker = nullptr;
825 ChatBackend *chat_backend = nullptr;
827 EventManager *eventmgr = nullptr;
828 QuicktuneShortcutter *quicktune = nullptr;
829 bool registration_confirmation_shown = false;
831 std::unique_ptr<GameUI> m_game_ui;
832 GUIChatConsole *gui_chat_console = nullptr; // Free using ->Drop()
833 MapDrawControl *draw_control = nullptr;
834 Camera *camera = nullptr;
835 Clouds *clouds = nullptr; // Free using ->Drop()
836 Sky *sky = nullptr; // Free using ->Drop()
838 Minimap *mapper = nullptr;
844 This class does take ownership/responsibily for cleaning up etc of any of
845 these items (e.g. device)
847 IrrlichtDevice *device;
848 video::IVideoDriver *driver;
849 scene::ISceneManager *smgr;
851 std::string *error_message;
852 bool *reconnect_requested;
853 scene::ISceneNode *skybox;
856 bool simple_singleplayer_mode;
859 /* Pre-calculated values
861 int crack_animation_length;
863 IntervalLimiter profiler_interval;
866 * TODO: Local caching of settings is not optimal and should at some stage
867 * be updated to use a global settings object for getting thse values
868 * (as opposed to the this local caching). This can be addressed in
871 bool m_cache_doubletap_jump;
872 bool m_cache_enable_clouds;
873 bool m_cache_enable_joysticks;
874 bool m_cache_enable_particles;
875 bool m_cache_enable_fog;
876 bool m_cache_enable_noclip;
877 bool m_cache_enable_free_move;
878 f32 m_cache_mouse_sensitivity;
879 f32 m_cache_joystick_frustum_sensitivity;
880 f32 m_repeat_right_click_time;
881 f32 m_cache_cam_smoothing;
882 f32 m_cache_fog_start;
884 bool m_invert_mouse = false;
885 bool m_first_loop_after_window_activation = false;
886 bool m_camera_offset_changed = false;
888 bool m_does_lost_focus_pause_game = false;
891 bool m_cache_hold_aux1;
892 bool m_android_chat_open;
897 m_game_ui(new GameUI())
899 g_settings->registerChangedCallback("doubletap_jump",
900 &settingChangedCallback, this);
901 g_settings->registerChangedCallback("enable_clouds",
902 &settingChangedCallback, this);
903 g_settings->registerChangedCallback("doubletap_joysticks",
904 &settingChangedCallback, this);
905 g_settings->registerChangedCallback("enable_particles",
906 &settingChangedCallback, this);
907 g_settings->registerChangedCallback("enable_fog",
908 &settingChangedCallback, this);
909 g_settings->registerChangedCallback("mouse_sensitivity",
910 &settingChangedCallback, this);
911 g_settings->registerChangedCallback("joystick_frustum_sensitivity",
912 &settingChangedCallback, this);
913 g_settings->registerChangedCallback("repeat_rightclick_time",
914 &settingChangedCallback, this);
915 g_settings->registerChangedCallback("noclip",
916 &settingChangedCallback, this);
917 g_settings->registerChangedCallback("free_move",
918 &settingChangedCallback, this);
919 g_settings->registerChangedCallback("cinematic",
920 &settingChangedCallback, this);
921 g_settings->registerChangedCallback("cinematic_camera_smoothing",
922 &settingChangedCallback, this);
923 g_settings->registerChangedCallback("camera_smoothing",
924 &settingChangedCallback, this);
929 m_cache_hold_aux1 = false; // This is initialised properly later
936 /****************************************************************************
938 ****************************************************************************/
947 delete server; // deleted first to stop all server threads
955 delete nodedef_manager;
956 delete itemdef_manager;
959 extendedResourceCleanup();
961 g_settings->deregisterChangedCallback("doubletap_jump",
962 &settingChangedCallback, this);
963 g_settings->deregisterChangedCallback("enable_clouds",
964 &settingChangedCallback, this);
965 g_settings->deregisterChangedCallback("enable_particles",
966 &settingChangedCallback, this);
967 g_settings->deregisterChangedCallback("enable_fog",
968 &settingChangedCallback, this);
969 g_settings->deregisterChangedCallback("mouse_sensitivity",
970 &settingChangedCallback, this);
971 g_settings->deregisterChangedCallback("repeat_rightclick_time",
972 &settingChangedCallback, this);
973 g_settings->deregisterChangedCallback("noclip",
974 &settingChangedCallback, this);
975 g_settings->deregisterChangedCallback("free_move",
976 &settingChangedCallback, this);
977 g_settings->deregisterChangedCallback("cinematic",
978 &settingChangedCallback, this);
979 g_settings->deregisterChangedCallback("cinematic_camera_smoothing",
980 &settingChangedCallback, this);
981 g_settings->deregisterChangedCallback("camera_smoothing",
982 &settingChangedCallback, this);
985 bool Game::startup(bool *kill,
988 const std::string &map_dir,
989 const std::string &playername,
990 const std::string &password,
991 std::string *address, // can change if simple_singleplayer_mode
993 std::string &error_message,
995 ChatBackend *chat_backend,
996 const SubgameSpec &gamespec,
997 bool simple_singleplayer_mode)
1000 this->device = RenderingEngine::get_raw_device();
1002 this->error_message = &error_message;
1003 this->reconnect_requested = reconnect;
1004 this->random_input = random_input;
1005 this->input = input;
1006 this->chat_backend = chat_backend;
1007 this->simple_singleplayer_mode = simple_singleplayer_mode;
1009 input->keycache.populate();
1011 driver = device->getVideoDriver();
1012 smgr = RenderingEngine::get_scene_manager();
1014 RenderingEngine::get_scene_manager()->getParameters()->
1015 setAttribute(scene::OBJ_LOADER_IGNORE_MATERIAL_FILES, true);
1018 runData = GameRunData();
1019 runData.time_from_last_punch = 10.0;
1021 m_game_ui->initFlags();
1023 m_invert_mouse = g_settings->getBool("invert_mouse");
1024 m_first_loop_after_window_activation = true;
1026 g_translations->clear();
1028 if (!init(map_dir, address, port, gamespec))
1031 if (!createClient(playername, password, address, port))
1034 RenderingEngine::initialize(client, hud);
1042 ProfilerGraph graph;
1043 RunStats stats = { 0 };
1044 CameraOrientation cam_view_target = { 0 };
1045 CameraOrientation cam_view = { 0 };
1046 FpsControl draw_times = { 0 };
1047 f32 dtime; // in seconds
1049 /* Clear the profiler */
1050 Profiler::GraphValues dummyvalues;
1051 g_profiler->graphGet(dummyvalues);
1053 draw_times.last_time = RenderingEngine::get_timer_time();
1055 set_light_table(g_settings->getFloat("display_gamma"));
1058 m_cache_hold_aux1 = g_settings->getBool("fast_move")
1059 && client->checkPrivilege("fast");
1062 irr::core::dimension2d<u32> previous_screen_size(g_settings->getU16("screen_w"),
1063 g_settings->getU16("screen_h"));
1065 while (RenderingEngine::run()
1066 && !(*kill || g_gamecallback->shutdown_requested
1067 || (server && server->isShutdownRequested()))) {
1069 const irr::core::dimension2d<u32> ¤t_screen_size =
1070 RenderingEngine::get_video_driver()->getScreenSize();
1071 // Verify if window size has changed and save it if it's the case
1072 // Ensure evaluating settings->getBool after verifying screensize
1073 // First condition is cheaper
1074 if (previous_screen_size != current_screen_size &&
1075 current_screen_size != irr::core::dimension2d<u32>(0,0) &&
1076 g_settings->getBool("autosave_screensize")) {
1077 g_settings->setU16("screen_w", current_screen_size.Width);
1078 g_settings->setU16("screen_h", current_screen_size.Height);
1079 previous_screen_size = current_screen_size;
1082 // Calculate dtime =
1083 // RenderingEngine::run() from this iteration
1084 // + Sleep time until the wanted FPS are reached
1085 limitFps(&draw_times, &dtime);
1087 // Prepare render data for next iteration
1089 updateStats(&stats, draw_times, dtime);
1090 updateInteractTimers(dtime);
1092 if (!checkConnection())
1094 if (!handleCallbacks())
1099 m_game_ui->clearInfoText();
1100 hud->resizeHotbar();
1102 updateProfilers(stats, draw_times, dtime);
1103 processUserInput(dtime);
1104 // Update camera before player movement to avoid camera lag of one frame
1105 updateCameraDirection(&cam_view_target, dtime);
1106 cam_view.camera_yaw += (cam_view_target.camera_yaw -
1107 cam_view.camera_yaw) * m_cache_cam_smoothing;
1108 cam_view.camera_pitch += (cam_view_target.camera_pitch -
1109 cam_view.camera_pitch) * m_cache_cam_smoothing;
1110 updatePlayerControl(cam_view);
1112 processClientEvents(&cam_view_target);
1113 updateCamera(draw_times.busy_time, dtime);
1115 processPlayerInteraction(dtime, m_game_ui->m_flags.show_hud,
1116 m_game_ui->m_flags.show_debug);
1117 updateFrame(&graph, &stats, dtime, cam_view);
1118 updateProfilerGraphs(&graph);
1120 // Update if minimap has been disabled by the server
1121 m_game_ui->m_flags.show_minimap &= client->shouldShowMinimap();
1123 if (m_does_lost_focus_pause_game && !device->isWindowFocused() && !isMenuActive()) {
1130 void Game::shutdown()
1132 RenderingEngine::finalize();
1133 #if IRRLICHT_VERSION_MAJOR == 1 && IRRLICHT_VERSION_MINOR <= 8
1134 if (g_settings->get("3d_mode") == "pageflip") {
1135 driver->setRenderTarget(irr::video::ERT_STEREO_BOTH_BUFFERS);
1138 auto formspec = m_game_ui->getFormspecGUI();
1140 formspec->quitMenu();
1142 showOverlayMessage(N_("Shutting down..."), 0, 0, false);
1147 if (gui_chat_console)
1148 gui_chat_console->drop();
1154 while (g_menumgr.menuCount() > 0) {
1155 g_menumgr.m_stack.front()->setVisible(false);
1156 g_menumgr.deletingMenu(g_menumgr.m_stack.front());
1159 m_game_ui->deleteFormspec();
1161 chat_backend->addMessage(L"", L"# Disconnected.");
1162 chat_backend->addMessage(L"", L"");
1166 while (!client->isShutdown()) {
1167 assert(texture_src != NULL);
1168 assert(shader_src != NULL);
1169 texture_src->processQueue();
1170 shader_src->processQueue();
1177 /****************************************************************************/
1178 /****************************************************************************
1180 ****************************************************************************/
1181 /****************************************************************************/
1184 const std::string &map_dir,
1185 std::string *address,
1187 const SubgameSpec &gamespec)
1189 texture_src = createTextureSource();
1191 showOverlayMessage(N_("Loading..."), 0, 0);
1193 shader_src = createShaderSource();
1195 itemdef_manager = createItemDefManager();
1196 nodedef_manager = createNodeDefManager();
1198 eventmgr = new EventManager();
1199 quicktune = new QuicktuneShortcutter();
1201 if (!(texture_src && shader_src && itemdef_manager && nodedef_manager
1202 && eventmgr && quicktune))
1208 // Create a server if not connecting to an existing one
1209 if (address->empty()) {
1210 if (!createSingleplayerServer(map_dir, gamespec, port, address))
1217 bool Game::initSound()
1220 if (g_settings->getBool("enable_sound")) {
1221 infostream << "Attempting to use OpenAL audio" << std::endl;
1222 sound = createOpenALSoundManager(g_sound_manager_singleton.get(), &soundfetcher);
1224 infostream << "Failed to initialize OpenAL audio" << std::endl;
1226 infostream << "Sound disabled." << std::endl;
1230 infostream << "Using dummy audio." << std::endl;
1231 sound = &dummySoundManager;
1232 sound_is_dummy = true;
1235 soundmaker = new SoundMaker(sound, nodedef_manager);
1239 soundmaker->registerReceiver(eventmgr);
1244 bool Game::createSingleplayerServer(const std::string &map_dir,
1245 const SubgameSpec &gamespec, u16 port, std::string *address)
1247 showOverlayMessage(N_("Creating server..."), 0, 5);
1249 std::string bind_str = g_settings->get("bind_address");
1250 Address bind_addr(0, 0, 0, 0, port);
1252 if (g_settings->getBool("ipv6_server")) {
1253 bind_addr.setAddress((IPv6AddressBytes *) NULL);
1257 bind_addr.Resolve(bind_str.c_str());
1258 } catch (ResolveError &e) {
1259 infostream << "Resolving bind address \"" << bind_str
1260 << "\" failed: " << e.what()
1261 << " -- Listening on all addresses." << std::endl;
1264 if (bind_addr.isIPv6() && !g_settings->getBool("enable_ipv6")) {
1265 *error_message = "Unable to listen on " +
1266 bind_addr.serializeString() +
1267 " because IPv6 is disabled";
1268 errorstream << *error_message << std::endl;
1272 server = new Server(map_dir, gamespec, simple_singleplayer_mode, bind_addr, false);
1279 bool Game::createClient(const std::string &playername,
1280 const std::string &password, std::string *address, u16 port)
1282 showOverlayMessage(N_("Creating client..."), 0, 10);
1284 draw_control = new MapDrawControl;
1288 bool could_connect, connect_aborted;
1289 #ifdef HAVE_TOUCHSCREENGUI
1290 if (g_touchscreengui) {
1291 g_touchscreengui->init(texture_src);
1292 g_touchscreengui->hide();
1295 if (!connectToServer(playername, password, address, port,
1296 &could_connect, &connect_aborted))
1299 if (!could_connect) {
1300 if (error_message->empty() && !connect_aborted) {
1301 // Should not happen if error messages are set properly
1302 *error_message = "Connection failed for unknown reason";
1303 errorstream << *error_message << std::endl;
1308 if (!getServerContent(&connect_aborted)) {
1309 if (error_message->empty() && !connect_aborted) {
1310 // Should not happen if error messages are set properly
1311 *error_message = "Connection failed for unknown reason";
1312 errorstream << *error_message << std::endl;
1317 GameGlobalShaderConstantSetterFactory *scsf = new GameGlobalShaderConstantSetterFactory(
1318 &m_flags.force_fog_off, &runData.fog_range, client);
1319 shader_src->addShaderConstantSetterFactory(scsf);
1321 // Update cached textures, meshes and materials
1322 client->afterContentReceived();
1326 camera = new Camera(*draw_control, client);
1327 if (!camera || !camera->successfullyCreated(*error_message))
1329 client->setCamera(camera);
1333 if (m_cache_enable_clouds) {
1334 clouds = new Clouds(smgr, -1, time(0));
1336 *error_message = "Memory allocation error (clouds)";
1337 errorstream << *error_message << std::endl;
1344 sky = new Sky(-1, texture_src);
1346 skybox = NULL; // This is used/set later on in the main run loop
1349 *error_message = "Memory allocation error sky";
1350 errorstream << *error_message << std::endl;
1354 /* Pre-calculated values
1356 video::ITexture *t = texture_src->getTexture("crack_anylength.png");
1358 v2u32 size = t->getOriginalSize();
1359 crack_animation_length = size.Y / size.X;
1361 crack_animation_length = 5;
1367 /* Set window caption
1369 std::wstring str = utf8_to_wide(PROJECT_NAME_C);
1371 str += utf8_to_wide(g_version_hash);
1373 str += driver->getName();
1375 device->setWindowCaption(str.c_str());
1377 LocalPlayer *player = client->getEnv().getLocalPlayer();
1378 player->hurt_tilt_timer = 0;
1379 player->hurt_tilt_strength = 0;
1381 hud = new Hud(guienv, client, player, &player->inventory);
1384 *error_message = "Memory error: could not create HUD";
1385 errorstream << *error_message << std::endl;
1389 mapper = client->getMinimap();
1391 mapper->setMinimapMode(MINIMAP_MODE_OFF);
1396 bool Game::initGui()
1400 // Remove stale "recent" chat messages from previous connections
1401 chat_backend->clearRecentChat();
1403 // Make sure the size of the recent messages buffer is right
1404 chat_backend->applySettings();
1406 // Chat backend and console
1407 gui_chat_console = new GUIChatConsole(guienv, guienv->getRootGUIElement(),
1408 -1, chat_backend, client, &g_menumgr);
1409 if (!gui_chat_console) {
1410 *error_message = "Could not allocate memory for chat console";
1411 errorstream << *error_message << std::endl;
1415 #ifdef HAVE_TOUCHSCREENGUI
1417 if (g_touchscreengui)
1418 g_touchscreengui->show();
1425 bool Game::connectToServer(const std::string &playername,
1426 const std::string &password, std::string *address, u16 port,
1427 bool *connect_ok, bool *connection_aborted)
1429 *connect_ok = false; // Let's not be overly optimistic
1430 *connection_aborted = false;
1431 bool local_server_mode = false;
1433 showOverlayMessage(N_("Resolving address..."), 0, 15);
1435 Address connect_address(0, 0, 0, 0, port);
1438 connect_address.Resolve(address->c_str());
1440 if (connect_address.isZero()) { // i.e. INADDR_ANY, IN6ADDR_ANY
1441 //connect_address.Resolve("localhost");
1442 if (connect_address.isIPv6()) {
1443 IPv6AddressBytes addr_bytes;
1444 addr_bytes.bytes[15] = 1;
1445 connect_address.setAddress(&addr_bytes);
1447 connect_address.setAddress(127, 0, 0, 1);
1449 local_server_mode = true;
1451 } catch (ResolveError &e) {
1452 *error_message = std::string("Couldn't resolve address: ") + e.what();
1453 errorstream << *error_message << std::endl;
1457 if (connect_address.isIPv6() && !g_settings->getBool("enable_ipv6")) {
1458 *error_message = "Unable to connect to " +
1459 connect_address.serializeString() +
1460 " because IPv6 is disabled";
1461 errorstream << *error_message << std::endl;
1465 client = new Client(playername.c_str(), password, *address,
1466 *draw_control, texture_src, shader_src,
1467 itemdef_manager, nodedef_manager, sound, eventmgr,
1468 connect_address.isIPv6(), m_game_ui.get());
1473 client->m_simple_singleplayer_mode = simple_singleplayer_mode;
1475 infostream << "Connecting to server at ";
1476 connect_address.print(&infostream);
1477 infostream << std::endl;
1479 client->connect(connect_address,
1480 simple_singleplayer_mode || local_server_mode);
1483 Wait for server to accept connection
1489 FpsControl fps_control = { 0 };
1491 f32 wait_time = 0; // in seconds
1493 fps_control.last_time = RenderingEngine::get_timer_time();
1495 while (RenderingEngine::run()) {
1497 limitFps(&fps_control, &dtime);
1499 // Update client and server
1500 client->step(dtime);
1503 server->step(dtime);
1506 if (client->getState() == LC_Init) {
1512 if (*connection_aborted)
1515 if (client->accessDenied()) {
1516 *error_message = "Access denied. Reason: "
1517 + client->accessDeniedReason();
1518 *reconnect_requested = client->reconnectRequested();
1519 errorstream << *error_message << std::endl;
1523 if (input->cancelPressed()) {
1524 *connection_aborted = true;
1525 infostream << "Connect aborted [Escape]" << std::endl;
1529 if (client->m_is_registration_confirmation_state) {
1530 if (registration_confirmation_shown) {
1531 // Keep drawing the GUI
1532 RenderingEngine::draw_menu_scene(guienv, dtime, true);
1534 registration_confirmation_shown = true;
1535 (new GUIConfirmRegistration(guienv, guienv->getRootGUIElement(), -1,
1536 &g_menumgr, client, playername, password, connection_aborted))->drop();
1540 // Only time out if we aren't waiting for the server we started
1541 if (!address->empty() && wait_time > 10) {
1542 *error_message = "Connection timed out.";
1543 errorstream << *error_message << std::endl;
1548 showOverlayMessage(N_("Connecting to server..."), dtime, 20);
1551 } catch (con::PeerNotFoundException &e) {
1552 // TODO: Should something be done here? At least an info/error
1560 bool Game::getServerContent(bool *aborted)
1564 FpsControl fps_control = { 0 };
1565 f32 dtime; // in seconds
1567 fps_control.last_time = RenderingEngine::get_timer_time();
1569 while (RenderingEngine::run()) {
1571 limitFps(&fps_control, &dtime);
1573 // Update client and server
1574 client->step(dtime);
1577 server->step(dtime);
1580 if (client->mediaReceived() && client->itemdefReceived() &&
1581 client->nodedefReceived()) {
1586 if (!checkConnection())
1589 if (client->getState() < LC_Init) {
1590 *error_message = "Client disconnected";
1591 errorstream << *error_message << std::endl;
1595 if (input->cancelPressed()) {
1597 infostream << "Connect aborted [Escape]" << std::endl;
1604 if (!client->itemdefReceived()) {
1605 const wchar_t *text = wgettext("Item definitions...");
1607 RenderingEngine::draw_load_screen(text, guienv, texture_src,
1610 } else if (!client->nodedefReceived()) {
1611 const wchar_t *text = wgettext("Node definitions...");
1613 RenderingEngine::draw_load_screen(text, guienv, texture_src,
1617 std::stringstream message;
1618 std::fixed(message);
1619 message.precision(0);
1620 message << gettext("Media...") << " " << (client->mediaReceiveProgress()*100) << "%";
1621 message.precision(2);
1623 if ((USE_CURL == 0) ||
1624 (!g_settings->getBool("enable_remote_media_server"))) {
1625 float cur = client->getCurRate();
1626 std::string cur_unit = gettext("KiB/s");
1630 cur_unit = gettext("MiB/s");
1633 message << " (" << cur << ' ' << cur_unit << ")";
1636 progress = 30 + client->mediaReceiveProgress() * 35 + 0.5;
1637 RenderingEngine::draw_load_screen(utf8_to_wide(message.str()), guienv,
1638 texture_src, dtime, progress);
1646 /****************************************************************************/
1647 /****************************************************************************
1649 ****************************************************************************/
1650 /****************************************************************************/
1652 inline void Game::updateInteractTimers(f32 dtime)
1654 if (runData.nodig_delay_timer >= 0)
1655 runData.nodig_delay_timer -= dtime;
1657 if (runData.object_hit_delay_timer >= 0)
1658 runData.object_hit_delay_timer -= dtime;
1660 runData.time_from_last_punch += dtime;
1664 /* returns false if game should exit, otherwise true
1666 inline bool Game::checkConnection()
1668 if (client->accessDenied()) {
1669 *error_message = "Access denied. Reason: "
1670 + client->accessDeniedReason();
1671 *reconnect_requested = client->reconnectRequested();
1672 errorstream << *error_message << std::endl;
1680 /* returns false if game should exit, otherwise true
1682 inline bool Game::handleCallbacks()
1684 if (g_gamecallback->disconnect_requested) {
1685 g_gamecallback->disconnect_requested = false;
1689 if (g_gamecallback->changepassword_requested) {
1690 (new GUIPasswordChange(guienv, guiroot, -1,
1691 &g_menumgr, client))->drop();
1692 g_gamecallback->changepassword_requested = false;
1695 if (g_gamecallback->changevolume_requested) {
1696 (new GUIVolumeChange(guienv, guiroot, -1,
1697 &g_menumgr))->drop();
1698 g_gamecallback->changevolume_requested = false;
1701 if (g_gamecallback->keyconfig_requested) {
1702 (new GUIKeyChangeMenu(guienv, guiroot, -1,
1703 &g_menumgr))->drop();
1704 g_gamecallback->keyconfig_requested = false;
1707 if (g_gamecallback->keyconfig_changed) {
1708 input->keycache.populate(); // update the cache with new settings
1709 g_gamecallback->keyconfig_changed = false;
1716 void Game::processQueues()
1718 texture_src->processQueue();
1719 itemdef_manager->processQueue(client);
1720 shader_src->processQueue();
1724 void Game::updateProfilers(const RunStats &stats, const FpsControl &draw_times,
1727 float profiler_print_interval =
1728 g_settings->getFloat("profiler_print_interval");
1729 bool print_to_log = true;
1731 if (profiler_print_interval == 0) {
1732 print_to_log = false;
1733 profiler_print_interval = 3;
1736 if (profiler_interval.step(dtime, profiler_print_interval)) {
1738 infostream << "Profiler:" << std::endl;
1739 g_profiler->print(infostream);
1742 m_game_ui->updateProfiler();
1743 g_profiler->clear();
1746 // Update update graphs
1747 g_profiler->graphAdd("Time non-rendering [ms]",
1748 draw_times.busy_time - stats.drawtime);
1750 g_profiler->graphAdd("Sleep [ms]", draw_times.sleep_time);
1751 g_profiler->graphAdd("FPS", 1.0f / dtime);
1754 void Game::updateStats(RunStats *stats, const FpsControl &draw_times,
1761 /* Time average and jitter calculation
1763 jp = &stats->dtime_jitter;
1764 jp->avg = jp->avg * 0.96 + dtime * 0.04;
1766 jitter = dtime - jp->avg;
1768 if (jitter > jp->max)
1771 jp->counter += dtime;
1773 if (jp->counter > 0.0) {
1775 jp->max_sample = jp->max;
1776 jp->max_fraction = jp->max_sample / (jp->avg + 0.001);
1780 /* Busytime average and jitter calculation
1782 jp = &stats->busy_time_jitter;
1783 jp->avg = jp->avg + draw_times.busy_time * 0.02;
1785 jitter = draw_times.busy_time - jp->avg;
1787 if (jitter > jp->max)
1789 if (jitter < jp->min)
1792 jp->counter += dtime;
1794 if (jp->counter > 0.0) {
1796 jp->max_sample = jp->max;
1797 jp->min_sample = jp->min;
1805 /****************************************************************************
1807 ****************************************************************************/
1809 void Game::processUserInput(f32 dtime)
1811 // Reset input if window not active or some menu is active
1812 if (!device->isWindowActive() || isMenuActive() || guienv->hasFocus(gui_chat_console)) {
1814 #ifdef HAVE_TOUCHSCREENGUI
1815 g_touchscreengui->hide();
1818 #ifdef HAVE_TOUCHSCREENGUI
1819 else if (g_touchscreengui) {
1820 /* on touchscreengui step may generate own input events which ain't
1821 * what we want in case we just did clear them */
1822 g_touchscreengui->step(dtime);
1826 if (!guienv->hasFocus(gui_chat_console) && gui_chat_console->isOpen()) {
1827 gui_chat_console->closeConsoleAtOnce();
1830 // Input handler step() (used by the random input generator)
1834 auto formspec = m_game_ui->getFormspecGUI();
1836 formspec->getAndroidUIInput();
1838 handleAndroidChatInput();
1841 // Increase timer for double tap of "keymap_jump"
1842 if (m_cache_doubletap_jump && runData.jump_timer <= 0.2f)
1843 runData.jump_timer += dtime;
1846 processItemSelection(&runData.new_playeritem);
1850 void Game::processKeyInput()
1852 if (wasKeyDown(KeyType::DROP)) {
1853 dropSelectedItem(isKeyDown(KeyType::SNEAK));
1854 } else if (wasKeyDown(KeyType::AUTOFORWARD)) {
1855 toggleAutoforward();
1856 } else if (wasKeyDown(KeyType::BACKWARD)) {
1857 if (g_settings->getBool("continuous_forward"))
1858 toggleAutoforward();
1859 } else if (wasKeyDown(KeyType::INVENTORY)) {
1861 } else if (input->cancelPressed()) {
1863 m_android_chat_open = false;
1865 if (!gui_chat_console->isOpenInhibited()) {
1868 } else if (wasKeyDown(KeyType::CHAT)) {
1869 openConsole(0.2, L"");
1870 } else if (wasKeyDown(KeyType::CMD)) {
1871 openConsole(0.2, L"/");
1872 } else if (wasKeyDown(KeyType::CMD_LOCAL)) {
1873 if (client->modsLoaded())
1874 openConsole(0.2, L".");
1876 m_game_ui->showStatusText(wgettext("Client side scripting is disabled"));
1877 } else if (wasKeyDown(KeyType::CONSOLE)) {
1878 openConsole(core::clamp(g_settings->getFloat("console_height"), 0.1f, 1.0f));
1879 } else if (wasKeyDown(KeyType::FREEMOVE)) {
1881 } else if (wasKeyDown(KeyType::JUMP)) {
1882 toggleFreeMoveAlt();
1883 } else if (wasKeyDown(KeyType::PITCHMOVE)) {
1885 } else if (wasKeyDown(KeyType::FASTMOVE)) {
1887 } else if (wasKeyDown(KeyType::NOCLIP)) {
1889 } else if (wasKeyDown(KeyType::MUTE)) {
1890 bool new_mute_sound = !g_settings->getBool("mute_sound");
1891 g_settings->setBool("mute_sound", new_mute_sound);
1893 m_game_ui->showTranslatedStatusText("Sound muted");
1895 m_game_ui->showTranslatedStatusText("Sound unmuted");
1896 } else if (wasKeyDown(KeyType::INC_VOLUME)) {
1897 float new_volume = rangelim(g_settings->getFloat("sound_volume") + 0.1f, 0.0f, 1.0f);
1899 g_settings->setFloat("sound_volume", new_volume);
1900 const wchar_t *str = wgettext("Volume changed to %d%%");
1901 swprintf(buf, sizeof(buf) / sizeof(wchar_t), str, myround(new_volume * 100));
1903 m_game_ui->showStatusText(buf);
1904 } else if (wasKeyDown(KeyType::DEC_VOLUME)) {
1905 float new_volume = rangelim(g_settings->getFloat("sound_volume") - 0.1f, 0.0f, 1.0f);
1907 g_settings->setFloat("sound_volume", new_volume);
1908 const wchar_t *str = wgettext("Volume changed to %d%%");
1909 swprintf(buf, sizeof(buf) / sizeof(wchar_t), str, myround(new_volume * 100));
1911 m_game_ui->showStatusText(buf);
1912 } else if (wasKeyDown(KeyType::CINEMATIC)) {
1914 } else if (wasKeyDown(KeyType::SCREENSHOT)) {
1915 client->makeScreenshot();
1916 } else if (wasKeyDown(KeyType::TOGGLE_HUD)) {
1917 m_game_ui->toggleHud();
1918 } else if (wasKeyDown(KeyType::MINIMAP)) {
1919 toggleMinimap(isKeyDown(KeyType::SNEAK));
1920 } else if (wasKeyDown(KeyType::TOGGLE_CHAT)) {
1921 m_game_ui->toggleChat();
1922 } else if (wasKeyDown(KeyType::TOGGLE_FOG)) {
1924 } else if (wasKeyDown(KeyType::TOGGLE_UPDATE_CAMERA)) {
1925 toggleUpdateCamera();
1926 } else if (wasKeyDown(KeyType::TOGGLE_DEBUG)) {
1928 } else if (wasKeyDown(KeyType::TOGGLE_PROFILER)) {
1929 m_game_ui->toggleProfiler();
1930 } else if (wasKeyDown(KeyType::INCREASE_VIEWING_RANGE)) {
1931 increaseViewRange();
1932 } else if (wasKeyDown(KeyType::DECREASE_VIEWING_RANGE)) {
1933 decreaseViewRange();
1934 } else if (wasKeyDown(KeyType::RANGESELECT)) {
1935 toggleFullViewRange();
1936 } else if (wasKeyDown(KeyType::ZOOM)) {
1938 } else if (wasKeyDown(KeyType::QUICKTUNE_NEXT)) {
1940 } else if (wasKeyDown(KeyType::QUICKTUNE_PREV)) {
1942 } else if (wasKeyDown(KeyType::QUICKTUNE_INC)) {
1944 } else if (wasKeyDown(KeyType::QUICKTUNE_DEC)) {
1948 if (!isKeyDown(KeyType::JUMP) && runData.reset_jump_timer) {
1949 runData.reset_jump_timer = false;
1950 runData.jump_timer = 0.0f;
1953 if (quicktune->hasMessage()) {
1954 m_game_ui->showStatusText(utf8_to_wide(quicktune->getMessage()));
1958 void Game::processItemSelection(u16 *new_playeritem)
1960 LocalPlayer *player = client->getEnv().getLocalPlayer();
1962 /* Item selection using mouse wheel
1964 *new_playeritem = player->getWieldIndex();
1966 s32 wheel = input->getMouseWheel();
1967 u16 max_item = MYMIN(PLAYER_INVENTORY_SIZE - 1,
1968 player->hud_hotbar_itemcount - 1);
1972 if (input->joystick.wasKeyDown(KeyType::SCROLL_DOWN) ||
1973 wasKeyDown(KeyType::HOTBAR_NEXT)) {
1977 if (input->joystick.wasKeyDown(KeyType::SCROLL_UP) ||
1978 wasKeyDown(KeyType::HOTBAR_PREV)) {
1983 *new_playeritem = *new_playeritem < max_item ? *new_playeritem + 1 : 0;
1985 *new_playeritem = *new_playeritem > 0 ? *new_playeritem - 1 : max_item;
1988 /* Item selection using hotbar slot keys
1990 for (u16 i = 0; i <= max_item; i++) {
1991 if (wasKeyDown((GameKeyType) (KeyType::SLOT_1 + i))) {
1992 *new_playeritem = i;
1993 infostream << "Selected item: " << new_playeritem << std::endl;
2000 void Game::dropSelectedItem(bool single_item)
2002 IDropAction *a = new IDropAction();
2003 a->count = single_item ? 1 : 0;
2004 a->from_inv.setCurrentPlayer();
2005 a->from_list = "main";
2006 a->from_i = client->getEnv().getLocalPlayer()->getWieldIndex();
2007 client->inventoryAction(a);
2011 void Game::openInventory()
2014 * Don't permit to open inventory is CAO or player doesn't exists.
2015 * This prevent showing an empty inventory at player load
2018 LocalPlayer *player = client->getEnv().getLocalPlayer();
2019 if (!player || !player->getCAO())
2022 infostream << "the_game: " << "Launching inventory" << std::endl;
2024 PlayerInventoryFormSource *fs_src = new PlayerInventoryFormSource(client);
2026 InventoryLocation inventoryloc;
2027 inventoryloc.setCurrentPlayer();
2029 if (!client->modsLoaded()
2030 || !client->getScript()->on_inventory_open(fs_src->m_client->getInventory(inventoryloc))) {
2031 TextDest *txt_dst = new TextDestPlayerInventory(client);
2032 auto *&formspec = m_game_ui->updateFormspec("");
2033 GUIFormSpecMenu::create(formspec, client, &input->joystick, fs_src,
2034 txt_dst, client->getFormspecPrepend());
2036 formspec->setFormSpec(fs_src->getForm(), inventoryloc);
2041 void Game::openConsole(float scale, const wchar_t *line)
2043 assert(scale > 0.0f && scale <= 1.0f);
2046 porting::showInputDialog(gettext("ok"), "", "", 2);
2047 m_android_chat_open = true;
2049 if (gui_chat_console->isOpenInhibited())
2051 gui_chat_console->openConsole(scale);
2053 gui_chat_console->setCloseOnEnter(true);
2054 gui_chat_console->replaceAndAddToHistory(line);
2060 void Game::handleAndroidChatInput()
2062 if (m_android_chat_open && porting::getInputDialogState() == 0) {
2063 std::string text = porting::getInputDialogValue();
2064 client->typeChatMessage(utf8_to_wide(text));
2065 m_android_chat_open = false;
2071 void Game::toggleFreeMove()
2073 bool free_move = !g_settings->getBool("free_move");
2074 g_settings->set("free_move", bool_to_cstr(free_move));
2077 if (client->checkPrivilege("fly")) {
2078 m_game_ui->showTranslatedStatusText("Fly mode enabled");
2080 m_game_ui->showTranslatedStatusText("Fly mode enabled (note: no 'fly' privilege)");
2083 m_game_ui->showTranslatedStatusText("Fly mode disabled");
2087 void Game::toggleFreeMoveAlt()
2089 if (m_cache_doubletap_jump && runData.jump_timer < 0.2f)
2092 runData.reset_jump_timer = true;
2096 void Game::togglePitchMove()
2098 bool pitch_move = !g_settings->getBool("pitch_move");
2099 g_settings->set("pitch_move", bool_to_cstr(pitch_move));
2102 m_game_ui->showTranslatedStatusText("Pitch move mode enabled");
2104 m_game_ui->showTranslatedStatusText("Pitch move mode disabled");
2109 void Game::toggleFast()
2111 bool fast_move = !g_settings->getBool("fast_move");
2112 bool has_fast_privs = client->checkPrivilege("fast");
2113 g_settings->set("fast_move", bool_to_cstr(fast_move));
2116 if (has_fast_privs) {
2117 m_game_ui->showTranslatedStatusText("Fast mode enabled");
2119 m_game_ui->showTranslatedStatusText("Fast mode enabled (note: no 'fast' privilege)");
2122 m_game_ui->showTranslatedStatusText("Fast mode disabled");
2126 m_cache_hold_aux1 = fast_move && has_fast_privs;
2131 void Game::toggleNoClip()
2133 bool noclip = !g_settings->getBool("noclip");
2134 g_settings->set("noclip", bool_to_cstr(noclip));
2137 if (client->checkPrivilege("noclip")) {
2138 m_game_ui->showTranslatedStatusText("Noclip mode enabled");
2140 m_game_ui->showTranslatedStatusText("Noclip mode enabled (note: no 'noclip' privilege)");
2143 m_game_ui->showTranslatedStatusText("Noclip mode disabled");
2147 void Game::toggleCinematic()
2149 bool cinematic = !g_settings->getBool("cinematic");
2150 g_settings->set("cinematic", bool_to_cstr(cinematic));
2153 m_game_ui->showTranslatedStatusText("Cinematic mode enabled");
2155 m_game_ui->showTranslatedStatusText("Cinematic mode disabled");
2158 // Autoforward by toggling continuous forward.
2159 void Game::toggleAutoforward()
2161 bool autorun_enabled = !g_settings->getBool("continuous_forward");
2162 g_settings->set("continuous_forward", bool_to_cstr(autorun_enabled));
2164 if (autorun_enabled)
2165 m_game_ui->showTranslatedStatusText("Automatic forward enabled");
2167 m_game_ui->showTranslatedStatusText("Automatic forward disabled");
2170 void Game::toggleMinimap(bool shift_pressed)
2172 if (!mapper || !m_game_ui->m_flags.show_hud || !g_settings->getBool("enable_minimap"))
2175 if (shift_pressed) {
2176 mapper->toggleMinimapShape();
2180 u32 hud_flags = client->getEnv().getLocalPlayer()->hud_flags;
2182 MinimapMode mode = MINIMAP_MODE_OFF;
2183 if (hud_flags & HUD_FLAG_MINIMAP_VISIBLE) {
2184 mode = mapper->getMinimapMode();
2185 mode = (MinimapMode)((int)mode + 1);
2186 // If radar is disabled and in, or switching to, radar mode
2187 if (!(hud_flags & HUD_FLAG_MINIMAP_RADAR_VISIBLE) && mode > 3)
2188 mode = MINIMAP_MODE_OFF;
2191 m_game_ui->m_flags.show_minimap = true;
2193 case MINIMAP_MODE_SURFACEx1:
2194 m_game_ui->showTranslatedStatusText("Minimap in surface mode, Zoom x1");
2196 case MINIMAP_MODE_SURFACEx2:
2197 m_game_ui->showTranslatedStatusText("Minimap in surface mode, Zoom x2");
2199 case MINIMAP_MODE_SURFACEx4:
2200 m_game_ui->showTranslatedStatusText("Minimap in surface mode, Zoom x4");
2202 case MINIMAP_MODE_RADARx1:
2203 m_game_ui->showTranslatedStatusText("Minimap in radar mode, Zoom x1");
2205 case MINIMAP_MODE_RADARx2:
2206 m_game_ui->showTranslatedStatusText("Minimap in radar mode, Zoom x2");
2208 case MINIMAP_MODE_RADARx4:
2209 m_game_ui->showTranslatedStatusText("Minimap in radar mode, Zoom x4");
2212 mode = MINIMAP_MODE_OFF;
2213 m_game_ui->m_flags.show_minimap = false;
2214 if (hud_flags & HUD_FLAG_MINIMAP_VISIBLE)
2215 m_game_ui->showTranslatedStatusText("Minimap hidden");
2217 m_game_ui->showTranslatedStatusText("Minimap currently disabled by game or mod");
2220 mapper->setMinimapMode(mode);
2223 void Game::toggleFog()
2225 bool fog_enabled = g_settings->getBool("enable_fog");
2226 g_settings->setBool("enable_fog", !fog_enabled);
2228 m_game_ui->showTranslatedStatusText("Fog disabled");
2230 m_game_ui->showTranslatedStatusText("Fog enabled");
2234 void Game::toggleDebug()
2236 // Initial / 4x toggle: Chat only
2237 // 1x toggle: Debug text with chat
2238 // 2x toggle: Debug text with profiler graph
2239 // 3x toggle: Debug text and wireframe
2240 if (!m_game_ui->m_flags.show_debug) {
2241 m_game_ui->m_flags.show_debug = true;
2242 m_game_ui->m_flags.show_profiler_graph = false;
2243 draw_control->show_wireframe = false;
2244 m_game_ui->showTranslatedStatusText("Debug info shown");
2245 } else if (!m_game_ui->m_flags.show_profiler_graph && !draw_control->show_wireframe) {
2246 m_game_ui->m_flags.show_profiler_graph = true;
2247 m_game_ui->showTranslatedStatusText("Profiler graph shown");
2248 } else if (!draw_control->show_wireframe && client->checkPrivilege("debug")) {
2249 m_game_ui->m_flags.show_profiler_graph = false;
2250 draw_control->show_wireframe = true;
2251 m_game_ui->showTranslatedStatusText("Wireframe shown");
2253 m_game_ui->m_flags.show_debug = false;
2254 m_game_ui->m_flags.show_profiler_graph = false;
2255 draw_control->show_wireframe = false;
2256 if (client->checkPrivilege("debug")) {
2257 m_game_ui->showTranslatedStatusText("Debug info, profiler graph, and wireframe hidden");
2259 m_game_ui->showTranslatedStatusText("Debug info and profiler graph hidden");
2265 void Game::toggleUpdateCamera()
2267 m_flags.disable_camera_update = !m_flags.disable_camera_update;
2268 if (m_flags.disable_camera_update)
2269 m_game_ui->showTranslatedStatusText("Camera update disabled");
2271 m_game_ui->showTranslatedStatusText("Camera update enabled");
2275 void Game::increaseViewRange()
2277 s16 range = g_settings->getS16("viewing_range");
2278 s16 range_new = range + 10;
2282 if (range_new > 4000) {
2284 str = wgettext("Viewing range is at maximum: %d");
2285 swprintf(buf, sizeof(buf) / sizeof(wchar_t), str, range_new);
2287 m_game_ui->showStatusText(buf);
2290 str = wgettext("Viewing range changed to %d");
2291 swprintf(buf, sizeof(buf) / sizeof(wchar_t), str, range_new);
2293 m_game_ui->showStatusText(buf);
2295 g_settings->set("viewing_range", itos(range_new));
2299 void Game::decreaseViewRange()
2301 s16 range = g_settings->getS16("viewing_range");
2302 s16 range_new = range - 10;
2306 if (range_new < 20) {
2308 str = wgettext("Viewing range is at minimum: %d");
2309 swprintf(buf, sizeof(buf) / sizeof(wchar_t), str, range_new);
2311 m_game_ui->showStatusText(buf);
2313 str = wgettext("Viewing range changed to %d");
2314 swprintf(buf, sizeof(buf) / sizeof(wchar_t), str, range_new);
2316 m_game_ui->showStatusText(buf);
2318 g_settings->set("viewing_range", itos(range_new));
2322 void Game::toggleFullViewRange()
2324 draw_control->range_all = !draw_control->range_all;
2325 if (draw_control->range_all)
2326 m_game_ui->showTranslatedStatusText("Enabled unlimited viewing range");
2328 m_game_ui->showTranslatedStatusText("Disabled unlimited viewing range");
2332 void Game::checkZoomEnabled()
2334 LocalPlayer *player = client->getEnv().getLocalPlayer();
2335 if (player->getZoomFOV() < 0.001f)
2336 m_game_ui->showTranslatedStatusText("Zoom currently disabled by game or mod");
2340 void Game::updateCameraDirection(CameraOrientation *cam, float dtime)
2342 if ((device->isWindowActive() && device->isWindowFocused()
2343 && !isMenuActive()) || random_input) {
2346 if (!random_input) {
2347 // Mac OSX gets upset if this is set every frame
2348 if (device->getCursorControl()->isVisible())
2349 device->getCursorControl()->setVisible(false);
2353 if (m_first_loop_after_window_activation) {
2354 m_first_loop_after_window_activation = false;
2356 input->setMousePos(driver->getScreenSize().Width / 2,
2357 driver->getScreenSize().Height / 2);
2359 updateCameraOrientation(cam, dtime);
2365 // Mac OSX gets upset if this is set every frame
2366 if (!device->getCursorControl()->isVisible())
2367 device->getCursorControl()->setVisible(true);
2370 m_first_loop_after_window_activation = true;
2375 void Game::updateCameraOrientation(CameraOrientation *cam, float dtime)
2377 #ifdef HAVE_TOUCHSCREENGUI
2378 if (g_touchscreengui) {
2379 cam->camera_yaw += g_touchscreengui->getYawChange();
2380 cam->camera_pitch = g_touchscreengui->getPitch();
2383 v2s32 center(driver->getScreenSize().Width / 2, driver->getScreenSize().Height / 2);
2384 v2s32 dist = input->getMousePos() - center;
2386 if (m_invert_mouse || camera->getCameraMode() == CAMERA_MODE_THIRD_FRONT) {
2390 cam->camera_yaw -= dist.X * m_cache_mouse_sensitivity;
2391 cam->camera_pitch += dist.Y * m_cache_mouse_sensitivity;
2393 if (dist.X != 0 || dist.Y != 0)
2394 input->setMousePos(center.X, center.Y);
2395 #ifdef HAVE_TOUCHSCREENGUI
2399 if (m_cache_enable_joysticks) {
2400 f32 c = m_cache_joystick_frustum_sensitivity * (1.f / 32767.f) * dtime;
2401 cam->camera_yaw -= input->joystick.getAxisWithoutDead(JA_FRUSTUM_HORIZONTAL) * c;
2402 cam->camera_pitch += input->joystick.getAxisWithoutDead(JA_FRUSTUM_VERTICAL) * c;
2405 cam->camera_pitch = rangelim(cam->camera_pitch, -89.5, 89.5);
2409 void Game::updatePlayerControl(const CameraOrientation &cam)
2411 //TimeTaker tt("update player control", NULL, PRECISION_NANO);
2413 // DO NOT use the isKeyDown method for the forward, backward, left, right
2414 // buttons, as the code that uses the controls needs to be able to
2415 // distinguish between the two in order to know when to use joysticks.
2417 PlayerControl control(
2418 input->isKeyDown(KeyType::FORWARD),
2419 input->isKeyDown(KeyType::BACKWARD),
2420 input->isKeyDown(KeyType::LEFT),
2421 input->isKeyDown(KeyType::RIGHT),
2422 isKeyDown(KeyType::JUMP),
2423 isKeyDown(KeyType::SPECIAL1),
2424 isKeyDown(KeyType::SNEAK),
2425 isKeyDown(KeyType::ZOOM),
2426 input->getLeftState(),
2427 input->getRightState(),
2430 input->joystick.getAxisWithoutDead(JA_SIDEWARD_MOVE),
2431 input->joystick.getAxisWithoutDead(JA_FORWARD_MOVE)
2435 ( (u32)(isKeyDown(KeyType::FORWARD) & 0x1) << 0) |
2436 ( (u32)(isKeyDown(KeyType::BACKWARD) & 0x1) << 1) |
2437 ( (u32)(isKeyDown(KeyType::LEFT) & 0x1) << 2) |
2438 ( (u32)(isKeyDown(KeyType::RIGHT) & 0x1) << 3) |
2439 ( (u32)(isKeyDown(KeyType::JUMP) & 0x1) << 4) |
2440 ( (u32)(isKeyDown(KeyType::SPECIAL1) & 0x1) << 5) |
2441 ( (u32)(isKeyDown(KeyType::SNEAK) & 0x1) << 6) |
2442 ( (u32)(input->getLeftState() & 0x1) << 7) |
2443 ( (u32)(input->getRightState() & 0x1) << 8
2447 /* For Android, simulate holding down AUX1 (fast move) if the user has
2448 * the fast_move setting toggled on. If there is an aux1 key defined for
2449 * Android then its meaning is inverted (i.e. holding aux1 means walk and
2452 if (m_cache_hold_aux1) {
2453 control.aux1 = control.aux1 ^ true;
2454 keypress_bits ^= ((u32)(1U << 5));
2458 LocalPlayer *player = client->getEnv().getLocalPlayer();
2460 // autojump if set: simulate "jump" key
2461 if (player->getAutojump()) {
2462 control.jump = true;
2463 keypress_bits |= 1U << 4;
2466 // autoforward if set: simulate "up" key
2467 if (player->getPlayerSettings().continuous_forward && !player->isDead()) {
2469 keypress_bits |= 1U << 0;
2472 client->setPlayerControl(control);
2473 player->keyPressed = keypress_bits;
2479 inline void Game::step(f32 *dtime)
2481 bool can_be_and_is_paused =
2482 (simple_singleplayer_mode && g_menumgr.pausesGame());
2484 if (can_be_and_is_paused) { // This is for a singleplayer server
2485 *dtime = 0; // No time passes
2488 server->step(*dtime);
2490 client->step(*dtime);
2494 const ClientEventHandler Game::clientEventHandler[CLIENTEVENT_MAX] = {
2495 {&Game::handleClientEvent_None},
2496 {&Game::handleClientEvent_PlayerDamage},
2497 {&Game::handleClientEvent_PlayerForceMove},
2498 {&Game::handleClientEvent_Deathscreen},
2499 {&Game::handleClientEvent_ShowFormSpec},
2500 {&Game::handleClientEvent_ShowLocalFormSpec},
2501 {&Game::handleClientEvent_HandleParticleEvent},
2502 {&Game::handleClientEvent_HandleParticleEvent},
2503 {&Game::handleClientEvent_HandleParticleEvent},
2504 {&Game::handleClientEvent_HudAdd},
2505 {&Game::handleClientEvent_HudRemove},
2506 {&Game::handleClientEvent_HudChange},
2507 {&Game::handleClientEvent_SetSky},
2508 {&Game::handleClientEvent_OverrideDayNigthRatio},
2509 {&Game::handleClientEvent_CloudParams},
2512 void Game::handleClientEvent_None(ClientEvent *event, CameraOrientation *cam)
2514 FATAL_ERROR("ClientEvent type None received");
2517 void Game::handleClientEvent_PlayerDamage(ClientEvent *event, CameraOrientation *cam)
2519 if (client->modsLoaded())
2520 client->getScript()->on_damage_taken(event->player_damage.amount);
2522 // Damage flash and hurt tilt are not used at death
2523 if (client->getHP() > 0) {
2524 runData.damage_flash += 95.0f + 3.2f * event->player_damage.amount;
2525 runData.damage_flash = MYMIN(runData.damage_flash, 127.0f);
2527 LocalPlayer *player = client->getEnv().getLocalPlayer();
2529 player->hurt_tilt_timer = 1.5f;
2530 player->hurt_tilt_strength =
2531 rangelim(event->player_damage.amount / 4.0f, 1.0f, 4.0f);
2534 // Play damage sound
2535 client->getEventManager()->put(new SimpleTriggerEvent(MtEvent::PLAYER_DAMAGE));
2538 void Game::handleClientEvent_PlayerForceMove(ClientEvent *event, CameraOrientation *cam)
2540 cam->camera_yaw = event->player_force_move.yaw;
2541 cam->camera_pitch = event->player_force_move.pitch;
2544 void Game::handleClientEvent_Deathscreen(ClientEvent *event, CameraOrientation *cam)
2546 // If client scripting is enabled, deathscreen is handled by CSM code in
2547 // builtin/client/init.lua
2548 if (client->modsLoaded())
2549 client->getScript()->on_death();
2551 showDeathFormspec();
2553 /* Handle visualization */
2554 LocalPlayer *player = client->getEnv().getLocalPlayer();
2555 runData.damage_flash = 0;
2556 player->hurt_tilt_timer = 0;
2557 player->hurt_tilt_strength = 0;
2560 void Game::handleClientEvent_ShowFormSpec(ClientEvent *event, CameraOrientation *cam)
2562 if (event->show_formspec.formspec->empty()) {
2563 auto formspec = m_game_ui->getFormspecGUI();
2564 if (formspec && (event->show_formspec.formname->empty()
2565 || *(event->show_formspec.formname) == m_game_ui->getFormspecName())) {
2566 formspec->quitMenu();
2569 FormspecFormSource *fs_src =
2570 new FormspecFormSource(*(event->show_formspec.formspec));
2571 TextDestPlayerInventory *txt_dst =
2572 new TextDestPlayerInventory(client, *(event->show_formspec.formname));
2574 auto *&formspec = m_game_ui->updateFormspec(*(event->show_formspec.formname));
2575 GUIFormSpecMenu::create(formspec, client, &input->joystick,
2576 fs_src, txt_dst, client->getFormspecPrepend());
2579 delete event->show_formspec.formspec;
2580 delete event->show_formspec.formname;
2583 void Game::handleClientEvent_ShowLocalFormSpec(ClientEvent *event, CameraOrientation *cam)
2585 FormspecFormSource *fs_src = new FormspecFormSource(*event->show_formspec.formspec);
2586 LocalFormspecHandler *txt_dst =
2587 new LocalFormspecHandler(*event->show_formspec.formname, client);
2588 GUIFormSpecMenu::create(m_game_ui->getFormspecGUI(), client, &input->joystick,
2589 fs_src, txt_dst, client->getFormspecPrepend());
2591 delete event->show_formspec.formspec;
2592 delete event->show_formspec.formname;
2595 void Game::handleClientEvent_HandleParticleEvent(ClientEvent *event,
2596 CameraOrientation *cam)
2598 LocalPlayer *player = client->getEnv().getLocalPlayer();
2599 client->getParticleManager()->handleParticleEvent(event, client, player);
2602 void Game::handleClientEvent_HudAdd(ClientEvent *event, CameraOrientation *cam)
2604 LocalPlayer *player = client->getEnv().getLocalPlayer();
2605 auto &hud_server_to_client = client->getHUDTranslationMap();
2607 u32 server_id = event->hudadd.server_id;
2608 // ignore if we already have a HUD with that ID
2609 auto i = hud_server_to_client.find(server_id);
2610 if (i != hud_server_to_client.end()) {
2611 delete event->hudadd.pos;
2612 delete event->hudadd.name;
2613 delete event->hudadd.scale;
2614 delete event->hudadd.text;
2615 delete event->hudadd.align;
2616 delete event->hudadd.offset;
2617 delete event->hudadd.world_pos;
2618 delete event->hudadd.size;
2622 HudElement *e = new HudElement;
2623 e->type = (HudElementType)event->hudadd.type;
2624 e->pos = *event->hudadd.pos;
2625 e->name = *event->hudadd.name;
2626 e->scale = *event->hudadd.scale;
2627 e->text = *event->hudadd.text;
2628 e->number = event->hudadd.number;
2629 e->item = event->hudadd.item;
2630 e->dir = event->hudadd.dir;
2631 e->align = *event->hudadd.align;
2632 e->offset = *event->hudadd.offset;
2633 e->world_pos = *event->hudadd.world_pos;
2634 e->size = *event->hudadd.size;
2635 hud_server_to_client[server_id] = player->addHud(e);
2637 delete event->hudadd.pos;
2638 delete event->hudadd.name;
2639 delete event->hudadd.scale;
2640 delete event->hudadd.text;
2641 delete event->hudadd.align;
2642 delete event->hudadd.offset;
2643 delete event->hudadd.world_pos;
2644 delete event->hudadd.size;
2647 void Game::handleClientEvent_HudRemove(ClientEvent *event, CameraOrientation *cam)
2649 LocalPlayer *player = client->getEnv().getLocalPlayer();
2650 HudElement *e = player->removeHud(event->hudrm.id);
2654 void Game::handleClientEvent_HudChange(ClientEvent *event, CameraOrientation *cam)
2656 LocalPlayer *player = client->getEnv().getLocalPlayer();
2658 u32 id = event->hudchange.id;
2659 HudElement *e = player->getHud(id);
2662 delete event->hudchange.v3fdata;
2663 delete event->hudchange.v2fdata;
2664 delete event->hudchange.sdata;
2665 delete event->hudchange.v2s32data;
2669 switch (event->hudchange.stat) {
2671 e->pos = *event->hudchange.v2fdata;
2675 e->name = *event->hudchange.sdata;
2678 case HUD_STAT_SCALE:
2679 e->scale = *event->hudchange.v2fdata;
2683 e->text = *event->hudchange.sdata;
2686 case HUD_STAT_NUMBER:
2687 e->number = event->hudchange.data;
2691 e->item = event->hudchange.data;
2695 e->dir = event->hudchange.data;
2698 case HUD_STAT_ALIGN:
2699 e->align = *event->hudchange.v2fdata;
2702 case HUD_STAT_OFFSET:
2703 e->offset = *event->hudchange.v2fdata;
2706 case HUD_STAT_WORLD_POS:
2707 e->world_pos = *event->hudchange.v3fdata;
2711 e->size = *event->hudchange.v2s32data;
2715 delete event->hudchange.v3fdata;
2716 delete event->hudchange.v2fdata;
2717 delete event->hudchange.sdata;
2718 delete event->hudchange.v2s32data;
2721 void Game::handleClientEvent_SetSky(ClientEvent *event, CameraOrientation *cam)
2723 sky->setVisible(false);
2724 // Whether clouds are visible in front of a custom skybox
2725 sky->setCloudsEnabled(event->set_sky.clouds);
2732 // Handle according to type
2733 if (*event->set_sky.type == "regular") {
2734 sky->setVisible(true);
2735 sky->setCloudsEnabled(true);
2736 } else if (*event->set_sky.type == "skybox" &&
2737 event->set_sky.params->size() == 6) {
2738 sky->setFallbackBgColor(*event->set_sky.bgcolor);
2739 skybox = RenderingEngine::get_scene_manager()->addSkyBoxSceneNode(
2740 texture_src->getTextureForMesh((*event->set_sky.params)[0]),
2741 texture_src->getTextureForMesh((*event->set_sky.params)[1]),
2742 texture_src->getTextureForMesh((*event->set_sky.params)[2]),
2743 texture_src->getTextureForMesh((*event->set_sky.params)[3]),
2744 texture_src->getTextureForMesh((*event->set_sky.params)[4]),
2745 texture_src->getTextureForMesh((*event->set_sky.params)[5]));
2747 // Handle everything else as plain color
2749 if (*event->set_sky.type != "plain")
2750 infostream << "Unknown sky type: "
2751 << (*event->set_sky.type) << std::endl;
2753 sky->setFallbackBgColor(*event->set_sky.bgcolor);
2756 delete event->set_sky.bgcolor;
2757 delete event->set_sky.type;
2758 delete event->set_sky.params;
2761 void Game::handleClientEvent_OverrideDayNigthRatio(ClientEvent *event,
2762 CameraOrientation *cam)
2764 client->getEnv().setDayNightRatioOverride(
2765 event->override_day_night_ratio.do_override,
2766 event->override_day_night_ratio.ratio_f * 1000.0f);
2769 void Game::handleClientEvent_CloudParams(ClientEvent *event, CameraOrientation *cam)
2774 clouds->setDensity(event->cloud_params.density);
2775 clouds->setColorBright(video::SColor(event->cloud_params.color_bright));
2776 clouds->setColorAmbient(video::SColor(event->cloud_params.color_ambient));
2777 clouds->setHeight(event->cloud_params.height);
2778 clouds->setThickness(event->cloud_params.thickness);
2779 clouds->setSpeed(v2f(event->cloud_params.speed_x, event->cloud_params.speed_y));
2782 void Game::processClientEvents(CameraOrientation *cam)
2784 while (client->hasClientEvents()) {
2785 std::unique_ptr<ClientEvent> event(client->getClientEvent());
2786 FATAL_ERROR_IF(event->type >= CLIENTEVENT_MAX, "Invalid clientevent type");
2787 const ClientEventHandler& evHandler = clientEventHandler[event->type];
2788 (this->*evHandler.handler)(event.get(), cam);
2792 void Game::updateChat(f32 dtime, const v2u32 &screensize)
2794 // Add chat log output for errors to be shown in chat
2795 static LogOutputBuffer chat_log_error_buf(g_logger, LL_ERROR);
2797 // Get new messages from error log buffer
2798 while (!chat_log_error_buf.empty()) {
2799 std::wstring error_message = utf8_to_wide(chat_log_error_buf.get());
2800 if (!g_settings->getBool("disable_escape_sequences")) {
2801 error_message.insert(0, L"\x1b(c@red)");
2802 error_message.append(L"\x1b(c@white)");
2804 chat_backend->addMessage(L"", error_message);
2807 // Get new messages from client
2808 std::wstring message;
2809 while (client->getChatMessage(message)) {
2810 chat_backend->addUnparsedMessage(message);
2813 // Remove old messages
2814 chat_backend->step(dtime);
2816 // Display all messages in a static text element
2817 m_game_ui->setChatText(chat_backend->getRecentChat(),
2818 chat_backend->getRecentBuffer().getLineCount());
2821 void Game::updateCamera(u32 busy_time, f32 dtime)
2823 LocalPlayer *player = client->getEnv().getLocalPlayer();
2826 For interaction purposes, get info about the held item
2828 - Is it a usable item?
2829 - Can it point to liquids?
2831 ItemStack playeritem;
2833 ItemStack selected, hand;
2834 playeritem = player->getWieldedItem(&selected, &hand);
2837 ToolCapabilities playeritem_toolcap =
2838 playeritem.getToolCapabilities(itemdef_manager);
2840 v3s16 old_camera_offset = camera->getOffset();
2842 if (wasKeyDown(KeyType::CAMERA_MODE)) {
2843 GenericCAO *playercao = player->getCAO();
2845 // If playercao not loaded, don't change camera
2849 camera->toggleCameraMode();
2851 playercao->setVisible(camera->getCameraMode() > CAMERA_MODE_FIRST);
2852 playercao->setChildrenVisible(camera->getCameraMode() > CAMERA_MODE_FIRST);
2855 float full_punch_interval = playeritem_toolcap.full_punch_interval;
2856 float tool_reload_ratio = runData.time_from_last_punch / full_punch_interval;
2858 tool_reload_ratio = MYMIN(tool_reload_ratio, 1.0);
2859 camera->update(player, dtime, busy_time / 1000.0f, tool_reload_ratio);
2860 camera->step(dtime);
2862 v3f camera_position = camera->getPosition();
2863 v3f camera_direction = camera->getDirection();
2864 f32 camera_fov = camera->getFovMax();
2865 v3s16 camera_offset = camera->getOffset();
2867 m_camera_offset_changed = (camera_offset != old_camera_offset);
2869 if (!m_flags.disable_camera_update) {
2870 client->getEnv().getClientMap().updateCamera(camera_position,
2871 camera_direction, camera_fov, camera_offset);
2873 if (m_camera_offset_changed) {
2874 client->updateCameraOffset(camera_offset);
2875 client->getEnv().updateCameraOffset(camera_offset);
2878 clouds->updateCameraOffset(camera_offset);
2884 void Game::updateSound(f32 dtime)
2886 // Update sound listener
2887 v3s16 camera_offset = camera->getOffset();
2888 sound->updateListener(camera->getCameraNode()->getPosition() + intToFloat(camera_offset, BS),
2889 v3f(0, 0, 0), // velocity
2890 camera->getDirection(),
2891 camera->getCameraNode()->getUpVector());
2893 bool mute_sound = g_settings->getBool("mute_sound");
2895 sound->setListenerGain(0.0f);
2897 // Check if volume is in the proper range, else fix it.
2898 float old_volume = g_settings->getFloat("sound_volume");
2899 float new_volume = rangelim(old_volume, 0.0f, 1.0f);
2900 sound->setListenerGain(new_volume);
2902 if (old_volume != new_volume) {
2903 g_settings->setFloat("sound_volume", new_volume);
2907 LocalPlayer *player = client->getEnv().getLocalPlayer();
2909 // Tell the sound maker whether to make footstep sounds
2910 soundmaker->makes_footstep_sound = player->makes_footstep_sound;
2912 // Update sound maker
2913 if (player->makes_footstep_sound)
2914 soundmaker->step(dtime);
2916 ClientMap &map = client->getEnv().getClientMap();
2917 MapNode n = map.getNode(player->getFootstepNodePos());
2918 soundmaker->m_player_step_sound = nodedef_manager->get(n).sound_footstep;
2922 void Game::processPlayerInteraction(f32 dtime, bool show_hud, bool show_debug)
2924 LocalPlayer *player = client->getEnv().getLocalPlayer();
2926 v3f player_position = player->getPosition();
2927 v3f player_eye_position = player->getEyePosition();
2928 v3f camera_position = camera->getPosition();
2929 v3f camera_direction = camera->getDirection();
2930 v3s16 camera_offset = camera->getOffset();
2932 if (camera->getCameraMode() == CAMERA_MODE_FIRST)
2933 player_eye_position += player->eye_offset_first;
2935 player_eye_position += player->eye_offset_third;
2938 Calculate what block is the crosshair pointing to
2941 ItemStack selected_item, hand_item;
2942 const ItemStack &tool_item = player->getWieldedItem(&selected_item, &hand_item);
2944 const ItemDefinition &selected_def = selected_item.getDefinition(itemdef_manager);
2945 f32 d = getToolRange(selected_def, hand_item.getDefinition(itemdef_manager));
2947 core::line3d<f32> shootline;
2949 if (camera->getCameraMode() != CAMERA_MODE_THIRD_FRONT) {
2950 shootline = core::line3d<f32>(player_eye_position,
2951 player_eye_position + camera_direction * BS * d);
2953 // prevent player pointing anything in front-view
2954 shootline = core::line3d<f32>(camera_position, camera_position);
2957 #ifdef HAVE_TOUCHSCREENGUI
2959 if ((g_settings->getBool("touchtarget")) && (g_touchscreengui)) {
2960 shootline = g_touchscreengui->getShootline();
2961 // Scale shootline to the acual distance the player can reach
2962 shootline.end = shootline.start
2963 + shootline.getVector().normalize() * BS * d;
2964 shootline.start += intToFloat(camera_offset, BS);
2965 shootline.end += intToFloat(camera_offset, BS);
2970 PointedThing pointed = updatePointedThing(shootline,
2971 selected_def.liquids_pointable,
2972 !runData.ldown_for_dig,
2975 if (pointed != runData.pointed_old) {
2976 infostream << "Pointing at " << pointed.dump() << std::endl;
2977 hud->updateSelectionMesh(camera_offset);
2980 if (runData.digging_blocked && !input->getLeftState()) {
2981 // allow digging again if button is not pressed
2982 runData.digging_blocked = false;
2987 - releasing left mouse button
2988 - pointing away from node
2990 if (runData.digging) {
2991 if (input->getLeftReleased()) {
2992 infostream << "Left button released"
2993 << " (stopped digging)" << std::endl;
2994 runData.digging = false;
2995 } else if (pointed != runData.pointed_old) {
2996 if (pointed.type == POINTEDTHING_NODE
2997 && runData.pointed_old.type == POINTEDTHING_NODE
2998 && pointed.node_undersurface
2999 == runData.pointed_old.node_undersurface) {
3000 // Still pointing to the same node, but a different face.
3003 infostream << "Pointing away from node"
3004 << " (stopped digging)" << std::endl;
3005 runData.digging = false;
3006 hud->updateSelectionMesh(camera_offset);
3010 if (!runData.digging) {
3011 client->interact(INTERACT_STOP_DIGGING, runData.pointed_old);
3012 client->setCrack(-1, v3s16(0, 0, 0));
3013 runData.dig_time = 0.0;
3015 } else if (runData.dig_instantly && input->getLeftReleased()) {
3016 // Remove e.g. torches faster when clicking instead of holding LMB
3017 runData.nodig_delay_timer = 0;
3018 runData.dig_instantly = false;
3021 if (!runData.digging && runData.ldown_for_dig && !input->getLeftState()) {
3022 runData.ldown_for_dig = false;
3025 runData.left_punch = false;
3027 soundmaker->m_player_leftpunch_sound.name = "";
3029 // Prepare for repeating, unless we're not supposed to
3030 if (input->getRightState() && !g_settings->getBool("safe_dig_and_place"))
3031 runData.repeat_rightclick_timer += dtime;
3033 runData.repeat_rightclick_timer = 0;
3035 if (selected_def.usable && input->getLeftState()) {
3036 if (input->getLeftClicked() && (!client->modsLoaded()
3037 || !client->getScript()->on_item_use(selected_item, pointed)))
3038 client->interact(INTERACT_USE, pointed);
3039 } else if (pointed.type == POINTEDTHING_NODE) {
3040 handlePointingAtNode(pointed, selected_item, hand_item, dtime);
3041 } else if (pointed.type == POINTEDTHING_OBJECT) {
3042 handlePointingAtObject(pointed, tool_item, player_position, show_debug);
3043 } else if (input->getLeftState()) {
3044 // When button is held down in air, show continuous animation
3045 runData.left_punch = true;
3046 } else if (input->getRightClicked()) {
3047 handlePointingAtNothing(selected_item);
3050 runData.pointed_old = pointed;
3052 if (runData.left_punch || input->getLeftClicked())
3053 camera->setDigging(0); // left click animation
3055 input->resetLeftClicked();
3056 input->resetRightClicked();
3058 input->resetLeftReleased();
3059 input->resetRightReleased();
3063 PointedThing Game::updatePointedThing(
3064 const core::line3d<f32> &shootline,
3065 bool liquids_pointable,
3066 bool look_for_object,
3067 const v3s16 &camera_offset)
3069 std::vector<aabb3f> *selectionboxes = hud->getSelectionBoxes();
3070 selectionboxes->clear();
3071 hud->setSelectedFaceNormal(v3f(0.0, 0.0, 0.0));
3072 static thread_local const bool show_entity_selectionbox = g_settings->getBool(
3073 "show_entity_selectionbox");
3075 ClientEnvironment &env = client->getEnv();
3076 ClientMap &map = env.getClientMap();
3077 const NodeDefManager *nodedef = map.getNodeDefManager();
3079 runData.selected_object = NULL;
3081 RaycastState s(shootline, look_for_object, liquids_pointable);
3082 PointedThing result;
3083 env.continueRaycast(&s, &result);
3084 if (result.type == POINTEDTHING_OBJECT) {
3085 runData.selected_object = client->getEnv().getActiveObject(result.object_id);
3086 aabb3f selection_box;
3087 if (show_entity_selectionbox && runData.selected_object->doShowSelectionBox() &&
3088 runData.selected_object->getSelectionBox(&selection_box)) {
3089 v3f pos = runData.selected_object->getPosition();
3090 selectionboxes->push_back(aabb3f(selection_box));
3091 hud->setSelectionPos(pos, camera_offset);
3093 } else if (result.type == POINTEDTHING_NODE) {
3094 // Update selection boxes
3095 MapNode n = map.getNode(result.node_undersurface);
3096 std::vector<aabb3f> boxes;
3097 n.getSelectionBoxes(nodedef, &boxes,
3098 n.getNeighbors(result.node_undersurface, &map));
3101 for (std::vector<aabb3f>::const_iterator i = boxes.begin();
3102 i != boxes.end(); ++i) {
3104 box.MinEdge -= v3f(d, d, d);
3105 box.MaxEdge += v3f(d, d, d);
3106 selectionboxes->push_back(box);
3108 hud->setSelectionPos(intToFloat(result.node_undersurface, BS),
3110 hud->setSelectedFaceNormal(v3f(
3111 result.intersection_normal.X,
3112 result.intersection_normal.Y,
3113 result.intersection_normal.Z));
3116 // Update selection mesh light level and vertex colors
3117 if (!selectionboxes->empty()) {
3118 v3f pf = hud->getSelectionPos();
3119 v3s16 p = floatToInt(pf, BS);
3121 // Get selection mesh light level
3122 MapNode n = map.getNode(p);
3123 u16 node_light = getInteriorLight(n, -1, nodedef);
3124 u16 light_level = node_light;
3126 for (const v3s16 &dir : g_6dirs) {
3127 n = map.getNode(p + dir);
3128 node_light = getInteriorLight(n, -1, nodedef);
3129 if (node_light > light_level)
3130 light_level = node_light;
3133 u32 daynight_ratio = client->getEnv().getDayNightRatio();
3135 final_color_blend(&c, light_level, daynight_ratio);
3137 // Modify final color a bit with time
3138 u32 timer = porting::getTimeMs() % 5000;
3139 float timerf = (float) (irr::core::PI * ((timer / 2500.0) - 0.5));
3140 float sin_r = 0.08f * std::sin(timerf);
3141 float sin_g = 0.08f * std::sin(timerf + irr::core::PI * 0.5f);
3142 float sin_b = 0.08f * std::sin(timerf + irr::core::PI);
3143 c.setRed(core::clamp(core::round32(c.getRed() * (0.8 + sin_r)), 0, 255));
3144 c.setGreen(core::clamp(core::round32(c.getGreen() * (0.8 + sin_g)), 0, 255));
3145 c.setBlue(core::clamp(core::round32(c.getBlue() * (0.8 + sin_b)), 0, 255));
3147 // Set mesh final color
3148 hud->setSelectionMeshColor(c);
3154 void Game::handlePointingAtNothing(const ItemStack &playerItem)
3156 infostream << "Right Clicked in Air" << std::endl;
3157 PointedThing fauxPointed;
3158 fauxPointed.type = POINTEDTHING_NOTHING;
3159 client->interact(INTERACT_ACTIVATE, fauxPointed);
3163 void Game::handlePointingAtNode(const PointedThing &pointed,
3164 const ItemStack &selected_item, const ItemStack &hand_item, f32 dtime)
3166 v3s16 nodepos = pointed.node_undersurface;
3167 v3s16 neighbourpos = pointed.node_abovesurface;
3170 Check information text of node
3173 ClientMap &map = client->getEnv().getClientMap();
3175 if (runData.nodig_delay_timer <= 0.0 && input->getLeftState()
3176 && !runData.digging_blocked
3177 && client->checkPrivilege("interact")) {
3178 handleDigging(pointed, nodepos, selected_item, hand_item, dtime);
3181 // This should be done after digging handling
3182 NodeMetadata *meta = map.getNodeMetadata(nodepos);
3185 m_game_ui->setInfoText(unescape_translate(utf8_to_wide(
3186 meta->getString("infotext"))));
3188 MapNode n = map.getNode(nodepos);
3190 if (nodedef_manager->get(n).tiledef[0].name == "unknown_node.png") {
3191 m_game_ui->setInfoText(L"Unknown node: " +
3192 utf8_to_wide(nodedef_manager->get(n).name));
3196 if ((input->getRightClicked() ||
3197 runData.repeat_rightclick_timer >= m_repeat_right_click_time) &&
3198 client->checkPrivilege("interact")) {
3199 runData.repeat_rightclick_timer = 0;
3200 infostream << "Ground right-clicked" << std::endl;
3202 if (meta && !meta->getString("formspec").empty() && !random_input
3203 && !isKeyDown(KeyType::SNEAK)) {
3204 // Report right click to server
3205 if (nodedef_manager->get(map.getNode(nodepos)).rightclickable) {
3206 client->interact(INTERACT_PLACE, pointed);
3209 infostream << "Launching custom inventory view" << std::endl;
3211 InventoryLocation inventoryloc;
3212 inventoryloc.setNodeMeta(nodepos);
3214 NodeMetadataFormSource *fs_src = new NodeMetadataFormSource(
3215 &client->getEnv().getClientMap(), nodepos);
3216 TextDest *txt_dst = new TextDestNodeMetadata(nodepos, client);
3218 auto *&formspec = m_game_ui->updateFormspec("");
3219 GUIFormSpecMenu::create(formspec, client, &input->joystick, fs_src,
3220 txt_dst, client->getFormspecPrepend());
3222 formspec->setFormSpec(meta->getString("formspec"), inventoryloc);
3224 // Report right click to server
3226 camera->setDigging(1); // right click animation (always shown for feedback)
3228 // If the wielded item has node placement prediction,
3230 auto &def = selected_item.getDefinition(itemdef_manager);
3231 bool placed = nodePlacementPrediction(def, selected_item, nodepos,
3236 client->interact(INTERACT_PLACE, pointed);
3238 soundmaker->m_player_rightpunch_sound =
3241 if (client->modsLoaded())
3242 client->getScript()->on_placenode(pointed, def);
3244 soundmaker->m_player_rightpunch_sound =
3247 if (def.node_placement_prediction.empty() ||
3248 nodedef_manager->get(map.getNode(nodepos)).rightclickable) {
3249 client->interact(INTERACT_PLACE, pointed); // Report to server
3251 soundmaker->m_player_rightpunch_sound =
3252 def.sound_place_failed;
3259 bool Game::nodePlacementPrediction(const ItemDefinition &selected_def,
3260 const ItemStack &selected_item, const v3s16 &nodepos, const v3s16 &neighbourpos)
3262 std::string prediction = selected_def.node_placement_prediction;
3263 const NodeDefManager *nodedef = client->ndef();
3264 ClientMap &map = client->getEnv().getClientMap();
3266 bool is_valid_position;
3268 node = map.getNode(nodepos, &is_valid_position);
3269 if (!is_valid_position)
3272 if (!prediction.empty() && !(nodedef->get(node).rightclickable &&
3273 !isKeyDown(KeyType::SNEAK))) {
3274 verbosestream << "Node placement prediction for "
3275 << selected_item.name << " is "
3276 << prediction << std::endl;
3277 v3s16 p = neighbourpos;
3279 // Place inside node itself if buildable_to
3280 MapNode n_under = map.getNode(nodepos, &is_valid_position);
3281 if (is_valid_position)
3283 if (nodedef->get(n_under).buildable_to)
3286 node = map.getNode(p, &is_valid_position);
3287 if (is_valid_position &&!nodedef->get(node).buildable_to)
3292 // Find id of predicted node
3294 bool found = nodedef->getId(prediction, id);
3297 errorstream << "Node placement prediction failed for "
3298 << selected_item.name << " (places "
3300 << ") - Name not known" << std::endl;
3304 const ContentFeatures &predicted_f = nodedef->get(id);
3306 // Predict param2 for facedir and wallmounted nodes
3309 if (predicted_f.param_type_2 == CPT2_WALLMOUNTED ||
3310 predicted_f.param_type_2 == CPT2_COLORED_WALLMOUNTED) {
3311 v3s16 dir = nodepos - neighbourpos;
3313 if (abs(dir.Y) > MYMAX(abs(dir.X), abs(dir.Z))) {
3314 param2 = dir.Y < 0 ? 1 : 0;
3315 } else if (abs(dir.X) > abs(dir.Z)) {
3316 param2 = dir.X < 0 ? 3 : 2;
3318 param2 = dir.Z < 0 ? 5 : 4;
3322 if (predicted_f.param_type_2 == CPT2_FACEDIR ||
3323 predicted_f.param_type_2 == CPT2_COLORED_FACEDIR) {
3324 v3s16 dir = nodepos - floatToInt(client->getEnv().getLocalPlayer()->getPosition(), BS);
3326 if (abs(dir.X) > abs(dir.Z)) {
3327 param2 = dir.X < 0 ? 3 : 1;
3329 param2 = dir.Z < 0 ? 2 : 0;
3333 assert(param2 <= 5);
3335 //Check attachment if node is in group attached_node
3336 if (((ItemGroupList) predicted_f.groups)["attached_node"] != 0) {
3337 static v3s16 wallmounted_dirs[8] = {
3347 if (predicted_f.param_type_2 == CPT2_WALLMOUNTED ||
3348 predicted_f.param_type_2 == CPT2_COLORED_WALLMOUNTED)
3349 pp = p + wallmounted_dirs[param2];
3351 pp = p + v3s16(0, -1, 0);
3353 if (!nodedef->get(map.getNode(pp)).walkable)
3358 if ((predicted_f.param_type_2 == CPT2_COLOR
3359 || predicted_f.param_type_2 == CPT2_COLORED_FACEDIR
3360 || predicted_f.param_type_2 == CPT2_COLORED_WALLMOUNTED)) {
3361 const std::string &indexstr = selected_item.metadata.getString(
3362 "palette_index", 0);
3363 if (!indexstr.empty()) {
3364 s32 index = mystoi(indexstr);
3365 if (predicted_f.param_type_2 == CPT2_COLOR) {
3367 } else if (predicted_f.param_type_2
3368 == CPT2_COLORED_WALLMOUNTED) {
3369 // param2 = pure palette index + other
3370 param2 = (index & 0xf8) | (param2 & 0x07);
3371 } else if (predicted_f.param_type_2
3372 == CPT2_COLORED_FACEDIR) {
3373 // param2 = pure palette index + other
3374 param2 = (index & 0xe0) | (param2 & 0x1f);
3379 // Add node to client map
3380 MapNode n(id, 0, param2);
3383 LocalPlayer *player = client->getEnv().getLocalPlayer();
3385 // Dont place node when player would be inside new node
3386 // NOTE: This is to be eventually implemented by a mod as client-side Lua
3387 if (!nodedef->get(n).walkable ||
3388 g_settings->getBool("enable_build_where_you_stand") ||
3389 (client->checkPrivilege("noclip") && g_settings->getBool("noclip")) ||
3390 (nodedef->get(n).walkable &&
3391 neighbourpos != player->getStandingNodePos() + v3s16(0, 1, 0) &&
3392 neighbourpos != player->getStandingNodePos() + v3s16(0, 2, 0))) {
3394 // This triggers the required mesh update too
3395 client->addNode(p, n);
3398 } catch (InvalidPositionException &e) {
3399 errorstream << "Node placement prediction failed for "
3400 << selected_item.name << " (places "
3402 << ") - Position not loaded" << std::endl;
3409 void Game::handlePointingAtObject(const PointedThing &pointed,
3410 const ItemStack &tool_item, const v3f &player_position, bool show_debug)
3412 std::wstring infotext = unescape_translate(
3413 utf8_to_wide(runData.selected_object->infoText()));
3416 if (!infotext.empty()) {
3419 infotext += utf8_to_wide(runData.selected_object->debugInfoText());
3422 m_game_ui->setInfoText(infotext);
3424 if (input->getLeftState()) {
3425 bool do_punch = false;
3426 bool do_punch_damage = false;
3428 if (runData.object_hit_delay_timer <= 0.0) {
3430 do_punch_damage = true;
3431 runData.object_hit_delay_timer = object_hit_delay;
3434 if (input->getLeftClicked())
3438 infostream << "Left-clicked object" << std::endl;
3439 runData.left_punch = true;
3442 if (do_punch_damage) {
3443 // Report direct punch
3444 v3f objpos = runData.selected_object->getPosition();
3445 v3f dir = (objpos - player_position).normalize();
3447 bool disable_send = runData.selected_object->directReportPunch(
3448 dir, &tool_item, runData.time_from_last_punch);
3449 runData.time_from_last_punch = 0;
3452 client->interact(INTERACT_START_DIGGING, pointed);
3454 } else if (input->getRightClicked()) {
3455 infostream << "Right-clicked object" << std::endl;
3456 client->interact(INTERACT_PLACE, pointed); // place
3461 void Game::handleDigging(const PointedThing &pointed, const v3s16 &nodepos,
3462 const ItemStack &selected_item, const ItemStack &hand_item, f32 dtime)
3464 // See also: serverpackethandle.cpp, action == 2
3465 LocalPlayer *player = client->getEnv().getLocalPlayer();
3466 ClientMap &map = client->getEnv().getClientMap();
3467 MapNode n = client->getEnv().getClientMap().getNode(nodepos);
3469 // NOTE: Similar piece of code exists on the server side for
3471 // Get digging parameters
3472 DigParams params = getDigParams(nodedef_manager->get(n).groups,
3473 &selected_item.getToolCapabilities(itemdef_manager));
3475 // If can't dig, try hand
3476 if (!params.diggable) {
3477 params = getDigParams(nodedef_manager->get(n).groups,
3478 &hand_item.getToolCapabilities(itemdef_manager));
3481 if (!params.diggable) {
3482 // I guess nobody will wait for this long
3483 runData.dig_time_complete = 10000000.0;
3485 runData.dig_time_complete = params.time;
3487 if (m_cache_enable_particles) {
3488 const ContentFeatures &features = client->getNodeDefManager()->get(n);
3489 client->getParticleManager()->addNodeParticle(client,
3490 player, nodepos, n, features);
3494 if (!runData.digging) {
3495 infostream << "Started digging" << std::endl;
3496 runData.dig_instantly = runData.dig_time_complete == 0;
3497 if (client->modsLoaded() && client->getScript()->on_punchnode(nodepos, n))
3499 client->interact(INTERACT_START_DIGGING, pointed);
3500 runData.digging = true;
3501 runData.ldown_for_dig = true;
3504 if (!runData.dig_instantly) {
3505 runData.dig_index = (float)crack_animation_length
3507 / runData.dig_time_complete;
3509 // This is for e.g. torches
3510 runData.dig_index = crack_animation_length;
3513 SimpleSoundSpec sound_dig = nodedef_manager->get(n).sound_dig;
3515 if (sound_dig.exists() && params.diggable) {
3516 if (sound_dig.name == "__group") {
3517 if (!params.main_group.empty()) {
3518 soundmaker->m_player_leftpunch_sound.gain = 0.5;
3519 soundmaker->m_player_leftpunch_sound.name =
3520 std::string("default_dig_") +
3524 soundmaker->m_player_leftpunch_sound = sound_dig;
3528 // Don't show cracks if not diggable
3529 if (runData.dig_time_complete >= 100000.0) {
3530 } else if (runData.dig_index < crack_animation_length) {
3531 //TimeTaker timer("client.setTempMod");
3532 //infostream<<"dig_index="<<dig_index<<std::endl;
3533 client->setCrack(runData.dig_index, nodepos);
3535 infostream << "Digging completed" << std::endl;
3536 client->setCrack(-1, v3s16(0, 0, 0));
3538 runData.dig_time = 0;
3539 runData.digging = false;
3540 // we successfully dug, now block it from repeating if we want to be safe
3541 if (g_settings->getBool("safe_dig_and_place"))
3542 runData.digging_blocked = true;
3544 runData.nodig_delay_timer =
3545 runData.dig_time_complete / (float)crack_animation_length;
3547 // We don't want a corresponding delay to very time consuming nodes
3548 // and nodes without digging time (e.g. torches) get a fixed delay.
3549 if (runData.nodig_delay_timer > 0.3)
3550 runData.nodig_delay_timer = 0.3;
3551 else if (runData.dig_instantly)
3552 runData.nodig_delay_timer = 0.15;
3554 bool is_valid_position;
3555 MapNode wasnode = map.getNode(nodepos, &is_valid_position);
3556 if (is_valid_position) {
3557 if (client->modsLoaded() &&
3558 client->getScript()->on_dignode(nodepos, wasnode)) {
3562 const ContentFeatures &f = client->ndef()->get(wasnode);
3563 if (f.node_dig_prediction == "air") {
3564 client->removeNode(nodepos);
3565 } else if (!f.node_dig_prediction.empty()) {
3567 bool found = client->ndef()->getId(f.node_dig_prediction, id);
3569 client->addNode(nodepos, id, true);
3571 // implicit else: no prediction
3574 client->interact(INTERACT_DIGGING_COMPLETED, pointed);
3576 if (m_cache_enable_particles) {
3577 const ContentFeatures &features =
3578 client->getNodeDefManager()->get(wasnode);
3579 client->getParticleManager()->addDiggingParticles(client,
3580 player, nodepos, wasnode, features);
3584 // Send event to trigger sound
3585 client->getEventManager()->put(new NodeDugEvent(nodepos, wasnode));
3588 if (runData.dig_time_complete < 100000.0) {
3589 runData.dig_time += dtime;
3591 runData.dig_time = 0;
3592 client->setCrack(-1, nodepos);
3595 camera->setDigging(0); // left click animation
3599 void Game::updateFrame(ProfilerGraph *graph, RunStats *stats, f32 dtime,
3600 const CameraOrientation &cam)
3602 TimeTaker tt_update("Game::updateFrame()");
3603 LocalPlayer *player = client->getEnv().getLocalPlayer();
3609 if (draw_control->range_all) {
3610 runData.fog_range = 100000 * BS;
3612 runData.fog_range = draw_control->wanted_range * BS;
3616 Calculate general brightness
3618 u32 daynight_ratio = client->getEnv().getDayNightRatio();
3619 float time_brightness = decode_light_f((float)daynight_ratio / 1000.0);
3620 float direct_brightness;
3623 if (m_cache_enable_noclip && m_cache_enable_free_move) {
3624 direct_brightness = time_brightness;
3625 sunlight_seen = true;
3627 float old_brightness = sky->getBrightness();
3628 direct_brightness = client->getEnv().getClientMap()
3629 .getBackgroundBrightness(MYMIN(runData.fog_range * 1.2, 60 * BS),
3630 daynight_ratio, (int)(old_brightness * 255.5), &sunlight_seen)
3634 float time_of_day_smooth = runData.time_of_day_smooth;
3635 float time_of_day = client->getEnv().getTimeOfDayF();
3637 static const float maxsm = 0.05f;
3638 static const float todsm = 0.05f;
3640 if (std::fabs(time_of_day - time_of_day_smooth) > maxsm &&
3641 std::fabs(time_of_day - time_of_day_smooth + 1.0) > maxsm &&
3642 std::fabs(time_of_day - time_of_day_smooth - 1.0) > maxsm)
3643 time_of_day_smooth = time_of_day;
3645 if (time_of_day_smooth > 0.8 && time_of_day < 0.2)
3646 time_of_day_smooth = time_of_day_smooth * (1.0 - todsm)
3647 + (time_of_day + 1.0) * todsm;
3649 time_of_day_smooth = time_of_day_smooth * (1.0 - todsm)
3650 + time_of_day * todsm;
3652 runData.time_of_day_smooth = time_of_day_smooth;
3654 sky->update(time_of_day_smooth, time_brightness, direct_brightness,
3655 sunlight_seen, camera->getCameraMode(), player->getYaw(),
3656 player->getPitch());
3662 if (sky->getCloudsVisible()) {
3663 clouds->setVisible(true);
3664 clouds->step(dtime);
3665 // camera->getPosition is not enough for 3rd person views
3666 v3f camera_node_position = camera->getCameraNode()->getPosition();
3667 v3s16 camera_offset = camera->getOffset();
3668 camera_node_position.X = camera_node_position.X + camera_offset.X * BS;
3669 camera_node_position.Y = camera_node_position.Y + camera_offset.Y * BS;
3670 camera_node_position.Z = camera_node_position.Z + camera_offset.Z * BS;
3671 clouds->update(camera_node_position,
3672 sky->getCloudColor());
3673 if (clouds->isCameraInsideCloud() && m_cache_enable_fog) {
3674 // if inside clouds, and fog enabled, use that as sky
3676 video::SColor clouds_dark = clouds->getColor()
3677 .getInterpolated(video::SColor(255, 0, 0, 0), 0.9);
3678 sky->overrideColors(clouds_dark, clouds->getColor());
3679 sky->setBodiesVisible(false);
3680 runData.fog_range = std::fmin(runData.fog_range * 0.5f, 32.0f * BS);
3681 // do not draw clouds after all
3682 clouds->setVisible(false);
3685 clouds->setVisible(false);
3692 client->getParticleManager()->step(dtime);
3698 if (m_cache_enable_fog) {
3701 video::EFT_FOG_LINEAR,
3702 runData.fog_range * m_cache_fog_start,
3703 runData.fog_range * 1.0,
3711 video::EFT_FOG_LINEAR,
3721 Get chat messages from client
3724 v2u32 screensize = driver->getScreenSize();
3726 updateChat(dtime, screensize);
3732 if (player->getWieldIndex() != runData.new_playeritem)
3733 client->setPlayerItem(runData.new_playeritem);
3735 if (client->updateWieldedItem()) {
3736 // Update wielded tool
3737 ItemStack selected_item, hand_item;
3738 ItemStack &tool_item = player->getWieldedItem(&selected_item, &hand_item);
3739 camera->wield(tool_item);
3743 Update block draw list every 200ms or when camera direction has
3746 runData.update_draw_list_timer += dtime;
3748 v3f camera_direction = camera->getDirection();
3749 if (runData.update_draw_list_timer >= 0.2
3750 || runData.update_draw_list_last_cam_dir.getDistanceFrom(camera_direction) > 0.2
3751 || m_camera_offset_changed) {
3752 runData.update_draw_list_timer = 0;
3753 client->getEnv().getClientMap().updateDrawList();
3754 runData.update_draw_list_last_cam_dir = camera_direction;
3757 m_game_ui->update(*stats, client, draw_control, cam, runData.pointed_old, gui_chat_console, dtime);
3760 make sure menu is on top
3761 1. Delete formspec menu reference if menu was removed
3762 2. Else, make sure formspec menu is on top
3764 auto formspec = m_game_ui->getFormspecGUI();
3765 do { // breakable. only runs for one iteration
3769 if (formspec->getReferenceCount() == 1) {
3770 m_game_ui->deleteFormspec();
3774 auto &loc = formspec->getFormspecLocation();
3775 if (loc.type == InventoryLocation::NODEMETA) {
3776 NodeMetadata *meta = client->getEnv().getClientMap().getNodeMetadata(loc.p);
3777 if (!meta || meta->getString("formspec").empty()) {
3778 formspec->quitMenu();
3784 guiroot->bringToFront(formspec);
3790 const video::SColor &skycolor = sky->getSkyColor();
3792 TimeTaker tt_draw("Draw scene");
3793 driver->beginScene(true, true, skycolor);
3795 bool draw_wield_tool = (m_game_ui->m_flags.show_hud &&
3796 (player->hud_flags & HUD_FLAG_WIELDITEM_VISIBLE) &&
3797 (camera->getCameraMode() == CAMERA_MODE_FIRST));
3798 bool draw_crosshair = (
3799 (player->hud_flags & HUD_FLAG_CROSSHAIR_VISIBLE) &&
3800 (camera->getCameraMode() != CAMERA_MODE_THIRD_FRONT));
3801 #ifdef HAVE_TOUCHSCREENGUI
3803 draw_crosshair = !g_settings->getBool("touchtarget");
3804 } catch (SettingNotFoundException) {
3807 RenderingEngine::draw_scene(skycolor, m_game_ui->m_flags.show_hud,
3808 m_game_ui->m_flags.show_minimap, draw_wield_tool, draw_crosshair);
3813 if (m_game_ui->m_flags.show_profiler_graph)
3814 graph->draw(10, screensize.Y - 10, driver, g_fontengine->getFont());
3819 if (runData.damage_flash > 0.0f) {
3820 video::SColor color(runData.damage_flash, 180, 0, 0);
3821 driver->draw2DRectangle(color,
3822 core::rect<s32>(0, 0, screensize.X, screensize.Y),
3825 runData.damage_flash -= 384.0f * dtime;
3831 if (player->hurt_tilt_timer > 0.0f) {
3832 player->hurt_tilt_timer -= dtime * 6.0f;
3834 if (player->hurt_tilt_timer < 0.0f)
3835 player->hurt_tilt_strength = 0.0f;
3839 Update minimap pos and rotation
3841 if (mapper && m_game_ui->m_flags.show_minimap && m_game_ui->m_flags.show_hud) {
3842 mapper->setPos(floatToInt(player->getPosition(), BS));
3843 mapper->setAngle(player->getYaw());
3851 stats->drawtime = tt_draw.stop(true);
3852 g_profiler->avg("Game::updateFrame(): draw scene [ms]", stats->drawtime);
3853 g_profiler->graphAdd("Update frame [ms]", tt_update.stop(true));
3856 /* Log times and stuff for visualization */
3857 inline void Game::updateProfilerGraphs(ProfilerGraph *graph)
3859 Profiler::GraphValues values;
3860 g_profiler->graphGet(values);
3866 /****************************************************************************
3868 ****************************************************************************/
3870 /* On some computers framerate doesn't seem to be automatically limited
3872 inline void Game::limitFps(FpsControl *fps_timings, f32 *dtime)
3874 // not using getRealTime is necessary for wine
3875 device->getTimer()->tick(); // Maker sure device time is up-to-date
3876 u32 time = device->getTimer()->getTime();
3877 u32 last_time = fps_timings->last_time;
3879 if (time > last_time) // Make sure time hasn't overflowed
3880 fps_timings->busy_time = time - last_time;
3882 fps_timings->busy_time = 0;
3884 u32 frametime_min = 1000 / (g_menumgr.pausesGame()
3885 ? g_settings->getFloat("pause_fps_max")
3886 : g_settings->getFloat("fps_max"));
3888 if (fps_timings->busy_time < frametime_min) {
3889 fps_timings->sleep_time = frametime_min - fps_timings->busy_time;
3890 device->sleep(fps_timings->sleep_time);
3892 fps_timings->sleep_time = 0;
3895 /* Get the new value of the device timer. Note that device->sleep() may
3896 * not sleep for the entire requested time as sleep may be interrupted and
3897 * therefore it is arguably more accurate to get the new time from the
3898 * device rather than calculating it by adding sleep_time to time.
3901 device->getTimer()->tick(); // Update device timer
3902 time = device->getTimer()->getTime();
3904 if (time > last_time) // Make sure last_time hasn't overflowed
3905 *dtime = (time - last_time) / 1000.0;
3909 fps_timings->last_time = time;
3912 void Game::showOverlayMessage(const char *msg, float dtime, int percent, bool draw_clouds)
3914 const wchar_t *wmsg = wgettext(msg);
3915 RenderingEngine::draw_load_screen(wmsg, guienv, texture_src, dtime, percent,
3920 void Game::settingChangedCallback(const std::string &setting_name, void *data)
3922 ((Game *)data)->readSettings();
3925 void Game::readSettings()
3927 m_cache_doubletap_jump = g_settings->getBool("doubletap_jump");
3928 m_cache_enable_clouds = g_settings->getBool("enable_clouds");
3929 m_cache_enable_joysticks = g_settings->getBool("enable_joysticks");
3930 m_cache_enable_particles = g_settings->getBool("enable_particles");
3931 m_cache_enable_fog = g_settings->getBool("enable_fog");
3932 m_cache_mouse_sensitivity = g_settings->getFloat("mouse_sensitivity");
3933 m_cache_joystick_frustum_sensitivity = g_settings->getFloat("joystick_frustum_sensitivity");
3934 m_repeat_right_click_time = g_settings->getFloat("repeat_rightclick_time");
3936 m_cache_enable_noclip = g_settings->getBool("noclip");
3937 m_cache_enable_free_move = g_settings->getBool("free_move");
3939 m_cache_fog_start = g_settings->getFloat("fog_start");
3941 m_cache_cam_smoothing = 0;
3942 if (g_settings->getBool("cinematic"))
3943 m_cache_cam_smoothing = 1 - g_settings->getFloat("cinematic_camera_smoothing");
3945 m_cache_cam_smoothing = 1 - g_settings->getFloat("camera_smoothing");
3947 m_cache_fog_start = rangelim(m_cache_fog_start, 0.0f, 0.99f);
3948 m_cache_cam_smoothing = rangelim(m_cache_cam_smoothing, 0.01f, 1.0f);
3949 m_cache_mouse_sensitivity = rangelim(m_cache_mouse_sensitivity, 0.001, 100.0);
3951 m_does_lost_focus_pause_game = g_settings->getBool("pause_on_lost_focus");
3954 /****************************************************************************/
3955 /****************************************************************************
3957 ****************************************************************************/
3958 /****************************************************************************/
3960 void Game::extendedResourceCleanup()
3962 // Extended resource accounting
3963 infostream << "Irrlicht resources after cleanup:" << std::endl;
3964 infostream << "\tRemaining meshes : "
3965 << RenderingEngine::get_mesh_cache()->getMeshCount() << std::endl;
3966 infostream << "\tRemaining textures : "
3967 << driver->getTextureCount() << std::endl;
3969 for (unsigned int i = 0; i < driver->getTextureCount(); i++) {
3970 irr::video::ITexture *texture = driver->getTextureByIndex(i);
3971 infostream << "\t\t" << i << ":" << texture->getName().getPath().c_str()
3975 clearTextureNameCache();
3976 infostream << "\tRemaining materials: "
3977 << driver-> getMaterialRendererCount()
3978 << " (note: irrlicht doesn't support removing renderers)" << std::endl;
3981 void Game::showDeathFormspec()
3983 static std::string formspec_str =
3984 std::string("formspec_version[1]") +
3986 "bgcolor[#320000b4;true]"
3987 "label[4.85,1.35;" + gettext("You died") + "]"
3988 "button_exit[4,3;3,0.5;btn_respawn;" + gettext("Respawn") + "]"
3992 /* Note: FormspecFormSource and LocalFormspecHandler *
3993 * are deleted by guiFormSpecMenu */
3994 FormspecFormSource *fs_src = new FormspecFormSource(formspec_str);
3995 LocalFormspecHandler *txt_dst = new LocalFormspecHandler("MT_DEATH_SCREEN", client);
3997 auto *&formspec = m_game_ui->getFormspecGUI();
3998 GUIFormSpecMenu::create(formspec, client, &input->joystick,
3999 fs_src, txt_dst, client->getFormspecPrepend());
4000 formspec->setFocus("btn_respawn");
4003 #define GET_KEY_NAME(KEY) gettext(getKeySetting(#KEY).name())
4004 void Game::showPauseMenu()
4007 static const std::string control_text = strgettext("Default Controls:\n"
4008 "No menu visible:\n"
4009 "- single tap: button activate\n"
4010 "- double tap: place/use\n"
4011 "- slide finger: look around\n"
4012 "Menu/Inventory visible:\n"
4013 "- double tap (outside):\n"
4015 "- touch stack, touch slot:\n"
4017 "- touch&drag, tap 2nd finger\n"
4018 " --> place single item to slot\n"
4021 static const std::string control_text_template = strgettext("Controls:\n"
4022 "- %s: move forwards\n"
4023 "- %s: move backwards\n"
4025 "- %s: move right\n"
4026 "- %s: jump/climb\n"
4027 "- %s: sneak/go down\n"
4030 "- Mouse: turn/look\n"
4031 "- Mouse left: dig/punch\n"
4032 "- Mouse right: place/use\n"
4033 "- Mouse wheel: select item\n"
4037 char control_text_buf[600];
4039 porting::mt_snprintf(control_text_buf, sizeof(control_text_buf), control_text_template.c_str(),
4040 GET_KEY_NAME(keymap_forward),
4041 GET_KEY_NAME(keymap_backward),
4042 GET_KEY_NAME(keymap_left),
4043 GET_KEY_NAME(keymap_right),
4044 GET_KEY_NAME(keymap_jump),
4045 GET_KEY_NAME(keymap_sneak),
4046 GET_KEY_NAME(keymap_drop),
4047 GET_KEY_NAME(keymap_inventory),
4048 GET_KEY_NAME(keymap_chat)
4051 std::string control_text = std::string(control_text_buf);
4052 str_formspec_escape(control_text);
4055 float ypos = simple_singleplayer_mode ? 0.7f : 0.1f;
4056 std::ostringstream os;
4058 os << "formspec_version[1]" << SIZE_TAG
4059 << "button_exit[4," << (ypos++) << ";3,0.5;btn_continue;"
4060 << strgettext("Continue") << "]";
4062 if (!simple_singleplayer_mode) {
4063 os << "button_exit[4," << (ypos++) << ";3,0.5;btn_change_password;"
4064 << strgettext("Change Password") << "]";
4066 os << "field[4.95,0;5,1.5;;" << strgettext("Game paused") << ";]";
4070 os << "button_exit[4," << (ypos++) << ";3,0.5;btn_sound;"
4071 << strgettext("Sound Volume") << "]";
4072 os << "button_exit[4," << (ypos++) << ";3,0.5;btn_key_config;"
4073 << strgettext("Change Keys") << "]";
4075 os << "button_exit[4," << (ypos++) << ";3,0.5;btn_exit_menu;"
4076 << strgettext("Exit to Menu") << "]";
4077 os << "button_exit[4," << (ypos++) << ";3,0.5;btn_exit_os;"
4078 << strgettext("Exit to OS") << "]"
4079 << "textarea[7.5,0.25;3.9,6.25;;" << control_text << ";]"
4080 << "textarea[0.4,0.25;3.9,6.25;;" << PROJECT_NAME_C " " VERSION_STRING "\n"
4082 << strgettext("Game info:") << "\n";
4083 const std::string &address = client->getAddressName();
4084 static const std::string mode = strgettext("- Mode: ");
4085 if (!simple_singleplayer_mode) {
4086 Address serverAddress = client->getServerAddress();
4087 if (!address.empty()) {
4088 os << mode << strgettext("Remote server") << "\n"
4089 << strgettext("- Address: ") << address;
4091 os << mode << strgettext("Hosting server");
4093 os << "\n" << strgettext("- Port: ") << serverAddress.getPort() << "\n";
4095 os << mode << strgettext("Singleplayer") << "\n";
4097 if (simple_singleplayer_mode || address.empty()) {
4098 static const std::string on = strgettext("On");
4099 static const std::string off = strgettext("Off");
4100 const std::string &damage = g_settings->getBool("enable_damage") ? on : off;
4101 const std::string &creative = g_settings->getBool("creative_mode") ? on : off;
4102 const std::string &announced = g_settings->getBool("server_announce") ? on : off;
4103 os << strgettext("- Damage: ") << damage << "\n"
4104 << strgettext("- Creative Mode: ") << creative << "\n";
4105 if (!simple_singleplayer_mode) {
4106 const std::string &pvp = g_settings->getBool("enable_pvp") ? on : off;
4107 os << strgettext("- PvP: ") << pvp << "\n"
4108 << strgettext("- Public: ") << announced << "\n";
4109 std::string server_name = g_settings->get("server_name");
4110 str_formspec_escape(server_name);
4111 if (announced == on && !server_name.empty())
4112 os << strgettext("- Server Name: ") << server_name;
4119 /* Note: FormspecFormSource and LocalFormspecHandler *
4120 * are deleted by guiFormSpecMenu */
4121 FormspecFormSource *fs_src = new FormspecFormSource(os.str());
4122 LocalFormspecHandler *txt_dst = new LocalFormspecHandler("MT_PAUSE_MENU");
4124 auto *&formspec = m_game_ui->getFormspecGUI();
4125 GUIFormSpecMenu::create(formspec, client, &input->joystick,
4126 fs_src, txt_dst, client->getFormspecPrepend());
4127 formspec->setFocus("btn_continue");
4128 formspec->doPause = true;
4131 /****************************************************************************/
4132 /****************************************************************************
4133 extern function for launching the game
4134 ****************************************************************************/
4135 /****************************************************************************/
4137 void the_game(bool *kill,
4139 InputHandler *input,
4140 const std::string &map_dir,
4141 const std::string &playername,
4142 const std::string &password,
4143 const std::string &address, // If empty local server is created
4146 std::string &error_message,
4147 ChatBackend &chat_backend,
4148 bool *reconnect_requested,
4149 const SubgameSpec &gamespec, // Used for local game
4150 bool simple_singleplayer_mode)
4154 /* Make a copy of the server address because if a local singleplayer server
4155 * is created then this is updated and we don't want to change the value
4156 * passed to us by the calling function
4158 std::string server_address = address;
4162 if (game.startup(kill, random_input, input, map_dir,
4163 playername, password, &server_address, port, error_message,
4164 reconnect_requested, &chat_backend, gamespec,
4165 simple_singleplayer_mode)) {
4170 } catch (SerializationError &e) {
4171 error_message = std::string("A serialization error occurred:\n")
4172 + e.what() + "\n\nThe server is probably "
4173 " running a different version of " PROJECT_NAME_C ".";
4174 errorstream << error_message << std::endl;
4175 } catch (ServerError &e) {
4176 error_message = e.what();
4177 errorstream << "ServerError: " << error_message << std::endl;
4178 } catch (ModError &e) {
4179 error_message = std::string("ModError: ") + e.what() +
4180 strgettext("\nCheck debug.txt for details.");
4181 errorstream << error_message << std::endl;