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"
63 #include "translation.h"
64 #include "util/basic_macros.h"
65 #include "util/directiontables.h"
66 #include "util/pointedthing.h"
67 #include "util/quicktune_shortcutter.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;
269 float m_player_jump_timer;
271 SimpleSoundSpec m_player_step_sound;
272 SimpleSoundSpec m_player_leftpunch_sound;
273 SimpleSoundSpec m_player_rightpunch_sound;
275 SoundMaker(ISoundManager *sound, const NodeDefManager *ndef):
278 makes_footstep_sound(true),
279 m_player_step_timer(0.0f),
280 m_player_jump_timer(0.0f)
284 void playPlayerStep()
286 if (m_player_step_timer <= 0 && m_player_step_sound.exists()) {
287 m_player_step_timer = 0.03;
288 if (makes_footstep_sound)
289 m_sound->playSound(m_player_step_sound, false);
293 void playPlayerJump()
295 if (m_player_jump_timer <= 0.0f) {
296 m_player_jump_timer = 0.2f;
297 m_sound->playSound(SimpleSoundSpec("player_jump", 0.5f), false);
301 static void viewBobbingStep(MtEvent *e, void *data)
303 SoundMaker *sm = (SoundMaker *)data;
304 sm->playPlayerStep();
307 static void playerRegainGround(MtEvent *e, void *data)
309 SoundMaker *sm = (SoundMaker *)data;
310 sm->playPlayerStep();
313 static void playerJump(MtEvent *e, void *data)
315 SoundMaker *sm = (SoundMaker *)data;
316 sm->playPlayerJump();
319 static void cameraPunchLeft(MtEvent *e, void *data)
321 SoundMaker *sm = (SoundMaker *)data;
322 sm->m_sound->playSound(sm->m_player_leftpunch_sound, false);
325 static void cameraPunchRight(MtEvent *e, void *data)
327 SoundMaker *sm = (SoundMaker *)data;
328 sm->m_sound->playSound(sm->m_player_rightpunch_sound, false);
331 static void nodeDug(MtEvent *e, void *data)
333 SoundMaker *sm = (SoundMaker *)data;
334 NodeDugEvent *nde = (NodeDugEvent *)e;
335 sm->m_sound->playSound(sm->m_ndef->get(nde->n).sound_dug, false);
338 static void playerDamage(MtEvent *e, void *data)
340 SoundMaker *sm = (SoundMaker *)data;
341 sm->m_sound->playSound(SimpleSoundSpec("player_damage", 0.5), false);
344 static void playerFallingDamage(MtEvent *e, void *data)
346 SoundMaker *sm = (SoundMaker *)data;
347 sm->m_sound->playSound(SimpleSoundSpec("player_falling_damage", 0.5), false);
350 void registerReceiver(MtEventManager *mgr)
352 mgr->reg(MtEvent::VIEW_BOBBING_STEP, SoundMaker::viewBobbingStep, this);
353 mgr->reg(MtEvent::PLAYER_REGAIN_GROUND, SoundMaker::playerRegainGround, this);
354 mgr->reg(MtEvent::PLAYER_JUMP, SoundMaker::playerJump, this);
355 mgr->reg(MtEvent::CAMERA_PUNCH_LEFT, SoundMaker::cameraPunchLeft, this);
356 mgr->reg(MtEvent::CAMERA_PUNCH_RIGHT, SoundMaker::cameraPunchRight, this);
357 mgr->reg(MtEvent::NODE_DUG, SoundMaker::nodeDug, this);
358 mgr->reg(MtEvent::PLAYER_DAMAGE, SoundMaker::playerDamage, this);
359 mgr->reg(MtEvent::PLAYER_FALLING_DAMAGE, SoundMaker::playerFallingDamage, this);
362 void step(float dtime)
364 m_player_step_timer -= dtime;
365 m_player_jump_timer -= dtime;
369 // Locally stored sounds don't need to be preloaded because of this
370 class GameOnDemandSoundFetcher: public OnDemandSoundFetcher
372 std::set<std::string> m_fetched;
374 void paths_insert(std::set<std::string> &dst_paths,
375 const std::string &base,
376 const std::string &name)
378 dst_paths.insert(base + DIR_DELIM + "sounds" + DIR_DELIM + name + ".ogg");
379 dst_paths.insert(base + DIR_DELIM + "sounds" + DIR_DELIM + name + ".0.ogg");
380 dst_paths.insert(base + DIR_DELIM + "sounds" + DIR_DELIM + name + ".1.ogg");
381 dst_paths.insert(base + DIR_DELIM + "sounds" + DIR_DELIM + name + ".2.ogg");
382 dst_paths.insert(base + DIR_DELIM + "sounds" + DIR_DELIM + name + ".3.ogg");
383 dst_paths.insert(base + DIR_DELIM + "sounds" + DIR_DELIM + name + ".4.ogg");
384 dst_paths.insert(base + DIR_DELIM + "sounds" + DIR_DELIM + name + ".5.ogg");
385 dst_paths.insert(base + DIR_DELIM + "sounds" + DIR_DELIM + name + ".6.ogg");
386 dst_paths.insert(base + DIR_DELIM + "sounds" + DIR_DELIM + name + ".7.ogg");
387 dst_paths.insert(base + DIR_DELIM + "sounds" + DIR_DELIM + name + ".8.ogg");
388 dst_paths.insert(base + DIR_DELIM + "sounds" + DIR_DELIM + name + ".9.ogg");
391 void fetchSounds(const std::string &name,
392 std::set<std::string> &dst_paths,
393 std::set<std::string> &dst_datas)
395 if (m_fetched.count(name))
398 m_fetched.insert(name);
400 paths_insert(dst_paths, porting::path_share, name);
401 paths_insert(dst_paths, porting::path_user, name);
406 // before 1.8 there isn't a "integer interface", only float
407 #if (IRRLICHT_VERSION_MAJOR == 1 && IRRLICHT_VERSION_MINOR < 8)
408 typedef f32 SamplerLayer_t;
410 typedef s32 SamplerLayer_t;
414 class GameGlobalShaderConstantSetter : public IShaderConstantSetter
417 bool *m_force_fog_off;
420 CachedPixelShaderSetting<float, 4> m_sky_bg_color;
421 CachedPixelShaderSetting<float> m_fog_distance;
422 CachedVertexShaderSetting<float> m_animation_timer_vertex;
423 CachedPixelShaderSetting<float> m_animation_timer_pixel;
424 CachedPixelShaderSetting<float, 3> m_day_light;
425 CachedPixelShaderSetting<float, 3> m_eye_position_pixel;
426 CachedVertexShaderSetting<float, 3> m_eye_position_vertex;
427 CachedPixelShaderSetting<float, 3> m_minimap_yaw;
428 CachedPixelShaderSetting<float, 3> m_camera_offset_pixel;
429 CachedPixelShaderSetting<float, 3> m_camera_offset_vertex;
430 CachedPixelShaderSetting<SamplerLayer_t> m_base_texture;
431 CachedPixelShaderSetting<SamplerLayer_t> m_normal_texture;
432 CachedPixelShaderSetting<SamplerLayer_t> m_texture_flags;
436 void onSettingsChange(const std::string &name)
438 if (name == "enable_fog")
439 m_fog_enabled = g_settings->getBool("enable_fog");
442 static void settingsCallback(const std::string &name, void *userdata)
444 reinterpret_cast<GameGlobalShaderConstantSetter*>(userdata)->onSettingsChange(name);
447 void setSky(Sky *sky) { m_sky = sky; }
449 GameGlobalShaderConstantSetter(Sky *sky, bool *force_fog_off,
450 f32 *fog_range, Client *client) :
452 m_force_fog_off(force_fog_off),
453 m_fog_range(fog_range),
454 m_sky_bg_color("skyBgColor"),
455 m_fog_distance("fogDistance"),
456 m_animation_timer_vertex("animationTimer"),
457 m_animation_timer_pixel("animationTimer"),
458 m_day_light("dayLight"),
459 m_eye_position_pixel("eyePosition"),
460 m_eye_position_vertex("eyePosition"),
461 m_minimap_yaw("yawVec"),
462 m_camera_offset_pixel("cameraOffset"),
463 m_camera_offset_vertex("cameraOffset"),
464 m_base_texture("baseTexture"),
465 m_normal_texture("normalTexture"),
466 m_texture_flags("textureFlags"),
469 g_settings->registerChangedCallback("enable_fog", settingsCallback, this);
470 m_fog_enabled = g_settings->getBool("enable_fog");
473 ~GameGlobalShaderConstantSetter()
475 g_settings->deregisterChangedCallback("enable_fog", settingsCallback, this);
478 virtual void onSetConstants(video::IMaterialRendererServices *services,
485 video::SColor bgcolor = m_sky->getBgColor();
486 video::SColorf bgcolorf(bgcolor);
487 float bgcolorfa[4] = {
493 m_sky_bg_color.set(bgcolorfa, services);
496 float fog_distance = 10000 * BS;
498 if (m_fog_enabled && !*m_force_fog_off)
499 fog_distance = *m_fog_range;
501 m_fog_distance.set(&fog_distance, services);
503 u32 daynight_ratio = (float)m_client->getEnv().getDayNightRatio();
504 video::SColorf sunlight;
505 get_sunlight_color(&sunlight, daynight_ratio);
510 m_day_light.set(dnc, services);
512 u32 animation_timer = porting::getTimeMs() % 1000000;
513 float animation_timer_f = (float)animation_timer / 100000.f;
514 m_animation_timer_vertex.set(&animation_timer_f, services);
515 m_animation_timer_pixel.set(&animation_timer_f, services);
517 float eye_position_array[3];
518 v3f epos = m_client->getEnv().getLocalPlayer()->getEyePosition();
519 #if (IRRLICHT_VERSION_MAJOR == 1 && IRRLICHT_VERSION_MINOR < 8)
520 eye_position_array[0] = epos.X;
521 eye_position_array[1] = epos.Y;
522 eye_position_array[2] = epos.Z;
524 epos.getAs3Values(eye_position_array);
526 m_eye_position_pixel.set(eye_position_array, services);
527 m_eye_position_vertex.set(eye_position_array, services);
529 if (m_client->getMinimap()) {
530 float minimap_yaw_array[3];
531 v3f minimap_yaw = m_client->getMinimap()->getYawVec();
532 #if (IRRLICHT_VERSION_MAJOR == 1 && IRRLICHT_VERSION_MINOR < 8)
533 minimap_yaw_array[0] = minimap_yaw.X;
534 minimap_yaw_array[1] = minimap_yaw.Y;
535 minimap_yaw_array[2] = minimap_yaw.Z;
537 minimap_yaw.getAs3Values(minimap_yaw_array);
539 m_minimap_yaw.set(minimap_yaw_array, services);
542 float camera_offset_array[3];
543 v3f offset = intToFloat(m_client->getCamera()->getOffset(), BS);
544 #if (IRRLICHT_VERSION_MAJOR == 1 && IRRLICHT_VERSION_MINOR < 8)
545 camera_offset_array[0] = offset.X;
546 camera_offset_array[1] = offset.Y;
547 camera_offset_array[2] = offset.Z;
549 offset.getAs3Values(camera_offset_array);
551 m_camera_offset_pixel.set(camera_offset_array, services);
552 m_camera_offset_vertex.set(camera_offset_array, services);
554 SamplerLayer_t base_tex = 0,
557 m_base_texture.set(&base_tex, services);
558 m_normal_texture.set(&normal_tex, services);
559 m_texture_flags.set(&flags_tex, services);
564 class GameGlobalShaderConstantSetterFactory : public IShaderConstantSetterFactory
567 bool *m_force_fog_off;
570 std::vector<GameGlobalShaderConstantSetter *> created_nosky;
572 GameGlobalShaderConstantSetterFactory(bool *force_fog_off,
573 f32 *fog_range, Client *client) :
575 m_force_fog_off(force_fog_off),
576 m_fog_range(fog_range),
580 void setSky(Sky *sky) {
582 for (GameGlobalShaderConstantSetter *ggscs : created_nosky) {
583 ggscs->setSky(m_sky);
585 created_nosky.clear();
588 virtual IShaderConstantSetter* create()
590 GameGlobalShaderConstantSetter *scs = new GameGlobalShaderConstantSetter(
591 m_sky, m_force_fog_off, m_fog_range, m_client);
593 created_nosky.push_back(scs);
599 #define SIZE_TAG "size[11,5.5]"
601 #define SIZE_TAG "size[11,5.5,true]" // Fixed size on desktop
604 /****************************************************************************
606 ****************************************************************************/
608 const float object_hit_delay = 0.2;
611 u32 last_time, busy_time, sleep_time;
615 /* The reason the following structs are not anonymous structs within the
616 * class is that they are not used by the majority of member functions and
617 * many functions that do require objects of thse types do not modify them
618 * (so they can be passed as a const qualified parameter)
624 PointedThing pointed_old;
628 bool digging_blocked;
630 bool reset_jump_timer;
631 float nodig_delay_timer;
633 float dig_time_complete;
634 float repeat_rightclick_timer;
635 float object_hit_delay_timer;
636 float time_from_last_punch;
637 ClientActiveObject *selected_object;
641 float update_draw_list_timer;
645 v3f update_draw_list_last_cam_dir;
647 float time_of_day_smooth;
652 struct ClientEventHandler
654 void (Game::*handler)(ClientEvent *, CameraOrientation *);
657 /****************************************************************************
659 ****************************************************************************/
661 /* This is not intended to be a public class. If a public class becomes
662 * desirable then it may be better to create another 'wrapper' class that
663 * hides most of the stuff in this class (nothing in this class is required
664 * by any other file) but exposes the public methods/data only.
671 bool startup(bool *kill,
674 const std::string &map_dir,
675 const std::string &playername,
676 const std::string &password,
677 // If address is "", local server is used and address is updated
678 std::string *address,
680 std::string &error_message,
682 ChatBackend *chat_backend,
683 const SubgameSpec &gamespec, // Used for local game
684 bool simple_singleplayer_mode);
691 void extendedResourceCleanup();
693 // Basic initialisation
694 bool init(const std::string &map_dir, std::string *address,
696 const SubgameSpec &gamespec);
698 bool createSingleplayerServer(const std::string &map_dir,
699 const SubgameSpec &gamespec, u16 port, std::string *address);
702 bool createClient(const std::string &playername,
703 const std::string &password, std::string *address, u16 port);
707 bool connectToServer(const std::string &playername,
708 const std::string &password, std::string *address, u16 port,
709 bool *connect_ok, bool *aborted);
710 bool getServerContent(bool *aborted);
714 void updateInteractTimers(f32 dtime);
715 bool checkConnection();
716 bool handleCallbacks();
717 void processQueues();
718 void updateProfilers(const RunStats &stats, const FpsControl &draw_times, f32 dtime);
719 void updateStats(RunStats *stats, const FpsControl &draw_times, f32 dtime);
720 void updateProfilerGraphs(ProfilerGraph *graph);
723 void processUserInput(f32 dtime);
724 void processKeyInput();
725 void processItemSelection(u16 *new_playeritem);
727 void dropSelectedItem(bool single_item = false);
728 void openInventory();
729 void openConsole(float scale, const wchar_t *line=NULL);
730 void toggleFreeMove();
731 void toggleFreeMoveAlt();
732 void togglePitchMove();
735 void toggleCinematic();
736 void toggleAutoforward();
738 void toggleMinimap(bool shift_pressed);
741 void toggleUpdateCamera();
743 void increaseViewRange();
744 void decreaseViewRange();
745 void toggleFullViewRange();
746 void checkZoomEnabled();
748 void updateCameraDirection(CameraOrientation *cam, float dtime);
749 void updateCameraOrientation(CameraOrientation *cam, float dtime);
750 void updatePlayerControl(const CameraOrientation &cam);
751 void step(f32 *dtime);
752 void processClientEvents(CameraOrientation *cam);
753 void updateCamera(u32 busy_time, f32 dtime);
754 void updateSound(f32 dtime);
755 void processPlayerInteraction(f32 dtime, bool show_hud, bool show_debug);
757 * Returns the object or node the player is pointing at.
758 * Also updates the selected thing in the Hud.
760 * @param[in] shootline the shootline, starting from
761 * the camera position. This also gives the maximal distance
763 * @param[in] liquids_pointable if false, liquids are ignored
764 * @param[in] look_for_object if false, objects are ignored
765 * @param[in] camera_offset offset of the camera
766 * @param[out] selected_object the selected object or
769 PointedThing updatePointedThing(
770 const core::line3d<f32> &shootline, bool liquids_pointable,
771 bool look_for_object, const v3s16 &camera_offset);
772 void handlePointingAtNothing(const ItemStack &playerItem);
773 void handlePointingAtNode(const PointedThing &pointed,
774 const ItemStack &selected_item, const ItemStack &hand_item, f32 dtime);
775 void handlePointingAtObject(const PointedThing &pointed, const ItemStack &playeritem,
776 const v3f &player_position, bool show_debug);
777 void handleDigging(const PointedThing &pointed, const v3s16 &nodepos,
778 const ItemStack &selected_item, const ItemStack &hand_item, f32 dtime);
779 void updateFrame(ProfilerGraph *graph, RunStats *stats, f32 dtime,
780 const CameraOrientation &cam);
783 void limitFps(FpsControl *fps_timings, f32 *dtime);
785 void showOverlayMessage(const char *msg, float dtime, int percent,
786 bool draw_clouds = true);
788 static void settingChangedCallback(const std::string &setting_name, void *data);
791 inline bool isKeyDown(GameKeyType k)
793 return input->isKeyDown(k);
795 inline bool wasKeyDown(GameKeyType k)
797 return input->wasKeyDown(k);
801 void handleAndroidChatInput();
806 bool force_fog_off = false;
807 bool disable_camera_update = false;
810 void showDeathFormspec();
811 void showPauseMenu();
813 // ClientEvent handlers
814 void handleClientEvent_None(ClientEvent *event, CameraOrientation *cam);
815 void handleClientEvent_PlayerDamage(ClientEvent *event, CameraOrientation *cam);
816 void handleClientEvent_PlayerForceMove(ClientEvent *event, CameraOrientation *cam);
817 void handleClientEvent_Deathscreen(ClientEvent *event, CameraOrientation *cam);
818 void handleClientEvent_ShowFormSpec(ClientEvent *event, CameraOrientation *cam);
819 void handleClientEvent_ShowLocalFormSpec(ClientEvent *event, CameraOrientation *cam);
820 void handleClientEvent_HandleParticleEvent(ClientEvent *event,
821 CameraOrientation *cam);
822 void handleClientEvent_HudAdd(ClientEvent *event, CameraOrientation *cam);
823 void handleClientEvent_HudRemove(ClientEvent *event, CameraOrientation *cam);
824 void handleClientEvent_HudChange(ClientEvent *event, CameraOrientation *cam);
825 void handleClientEvent_SetSky(ClientEvent *event, CameraOrientation *cam);
826 void handleClientEvent_SetSun(ClientEvent *event, CameraOrientation *cam);
827 void handleClientEvent_SetMoon(ClientEvent *event, CameraOrientation *cam);
828 void handleClientEvent_SetStars(ClientEvent *event, CameraOrientation *cam);
829 void handleClientEvent_OverrideDayNigthRatio(ClientEvent *event,
830 CameraOrientation *cam);
831 void handleClientEvent_CloudParams(ClientEvent *event, CameraOrientation *cam);
833 void updateChat(f32 dtime, const v2u32 &screensize);
835 bool nodePlacement(const ItemDefinition &selected_def, const ItemStack &selected_item,
836 const v3s16 &nodepos, const v3s16 &neighbourpos, const PointedThing &pointed,
837 const NodeMetadata *meta);
838 static const ClientEventHandler clientEventHandler[CLIENTEVENT_MAX];
840 InputHandler *input = nullptr;
842 Client *client = nullptr;
843 Server *server = nullptr;
845 IWritableTextureSource *texture_src = nullptr;
846 IWritableShaderSource *shader_src = nullptr;
848 // When created, these will be filled with data received from the server
849 IWritableItemDefManager *itemdef_manager = nullptr;
850 NodeDefManager *nodedef_manager = nullptr;
852 GameOnDemandSoundFetcher soundfetcher; // useful when testing
853 ISoundManager *sound = nullptr;
854 bool sound_is_dummy = false;
855 SoundMaker *soundmaker = nullptr;
857 ChatBackend *chat_backend = nullptr;
858 LogOutputBuffer m_chat_log_buf;
860 EventManager *eventmgr = nullptr;
861 QuicktuneShortcutter *quicktune = nullptr;
862 bool registration_confirmation_shown = false;
864 std::unique_ptr<GameUI> m_game_ui;
865 GUIChatConsole *gui_chat_console = nullptr; // Free using ->Drop()
866 MapDrawControl *draw_control = nullptr;
867 Camera *camera = nullptr;
868 Clouds *clouds = nullptr; // Free using ->Drop()
869 Sky *sky = nullptr; // Free using ->Drop()
871 Minimap *mapper = nullptr;
877 This class does take ownership/responsibily for cleaning up etc of any of
878 these items (e.g. device)
880 IrrlichtDevice *device;
881 video::IVideoDriver *driver;
882 scene::ISceneManager *smgr;
884 std::string *error_message;
885 bool *reconnect_requested;
886 scene::ISceneNode *skybox;
889 bool simple_singleplayer_mode;
892 /* Pre-calculated values
894 int crack_animation_length;
896 IntervalLimiter profiler_interval;
899 * TODO: Local caching of settings is not optimal and should at some stage
900 * be updated to use a global settings object for getting thse values
901 * (as opposed to the this local caching). This can be addressed in
904 bool m_cache_doubletap_jump;
905 bool m_cache_enable_clouds;
906 bool m_cache_enable_joysticks;
907 bool m_cache_enable_particles;
908 bool m_cache_enable_fog;
909 bool m_cache_enable_noclip;
910 bool m_cache_enable_free_move;
911 f32 m_cache_mouse_sensitivity;
912 f32 m_cache_joystick_frustum_sensitivity;
913 f32 m_repeat_right_click_time;
914 f32 m_cache_cam_smoothing;
915 f32 m_cache_fog_start;
917 bool m_invert_mouse = false;
918 bool m_first_loop_after_window_activation = false;
919 bool m_camera_offset_changed = false;
921 bool m_does_lost_focus_pause_game = false;
924 bool m_cache_hold_aux1;
925 bool m_android_chat_open;
930 m_chat_log_buf(g_logger),
931 m_game_ui(new GameUI())
933 g_settings->registerChangedCallback("doubletap_jump",
934 &settingChangedCallback, this);
935 g_settings->registerChangedCallback("enable_clouds",
936 &settingChangedCallback, this);
937 g_settings->registerChangedCallback("doubletap_joysticks",
938 &settingChangedCallback, this);
939 g_settings->registerChangedCallback("enable_particles",
940 &settingChangedCallback, this);
941 g_settings->registerChangedCallback("enable_fog",
942 &settingChangedCallback, this);
943 g_settings->registerChangedCallback("mouse_sensitivity",
944 &settingChangedCallback, this);
945 g_settings->registerChangedCallback("joystick_frustum_sensitivity",
946 &settingChangedCallback, this);
947 g_settings->registerChangedCallback("repeat_rightclick_time",
948 &settingChangedCallback, this);
949 g_settings->registerChangedCallback("noclip",
950 &settingChangedCallback, this);
951 g_settings->registerChangedCallback("free_move",
952 &settingChangedCallback, this);
953 g_settings->registerChangedCallback("cinematic",
954 &settingChangedCallback, this);
955 g_settings->registerChangedCallback("cinematic_camera_smoothing",
956 &settingChangedCallback, this);
957 g_settings->registerChangedCallback("camera_smoothing",
958 &settingChangedCallback, this);
963 m_cache_hold_aux1 = false; // This is initialised properly later
970 /****************************************************************************
972 ****************************************************************************/
981 delete server; // deleted first to stop all server threads
989 delete nodedef_manager;
990 delete itemdef_manager;
993 extendedResourceCleanup();
995 g_settings->deregisterChangedCallback("doubletap_jump",
996 &settingChangedCallback, this);
997 g_settings->deregisterChangedCallback("enable_clouds",
998 &settingChangedCallback, this);
999 g_settings->deregisterChangedCallback("enable_particles",
1000 &settingChangedCallback, this);
1001 g_settings->deregisterChangedCallback("enable_fog",
1002 &settingChangedCallback, this);
1003 g_settings->deregisterChangedCallback("mouse_sensitivity",
1004 &settingChangedCallback, this);
1005 g_settings->deregisterChangedCallback("repeat_rightclick_time",
1006 &settingChangedCallback, this);
1007 g_settings->deregisterChangedCallback("noclip",
1008 &settingChangedCallback, this);
1009 g_settings->deregisterChangedCallback("free_move",
1010 &settingChangedCallback, this);
1011 g_settings->deregisterChangedCallback("cinematic",
1012 &settingChangedCallback, this);
1013 g_settings->deregisterChangedCallback("cinematic_camera_smoothing",
1014 &settingChangedCallback, this);
1015 g_settings->deregisterChangedCallback("camera_smoothing",
1016 &settingChangedCallback, this);
1019 bool Game::startup(bool *kill,
1021 InputHandler *input,
1022 const std::string &map_dir,
1023 const std::string &playername,
1024 const std::string &password,
1025 std::string *address, // can change if simple_singleplayer_mode
1027 std::string &error_message,
1029 ChatBackend *chat_backend,
1030 const SubgameSpec &gamespec,
1031 bool simple_singleplayer_mode)
1034 this->device = RenderingEngine::get_raw_device();
1036 this->error_message = &error_message;
1037 this->reconnect_requested = reconnect;
1038 this->random_input = random_input;
1039 this->input = input;
1040 this->chat_backend = chat_backend;
1041 this->simple_singleplayer_mode = simple_singleplayer_mode;
1043 input->keycache.populate();
1045 driver = device->getVideoDriver();
1046 smgr = RenderingEngine::get_scene_manager();
1048 RenderingEngine::get_scene_manager()->getParameters()->
1049 setAttribute(scene::OBJ_LOADER_IGNORE_MATERIAL_FILES, true);
1052 runData = GameRunData();
1053 runData.time_from_last_punch = 10.0;
1055 m_game_ui->initFlags();
1057 m_invert_mouse = g_settings->getBool("invert_mouse");
1058 m_first_loop_after_window_activation = true;
1060 g_client_translations->clear();
1062 if (!init(map_dir, address, port, gamespec))
1065 if (!createClient(playername, password, address, port))
1068 RenderingEngine::initialize(client, hud);
1076 ProfilerGraph graph;
1077 RunStats stats = { 0 };
1078 CameraOrientation cam_view_target = { 0 };
1079 CameraOrientation cam_view = { 0 };
1080 FpsControl draw_times = { 0 };
1081 f32 dtime; // in seconds
1083 /* Clear the profiler */
1084 Profiler::GraphValues dummyvalues;
1085 g_profiler->graphGet(dummyvalues);
1087 draw_times.last_time = RenderingEngine::get_timer_time();
1089 set_light_table(g_settings->getFloat("display_gamma"));
1092 m_cache_hold_aux1 = g_settings->getBool("fast_move")
1093 && client->checkPrivilege("fast");
1096 irr::core::dimension2d<u32> previous_screen_size(g_settings->getU16("screen_w"),
1097 g_settings->getU16("screen_h"));
1099 while (RenderingEngine::run()
1100 && !(*kill || g_gamecallback->shutdown_requested
1101 || (server && server->isShutdownRequested()))) {
1103 const irr::core::dimension2d<u32> ¤t_screen_size =
1104 RenderingEngine::get_video_driver()->getScreenSize();
1105 // Verify if window size has changed and save it if it's the case
1106 // Ensure evaluating settings->getBool after verifying screensize
1107 // First condition is cheaper
1108 if (previous_screen_size != current_screen_size &&
1109 current_screen_size != irr::core::dimension2d<u32>(0,0) &&
1110 g_settings->getBool("autosave_screensize")) {
1111 g_settings->setU16("screen_w", current_screen_size.Width);
1112 g_settings->setU16("screen_h", current_screen_size.Height);
1113 previous_screen_size = current_screen_size;
1116 // Calculate dtime =
1117 // RenderingEngine::run() from this iteration
1118 // + Sleep time until the wanted FPS are reached
1119 limitFps(&draw_times, &dtime);
1121 // Prepare render data for next iteration
1123 updateStats(&stats, draw_times, dtime);
1124 updateInteractTimers(dtime);
1126 if (!checkConnection())
1128 if (!handleCallbacks())
1133 m_game_ui->clearInfoText();
1134 hud->resizeHotbar();
1136 updateProfilers(stats, draw_times, dtime);
1137 processUserInput(dtime);
1138 // Update camera before player movement to avoid camera lag of one frame
1139 updateCameraDirection(&cam_view_target, dtime);
1140 cam_view.camera_yaw += (cam_view_target.camera_yaw -
1141 cam_view.camera_yaw) * m_cache_cam_smoothing;
1142 cam_view.camera_pitch += (cam_view_target.camera_pitch -
1143 cam_view.camera_pitch) * m_cache_cam_smoothing;
1144 updatePlayerControl(cam_view);
1146 processClientEvents(&cam_view_target);
1147 updateCamera(draw_times.busy_time, dtime);
1149 processPlayerInteraction(dtime, m_game_ui->m_flags.show_hud,
1150 m_game_ui->m_flags.show_debug);
1151 updateFrame(&graph, &stats, dtime, cam_view);
1152 updateProfilerGraphs(&graph);
1154 // Update if minimap has been disabled by the server
1155 m_game_ui->m_flags.show_minimap &= client->shouldShowMinimap();
1157 if (m_does_lost_focus_pause_game && !device->isWindowFocused() && !isMenuActive()) {
1164 void Game::shutdown()
1166 RenderingEngine::finalize();
1167 #if IRRLICHT_VERSION_MAJOR == 1 && IRRLICHT_VERSION_MINOR <= 8
1168 if (g_settings->get("3d_mode") == "pageflip") {
1169 driver->setRenderTarget(irr::video::ERT_STEREO_BOTH_BUFFERS);
1172 auto formspec = m_game_ui->getFormspecGUI();
1174 formspec->quitMenu();
1176 #ifdef HAVE_TOUCHSCREENGUI
1177 g_touchscreengui->hide();
1180 showOverlayMessage(N_("Shutting down..."), 0, 0, false);
1185 if (gui_chat_console)
1186 gui_chat_console->drop();
1192 while (g_menumgr.menuCount() > 0) {
1193 g_menumgr.m_stack.front()->setVisible(false);
1194 g_menumgr.deletingMenu(g_menumgr.m_stack.front());
1197 m_game_ui->deleteFormspec();
1199 chat_backend->addMessage(L"", L"# Disconnected.");
1200 chat_backend->addMessage(L"", L"");
1201 m_chat_log_buf.clear();
1205 while (!client->isShutdown()) {
1206 assert(texture_src != NULL);
1207 assert(shader_src != NULL);
1208 texture_src->processQueue();
1209 shader_src->processQueue();
1216 /****************************************************************************/
1217 /****************************************************************************
1219 ****************************************************************************/
1220 /****************************************************************************/
1223 const std::string &map_dir,
1224 std::string *address,
1226 const SubgameSpec &gamespec)
1228 texture_src = createTextureSource();
1230 showOverlayMessage(N_("Loading..."), 0, 0);
1232 shader_src = createShaderSource();
1234 itemdef_manager = createItemDefManager();
1235 nodedef_manager = createNodeDefManager();
1237 eventmgr = new EventManager();
1238 quicktune = new QuicktuneShortcutter();
1240 if (!(texture_src && shader_src && itemdef_manager && nodedef_manager
1241 && eventmgr && quicktune))
1247 // Create a server if not connecting to an existing one
1248 if (address->empty()) {
1249 if (!createSingleplayerServer(map_dir, gamespec, port, address))
1256 bool Game::initSound()
1259 if (g_settings->getBool("enable_sound") && g_sound_manager_singleton.get()) {
1260 infostream << "Attempting to use OpenAL audio" << std::endl;
1261 sound = createOpenALSoundManager(g_sound_manager_singleton.get(), &soundfetcher);
1263 infostream << "Failed to initialize OpenAL audio" << std::endl;
1265 infostream << "Sound disabled." << std::endl;
1269 infostream << "Using dummy audio." << std::endl;
1270 sound = &dummySoundManager;
1271 sound_is_dummy = true;
1274 soundmaker = new SoundMaker(sound, nodedef_manager);
1278 soundmaker->registerReceiver(eventmgr);
1283 bool Game::createSingleplayerServer(const std::string &map_dir,
1284 const SubgameSpec &gamespec, u16 port, std::string *address)
1286 showOverlayMessage(N_("Creating server..."), 0, 5);
1288 std::string bind_str = g_settings->get("bind_address");
1289 Address bind_addr(0, 0, 0, 0, port);
1291 if (g_settings->getBool("ipv6_server")) {
1292 bind_addr.setAddress((IPv6AddressBytes *) NULL);
1296 bind_addr.Resolve(bind_str.c_str());
1297 } catch (ResolveError &e) {
1298 infostream << "Resolving bind address \"" << bind_str
1299 << "\" failed: " << e.what()
1300 << " -- Listening on all addresses." << std::endl;
1303 if (bind_addr.isIPv6() && !g_settings->getBool("enable_ipv6")) {
1304 *error_message = "Unable to listen on " +
1305 bind_addr.serializeString() +
1306 " because IPv6 is disabled";
1307 errorstream << *error_message << std::endl;
1311 server = new Server(map_dir, gamespec, simple_singleplayer_mode, bind_addr, false);
1317 bool Game::createClient(const std::string &playername,
1318 const std::string &password, std::string *address, u16 port)
1320 showOverlayMessage(N_("Creating client..."), 0, 10);
1322 draw_control = new MapDrawControl;
1326 bool could_connect, connect_aborted;
1327 #ifdef HAVE_TOUCHSCREENGUI
1328 if (g_touchscreengui) {
1329 g_touchscreengui->init(texture_src);
1330 g_touchscreengui->hide();
1333 if (!connectToServer(playername, password, address, port,
1334 &could_connect, &connect_aborted))
1337 if (!could_connect) {
1338 if (error_message->empty() && !connect_aborted) {
1339 // Should not happen if error messages are set properly
1340 *error_message = "Connection failed for unknown reason";
1341 errorstream << *error_message << std::endl;
1346 if (!getServerContent(&connect_aborted)) {
1347 if (error_message->empty() && !connect_aborted) {
1348 // Should not happen if error messages are set properly
1349 *error_message = "Connection failed for unknown reason";
1350 errorstream << *error_message << std::endl;
1355 GameGlobalShaderConstantSetterFactory *scsf = new GameGlobalShaderConstantSetterFactory(
1356 &m_flags.force_fog_off, &runData.fog_range, client);
1357 shader_src->addShaderConstantSetterFactory(scsf);
1359 // Update cached textures, meshes and materials
1360 client->afterContentReceived();
1364 camera = new Camera(*draw_control, client);
1365 if (!camera || !camera->successfullyCreated(*error_message))
1367 client->setCamera(camera);
1371 if (m_cache_enable_clouds) {
1372 clouds = new Clouds(smgr, -1, time(0));
1374 *error_message = "Memory allocation error (clouds)";
1375 errorstream << *error_message << std::endl;
1382 sky = new Sky(-1, texture_src);
1384 skybox = NULL; // This is used/set later on in the main run loop
1387 *error_message = "Memory allocation error sky";
1388 errorstream << *error_message << std::endl;
1392 /* Pre-calculated values
1394 video::ITexture *t = texture_src->getTexture("crack_anylength.png");
1396 v2u32 size = t->getOriginalSize();
1397 crack_animation_length = size.Y / size.X;
1399 crack_animation_length = 5;
1405 /* Set window caption
1407 std::wstring str = utf8_to_wide(PROJECT_NAME_C);
1409 str += utf8_to_wide(g_version_hash);
1411 str += driver->getName();
1413 device->setWindowCaption(str.c_str());
1415 LocalPlayer *player = client->getEnv().getLocalPlayer();
1416 player->hurt_tilt_timer = 0;
1417 player->hurt_tilt_strength = 0;
1419 hud = new Hud(guienv, client, player, &player->inventory);
1422 *error_message = "Memory error: could not create HUD";
1423 errorstream << *error_message << std::endl;
1427 mapper = client->getMinimap();
1429 mapper->setMinimapMode(MINIMAP_MODE_OFF);
1430 if (client->modsLoaded())
1431 client->getScript()->on_minimap_ready(mapper);
1437 bool Game::initGui()
1441 // Remove stale "recent" chat messages from previous connections
1442 chat_backend->clearRecentChat();
1444 // Make sure the size of the recent messages buffer is right
1445 chat_backend->applySettings();
1447 // Chat backend and console
1448 gui_chat_console = new GUIChatConsole(guienv, guienv->getRootGUIElement(),
1449 -1, chat_backend, client, &g_menumgr);
1450 if (!gui_chat_console) {
1451 *error_message = "Could not allocate memory for chat console";
1452 errorstream << *error_message << std::endl;
1456 #ifdef HAVE_TOUCHSCREENGUI
1458 if (g_touchscreengui)
1459 g_touchscreengui->show();
1466 bool Game::connectToServer(const std::string &playername,
1467 const std::string &password, std::string *address, u16 port,
1468 bool *connect_ok, bool *connection_aborted)
1470 *connect_ok = false; // Let's not be overly optimistic
1471 *connection_aborted = false;
1472 bool local_server_mode = false;
1474 showOverlayMessage(N_("Resolving address..."), 0, 15);
1476 Address connect_address(0, 0, 0, 0, port);
1479 connect_address.Resolve(address->c_str());
1481 if (connect_address.isZero()) { // i.e. INADDR_ANY, IN6ADDR_ANY
1482 //connect_address.Resolve("localhost");
1483 if (connect_address.isIPv6()) {
1484 IPv6AddressBytes addr_bytes;
1485 addr_bytes.bytes[15] = 1;
1486 connect_address.setAddress(&addr_bytes);
1488 connect_address.setAddress(127, 0, 0, 1);
1490 local_server_mode = true;
1492 } catch (ResolveError &e) {
1493 *error_message = std::string("Couldn't resolve address: ") + e.what();
1494 errorstream << *error_message << std::endl;
1498 if (connect_address.isIPv6() && !g_settings->getBool("enable_ipv6")) {
1499 *error_message = "Unable to connect to " +
1500 connect_address.serializeString() +
1501 " because IPv6 is disabled";
1502 errorstream << *error_message << std::endl;
1506 client = new Client(playername.c_str(), password, *address,
1507 *draw_control, texture_src, shader_src,
1508 itemdef_manager, nodedef_manager, sound, eventmgr,
1509 connect_address.isIPv6(), m_game_ui.get());
1514 client->m_simple_singleplayer_mode = simple_singleplayer_mode;
1516 infostream << "Connecting to server at ";
1517 connect_address.print(&infostream);
1518 infostream << std::endl;
1520 client->connect(connect_address,
1521 simple_singleplayer_mode || local_server_mode);
1524 Wait for server to accept connection
1530 FpsControl fps_control = { 0 };
1532 f32 wait_time = 0; // in seconds
1534 fps_control.last_time = RenderingEngine::get_timer_time();
1536 while (RenderingEngine::run()) {
1538 limitFps(&fps_control, &dtime);
1540 // Update client and server
1541 client->step(dtime);
1544 server->step(dtime);
1547 if (client->getState() == LC_Init) {
1553 if (*connection_aborted)
1556 if (client->accessDenied()) {
1557 *error_message = "Access denied. Reason: "
1558 + client->accessDeniedReason();
1559 *reconnect_requested = client->reconnectRequested();
1560 errorstream << *error_message << std::endl;
1564 if (input->cancelPressed()) {
1565 *connection_aborted = true;
1566 infostream << "Connect aborted [Escape]" << std::endl;
1570 if (client->m_is_registration_confirmation_state) {
1571 if (registration_confirmation_shown) {
1572 // Keep drawing the GUI
1573 RenderingEngine::draw_menu_scene(guienv, dtime, true);
1575 registration_confirmation_shown = true;
1576 (new GUIConfirmRegistration(guienv, guienv->getRootGUIElement(), -1,
1577 &g_menumgr, client, playername, password,
1578 connection_aborted, texture_src))->drop();
1582 // Only time out if we aren't waiting for the server we started
1583 if (!address->empty() && wait_time > 10) {
1584 *error_message = "Connection timed out.";
1585 errorstream << *error_message << std::endl;
1590 showOverlayMessage(N_("Connecting to server..."), dtime, 20);
1593 } catch (con::PeerNotFoundException &e) {
1594 // TODO: Should something be done here? At least an info/error
1602 bool Game::getServerContent(bool *aborted)
1606 FpsControl fps_control = { 0 };
1607 f32 dtime; // in seconds
1609 fps_control.last_time = RenderingEngine::get_timer_time();
1611 while (RenderingEngine::run()) {
1613 limitFps(&fps_control, &dtime);
1615 // Update client and server
1616 client->step(dtime);
1619 server->step(dtime);
1622 if (client->mediaReceived() && client->itemdefReceived() &&
1623 client->nodedefReceived()) {
1628 if (!checkConnection())
1631 if (client->getState() < LC_Init) {
1632 *error_message = "Client disconnected";
1633 errorstream << *error_message << std::endl;
1637 if (input->cancelPressed()) {
1639 infostream << "Connect aborted [Escape]" << std::endl;
1646 if (!client->itemdefReceived()) {
1647 const wchar_t *text = wgettext("Item definitions...");
1649 RenderingEngine::draw_load_screen(text, guienv, texture_src,
1652 } else if (!client->nodedefReceived()) {
1653 const wchar_t *text = wgettext("Node definitions...");
1655 RenderingEngine::draw_load_screen(text, guienv, texture_src,
1659 std::stringstream message;
1660 std::fixed(message);
1661 message.precision(0);
1662 message << gettext("Media...") << " " << (client->mediaReceiveProgress()*100) << "%";
1663 message.precision(2);
1665 if ((USE_CURL == 0) ||
1666 (!g_settings->getBool("enable_remote_media_server"))) {
1667 float cur = client->getCurRate();
1668 std::string cur_unit = gettext("KiB/s");
1672 cur_unit = gettext("MiB/s");
1675 message << " (" << cur << ' ' << cur_unit << ")";
1678 progress = 30 + client->mediaReceiveProgress() * 35 + 0.5;
1679 RenderingEngine::draw_load_screen(utf8_to_wide(message.str()), guienv,
1680 texture_src, dtime, progress);
1688 /****************************************************************************/
1689 /****************************************************************************
1691 ****************************************************************************/
1692 /****************************************************************************/
1694 inline void Game::updateInteractTimers(f32 dtime)
1696 if (runData.nodig_delay_timer >= 0)
1697 runData.nodig_delay_timer -= dtime;
1699 if (runData.object_hit_delay_timer >= 0)
1700 runData.object_hit_delay_timer -= dtime;
1702 runData.time_from_last_punch += dtime;
1706 /* returns false if game should exit, otherwise true
1708 inline bool Game::checkConnection()
1710 if (client->accessDenied()) {
1711 *error_message = "Access denied. Reason: "
1712 + client->accessDeniedReason();
1713 *reconnect_requested = client->reconnectRequested();
1714 errorstream << *error_message << std::endl;
1722 /* returns false if game should exit, otherwise true
1724 inline bool Game::handleCallbacks()
1726 if (g_gamecallback->disconnect_requested) {
1727 g_gamecallback->disconnect_requested = false;
1731 if (g_gamecallback->changepassword_requested) {
1732 (new GUIPasswordChange(guienv, guiroot, -1,
1733 &g_menumgr, client, texture_src))->drop();
1734 g_gamecallback->changepassword_requested = false;
1737 if (g_gamecallback->changevolume_requested) {
1738 (new GUIVolumeChange(guienv, guiroot, -1,
1739 &g_menumgr, texture_src))->drop();
1740 g_gamecallback->changevolume_requested = false;
1743 if (g_gamecallback->keyconfig_requested) {
1744 (new GUIKeyChangeMenu(guienv, guiroot, -1,
1745 &g_menumgr, texture_src))->drop();
1746 g_gamecallback->keyconfig_requested = false;
1749 if (g_gamecallback->keyconfig_changed) {
1750 input->keycache.populate(); // update the cache with new settings
1751 g_gamecallback->keyconfig_changed = false;
1758 void Game::processQueues()
1760 texture_src->processQueue();
1761 itemdef_manager->processQueue(client);
1762 shader_src->processQueue();
1766 void Game::updateProfilers(const RunStats &stats, const FpsControl &draw_times,
1769 float profiler_print_interval =
1770 g_settings->getFloat("profiler_print_interval");
1771 bool print_to_log = true;
1773 if (profiler_print_interval == 0) {
1774 print_to_log = false;
1775 profiler_print_interval = 3;
1778 if (profiler_interval.step(dtime, profiler_print_interval)) {
1780 infostream << "Profiler:" << std::endl;
1781 g_profiler->print(infostream);
1784 m_game_ui->updateProfiler();
1785 g_profiler->clear();
1788 // Update update graphs
1789 g_profiler->graphAdd("Time non-rendering [ms]",
1790 draw_times.busy_time - stats.drawtime);
1792 g_profiler->graphAdd("Sleep [ms]", draw_times.sleep_time);
1793 g_profiler->graphAdd("FPS", 1.0f / dtime);
1796 void Game::updateStats(RunStats *stats, const FpsControl &draw_times,
1803 /* Time average and jitter calculation
1805 jp = &stats->dtime_jitter;
1806 jp->avg = jp->avg * 0.96 + dtime * 0.04;
1808 jitter = dtime - jp->avg;
1810 if (jitter > jp->max)
1813 jp->counter += dtime;
1815 if (jp->counter > 0.0) {
1817 jp->max_sample = jp->max;
1818 jp->max_fraction = jp->max_sample / (jp->avg + 0.001);
1822 /* Busytime average and jitter calculation
1824 jp = &stats->busy_time_jitter;
1825 jp->avg = jp->avg + draw_times.busy_time * 0.02;
1827 jitter = draw_times.busy_time - jp->avg;
1829 if (jitter > jp->max)
1831 if (jitter < jp->min)
1834 jp->counter += dtime;
1836 if (jp->counter > 0.0) {
1838 jp->max_sample = jp->max;
1839 jp->min_sample = jp->min;
1847 /****************************************************************************
1849 ****************************************************************************/
1851 void Game::processUserInput(f32 dtime)
1853 // Reset input if window not active or some menu is active
1854 if (!device->isWindowActive() || isMenuActive() || guienv->hasFocus(gui_chat_console)) {
1856 #ifdef HAVE_TOUCHSCREENGUI
1857 g_touchscreengui->hide();
1860 #ifdef HAVE_TOUCHSCREENGUI
1861 else if (g_touchscreengui) {
1862 /* on touchscreengui step may generate own input events which ain't
1863 * what we want in case we just did clear them */
1864 g_touchscreengui->step(dtime);
1868 if (!guienv->hasFocus(gui_chat_console) && gui_chat_console->isOpen()) {
1869 gui_chat_console->closeConsoleAtOnce();
1872 // Input handler step() (used by the random input generator)
1876 auto formspec = m_game_ui->getFormspecGUI();
1878 formspec->getAndroidUIInput();
1880 handleAndroidChatInput();
1883 // Increase timer for double tap of "keymap_jump"
1884 if (m_cache_doubletap_jump && runData.jump_timer <= 0.2f)
1885 runData.jump_timer += dtime;
1888 processItemSelection(&runData.new_playeritem);
1892 void Game::processKeyInput()
1894 if (wasKeyDown(KeyType::DROP)) {
1895 dropSelectedItem(isKeyDown(KeyType::SNEAK));
1896 } else if (wasKeyDown(KeyType::AUTOFORWARD)) {
1897 toggleAutoforward();
1898 } else if (wasKeyDown(KeyType::BACKWARD)) {
1899 if (g_settings->getBool("continuous_forward"))
1900 toggleAutoforward();
1901 } else if (wasKeyDown(KeyType::INVENTORY)) {
1903 } else if (input->cancelPressed()) {
1905 m_android_chat_open = false;
1907 if (!gui_chat_console->isOpenInhibited()) {
1910 } else if (wasKeyDown(KeyType::CHAT)) {
1911 openConsole(0.2, L"");
1912 } else if (wasKeyDown(KeyType::CMD)) {
1913 openConsole(0.2, L"/");
1914 } else if (wasKeyDown(KeyType::CMD_LOCAL)) {
1915 if (client->modsLoaded())
1916 openConsole(0.2, L".");
1918 m_game_ui->showStatusText(wgettext("Client side scripting is disabled"));
1919 } else if (wasKeyDown(KeyType::CONSOLE)) {
1920 openConsole(core::clamp(g_settings->getFloat("console_height"), 0.1f, 1.0f));
1921 } else if (wasKeyDown(KeyType::FREEMOVE)) {
1923 } else if (wasKeyDown(KeyType::JUMP)) {
1924 toggleFreeMoveAlt();
1925 } else if (wasKeyDown(KeyType::PITCHMOVE)) {
1927 } else if (wasKeyDown(KeyType::FASTMOVE)) {
1929 } else if (wasKeyDown(KeyType::NOCLIP)) {
1932 } else if (wasKeyDown(KeyType::MUTE)) {
1933 if (g_settings->getBool("enable_sound")) {
1934 bool new_mute_sound = !g_settings->getBool("mute_sound");
1935 g_settings->setBool("mute_sound", new_mute_sound);
1937 m_game_ui->showTranslatedStatusText("Sound muted");
1939 m_game_ui->showTranslatedStatusText("Sound unmuted");
1941 m_game_ui->showTranslatedStatusText("Sound system is disabled");
1943 } else if (wasKeyDown(KeyType::INC_VOLUME)) {
1944 if (g_settings->getBool("enable_sound")) {
1945 float new_volume = rangelim(g_settings->getFloat("sound_volume") + 0.1f, 0.0f, 1.0f);
1947 g_settings->setFloat("sound_volume", new_volume);
1948 const wchar_t *str = wgettext("Volume changed to %d%%");
1949 swprintf(buf, sizeof(buf) / sizeof(wchar_t), str, myround(new_volume * 100));
1951 m_game_ui->showStatusText(buf);
1953 m_game_ui->showTranslatedStatusText("Sound system is disabled");
1955 } else if (wasKeyDown(KeyType::DEC_VOLUME)) {
1956 if (g_settings->getBool("enable_sound")) {
1957 float new_volume = rangelim(g_settings->getFloat("sound_volume") - 0.1f, 0.0f, 1.0f);
1959 g_settings->setFloat("sound_volume", new_volume);
1960 const wchar_t *str = wgettext("Volume changed to %d%%");
1961 swprintf(buf, sizeof(buf) / sizeof(wchar_t), str, myround(new_volume * 100));
1963 m_game_ui->showStatusText(buf);
1965 m_game_ui->showTranslatedStatusText("Sound system is disabled");
1968 } else if (wasKeyDown(KeyType::MUTE) || wasKeyDown(KeyType::INC_VOLUME)
1969 || wasKeyDown(KeyType::DEC_VOLUME)) {
1970 m_game_ui->showTranslatedStatusText("Sound system is not supported on this build");
1972 } else if (wasKeyDown(KeyType::CINEMATIC)) {
1974 } else if (wasKeyDown(KeyType::SCREENSHOT)) {
1975 client->makeScreenshot();
1976 } else if (wasKeyDown(KeyType::TOGGLE_HUD)) {
1977 m_game_ui->toggleHud();
1978 } else if (wasKeyDown(KeyType::MINIMAP)) {
1979 toggleMinimap(isKeyDown(KeyType::SNEAK));
1980 } else if (wasKeyDown(KeyType::TOGGLE_CHAT)) {
1981 m_game_ui->toggleChat();
1982 } else if (wasKeyDown(KeyType::TOGGLE_FOG)) {
1984 } else if (wasKeyDown(KeyType::TOGGLE_UPDATE_CAMERA)) {
1985 toggleUpdateCamera();
1986 } else if (wasKeyDown(KeyType::TOGGLE_DEBUG)) {
1988 } else if (wasKeyDown(KeyType::TOGGLE_PROFILER)) {
1989 m_game_ui->toggleProfiler();
1990 } else if (wasKeyDown(KeyType::INCREASE_VIEWING_RANGE)) {
1991 increaseViewRange();
1992 } else if (wasKeyDown(KeyType::DECREASE_VIEWING_RANGE)) {
1993 decreaseViewRange();
1994 } else if (wasKeyDown(KeyType::RANGESELECT)) {
1995 toggleFullViewRange();
1996 } else if (wasKeyDown(KeyType::ZOOM)) {
1998 } else if (wasKeyDown(KeyType::QUICKTUNE_NEXT)) {
2000 } else if (wasKeyDown(KeyType::QUICKTUNE_PREV)) {
2002 } else if (wasKeyDown(KeyType::QUICKTUNE_INC)) {
2004 } else if (wasKeyDown(KeyType::QUICKTUNE_DEC)) {
2008 if (!isKeyDown(KeyType::JUMP) && runData.reset_jump_timer) {
2009 runData.reset_jump_timer = false;
2010 runData.jump_timer = 0.0f;
2013 if (quicktune->hasMessage()) {
2014 m_game_ui->showStatusText(utf8_to_wide(quicktune->getMessage()));
2018 void Game::processItemSelection(u16 *new_playeritem)
2020 LocalPlayer *player = client->getEnv().getLocalPlayer();
2022 /* Item selection using mouse wheel
2024 *new_playeritem = player->getWieldIndex();
2026 s32 wheel = input->getMouseWheel();
2027 u16 max_item = MYMIN(PLAYER_INVENTORY_SIZE - 1,
2028 player->hud_hotbar_itemcount - 1);
2032 if (input->joystick.wasKeyDown(KeyType::SCROLL_DOWN) ||
2033 wasKeyDown(KeyType::HOTBAR_NEXT)) {
2037 if (input->joystick.wasKeyDown(KeyType::SCROLL_UP) ||
2038 wasKeyDown(KeyType::HOTBAR_PREV)) {
2043 *new_playeritem = *new_playeritem < max_item ? *new_playeritem + 1 : 0;
2045 *new_playeritem = *new_playeritem > 0 ? *new_playeritem - 1 : max_item;
2048 /* Item selection using hotbar slot keys
2050 for (u16 i = 0; i <= max_item; i++) {
2051 if (wasKeyDown((GameKeyType) (KeyType::SLOT_1 + i))) {
2052 *new_playeritem = i;
2059 void Game::dropSelectedItem(bool single_item)
2061 IDropAction *a = new IDropAction();
2062 a->count = single_item ? 1 : 0;
2063 a->from_inv.setCurrentPlayer();
2064 a->from_list = "main";
2065 a->from_i = client->getEnv().getLocalPlayer()->getWieldIndex();
2066 client->inventoryAction(a);
2070 void Game::openInventory()
2073 * Don't permit to open inventory is CAO or player doesn't exists.
2074 * This prevent showing an empty inventory at player load
2077 LocalPlayer *player = client->getEnv().getLocalPlayer();
2078 if (!player || !player->getCAO())
2081 infostream << "Game: Launching inventory" << std::endl;
2083 PlayerInventoryFormSource *fs_src = new PlayerInventoryFormSource(client);
2085 InventoryLocation inventoryloc;
2086 inventoryloc.setCurrentPlayer();
2088 if (!client->modsLoaded()
2089 || !client->getScript()->on_inventory_open(fs_src->m_client->getInventory(inventoryloc))) {
2090 TextDest *txt_dst = new TextDestPlayerInventory(client);
2091 auto *&formspec = m_game_ui->updateFormspec("");
2092 GUIFormSpecMenu::create(formspec, client, &input->joystick, fs_src,
2093 txt_dst, client->getFormspecPrepend());
2095 formspec->setFormSpec(fs_src->getForm(), inventoryloc);
2100 void Game::openConsole(float scale, const wchar_t *line)
2102 assert(scale > 0.0f && scale <= 1.0f);
2105 porting::showInputDialog(gettext("ok"), "", "", 2);
2106 m_android_chat_open = true;
2108 if (gui_chat_console->isOpenInhibited())
2110 gui_chat_console->openConsole(scale);
2112 gui_chat_console->setCloseOnEnter(true);
2113 gui_chat_console->replaceAndAddToHistory(line);
2119 void Game::handleAndroidChatInput()
2121 if (m_android_chat_open && porting::getInputDialogState() == 0) {
2122 std::string text = porting::getInputDialogValue();
2123 client->typeChatMessage(utf8_to_wide(text));
2124 m_android_chat_open = false;
2130 void Game::toggleFreeMove()
2132 bool free_move = !g_settings->getBool("free_move");
2133 g_settings->set("free_move", bool_to_cstr(free_move));
2136 if (client->checkPrivilege("fly")) {
2137 m_game_ui->showTranslatedStatusText("Fly mode enabled");
2139 m_game_ui->showTranslatedStatusText("Fly mode enabled (note: no 'fly' privilege)");
2142 m_game_ui->showTranslatedStatusText("Fly mode disabled");
2146 void Game::toggleFreeMoveAlt()
2148 if (m_cache_doubletap_jump && runData.jump_timer < 0.2f)
2151 runData.reset_jump_timer = true;
2155 void Game::togglePitchMove()
2157 bool pitch_move = !g_settings->getBool("pitch_move");
2158 g_settings->set("pitch_move", bool_to_cstr(pitch_move));
2161 m_game_ui->showTranslatedStatusText("Pitch move mode enabled");
2163 m_game_ui->showTranslatedStatusText("Pitch move mode disabled");
2168 void Game::toggleFast()
2170 bool fast_move = !g_settings->getBool("fast_move");
2171 bool has_fast_privs = client->checkPrivilege("fast");
2172 g_settings->set("fast_move", bool_to_cstr(fast_move));
2175 if (has_fast_privs) {
2176 m_game_ui->showTranslatedStatusText("Fast mode enabled");
2178 m_game_ui->showTranslatedStatusText("Fast mode enabled (note: no 'fast' privilege)");
2181 m_game_ui->showTranslatedStatusText("Fast mode disabled");
2185 m_cache_hold_aux1 = fast_move && has_fast_privs;
2190 void Game::toggleNoClip()
2192 bool noclip = !g_settings->getBool("noclip");
2193 g_settings->set("noclip", bool_to_cstr(noclip));
2196 if (client->checkPrivilege("noclip")) {
2197 m_game_ui->showTranslatedStatusText("Noclip mode enabled");
2199 m_game_ui->showTranslatedStatusText("Noclip mode enabled (note: no 'noclip' privilege)");
2202 m_game_ui->showTranslatedStatusText("Noclip mode disabled");
2206 void Game::toggleCinematic()
2208 bool cinematic = !g_settings->getBool("cinematic");
2209 g_settings->set("cinematic", bool_to_cstr(cinematic));
2212 m_game_ui->showTranslatedStatusText("Cinematic mode enabled");
2214 m_game_ui->showTranslatedStatusText("Cinematic mode disabled");
2217 // Autoforward by toggling continuous forward.
2218 void Game::toggleAutoforward()
2220 bool autorun_enabled = !g_settings->getBool("continuous_forward");
2221 g_settings->set("continuous_forward", bool_to_cstr(autorun_enabled));
2223 if (autorun_enabled)
2224 m_game_ui->showTranslatedStatusText("Automatic forward enabled");
2226 m_game_ui->showTranslatedStatusText("Automatic forward disabled");
2229 void Game::toggleMinimap(bool shift_pressed)
2231 if (!mapper || !m_game_ui->m_flags.show_hud || !g_settings->getBool("enable_minimap"))
2234 if (shift_pressed) {
2235 mapper->toggleMinimapShape();
2239 u32 hud_flags = client->getEnv().getLocalPlayer()->hud_flags;
2241 MinimapMode mode = MINIMAP_MODE_OFF;
2242 if (hud_flags & HUD_FLAG_MINIMAP_VISIBLE) {
2243 mode = mapper->getMinimapMode();
2244 mode = (MinimapMode)((int)mode + 1);
2245 // If radar is disabled and in, or switching to, radar mode
2246 if (!(hud_flags & HUD_FLAG_MINIMAP_RADAR_VISIBLE) && mode > 3)
2247 mode = MINIMAP_MODE_OFF;
2250 m_game_ui->m_flags.show_minimap = true;
2252 case MINIMAP_MODE_SURFACEx1:
2253 m_game_ui->showTranslatedStatusText("Minimap in surface mode, Zoom x1");
2255 case MINIMAP_MODE_SURFACEx2:
2256 m_game_ui->showTranslatedStatusText("Minimap in surface mode, Zoom x2");
2258 case MINIMAP_MODE_SURFACEx4:
2259 m_game_ui->showTranslatedStatusText("Minimap in surface mode, Zoom x4");
2261 case MINIMAP_MODE_RADARx1:
2262 m_game_ui->showTranslatedStatusText("Minimap in radar mode, Zoom x1");
2264 case MINIMAP_MODE_RADARx2:
2265 m_game_ui->showTranslatedStatusText("Minimap in radar mode, Zoom x2");
2267 case MINIMAP_MODE_RADARx4:
2268 m_game_ui->showTranslatedStatusText("Minimap in radar mode, Zoom x4");
2271 mode = MINIMAP_MODE_OFF;
2272 m_game_ui->m_flags.show_minimap = false;
2273 if (hud_flags & HUD_FLAG_MINIMAP_VISIBLE)
2274 m_game_ui->showTranslatedStatusText("Minimap hidden");
2276 m_game_ui->showTranslatedStatusText("Minimap currently disabled by game or mod");
2279 mapper->setMinimapMode(mode);
2282 void Game::toggleFog()
2284 bool fog_enabled = g_settings->getBool("enable_fog");
2285 g_settings->setBool("enable_fog", !fog_enabled);
2287 m_game_ui->showTranslatedStatusText("Fog disabled");
2289 m_game_ui->showTranslatedStatusText("Fog enabled");
2293 void Game::toggleDebug()
2295 // Initial / 4x toggle: Chat only
2296 // 1x toggle: Debug text with chat
2297 // 2x toggle: Debug text with profiler graph
2298 // 3x toggle: Debug text and wireframe
2299 if (!m_game_ui->m_flags.show_debug) {
2300 m_game_ui->m_flags.show_debug = true;
2301 m_game_ui->m_flags.show_profiler_graph = false;
2302 draw_control->show_wireframe = false;
2303 m_game_ui->showTranslatedStatusText("Debug info shown");
2304 } else if (!m_game_ui->m_flags.show_profiler_graph && !draw_control->show_wireframe) {
2305 m_game_ui->m_flags.show_profiler_graph = true;
2306 m_game_ui->showTranslatedStatusText("Profiler graph shown");
2307 } else if (!draw_control->show_wireframe && client->checkPrivilege("debug")) {
2308 m_game_ui->m_flags.show_profiler_graph = false;
2309 draw_control->show_wireframe = true;
2310 m_game_ui->showTranslatedStatusText("Wireframe shown");
2312 m_game_ui->m_flags.show_debug = false;
2313 m_game_ui->m_flags.show_profiler_graph = false;
2314 draw_control->show_wireframe = false;
2315 if (client->checkPrivilege("debug")) {
2316 m_game_ui->showTranslatedStatusText("Debug info, profiler graph, and wireframe hidden");
2318 m_game_ui->showTranslatedStatusText("Debug info and profiler graph hidden");
2324 void Game::toggleUpdateCamera()
2326 m_flags.disable_camera_update = !m_flags.disable_camera_update;
2327 if (m_flags.disable_camera_update)
2328 m_game_ui->showTranslatedStatusText("Camera update disabled");
2330 m_game_ui->showTranslatedStatusText("Camera update enabled");
2334 void Game::increaseViewRange()
2336 s16 range = g_settings->getS16("viewing_range");
2337 s16 range_new = range + 10;
2341 if (range_new > 4000) {
2343 str = wgettext("Viewing range is at maximum: %d");
2344 swprintf(buf, sizeof(buf) / sizeof(wchar_t), str, range_new);
2346 m_game_ui->showStatusText(buf);
2349 str = wgettext("Viewing range changed to %d");
2350 swprintf(buf, sizeof(buf) / sizeof(wchar_t), str, range_new);
2352 m_game_ui->showStatusText(buf);
2354 g_settings->set("viewing_range", itos(range_new));
2358 void Game::decreaseViewRange()
2360 s16 range = g_settings->getS16("viewing_range");
2361 s16 range_new = range - 10;
2365 if (range_new < 20) {
2367 str = wgettext("Viewing range is at minimum: %d");
2368 swprintf(buf, sizeof(buf) / sizeof(wchar_t), str, range_new);
2370 m_game_ui->showStatusText(buf);
2372 str = wgettext("Viewing range changed to %d");
2373 swprintf(buf, sizeof(buf) / sizeof(wchar_t), str, range_new);
2375 m_game_ui->showStatusText(buf);
2377 g_settings->set("viewing_range", itos(range_new));
2381 void Game::toggleFullViewRange()
2383 draw_control->range_all = !draw_control->range_all;
2384 if (draw_control->range_all)
2385 m_game_ui->showTranslatedStatusText("Enabled unlimited viewing range");
2387 m_game_ui->showTranslatedStatusText("Disabled unlimited viewing range");
2391 void Game::checkZoomEnabled()
2393 LocalPlayer *player = client->getEnv().getLocalPlayer();
2394 if (player->getZoomFOV() < 0.001f || player->getFov().fov > 0.0f)
2395 m_game_ui->showTranslatedStatusText("Zoom currently disabled by game or mod");
2399 void Game::updateCameraDirection(CameraOrientation *cam, float dtime)
2401 if ((device->isWindowActive() && device->isWindowFocused()
2402 && !isMenuActive()) || random_input) {
2405 if (!random_input) {
2406 // Mac OSX gets upset if this is set every frame
2407 if (device->getCursorControl()->isVisible())
2408 device->getCursorControl()->setVisible(false);
2412 if (m_first_loop_after_window_activation) {
2413 m_first_loop_after_window_activation = false;
2415 input->setMousePos(driver->getScreenSize().Width / 2,
2416 driver->getScreenSize().Height / 2);
2418 updateCameraOrientation(cam, dtime);
2424 // Mac OSX gets upset if this is set every frame
2425 if (!device->getCursorControl()->isVisible())
2426 device->getCursorControl()->setVisible(true);
2429 m_first_loop_after_window_activation = true;
2434 void Game::updateCameraOrientation(CameraOrientation *cam, float dtime)
2436 #ifdef HAVE_TOUCHSCREENGUI
2437 if (g_touchscreengui) {
2438 cam->camera_yaw += g_touchscreengui->getYawChange();
2439 cam->camera_pitch = g_touchscreengui->getPitch();
2442 v2s32 center(driver->getScreenSize().Width / 2, driver->getScreenSize().Height / 2);
2443 v2s32 dist = input->getMousePos() - center;
2445 if (m_invert_mouse || camera->getCameraMode() == CAMERA_MODE_THIRD_FRONT) {
2449 cam->camera_yaw -= dist.X * m_cache_mouse_sensitivity;
2450 cam->camera_pitch += dist.Y * m_cache_mouse_sensitivity;
2452 if (dist.X != 0 || dist.Y != 0)
2453 input->setMousePos(center.X, center.Y);
2454 #ifdef HAVE_TOUCHSCREENGUI
2458 if (m_cache_enable_joysticks) {
2459 f32 c = m_cache_joystick_frustum_sensitivity * (1.f / 32767.f) * dtime;
2460 cam->camera_yaw -= input->joystick.getAxisWithoutDead(JA_FRUSTUM_HORIZONTAL) * c;
2461 cam->camera_pitch += input->joystick.getAxisWithoutDead(JA_FRUSTUM_VERTICAL) * c;
2464 cam->camera_pitch = rangelim(cam->camera_pitch, -89.5, 89.5);
2468 void Game::updatePlayerControl(const CameraOrientation &cam)
2470 //TimeTaker tt("update player control", NULL, PRECISION_NANO);
2472 // DO NOT use the isKeyDown method for the forward, backward, left, right
2473 // buttons, as the code that uses the controls needs to be able to
2474 // distinguish between the two in order to know when to use joysticks.
2476 PlayerControl control(
2477 input->isKeyDown(KeyType::FORWARD),
2478 input->isKeyDown(KeyType::BACKWARD),
2479 input->isKeyDown(KeyType::LEFT),
2480 input->isKeyDown(KeyType::RIGHT),
2481 isKeyDown(KeyType::JUMP),
2482 isKeyDown(KeyType::SPECIAL1),
2483 isKeyDown(KeyType::SNEAK),
2484 isKeyDown(KeyType::ZOOM),
2485 input->getLeftState(),
2486 input->getRightState(),
2489 input->joystick.getAxisWithoutDead(JA_SIDEWARD_MOVE),
2490 input->joystick.getAxisWithoutDead(JA_FORWARD_MOVE)
2494 ( (u32)(isKeyDown(KeyType::FORWARD) & 0x1) << 0) |
2495 ( (u32)(isKeyDown(KeyType::BACKWARD) & 0x1) << 1) |
2496 ( (u32)(isKeyDown(KeyType::LEFT) & 0x1) << 2) |
2497 ( (u32)(isKeyDown(KeyType::RIGHT) & 0x1) << 3) |
2498 ( (u32)(isKeyDown(KeyType::JUMP) & 0x1) << 4) |
2499 ( (u32)(isKeyDown(KeyType::SPECIAL1) & 0x1) << 5) |
2500 ( (u32)(isKeyDown(KeyType::SNEAK) & 0x1) << 6) |
2501 ( (u32)(input->getLeftState() & 0x1) << 7) |
2502 ( (u32)(input->getRightState() & 0x1) << 8
2506 /* For Android, simulate holding down AUX1 (fast move) if the user has
2507 * the fast_move setting toggled on. If there is an aux1 key defined for
2508 * Android then its meaning is inverted (i.e. holding aux1 means walk and
2511 if (m_cache_hold_aux1) {
2512 control.aux1 = control.aux1 ^ true;
2513 keypress_bits ^= ((u32)(1U << 5));
2517 LocalPlayer *player = client->getEnv().getLocalPlayer();
2519 // autojump if set: simulate "jump" key
2520 if (player->getAutojump()) {
2521 control.jump = true;
2522 keypress_bits |= 1U << 4;
2525 // autoforward if set: simulate "up" key
2526 if (player->getPlayerSettings().continuous_forward &&
2527 client->activeObjectsReceived() && !player->isDead()) {
2529 keypress_bits |= 1U << 0;
2532 client->setPlayerControl(control);
2533 player->keyPressed = keypress_bits;
2539 inline void Game::step(f32 *dtime)
2541 bool can_be_and_is_paused =
2542 (simple_singleplayer_mode && g_menumgr.pausesGame());
2544 if (can_be_and_is_paused) { // This is for a singleplayer server
2545 *dtime = 0; // No time passes
2548 server->step(*dtime);
2550 client->step(*dtime);
2554 const ClientEventHandler Game::clientEventHandler[CLIENTEVENT_MAX] = {
2555 {&Game::handleClientEvent_None},
2556 {&Game::handleClientEvent_PlayerDamage},
2557 {&Game::handleClientEvent_PlayerForceMove},
2558 {&Game::handleClientEvent_Deathscreen},
2559 {&Game::handleClientEvent_ShowFormSpec},
2560 {&Game::handleClientEvent_ShowLocalFormSpec},
2561 {&Game::handleClientEvent_HandleParticleEvent},
2562 {&Game::handleClientEvent_HandleParticleEvent},
2563 {&Game::handleClientEvent_HandleParticleEvent},
2564 {&Game::handleClientEvent_HudAdd},
2565 {&Game::handleClientEvent_HudRemove},
2566 {&Game::handleClientEvent_HudChange},
2567 {&Game::handleClientEvent_SetSky},
2568 {&Game::handleClientEvent_SetSun},
2569 {&Game::handleClientEvent_SetMoon},
2570 {&Game::handleClientEvent_SetStars},
2571 {&Game::handleClientEvent_OverrideDayNigthRatio},
2572 {&Game::handleClientEvent_CloudParams},
2575 void Game::handleClientEvent_None(ClientEvent *event, CameraOrientation *cam)
2577 FATAL_ERROR("ClientEvent type None received");
2580 void Game::handleClientEvent_PlayerDamage(ClientEvent *event, CameraOrientation *cam)
2582 if (client->modsLoaded())
2583 client->getScript()->on_damage_taken(event->player_damage.amount);
2585 // Damage flash and hurt tilt are not used at death
2586 if (client->getHP() > 0) {
2587 runData.damage_flash += 95.0f + 3.2f * event->player_damage.amount;
2588 runData.damage_flash = MYMIN(runData.damage_flash, 127.0f);
2590 LocalPlayer *player = client->getEnv().getLocalPlayer();
2592 player->hurt_tilt_timer = 1.5f;
2593 player->hurt_tilt_strength =
2594 rangelim(event->player_damage.amount / 4.0f, 1.0f, 4.0f);
2597 // Play damage sound
2598 client->getEventManager()->put(new SimpleTriggerEvent(MtEvent::PLAYER_DAMAGE));
2601 void Game::handleClientEvent_PlayerForceMove(ClientEvent *event, CameraOrientation *cam)
2603 cam->camera_yaw = event->player_force_move.yaw;
2604 cam->camera_pitch = event->player_force_move.pitch;
2607 void Game::handleClientEvent_Deathscreen(ClientEvent *event, CameraOrientation *cam)
2609 // If client scripting is enabled, deathscreen is handled by CSM code in
2610 // builtin/client/init.lua
2611 if (client->modsLoaded())
2612 client->getScript()->on_death();
2614 showDeathFormspec();
2616 /* Handle visualization */
2617 LocalPlayer *player = client->getEnv().getLocalPlayer();
2618 runData.damage_flash = 0;
2619 player->hurt_tilt_timer = 0;
2620 player->hurt_tilt_strength = 0;
2623 void Game::handleClientEvent_ShowFormSpec(ClientEvent *event, CameraOrientation *cam)
2625 if (event->show_formspec.formspec->empty()) {
2626 auto formspec = m_game_ui->getFormspecGUI();
2627 if (formspec && (event->show_formspec.formname->empty()
2628 || *(event->show_formspec.formname) == m_game_ui->getFormspecName())) {
2629 formspec->quitMenu();
2632 FormspecFormSource *fs_src =
2633 new FormspecFormSource(*(event->show_formspec.formspec));
2634 TextDestPlayerInventory *txt_dst =
2635 new TextDestPlayerInventory(client, *(event->show_formspec.formname));
2637 auto *&formspec = m_game_ui->updateFormspec(*(event->show_formspec.formname));
2638 GUIFormSpecMenu::create(formspec, client, &input->joystick,
2639 fs_src, txt_dst, client->getFormspecPrepend());
2642 delete event->show_formspec.formspec;
2643 delete event->show_formspec.formname;
2646 void Game::handleClientEvent_ShowLocalFormSpec(ClientEvent *event, CameraOrientation *cam)
2648 FormspecFormSource *fs_src = new FormspecFormSource(*event->show_formspec.formspec);
2649 LocalFormspecHandler *txt_dst =
2650 new LocalFormspecHandler(*event->show_formspec.formname, client);
2651 GUIFormSpecMenu::create(m_game_ui->getFormspecGUI(), client, &input->joystick,
2652 fs_src, txt_dst, client->getFormspecPrepend());
2654 delete event->show_formspec.formspec;
2655 delete event->show_formspec.formname;
2658 void Game::handleClientEvent_HandleParticleEvent(ClientEvent *event,
2659 CameraOrientation *cam)
2661 LocalPlayer *player = client->getEnv().getLocalPlayer();
2662 client->getParticleManager()->handleParticleEvent(event, client, player);
2665 void Game::handleClientEvent_HudAdd(ClientEvent *event, CameraOrientation *cam)
2667 LocalPlayer *player = client->getEnv().getLocalPlayer();
2668 auto &hud_server_to_client = client->getHUDTranslationMap();
2670 u32 server_id = event->hudadd.server_id;
2671 // ignore if we already have a HUD with that ID
2672 auto i = hud_server_to_client.find(server_id);
2673 if (i != hud_server_to_client.end()) {
2674 delete event->hudadd.pos;
2675 delete event->hudadd.name;
2676 delete event->hudadd.scale;
2677 delete event->hudadd.text;
2678 delete event->hudadd.align;
2679 delete event->hudadd.offset;
2680 delete event->hudadd.world_pos;
2681 delete event->hudadd.size;
2682 delete event->hudadd.text2;
2686 HudElement *e = new HudElement;
2687 e->type = (HudElementType)event->hudadd.type;
2688 e->pos = *event->hudadd.pos;
2689 e->name = *event->hudadd.name;
2690 e->scale = *event->hudadd.scale;
2691 e->text = *event->hudadd.text;
2692 e->number = event->hudadd.number;
2693 e->item = event->hudadd.item;
2694 e->dir = event->hudadd.dir;
2695 e->align = *event->hudadd.align;
2696 e->offset = *event->hudadd.offset;
2697 e->world_pos = *event->hudadd.world_pos;
2698 e->size = *event->hudadd.size;
2699 e->z_index = event->hudadd.z_index;
2700 e->text2 = *event->hudadd.text2;
2701 hud_server_to_client[server_id] = player->addHud(e);
2703 delete event->hudadd.pos;
2704 delete event->hudadd.name;
2705 delete event->hudadd.scale;
2706 delete event->hudadd.text;
2707 delete event->hudadd.align;
2708 delete event->hudadd.offset;
2709 delete event->hudadd.world_pos;
2710 delete event->hudadd.size;
2711 delete event->hudadd.text2;
2714 void Game::handleClientEvent_HudRemove(ClientEvent *event, CameraOrientation *cam)
2716 LocalPlayer *player = client->getEnv().getLocalPlayer();
2717 HudElement *e = player->removeHud(event->hudrm.id);
2721 void Game::handleClientEvent_HudChange(ClientEvent *event, CameraOrientation *cam)
2723 LocalPlayer *player = client->getEnv().getLocalPlayer();
2725 u32 id = event->hudchange.id;
2726 HudElement *e = player->getHud(id);
2729 delete event->hudchange.v3fdata;
2730 delete event->hudchange.v2fdata;
2731 delete event->hudchange.sdata;
2732 delete event->hudchange.v2s32data;
2736 switch (event->hudchange.stat) {
2738 e->pos = *event->hudchange.v2fdata;
2742 e->name = *event->hudchange.sdata;
2745 case HUD_STAT_SCALE:
2746 e->scale = *event->hudchange.v2fdata;
2750 e->text = *event->hudchange.sdata;
2753 case HUD_STAT_NUMBER:
2754 e->number = event->hudchange.data;
2758 e->item = event->hudchange.data;
2762 e->dir = event->hudchange.data;
2765 case HUD_STAT_ALIGN:
2766 e->align = *event->hudchange.v2fdata;
2769 case HUD_STAT_OFFSET:
2770 e->offset = *event->hudchange.v2fdata;
2773 case HUD_STAT_WORLD_POS:
2774 e->world_pos = *event->hudchange.v3fdata;
2778 e->size = *event->hudchange.v2s32data;
2781 case HUD_STAT_Z_INDEX:
2782 e->z_index = event->hudchange.data;
2785 case HUD_STAT_TEXT2:
2786 e->text2 = *event->hudchange.sdata;
2790 delete event->hudchange.v3fdata;
2791 delete event->hudchange.v2fdata;
2792 delete event->hudchange.sdata;
2793 delete event->hudchange.v2s32data;
2796 void Game::handleClientEvent_SetSky(ClientEvent *event, CameraOrientation *cam)
2798 sky->setVisible(false);
2799 // Whether clouds are visible in front of a custom skybox.
2800 sky->setCloudsEnabled(event->set_sky->clouds);
2806 // Clear the old textures out in case we switch rendering type.
2807 sky->clearSkyboxTextures();
2808 // Handle according to type
2809 if (event->set_sky->type == "regular") {
2810 // Shows the mesh skybox
2811 sky->setVisible(true);
2812 // Update mesh based skybox colours if applicable.
2813 sky->setSkyColors(event->set_sky->sky_color);
2814 sky->setHorizonTint(
2815 event->set_sky->fog_sun_tint,
2816 event->set_sky->fog_moon_tint,
2817 event->set_sky->fog_tint_type
2819 } else if (event->set_sky->type == "skybox" &&
2820 event->set_sky->textures.size() == 6) {
2821 // Disable the dyanmic mesh skybox:
2822 sky->setVisible(false);
2824 sky->setFallbackBgColor(event->set_sky->bgcolor);
2825 // Set sunrise and sunset fog tinting:
2826 sky->setHorizonTint(
2827 event->set_sky->fog_sun_tint,
2828 event->set_sky->fog_moon_tint,
2829 event->set_sky->fog_tint_type
2831 // Add textures to skybox.
2832 for (int i = 0; i < 6; i++)
2833 sky->addTextureToSkybox(event->set_sky->textures[i], i, texture_src);
2835 // Handle everything else as plain color.
2836 if (event->set_sky->type != "plain")
2837 infostream << "Unknown sky type: "
2838 << (event->set_sky->type) << std::endl;
2839 sky->setVisible(false);
2840 sky->setFallbackBgColor(event->set_sky->bgcolor);
2841 // Disable directional sun/moon tinting on plain or invalid skyboxes.
2842 sky->setHorizonTint(
2843 event->set_sky->bgcolor,
2844 event->set_sky->bgcolor,
2848 delete event->set_sky;
2851 void Game::handleClientEvent_SetSun(ClientEvent *event, CameraOrientation *cam)
2853 sky->setSunVisible(event->sun_params->visible);
2854 sky->setSunTexture(event->sun_params->texture,
2855 event->sun_params->tonemap, texture_src);
2856 sky->setSunScale(event->sun_params->scale);
2857 sky->setSunriseVisible(event->sun_params->sunrise_visible);
2858 sky->setSunriseTexture(event->sun_params->sunrise, texture_src);
2859 delete event->sun_params;
2862 void Game::handleClientEvent_SetMoon(ClientEvent *event, CameraOrientation *cam)
2864 sky->setMoonVisible(event->moon_params->visible);
2865 sky->setMoonTexture(event->moon_params->texture,
2866 event->moon_params->tonemap, texture_src);
2867 sky->setMoonScale(event->moon_params->scale);
2868 delete event->moon_params;
2871 void Game::handleClientEvent_SetStars(ClientEvent *event, CameraOrientation *cam)
2873 sky->setStarsVisible(event->star_params->visible);
2874 sky->setStarCount(event->star_params->count, false);
2875 sky->setStarColor(event->star_params->starcolor);
2876 sky->setStarScale(event->star_params->scale);
2877 delete event->star_params;
2880 void Game::handleClientEvent_OverrideDayNigthRatio(ClientEvent *event,
2881 CameraOrientation *cam)
2883 client->getEnv().setDayNightRatioOverride(
2884 event->override_day_night_ratio.do_override,
2885 event->override_day_night_ratio.ratio_f * 1000.0f);
2888 void Game::handleClientEvent_CloudParams(ClientEvent *event, CameraOrientation *cam)
2893 clouds->setDensity(event->cloud_params.density);
2894 clouds->setColorBright(video::SColor(event->cloud_params.color_bright));
2895 clouds->setColorAmbient(video::SColor(event->cloud_params.color_ambient));
2896 clouds->setHeight(event->cloud_params.height);
2897 clouds->setThickness(event->cloud_params.thickness);
2898 clouds->setSpeed(v2f(event->cloud_params.speed_x, event->cloud_params.speed_y));
2901 void Game::processClientEvents(CameraOrientation *cam)
2903 while (client->hasClientEvents()) {
2904 std::unique_ptr<ClientEvent> event(client->getClientEvent());
2905 FATAL_ERROR_IF(event->type >= CLIENTEVENT_MAX, "Invalid clientevent type");
2906 const ClientEventHandler& evHandler = clientEventHandler[event->type];
2907 (this->*evHandler.handler)(event.get(), cam);
2911 void Game::updateChat(f32 dtime, const v2u32 &screensize)
2913 // Get new messages from error log buffer
2914 while (!m_chat_log_buf.empty())
2915 chat_backend->addMessage(L"", utf8_to_wide(m_chat_log_buf.get()));
2917 // Get new messages from client
2918 std::wstring message;
2919 while (client->getChatMessage(message)) {
2920 chat_backend->addUnparsedMessage(message);
2923 // Remove old messages
2924 chat_backend->step(dtime);
2926 // Display all messages in a static text element
2927 m_game_ui->setChatText(chat_backend->getRecentChat(),
2928 chat_backend->getRecentBuffer().getLineCount());
2931 void Game::updateCamera(u32 busy_time, f32 dtime)
2933 LocalPlayer *player = client->getEnv().getLocalPlayer();
2936 For interaction purposes, get info about the held item
2938 - Is it a usable item?
2939 - Can it point to liquids?
2941 ItemStack playeritem;
2943 ItemStack selected, hand;
2944 playeritem = player->getWieldedItem(&selected, &hand);
2947 ToolCapabilities playeritem_toolcap =
2948 playeritem.getToolCapabilities(itemdef_manager);
2950 v3s16 old_camera_offset = camera->getOffset();
2952 if (wasKeyDown(KeyType::CAMERA_MODE)) {
2953 GenericCAO *playercao = player->getCAO();
2955 // If playercao not loaded, don't change camera
2959 camera->toggleCameraMode();
2961 playercao->setVisible(camera->getCameraMode() > CAMERA_MODE_FIRST);
2962 playercao->setChildrenVisible(camera->getCameraMode() > CAMERA_MODE_FIRST);
2965 float full_punch_interval = playeritem_toolcap.full_punch_interval;
2966 float tool_reload_ratio = runData.time_from_last_punch / full_punch_interval;
2968 tool_reload_ratio = MYMIN(tool_reload_ratio, 1.0);
2969 camera->update(player, dtime, busy_time / 1000.0f, tool_reload_ratio);
2970 camera->step(dtime);
2972 v3f camera_position = camera->getPosition();
2973 v3f camera_direction = camera->getDirection();
2974 f32 camera_fov = camera->getFovMax();
2975 v3s16 camera_offset = camera->getOffset();
2977 m_camera_offset_changed = (camera_offset != old_camera_offset);
2979 if (!m_flags.disable_camera_update) {
2980 client->getEnv().getClientMap().updateCamera(camera_position,
2981 camera_direction, camera_fov, camera_offset);
2983 if (m_camera_offset_changed) {
2984 client->updateCameraOffset(camera_offset);
2985 client->getEnv().updateCameraOffset(camera_offset);
2988 clouds->updateCameraOffset(camera_offset);
2994 void Game::updateSound(f32 dtime)
2996 // Update sound listener
2997 v3s16 camera_offset = camera->getOffset();
2998 sound->updateListener(camera->getCameraNode()->getPosition() + intToFloat(camera_offset, BS),
2999 v3f(0, 0, 0), // velocity
3000 camera->getDirection(),
3001 camera->getCameraNode()->getUpVector());
3003 bool mute_sound = g_settings->getBool("mute_sound");
3005 sound->setListenerGain(0.0f);
3007 // Check if volume is in the proper range, else fix it.
3008 float old_volume = g_settings->getFloat("sound_volume");
3009 float new_volume = rangelim(old_volume, 0.0f, 1.0f);
3010 sound->setListenerGain(new_volume);
3012 if (old_volume != new_volume) {
3013 g_settings->setFloat("sound_volume", new_volume);
3017 LocalPlayer *player = client->getEnv().getLocalPlayer();
3019 // Tell the sound maker whether to make footstep sounds
3020 soundmaker->makes_footstep_sound = player->makes_footstep_sound;
3022 // Update sound maker
3023 if (player->makes_footstep_sound)
3024 soundmaker->step(dtime);
3026 ClientMap &map = client->getEnv().getClientMap();
3027 MapNode n = map.getNode(player->getFootstepNodePos());
3028 soundmaker->m_player_step_sound = nodedef_manager->get(n).sound_footstep;
3032 void Game::processPlayerInteraction(f32 dtime, bool show_hud, bool show_debug)
3034 LocalPlayer *player = client->getEnv().getLocalPlayer();
3036 const v3f camera_direction = camera->getDirection();
3037 const v3s16 camera_offset = camera->getOffset();
3040 Calculate what block is the crosshair pointing to
3043 ItemStack selected_item, hand_item;
3044 const ItemStack &tool_item = player->getWieldedItem(&selected_item, &hand_item);
3046 const ItemDefinition &selected_def = selected_item.getDefinition(itemdef_manager);
3047 f32 d = getToolRange(selected_def, hand_item.getDefinition(itemdef_manager));
3049 core::line3d<f32> shootline;
3051 switch (camera->getCameraMode()) {
3052 case CAMERA_MODE_FIRST:
3053 // Shoot from camera position, with bobbing
3054 shootline.start = camera->getPosition();
3056 case CAMERA_MODE_THIRD:
3057 // Shoot from player head, no bobbing
3058 shootline.start = camera->getHeadPosition();
3060 case CAMERA_MODE_THIRD_FRONT:
3061 shootline.start = camera->getHeadPosition();
3062 // prevent player pointing anything in front-view
3066 shootline.end = shootline.start + camera_direction * BS * d;
3068 #ifdef HAVE_TOUCHSCREENGUI
3070 if ((g_settings->getBool("touchtarget")) && (g_touchscreengui)) {
3071 shootline = g_touchscreengui->getShootline();
3072 // Scale shootline to the acual distance the player can reach
3073 shootline.end = shootline.start
3074 + shootline.getVector().normalize() * BS * d;
3075 shootline.start += intToFloat(camera_offset, BS);
3076 shootline.end += intToFloat(camera_offset, BS);
3081 PointedThing pointed = updatePointedThing(shootline,
3082 selected_def.liquids_pointable,
3083 !runData.ldown_for_dig,
3086 if (pointed != runData.pointed_old) {
3087 infostream << "Pointing at " << pointed.dump() << std::endl;
3088 hud->updateSelectionMesh(camera_offset);
3091 if (runData.digging_blocked && !input->getLeftState()) {
3092 // allow digging again if button is not pressed
3093 runData.digging_blocked = false;
3098 - releasing left mouse button
3099 - pointing away from node
3101 if (runData.digging) {
3102 if (input->getLeftReleased()) {
3103 infostream << "Left button released"
3104 << " (stopped digging)" << std::endl;
3105 runData.digging = false;
3106 } else if (pointed != runData.pointed_old) {
3107 if (pointed.type == POINTEDTHING_NODE
3108 && runData.pointed_old.type == POINTEDTHING_NODE
3109 && pointed.node_undersurface
3110 == runData.pointed_old.node_undersurface) {
3111 // Still pointing to the same node, but a different face.
3114 infostream << "Pointing away from node"
3115 << " (stopped digging)" << std::endl;
3116 runData.digging = false;
3117 hud->updateSelectionMesh(camera_offset);
3121 if (!runData.digging) {
3122 client->interact(INTERACT_STOP_DIGGING, runData.pointed_old);
3123 client->setCrack(-1, v3s16(0, 0, 0));
3124 runData.dig_time = 0.0;
3126 } else if (runData.dig_instantly && input->getLeftReleased()) {
3127 // Remove e.g. torches faster when clicking instead of holding LMB
3128 runData.nodig_delay_timer = 0;
3129 runData.dig_instantly = false;
3132 if (!runData.digging && runData.ldown_for_dig && !input->getLeftState()) {
3133 runData.ldown_for_dig = false;
3136 runData.left_punch = false;
3138 soundmaker->m_player_leftpunch_sound.name = "";
3140 // Prepare for repeating, unless we're not supposed to
3141 if (input->getRightState() && !g_settings->getBool("safe_dig_and_place"))
3142 runData.repeat_rightclick_timer += dtime;
3144 runData.repeat_rightclick_timer = 0;
3146 if (selected_def.usable && input->getLeftState()) {
3147 if (input->getLeftClicked() && (!client->modsLoaded()
3148 || !client->getScript()->on_item_use(selected_item, pointed)))
3149 client->interact(INTERACT_USE, pointed);
3150 } else if (pointed.type == POINTEDTHING_NODE) {
3151 handlePointingAtNode(pointed, selected_item, hand_item, dtime);
3152 } else if (pointed.type == POINTEDTHING_OBJECT) {
3153 v3f player_position = player->getPosition();
3154 handlePointingAtObject(pointed, tool_item, player_position, show_debug);
3155 } else if (input->getLeftState()) {
3156 // When button is held down in air, show continuous animation
3157 runData.left_punch = true;
3158 // Run callback even though item is not usable
3159 if (input->getLeftClicked() && client->modsLoaded())
3160 client->getScript()->on_item_use(selected_item, pointed);
3161 } else if (input->getRightClicked()) {
3162 handlePointingAtNothing(selected_item);
3165 runData.pointed_old = pointed;
3167 if (runData.left_punch || input->getLeftClicked())
3168 camera->setDigging(0); // left click animation
3170 input->resetLeftClicked();
3171 input->resetRightClicked();
3173 input->resetLeftReleased();
3174 input->resetRightReleased();
3178 PointedThing Game::updatePointedThing(
3179 const core::line3d<f32> &shootline,
3180 bool liquids_pointable,
3181 bool look_for_object,
3182 const v3s16 &camera_offset)
3184 std::vector<aabb3f> *selectionboxes = hud->getSelectionBoxes();
3185 selectionboxes->clear();
3186 hud->setSelectedFaceNormal(v3f(0.0, 0.0, 0.0));
3187 static thread_local const bool show_entity_selectionbox = g_settings->getBool(
3188 "show_entity_selectionbox");
3190 ClientEnvironment &env = client->getEnv();
3191 ClientMap &map = env.getClientMap();
3192 const NodeDefManager *nodedef = map.getNodeDefManager();
3194 runData.selected_object = NULL;
3196 RaycastState s(shootline, look_for_object, liquids_pointable);
3197 PointedThing result;
3198 env.continueRaycast(&s, &result);
3199 if (result.type == POINTEDTHING_OBJECT) {
3200 runData.selected_object = client->getEnv().getActiveObject(result.object_id);
3201 aabb3f selection_box;
3202 if (show_entity_selectionbox && runData.selected_object->doShowSelectionBox() &&
3203 runData.selected_object->getSelectionBox(&selection_box)) {
3204 v3f pos = runData.selected_object->getPosition();
3205 selectionboxes->push_back(aabb3f(selection_box));
3206 hud->setSelectionPos(pos, camera_offset);
3208 } else if (result.type == POINTEDTHING_NODE) {
3209 // Update selection boxes
3210 MapNode n = map.getNode(result.node_undersurface);
3211 std::vector<aabb3f> boxes;
3212 n.getSelectionBoxes(nodedef, &boxes,
3213 n.getNeighbors(result.node_undersurface, &map));
3216 for (std::vector<aabb3f>::const_iterator i = boxes.begin();
3217 i != boxes.end(); ++i) {
3219 box.MinEdge -= v3f(d, d, d);
3220 box.MaxEdge += v3f(d, d, d);
3221 selectionboxes->push_back(box);
3223 hud->setSelectionPos(intToFloat(result.node_undersurface, BS),
3225 hud->setSelectedFaceNormal(v3f(
3226 result.intersection_normal.X,
3227 result.intersection_normal.Y,
3228 result.intersection_normal.Z));
3231 // Update selection mesh light level and vertex colors
3232 if (!selectionboxes->empty()) {
3233 v3f pf = hud->getSelectionPos();
3234 v3s16 p = floatToInt(pf, BS);
3236 // Get selection mesh light level
3237 MapNode n = map.getNode(p);
3238 u16 node_light = getInteriorLight(n, -1, nodedef);
3239 u16 light_level = node_light;
3241 for (const v3s16 &dir : g_6dirs) {
3242 n = map.getNode(p + dir);
3243 node_light = getInteriorLight(n, -1, nodedef);
3244 if (node_light > light_level)
3245 light_level = node_light;
3248 u32 daynight_ratio = client->getEnv().getDayNightRatio();
3250 final_color_blend(&c, light_level, daynight_ratio);
3252 // Modify final color a bit with time
3253 u32 timer = porting::getTimeMs() % 5000;
3254 float timerf = (float) (irr::core::PI * ((timer / 2500.0) - 0.5));
3255 float sin_r = 0.08f * std::sin(timerf);
3256 float sin_g = 0.08f * std::sin(timerf + irr::core::PI * 0.5f);
3257 float sin_b = 0.08f * std::sin(timerf + irr::core::PI);
3258 c.setRed(core::clamp(core::round32(c.getRed() * (0.8 + sin_r)), 0, 255));
3259 c.setGreen(core::clamp(core::round32(c.getGreen() * (0.8 + sin_g)), 0, 255));
3260 c.setBlue(core::clamp(core::round32(c.getBlue() * (0.8 + sin_b)), 0, 255));
3262 // Set mesh final color
3263 hud->setSelectionMeshColor(c);
3269 void Game::handlePointingAtNothing(const ItemStack &playerItem)
3271 infostream << "Right Clicked in Air" << std::endl;
3272 PointedThing fauxPointed;
3273 fauxPointed.type = POINTEDTHING_NOTHING;
3274 client->interact(INTERACT_ACTIVATE, fauxPointed);
3278 void Game::handlePointingAtNode(const PointedThing &pointed,
3279 const ItemStack &selected_item, const ItemStack &hand_item, f32 dtime)
3281 v3s16 nodepos = pointed.node_undersurface;
3282 v3s16 neighbourpos = pointed.node_abovesurface;
3285 Check information text of node
3288 ClientMap &map = client->getEnv().getClientMap();
3290 if (runData.nodig_delay_timer <= 0.0 && input->getLeftState()
3291 && !runData.digging_blocked
3292 && client->checkPrivilege("interact")) {
3293 handleDigging(pointed, nodepos, selected_item, hand_item, dtime);
3296 // This should be done after digging handling
3297 NodeMetadata *meta = map.getNodeMetadata(nodepos);
3300 m_game_ui->setInfoText(unescape_translate(utf8_to_wide(
3301 meta->getString("infotext"))));
3303 MapNode n = map.getNode(nodepos);
3305 if (nodedef_manager->get(n).tiledef[0].name == "unknown_node.png") {
3306 m_game_ui->setInfoText(L"Unknown node: " +
3307 utf8_to_wide(nodedef_manager->get(n).name));
3311 if ((input->getRightClicked() ||
3312 runData.repeat_rightclick_timer >= m_repeat_right_click_time) &&
3313 client->checkPrivilege("interact")) {
3314 runData.repeat_rightclick_timer = 0;
3315 infostream << "Ground right-clicked" << std::endl;
3317 camera->setDigging(1); // right click animation (always shown for feedback)
3319 soundmaker->m_player_rightpunch_sound = SimpleSoundSpec();
3321 // If the wielded item has node placement prediction,
3323 // And also set the sound and send the interact
3324 // But first check for meta formspec and rightclickable
3325 auto &def = selected_item.getDefinition(itemdef_manager);
3326 bool placed = nodePlacement(def, selected_item, nodepos, neighbourpos,
3329 if (placed && client->modsLoaded())
3330 client->getScript()->on_placenode(pointed, def);
3334 bool Game::nodePlacement(const ItemDefinition &selected_def,
3335 const ItemStack &selected_item, const v3s16 &nodepos, const v3s16 &neighbourpos,
3336 const PointedThing &pointed, const NodeMetadata *meta)
3338 std::string prediction = selected_def.node_placement_prediction;
3339 const NodeDefManager *nodedef = client->ndef();
3340 ClientMap &map = client->getEnv().getClientMap();
3342 bool is_valid_position;
3344 node = map.getNode(nodepos, &is_valid_position);
3345 if (!is_valid_position) {
3346 soundmaker->m_player_rightpunch_sound = selected_def.sound_place_failed;
3351 if (meta && !meta->getString("formspec").empty() && !random_input
3352 && !isKeyDown(KeyType::SNEAK)) {
3353 // on_rightclick callbacks are called anyway
3354 if (nodedef_manager->get(map.getNode(nodepos)).rightclickable)
3355 client->interact(INTERACT_PLACE, pointed);
3357 infostream << "Launching custom inventory view" << std::endl;
3359 InventoryLocation inventoryloc;
3360 inventoryloc.setNodeMeta(nodepos);
3362 NodeMetadataFormSource *fs_src = new NodeMetadataFormSource(
3363 &client->getEnv().getClientMap(), nodepos);
3364 TextDest *txt_dst = new TextDestNodeMetadata(nodepos, client);
3366 auto *&formspec = m_game_ui->updateFormspec("");
3367 GUIFormSpecMenu::create(formspec, client, &input->joystick, fs_src,
3368 txt_dst, client->getFormspecPrepend());
3370 formspec->setFormSpec(meta->getString("formspec"), inventoryloc);
3374 // on_rightclick callback
3375 if (prediction.empty() || (nodedef->get(node).rightclickable &&
3376 !isKeyDown(KeyType::SNEAK))) {
3378 client->interact(INTERACT_PLACE, pointed);
3382 verbosestream << "Node placement prediction for "
3383 << selected_def.name << " is "
3384 << prediction << std::endl;
3385 v3s16 p = neighbourpos;
3387 // Place inside node itself if buildable_to
3388 MapNode n_under = map.getNode(nodepos, &is_valid_position);
3389 if (is_valid_position) {
3390 if (nodedef->get(n_under).buildable_to) {
3393 node = map.getNode(p, &is_valid_position);
3394 if (is_valid_position && !nodedef->get(node).buildable_to) {
3396 client->interact(INTERACT_PLACE, pointed);
3402 // Find id of predicted node
3404 bool found = nodedef->getId(prediction, id);
3407 errorstream << "Node placement prediction failed for "
3408 << selected_def.name << " (places "
3410 << ") - Name not known" << std::endl;
3411 // Handle this as if prediction was empty
3413 client->interact(INTERACT_PLACE, pointed);
3417 const ContentFeatures &predicted_f = nodedef->get(id);
3419 // Predict param2 for facedir and wallmounted nodes
3422 if (predicted_f.param_type_2 == CPT2_WALLMOUNTED ||
3423 predicted_f.param_type_2 == CPT2_COLORED_WALLMOUNTED) {
3424 v3s16 dir = nodepos - neighbourpos;
3426 if (abs(dir.Y) > MYMAX(abs(dir.X), abs(dir.Z))) {
3427 param2 = dir.Y < 0 ? 1 : 0;
3428 } else if (abs(dir.X) > abs(dir.Z)) {
3429 param2 = dir.X < 0 ? 3 : 2;
3431 param2 = dir.Z < 0 ? 5 : 4;
3435 if (predicted_f.param_type_2 == CPT2_FACEDIR ||
3436 predicted_f.param_type_2 == CPT2_COLORED_FACEDIR) {
3437 v3s16 dir = nodepos - floatToInt(client->getEnv().getLocalPlayer()->getPosition(), BS);
3439 if (abs(dir.X) > abs(dir.Z)) {
3440 param2 = dir.X < 0 ? 3 : 1;
3442 param2 = dir.Z < 0 ? 2 : 0;
3446 assert(param2 <= 5);
3448 //Check attachment if node is in group attached_node
3449 if (((ItemGroupList) predicted_f.groups)["attached_node"] != 0) {
3450 static v3s16 wallmounted_dirs[8] = {
3460 if (predicted_f.param_type_2 == CPT2_WALLMOUNTED ||
3461 predicted_f.param_type_2 == CPT2_COLORED_WALLMOUNTED)
3462 pp = p + wallmounted_dirs[param2];
3464 pp = p + v3s16(0, -1, 0);
3466 if (!nodedef->get(map.getNode(pp)).walkable) {
3468 client->interact(INTERACT_PLACE, pointed);
3474 if ((predicted_f.param_type_2 == CPT2_COLOR
3475 || predicted_f.param_type_2 == CPT2_COLORED_FACEDIR
3476 || predicted_f.param_type_2 == CPT2_COLORED_WALLMOUNTED)) {
3477 const std::string &indexstr = selected_item.metadata.getString(
3478 "palette_index", 0);
3479 if (!indexstr.empty()) {
3480 s32 index = mystoi(indexstr);
3481 if (predicted_f.param_type_2 == CPT2_COLOR) {
3483 } else if (predicted_f.param_type_2 == CPT2_COLORED_WALLMOUNTED) {
3484 // param2 = pure palette index + other
3485 param2 = (index & 0xf8) | (param2 & 0x07);
3486 } else if (predicted_f.param_type_2 == CPT2_COLORED_FACEDIR) {
3487 // param2 = pure palette index + other
3488 param2 = (index & 0xe0) | (param2 & 0x1f);
3493 // Add node to client map
3494 MapNode n(id, 0, param2);
3497 LocalPlayer *player = client->getEnv().getLocalPlayer();
3499 // Dont place node when player would be inside new node
3500 // NOTE: This is to be eventually implemented by a mod as client-side Lua
3501 if (!nodedef->get(n).walkable ||
3502 g_settings->getBool("enable_build_where_you_stand") ||
3503 (client->checkPrivilege("noclip") && g_settings->getBool("noclip")) ||
3504 (nodedef->get(n).walkable &&
3505 neighbourpos != player->getStandingNodePos() + v3s16(0, 1, 0) &&
3506 neighbourpos != player->getStandingNodePos() + v3s16(0, 2, 0))) {
3507 // This triggers the required mesh update too
3508 client->addNode(p, n);
3510 client->interact(INTERACT_PLACE, pointed);
3511 // A node is predicted, also play a sound
3512 soundmaker->m_player_rightpunch_sound = selected_def.sound_place;
3515 soundmaker->m_player_rightpunch_sound = selected_def.sound_place_failed;
3518 } catch (InvalidPositionException &e) {
3519 errorstream << "Node placement prediction failed for "
3520 << selected_def.name << " (places "
3522 << ") - Position not loaded" << std::endl;
3523 soundmaker->m_player_rightpunch_sound = selected_def.sound_place_failed;
3528 void Game::handlePointingAtObject(const PointedThing &pointed,
3529 const ItemStack &tool_item, const v3f &player_position, bool show_debug)
3531 std::wstring infotext = unescape_translate(
3532 utf8_to_wide(runData.selected_object->infoText()));
3535 if (!infotext.empty()) {
3538 infotext += utf8_to_wide(runData.selected_object->debugInfoText());
3541 m_game_ui->setInfoText(infotext);
3543 if (input->getLeftState()) {
3544 bool do_punch = false;
3545 bool do_punch_damage = false;
3547 if (runData.object_hit_delay_timer <= 0.0) {
3549 do_punch_damage = true;
3550 runData.object_hit_delay_timer = object_hit_delay;
3553 if (input->getLeftClicked())
3557 infostream << "Left-clicked object" << std::endl;
3558 runData.left_punch = true;
3561 if (do_punch_damage) {
3562 // Report direct punch
3563 v3f objpos = runData.selected_object->getPosition();
3564 v3f dir = (objpos - player_position).normalize();
3566 bool disable_send = runData.selected_object->directReportPunch(
3567 dir, &tool_item, runData.time_from_last_punch);
3568 runData.time_from_last_punch = 0;
3571 client->interact(INTERACT_START_DIGGING, pointed);
3573 } else if (input->getRightClicked()) {
3574 infostream << "Right-clicked object" << std::endl;
3575 client->interact(INTERACT_PLACE, pointed); // place
3580 void Game::handleDigging(const PointedThing &pointed, const v3s16 &nodepos,
3581 const ItemStack &selected_item, const ItemStack &hand_item, f32 dtime)
3583 // See also: serverpackethandle.cpp, action == 2
3584 LocalPlayer *player = client->getEnv().getLocalPlayer();
3585 ClientMap &map = client->getEnv().getClientMap();
3586 MapNode n = client->getEnv().getClientMap().getNode(nodepos);
3588 // NOTE: Similar piece of code exists on the server side for
3590 // Get digging parameters
3591 DigParams params = getDigParams(nodedef_manager->get(n).groups,
3592 &selected_item.getToolCapabilities(itemdef_manager));
3594 // If can't dig, try hand
3595 if (!params.diggable) {
3596 params = getDigParams(nodedef_manager->get(n).groups,
3597 &hand_item.getToolCapabilities(itemdef_manager));
3600 if (!params.diggable) {
3601 // I guess nobody will wait for this long
3602 runData.dig_time_complete = 10000000.0;
3604 runData.dig_time_complete = params.time;
3606 if (m_cache_enable_particles) {
3607 const ContentFeatures &features = client->getNodeDefManager()->get(n);
3608 client->getParticleManager()->addNodeParticle(client,
3609 player, nodepos, n, features);
3613 if (!runData.digging) {
3614 infostream << "Started digging" << std::endl;
3615 runData.dig_instantly = runData.dig_time_complete == 0;
3616 if (client->modsLoaded() && client->getScript()->on_punchnode(nodepos, n))
3618 client->interact(INTERACT_START_DIGGING, pointed);
3619 runData.digging = true;
3620 runData.ldown_for_dig = true;
3623 if (!runData.dig_instantly) {
3624 runData.dig_index = (float)crack_animation_length
3626 / runData.dig_time_complete;
3628 // This is for e.g. torches
3629 runData.dig_index = crack_animation_length;
3632 SimpleSoundSpec sound_dig = nodedef_manager->get(n).sound_dig;
3634 if (sound_dig.exists() && params.diggable) {
3635 if (sound_dig.name == "__group") {
3636 if (!params.main_group.empty()) {
3637 soundmaker->m_player_leftpunch_sound.gain = 0.5;
3638 soundmaker->m_player_leftpunch_sound.name =
3639 std::string("default_dig_") +
3643 soundmaker->m_player_leftpunch_sound = sound_dig;
3647 // Don't show cracks if not diggable
3648 if (runData.dig_time_complete >= 100000.0) {
3649 } else if (runData.dig_index < crack_animation_length) {
3650 //TimeTaker timer("client.setTempMod");
3651 //infostream<<"dig_index="<<dig_index<<std::endl;
3652 client->setCrack(runData.dig_index, nodepos);
3654 infostream << "Digging completed" << std::endl;
3655 client->setCrack(-1, v3s16(0, 0, 0));
3657 runData.dig_time = 0;
3658 runData.digging = false;
3659 // we successfully dug, now block it from repeating if we want to be safe
3660 if (g_settings->getBool("safe_dig_and_place"))
3661 runData.digging_blocked = true;
3663 runData.nodig_delay_timer =
3664 runData.dig_time_complete / (float)crack_animation_length;
3666 // We don't want a corresponding delay to very time consuming nodes
3667 // and nodes without digging time (e.g. torches) get a fixed delay.
3668 if (runData.nodig_delay_timer > 0.3)
3669 runData.nodig_delay_timer = 0.3;
3670 else if (runData.dig_instantly)
3671 runData.nodig_delay_timer = 0.15;
3673 bool is_valid_position;
3674 MapNode wasnode = map.getNode(nodepos, &is_valid_position);
3675 if (is_valid_position) {
3676 if (client->modsLoaded() &&
3677 client->getScript()->on_dignode(nodepos, wasnode)) {
3681 const ContentFeatures &f = client->ndef()->get(wasnode);
3682 if (f.node_dig_prediction == "air") {
3683 client->removeNode(nodepos);
3684 } else if (!f.node_dig_prediction.empty()) {
3686 bool found = client->ndef()->getId(f.node_dig_prediction, id);
3688 client->addNode(nodepos, id, true);
3690 // implicit else: no prediction
3693 client->interact(INTERACT_DIGGING_COMPLETED, pointed);
3695 if (m_cache_enable_particles) {
3696 const ContentFeatures &features =
3697 client->getNodeDefManager()->get(wasnode);
3698 client->getParticleManager()->addDiggingParticles(client,
3699 player, nodepos, wasnode, features);
3703 // Send event to trigger sound
3704 client->getEventManager()->put(new NodeDugEvent(nodepos, wasnode));
3707 if (runData.dig_time_complete < 100000.0) {
3708 runData.dig_time += dtime;
3710 runData.dig_time = 0;
3711 client->setCrack(-1, nodepos);
3714 camera->setDigging(0); // left click animation
3718 void Game::updateFrame(ProfilerGraph *graph, RunStats *stats, f32 dtime,
3719 const CameraOrientation &cam)
3721 TimeTaker tt_update("Game::updateFrame()");
3722 LocalPlayer *player = client->getEnv().getLocalPlayer();
3728 if (draw_control->range_all) {
3729 runData.fog_range = 100000 * BS;
3731 runData.fog_range = draw_control->wanted_range * BS;
3735 Calculate general brightness
3737 u32 daynight_ratio = client->getEnv().getDayNightRatio();
3738 float time_brightness = decode_light_f((float)daynight_ratio / 1000.0);
3739 float direct_brightness;
3742 if (m_cache_enable_noclip && m_cache_enable_free_move) {
3743 direct_brightness = time_brightness;
3744 sunlight_seen = true;
3746 float old_brightness = sky->getBrightness();
3747 direct_brightness = client->getEnv().getClientMap()
3748 .getBackgroundBrightness(MYMIN(runData.fog_range * 1.2, 60 * BS),
3749 daynight_ratio, (int)(old_brightness * 255.5), &sunlight_seen)
3753 float time_of_day_smooth = runData.time_of_day_smooth;
3754 float time_of_day = client->getEnv().getTimeOfDayF();
3756 static const float maxsm = 0.05f;
3757 static const float todsm = 0.05f;
3759 if (std::fabs(time_of_day - time_of_day_smooth) > maxsm &&
3760 std::fabs(time_of_day - time_of_day_smooth + 1.0) > maxsm &&
3761 std::fabs(time_of_day - time_of_day_smooth - 1.0) > maxsm)
3762 time_of_day_smooth = time_of_day;
3764 if (time_of_day_smooth > 0.8 && time_of_day < 0.2)
3765 time_of_day_smooth = time_of_day_smooth * (1.0 - todsm)
3766 + (time_of_day + 1.0) * todsm;
3768 time_of_day_smooth = time_of_day_smooth * (1.0 - todsm)
3769 + time_of_day * todsm;
3771 runData.time_of_day_smooth = time_of_day_smooth;
3773 sky->update(time_of_day_smooth, time_brightness, direct_brightness,
3774 sunlight_seen, camera->getCameraMode(), player->getYaw(),
3775 player->getPitch());
3781 if (sky->getCloudsVisible()) {
3782 clouds->setVisible(true);
3783 clouds->step(dtime);
3784 // camera->getPosition is not enough for 3rd person views
3785 v3f camera_node_position = camera->getCameraNode()->getPosition();
3786 v3s16 camera_offset = camera->getOffset();
3787 camera_node_position.X = camera_node_position.X + camera_offset.X * BS;
3788 camera_node_position.Y = camera_node_position.Y + camera_offset.Y * BS;
3789 camera_node_position.Z = camera_node_position.Z + camera_offset.Z * BS;
3790 clouds->update(camera_node_position,
3791 sky->getCloudColor());
3792 if (clouds->isCameraInsideCloud() && m_cache_enable_fog) {
3793 // if inside clouds, and fog enabled, use that as sky
3795 video::SColor clouds_dark = clouds->getColor()
3796 .getInterpolated(video::SColor(255, 0, 0, 0), 0.9);
3797 sky->overrideColors(clouds_dark, clouds->getColor());
3798 sky->setInClouds(true);
3799 runData.fog_range = std::fmin(runData.fog_range * 0.5f, 32.0f * BS);
3800 // do not draw clouds after all
3801 clouds->setVisible(false);
3804 clouds->setVisible(false);
3811 client->getParticleManager()->step(dtime);
3817 if (m_cache_enable_fog) {
3820 video::EFT_FOG_LINEAR,
3821 runData.fog_range * m_cache_fog_start,
3822 runData.fog_range * 1.0,
3830 video::EFT_FOG_LINEAR,
3840 Get chat messages from client
3843 v2u32 screensize = driver->getScreenSize();
3845 updateChat(dtime, screensize);
3851 if (player->getWieldIndex() != runData.new_playeritem)
3852 client->setPlayerItem(runData.new_playeritem);
3854 if (client->updateWieldedItem()) {
3855 // Update wielded tool
3856 ItemStack selected_item, hand_item;
3857 ItemStack &tool_item = player->getWieldedItem(&selected_item, &hand_item);
3858 camera->wield(tool_item);
3862 Update block draw list every 200ms or when camera direction has
3865 runData.update_draw_list_timer += dtime;
3867 v3f camera_direction = camera->getDirection();
3868 if (runData.update_draw_list_timer >= 0.2
3869 || runData.update_draw_list_last_cam_dir.getDistanceFrom(camera_direction) > 0.2
3870 || m_camera_offset_changed) {
3871 runData.update_draw_list_timer = 0;
3872 client->getEnv().getClientMap().updateDrawList();
3873 runData.update_draw_list_last_cam_dir = camera_direction;
3876 m_game_ui->update(*stats, client, draw_control, cam, runData.pointed_old, gui_chat_console, dtime);
3879 make sure menu is on top
3880 1. Delete formspec menu reference if menu was removed
3881 2. Else, make sure formspec menu is on top
3883 auto formspec = m_game_ui->getFormspecGUI();
3884 do { // breakable. only runs for one iteration
3888 if (formspec->getReferenceCount() == 1) {
3889 m_game_ui->deleteFormspec();
3893 auto &loc = formspec->getFormspecLocation();
3894 if (loc.type == InventoryLocation::NODEMETA) {
3895 NodeMetadata *meta = client->getEnv().getClientMap().getNodeMetadata(loc.p);
3896 if (!meta || meta->getString("formspec").empty()) {
3897 formspec->quitMenu();
3903 guiroot->bringToFront(formspec);
3909 const video::SColor &skycolor = sky->getSkyColor();
3911 TimeTaker tt_draw("Draw scene");
3912 driver->beginScene(true, true, skycolor);
3914 bool draw_wield_tool = (m_game_ui->m_flags.show_hud &&
3915 (player->hud_flags & HUD_FLAG_WIELDITEM_VISIBLE) &&
3916 (camera->getCameraMode() == CAMERA_MODE_FIRST));
3917 bool draw_crosshair = (
3918 (player->hud_flags & HUD_FLAG_CROSSHAIR_VISIBLE) &&
3919 (camera->getCameraMode() != CAMERA_MODE_THIRD_FRONT));
3920 #ifdef HAVE_TOUCHSCREENGUI
3922 draw_crosshair = !g_settings->getBool("touchtarget");
3923 } catch (SettingNotFoundException) {
3926 RenderingEngine::draw_scene(skycolor, m_game_ui->m_flags.show_hud,
3927 m_game_ui->m_flags.show_minimap, draw_wield_tool, draw_crosshair);
3932 if (m_game_ui->m_flags.show_profiler_graph)
3933 graph->draw(10, screensize.Y - 10, driver, g_fontengine->getFont());
3938 if (runData.damage_flash > 0.0f) {
3939 video::SColor color(runData.damage_flash, 180, 0, 0);
3940 driver->draw2DRectangle(color,
3941 core::rect<s32>(0, 0, screensize.X, screensize.Y),
3944 runData.damage_flash -= 384.0f * dtime;
3950 if (player->hurt_tilt_timer > 0.0f) {
3951 player->hurt_tilt_timer -= dtime * 6.0f;
3953 if (player->hurt_tilt_timer < 0.0f)
3954 player->hurt_tilt_strength = 0.0f;
3958 Update minimap pos and rotation
3960 if (mapper && m_game_ui->m_flags.show_minimap && m_game_ui->m_flags.show_hud) {
3961 mapper->setPos(floatToInt(player->getPosition(), BS));
3962 mapper->setAngle(player->getYaw());
3970 stats->drawtime = tt_draw.stop(true);
3971 g_profiler->avg("Game::updateFrame(): draw scene [ms]", stats->drawtime);
3972 g_profiler->graphAdd("Update frame [ms]", tt_update.stop(true));
3975 /* Log times and stuff for visualization */
3976 inline void Game::updateProfilerGraphs(ProfilerGraph *graph)
3978 Profiler::GraphValues values;
3979 g_profiler->graphGet(values);
3985 /****************************************************************************
3987 ****************************************************************************/
3989 /* On some computers framerate doesn't seem to be automatically limited
3991 inline void Game::limitFps(FpsControl *fps_timings, f32 *dtime)
3993 // not using getRealTime is necessary for wine
3994 device->getTimer()->tick(); // Maker sure device time is up-to-date
3995 u32 time = device->getTimer()->getTime();
3996 u32 last_time = fps_timings->last_time;
3998 if (time > last_time) // Make sure time hasn't overflowed
3999 fps_timings->busy_time = time - last_time;
4001 fps_timings->busy_time = 0;
4003 u32 frametime_min = 1000 / (g_menumgr.pausesGame()
4004 ? g_settings->getFloat("pause_fps_max")
4005 : g_settings->getFloat("fps_max"));
4007 if (fps_timings->busy_time < frametime_min) {
4008 fps_timings->sleep_time = frametime_min - fps_timings->busy_time;
4009 device->sleep(fps_timings->sleep_time);
4011 fps_timings->sleep_time = 0;
4014 /* Get the new value of the device timer. Note that device->sleep() may
4015 * not sleep for the entire requested time as sleep may be interrupted and
4016 * therefore it is arguably more accurate to get the new time from the
4017 * device rather than calculating it by adding sleep_time to time.
4020 device->getTimer()->tick(); // Update device timer
4021 time = device->getTimer()->getTime();
4023 if (time > last_time) // Make sure last_time hasn't overflowed
4024 *dtime = (time - last_time) / 1000.0;
4028 fps_timings->last_time = time;
4031 void Game::showOverlayMessage(const char *msg, float dtime, int percent, bool draw_clouds)
4033 const wchar_t *wmsg = wgettext(msg);
4034 RenderingEngine::draw_load_screen(wmsg, guienv, texture_src, dtime, percent,
4039 void Game::settingChangedCallback(const std::string &setting_name, void *data)
4041 ((Game *)data)->readSettings();
4044 void Game::readSettings()
4046 m_cache_doubletap_jump = g_settings->getBool("doubletap_jump");
4047 m_cache_enable_clouds = g_settings->getBool("enable_clouds");
4048 m_cache_enable_joysticks = g_settings->getBool("enable_joysticks");
4049 m_cache_enable_particles = g_settings->getBool("enable_particles");
4050 m_cache_enable_fog = g_settings->getBool("enable_fog");
4051 m_cache_mouse_sensitivity = g_settings->getFloat("mouse_sensitivity");
4052 m_cache_joystick_frustum_sensitivity = g_settings->getFloat("joystick_frustum_sensitivity");
4053 m_repeat_right_click_time = g_settings->getFloat("repeat_rightclick_time");
4055 m_cache_enable_noclip = g_settings->getBool("noclip");
4056 m_cache_enable_free_move = g_settings->getBool("free_move");
4058 m_cache_fog_start = g_settings->getFloat("fog_start");
4060 m_cache_cam_smoothing = 0;
4061 if (g_settings->getBool("cinematic"))
4062 m_cache_cam_smoothing = 1 - g_settings->getFloat("cinematic_camera_smoothing");
4064 m_cache_cam_smoothing = 1 - g_settings->getFloat("camera_smoothing");
4066 m_cache_fog_start = rangelim(m_cache_fog_start, 0.0f, 0.99f);
4067 m_cache_cam_smoothing = rangelim(m_cache_cam_smoothing, 0.01f, 1.0f);
4068 m_cache_mouse_sensitivity = rangelim(m_cache_mouse_sensitivity, 0.001, 100.0);
4070 m_does_lost_focus_pause_game = g_settings->getBool("pause_on_lost_focus");
4073 /****************************************************************************/
4074 /****************************************************************************
4076 ****************************************************************************/
4077 /****************************************************************************/
4079 void Game::extendedResourceCleanup()
4081 // Extended resource accounting
4082 infostream << "Irrlicht resources after cleanup:" << std::endl;
4083 infostream << "\tRemaining meshes : "
4084 << RenderingEngine::get_mesh_cache()->getMeshCount() << std::endl;
4085 infostream << "\tRemaining textures : "
4086 << driver->getTextureCount() << std::endl;
4088 for (unsigned int i = 0; i < driver->getTextureCount(); i++) {
4089 irr::video::ITexture *texture = driver->getTextureByIndex(i);
4090 infostream << "\t\t" << i << ":" << texture->getName().getPath().c_str()
4094 clearTextureNameCache();
4095 infostream << "\tRemaining materials: "
4096 << driver-> getMaterialRendererCount()
4097 << " (note: irrlicht doesn't support removing renderers)" << std::endl;
4100 void Game::showDeathFormspec()
4102 static std::string formspec_str =
4103 std::string("formspec_version[1]") +
4105 "bgcolor[#320000b4;true]"
4106 "label[4.85,1.35;" + gettext("You died") + "]"
4107 "button_exit[4,3;3,0.5;btn_respawn;" + gettext("Respawn") + "]"
4111 /* Note: FormspecFormSource and LocalFormspecHandler *
4112 * are deleted by guiFormSpecMenu */
4113 FormspecFormSource *fs_src = new FormspecFormSource(formspec_str);
4114 LocalFormspecHandler *txt_dst = new LocalFormspecHandler("MT_DEATH_SCREEN", client);
4116 auto *&formspec = m_game_ui->getFormspecGUI();
4117 GUIFormSpecMenu::create(formspec, client, &input->joystick,
4118 fs_src, txt_dst, client->getFormspecPrepend());
4119 formspec->setFocus("btn_respawn");
4122 #define GET_KEY_NAME(KEY) gettext(getKeySetting(#KEY).name())
4123 void Game::showPauseMenu()
4126 static const std::string control_text = strgettext("Default Controls:\n"
4127 "No menu visible:\n"
4128 "- single tap: button activate\n"
4129 "- double tap: place/use\n"
4130 "- slide finger: look around\n"
4131 "Menu/Inventory visible:\n"
4132 "- double tap (outside):\n"
4134 "- touch stack, touch slot:\n"
4136 "- touch&drag, tap 2nd finger\n"
4137 " --> place single item to slot\n"
4140 static const std::string control_text_template = strgettext("Controls:\n"
4141 "- %s: move forwards\n"
4142 "- %s: move backwards\n"
4144 "- %s: move right\n"
4145 "- %s: jump/climb\n"
4146 "- %s: sneak/go down\n"
4149 "- Mouse: turn/look\n"
4150 "- Mouse left: dig/punch\n"
4151 "- Mouse right: place/use\n"
4152 "- Mouse wheel: select item\n"
4156 char control_text_buf[600];
4158 porting::mt_snprintf(control_text_buf, sizeof(control_text_buf), control_text_template.c_str(),
4159 GET_KEY_NAME(keymap_forward),
4160 GET_KEY_NAME(keymap_backward),
4161 GET_KEY_NAME(keymap_left),
4162 GET_KEY_NAME(keymap_right),
4163 GET_KEY_NAME(keymap_jump),
4164 GET_KEY_NAME(keymap_sneak),
4165 GET_KEY_NAME(keymap_drop),
4166 GET_KEY_NAME(keymap_inventory),
4167 GET_KEY_NAME(keymap_chat)
4170 std::string control_text = std::string(control_text_buf);
4171 str_formspec_escape(control_text);
4174 float ypos = simple_singleplayer_mode ? 0.7f : 0.1f;
4175 std::ostringstream os;
4177 os << "formspec_version[1]" << SIZE_TAG
4178 << "button_exit[4," << (ypos++) << ";3,0.5;btn_continue;"
4179 << strgettext("Continue") << "]";
4181 if (!simple_singleplayer_mode) {
4182 os << "button_exit[4," << (ypos++) << ";3,0.5;btn_change_password;"
4183 << strgettext("Change Password") << "]";
4185 os << "field[4.95,0;5,1.5;;" << strgettext("Game paused") << ";]";
4190 if (g_settings->getBool("enable_sound")) {
4191 os << "button_exit[4," << (ypos++) << ";3,0.5;btn_sound;"
4192 << strgettext("Sound Volume") << "]";
4195 os << "button_exit[4," << (ypos++) << ";3,0.5;btn_key_config;"
4196 << strgettext("Change Keys") << "]";
4198 os << "button_exit[4," << (ypos++) << ";3,0.5;btn_exit_menu;"
4199 << strgettext("Exit to Menu") << "]";
4200 os << "button_exit[4," << (ypos++) << ";3,0.5;btn_exit_os;"
4201 << strgettext("Exit to OS") << "]"
4202 << "textarea[7.5,0.25;3.9,6.25;;" << control_text << ";]"
4203 << "textarea[0.4,0.25;3.9,6.25;;" << PROJECT_NAME_C " " VERSION_STRING "\n"
4205 << strgettext("Game info:") << "\n";
4206 const std::string &address = client->getAddressName();
4207 static const std::string mode = strgettext("- Mode: ");
4208 if (!simple_singleplayer_mode) {
4209 Address serverAddress = client->getServerAddress();
4210 if (!address.empty()) {
4211 os << mode << strgettext("Remote server") << "\n"
4212 << strgettext("- Address: ") << address;
4214 os << mode << strgettext("Hosting server");
4216 os << "\n" << strgettext("- Port: ") << serverAddress.getPort() << "\n";
4218 os << mode << strgettext("Singleplayer") << "\n";
4220 if (simple_singleplayer_mode || address.empty()) {
4221 static const std::string on = strgettext("On");
4222 static const std::string off = strgettext("Off");
4223 const std::string &damage = g_settings->getBool("enable_damage") ? on : off;
4224 const std::string &creative = g_settings->getBool("creative_mode") ? on : off;
4225 const std::string &announced = g_settings->getBool("server_announce") ? on : off;
4226 os << strgettext("- Damage: ") << damage << "\n"
4227 << strgettext("- Creative Mode: ") << creative << "\n";
4228 if (!simple_singleplayer_mode) {
4229 const std::string &pvp = g_settings->getBool("enable_pvp") ? on : off;
4230 //~ PvP = Player versus Player
4231 os << strgettext("- PvP: ") << pvp << "\n"
4232 << strgettext("- Public: ") << announced << "\n";
4233 std::string server_name = g_settings->get("server_name");
4234 str_formspec_escape(server_name);
4235 if (announced == on && !server_name.empty())
4236 os << strgettext("- Server Name: ") << server_name;
4243 /* Note: FormspecFormSource and LocalFormspecHandler *
4244 * are deleted by guiFormSpecMenu */
4245 FormspecFormSource *fs_src = new FormspecFormSource(os.str());
4246 LocalFormspecHandler *txt_dst = new LocalFormspecHandler("MT_PAUSE_MENU");
4248 auto *&formspec = m_game_ui->getFormspecGUI();
4249 GUIFormSpecMenu::create(formspec, client, &input->joystick,
4250 fs_src, txt_dst, client->getFormspecPrepend());
4251 formspec->setFocus("btn_continue");
4252 formspec->doPause = true;
4255 /****************************************************************************/
4256 /****************************************************************************
4257 extern function for launching the game
4258 ****************************************************************************/
4259 /****************************************************************************/
4261 void the_game(bool *kill,
4263 InputHandler *input,
4264 const std::string &map_dir,
4265 const std::string &playername,
4266 const std::string &password,
4267 const std::string &address, // If empty local server is created
4270 std::string &error_message,
4271 ChatBackend &chat_backend,
4272 bool *reconnect_requested,
4273 const SubgameSpec &gamespec, // Used for local game
4274 bool simple_singleplayer_mode)
4278 /* Make a copy of the server address because if a local singleplayer server
4279 * is created then this is updated and we don't want to change the value
4280 * passed to us by the calling function
4282 std::string server_address = address;
4286 if (game.startup(kill, random_input, input, map_dir,
4287 playername, password, &server_address, port, error_message,
4288 reconnect_requested, &chat_backend, gamespec,
4289 simple_singleplayer_mode)) {
4293 } catch (SerializationError &e) {
4294 error_message = std::string("A serialization error occurred:\n")
4295 + e.what() + "\n\nThe server is probably "
4296 " running a different version of " PROJECT_NAME_C ".";
4297 errorstream << error_message << std::endl;
4298 } catch (ServerError &e) {
4299 error_message = e.what();
4300 errorstream << "ServerError: " << error_message << std::endl;
4301 } catch (ModError &e) {
4302 error_message = std::string("ModError: ") + e.what() +
4303 strgettext("\nCheck debug.txt for details.");
4304 errorstream << error_message << std::endl;