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;
270 SimpleSoundSpec m_player_step_sound;
271 SimpleSoundSpec m_player_leftpunch_sound;
272 SimpleSoundSpec m_player_rightpunch_sound;
274 SoundMaker(ISoundManager *sound, const NodeDefManager *ndef):
277 makes_footstep_sound(true),
278 m_player_step_timer(0)
282 void playPlayerStep()
284 if (m_player_step_timer <= 0 && m_player_step_sound.exists()) {
285 m_player_step_timer = 0.03;
286 if (makes_footstep_sound)
287 m_sound->playSound(m_player_step_sound, false);
291 static void viewBobbingStep(MtEvent *e, void *data)
293 SoundMaker *sm = (SoundMaker *)data;
294 sm->playPlayerStep();
297 static void playerRegainGround(MtEvent *e, void *data)
299 SoundMaker *sm = (SoundMaker *)data;
300 sm->playPlayerStep();
303 static void playerJump(MtEvent *e, void *data)
305 //SoundMaker *sm = (SoundMaker*)data;
308 static void cameraPunchLeft(MtEvent *e, void *data)
310 SoundMaker *sm = (SoundMaker *)data;
311 sm->m_sound->playSound(sm->m_player_leftpunch_sound, false);
314 static void cameraPunchRight(MtEvent *e, void *data)
316 SoundMaker *sm = (SoundMaker *)data;
317 sm->m_sound->playSound(sm->m_player_rightpunch_sound, false);
320 static void nodeDug(MtEvent *e, void *data)
322 SoundMaker *sm = (SoundMaker *)data;
323 NodeDugEvent *nde = (NodeDugEvent *)e;
324 sm->m_sound->playSound(sm->m_ndef->get(nde->n).sound_dug, false);
327 static void playerDamage(MtEvent *e, void *data)
329 SoundMaker *sm = (SoundMaker *)data;
330 sm->m_sound->playSound(SimpleSoundSpec("player_damage", 0.5), false);
333 static void playerFallingDamage(MtEvent *e, void *data)
335 SoundMaker *sm = (SoundMaker *)data;
336 sm->m_sound->playSound(SimpleSoundSpec("player_falling_damage", 0.5), false);
339 void registerReceiver(MtEventManager *mgr)
341 mgr->reg(MtEvent::VIEW_BOBBING_STEP, SoundMaker::viewBobbingStep, this);
342 mgr->reg(MtEvent::PLAYER_REGAIN_GROUND, SoundMaker::playerRegainGround, this);
343 mgr->reg(MtEvent::PLAYER_JUMP, SoundMaker::playerJump, this);
344 mgr->reg(MtEvent::CAMERA_PUNCH_LEFT, SoundMaker::cameraPunchLeft, this);
345 mgr->reg(MtEvent::CAMERA_PUNCH_RIGHT, SoundMaker::cameraPunchRight, this);
346 mgr->reg(MtEvent::NODE_DUG, SoundMaker::nodeDug, this);
347 mgr->reg(MtEvent::PLAYER_DAMAGE, SoundMaker::playerDamage, this);
348 mgr->reg(MtEvent::PLAYER_FALLING_DAMAGE, SoundMaker::playerFallingDamage, this);
351 void step(float dtime)
353 m_player_step_timer -= dtime;
357 // Locally stored sounds don't need to be preloaded because of this
358 class GameOnDemandSoundFetcher: public OnDemandSoundFetcher
360 std::set<std::string> m_fetched;
362 void paths_insert(std::set<std::string> &dst_paths,
363 const std::string &base,
364 const std::string &name)
366 dst_paths.insert(base + DIR_DELIM + "sounds" + DIR_DELIM + name + ".ogg");
367 dst_paths.insert(base + DIR_DELIM + "sounds" + DIR_DELIM + name + ".0.ogg");
368 dst_paths.insert(base + DIR_DELIM + "sounds" + DIR_DELIM + name + ".1.ogg");
369 dst_paths.insert(base + DIR_DELIM + "sounds" + DIR_DELIM + name + ".2.ogg");
370 dst_paths.insert(base + DIR_DELIM + "sounds" + DIR_DELIM + name + ".3.ogg");
371 dst_paths.insert(base + DIR_DELIM + "sounds" + DIR_DELIM + name + ".4.ogg");
372 dst_paths.insert(base + DIR_DELIM + "sounds" + DIR_DELIM + name + ".5.ogg");
373 dst_paths.insert(base + DIR_DELIM + "sounds" + DIR_DELIM + name + ".6.ogg");
374 dst_paths.insert(base + DIR_DELIM + "sounds" + DIR_DELIM + name + ".7.ogg");
375 dst_paths.insert(base + DIR_DELIM + "sounds" + DIR_DELIM + name + ".8.ogg");
376 dst_paths.insert(base + DIR_DELIM + "sounds" + DIR_DELIM + name + ".9.ogg");
379 void fetchSounds(const std::string &name,
380 std::set<std::string> &dst_paths,
381 std::set<std::string> &dst_datas)
383 if (m_fetched.count(name))
386 m_fetched.insert(name);
388 paths_insert(dst_paths, porting::path_share, name);
389 paths_insert(dst_paths, porting::path_user, name);
394 // before 1.8 there isn't a "integer interface", only float
395 #if (IRRLICHT_VERSION_MAJOR == 1 && IRRLICHT_VERSION_MINOR < 8)
396 typedef f32 SamplerLayer_t;
398 typedef s32 SamplerLayer_t;
402 class GameGlobalShaderConstantSetter : public IShaderConstantSetter
405 bool *m_force_fog_off;
408 CachedPixelShaderSetting<float, 4> m_sky_bg_color;
409 CachedPixelShaderSetting<float> m_fog_distance;
410 CachedVertexShaderSetting<float> m_animation_timer_vertex;
411 CachedPixelShaderSetting<float> m_animation_timer_pixel;
412 CachedPixelShaderSetting<float, 3> m_day_light;
413 CachedPixelShaderSetting<float, 3> m_eye_position_pixel;
414 CachedVertexShaderSetting<float, 3> m_eye_position_vertex;
415 CachedPixelShaderSetting<float, 3> m_minimap_yaw;
416 CachedPixelShaderSetting<float, 3> m_camera_offset_pixel;
417 CachedPixelShaderSetting<float, 3> m_camera_offset_vertex;
418 CachedPixelShaderSetting<SamplerLayer_t> m_base_texture;
419 CachedPixelShaderSetting<SamplerLayer_t> m_normal_texture;
420 CachedPixelShaderSetting<SamplerLayer_t> m_texture_flags;
424 void onSettingsChange(const std::string &name)
426 if (name == "enable_fog")
427 m_fog_enabled = g_settings->getBool("enable_fog");
430 static void settingsCallback(const std::string &name, void *userdata)
432 reinterpret_cast<GameGlobalShaderConstantSetter*>(userdata)->onSettingsChange(name);
435 void setSky(Sky *sky) { m_sky = sky; }
437 GameGlobalShaderConstantSetter(Sky *sky, bool *force_fog_off,
438 f32 *fog_range, Client *client) :
440 m_force_fog_off(force_fog_off),
441 m_fog_range(fog_range),
442 m_sky_bg_color("skyBgColor"),
443 m_fog_distance("fogDistance"),
444 m_animation_timer_vertex("animationTimer"),
445 m_animation_timer_pixel("animationTimer"),
446 m_day_light("dayLight"),
447 m_eye_position_pixel("eyePosition"),
448 m_eye_position_vertex("eyePosition"),
449 m_minimap_yaw("yawVec"),
450 m_camera_offset_pixel("cameraOffset"),
451 m_camera_offset_vertex("cameraOffset"),
452 m_base_texture("baseTexture"),
453 m_normal_texture("normalTexture"),
454 m_texture_flags("textureFlags"),
457 g_settings->registerChangedCallback("enable_fog", settingsCallback, this);
458 m_fog_enabled = g_settings->getBool("enable_fog");
461 ~GameGlobalShaderConstantSetter()
463 g_settings->deregisterChangedCallback("enable_fog", settingsCallback, this);
466 virtual void onSetConstants(video::IMaterialRendererServices *services,
473 video::SColor bgcolor = m_sky->getBgColor();
474 video::SColorf bgcolorf(bgcolor);
475 float bgcolorfa[4] = {
481 m_sky_bg_color.set(bgcolorfa, services);
484 float fog_distance = 10000 * BS;
486 if (m_fog_enabled && !*m_force_fog_off)
487 fog_distance = *m_fog_range;
489 m_fog_distance.set(&fog_distance, services);
491 u32 daynight_ratio = (float)m_client->getEnv().getDayNightRatio();
492 video::SColorf sunlight;
493 get_sunlight_color(&sunlight, daynight_ratio);
498 m_day_light.set(dnc, services);
500 u32 animation_timer = porting::getTimeMs() % 1000000;
501 float animation_timer_f = (float)animation_timer / 100000.f;
502 m_animation_timer_vertex.set(&animation_timer_f, services);
503 m_animation_timer_pixel.set(&animation_timer_f, services);
505 float eye_position_array[3];
506 v3f epos = m_client->getEnv().getLocalPlayer()->getEyePosition();
507 #if (IRRLICHT_VERSION_MAJOR == 1 && IRRLICHT_VERSION_MINOR < 8)
508 eye_position_array[0] = epos.X;
509 eye_position_array[1] = epos.Y;
510 eye_position_array[2] = epos.Z;
512 epos.getAs3Values(eye_position_array);
514 m_eye_position_pixel.set(eye_position_array, services);
515 m_eye_position_vertex.set(eye_position_array, services);
517 if (m_client->getMinimap()) {
518 float minimap_yaw_array[3];
519 v3f minimap_yaw = m_client->getMinimap()->getYawVec();
520 #if (IRRLICHT_VERSION_MAJOR == 1 && IRRLICHT_VERSION_MINOR < 8)
521 minimap_yaw_array[0] = minimap_yaw.X;
522 minimap_yaw_array[1] = minimap_yaw.Y;
523 minimap_yaw_array[2] = minimap_yaw.Z;
525 minimap_yaw.getAs3Values(minimap_yaw_array);
527 m_minimap_yaw.set(minimap_yaw_array, services);
530 float camera_offset_array[3];
531 v3f offset = intToFloat(m_client->getCamera()->getOffset(), BS);
532 #if (IRRLICHT_VERSION_MAJOR == 1 && IRRLICHT_VERSION_MINOR < 8)
533 camera_offset_array[0] = offset.X;
534 camera_offset_array[1] = offset.Y;
535 camera_offset_array[2] = offset.Z;
537 offset.getAs3Values(camera_offset_array);
539 m_camera_offset_pixel.set(camera_offset_array, services);
540 m_camera_offset_vertex.set(camera_offset_array, services);
542 SamplerLayer_t base_tex = 0,
545 m_base_texture.set(&base_tex, services);
546 m_normal_texture.set(&normal_tex, services);
547 m_texture_flags.set(&flags_tex, services);
552 class GameGlobalShaderConstantSetterFactory : public IShaderConstantSetterFactory
555 bool *m_force_fog_off;
558 std::vector<GameGlobalShaderConstantSetter *> created_nosky;
560 GameGlobalShaderConstantSetterFactory(bool *force_fog_off,
561 f32 *fog_range, Client *client) :
563 m_force_fog_off(force_fog_off),
564 m_fog_range(fog_range),
568 void setSky(Sky *sky) {
570 for (GameGlobalShaderConstantSetter *ggscs : created_nosky) {
571 ggscs->setSky(m_sky);
573 created_nosky.clear();
576 virtual IShaderConstantSetter* create()
578 GameGlobalShaderConstantSetter *scs = new GameGlobalShaderConstantSetter(
579 m_sky, m_force_fog_off, m_fog_range, m_client);
581 created_nosky.push_back(scs);
587 #define SIZE_TAG "size[11,5.5]"
589 #define SIZE_TAG "size[11,5.5,true]" // Fixed size on desktop
592 /****************************************************************************
594 ****************************************************************************/
596 const float object_hit_delay = 0.2;
599 u32 last_time, busy_time, sleep_time;
603 /* The reason the following structs are not anonymous structs within the
604 * class is that they are not used by the majority of member functions and
605 * many functions that do require objects of thse types do not modify them
606 * (so they can be passed as a const qualified parameter)
612 PointedThing pointed_old;
616 bool digging_blocked;
618 bool reset_jump_timer;
619 float nodig_delay_timer;
621 float dig_time_complete;
622 float repeat_rightclick_timer;
623 float object_hit_delay_timer;
624 float time_from_last_punch;
625 ClientActiveObject *selected_object;
629 float update_draw_list_timer;
633 v3f update_draw_list_last_cam_dir;
635 float time_of_day_smooth;
640 struct ClientEventHandler
642 void (Game::*handler)(ClientEvent *, CameraOrientation *);
645 /****************************************************************************
647 ****************************************************************************/
649 /* This is not intended to be a public class. If a public class becomes
650 * desirable then it may be better to create another 'wrapper' class that
651 * hides most of the stuff in this class (nothing in this class is required
652 * by any other file) but exposes the public methods/data only.
659 bool startup(bool *kill,
662 const std::string &map_dir,
663 const std::string &playername,
664 const std::string &password,
665 // If address is "", local server is used and address is updated
666 std::string *address,
668 std::string &error_message,
670 ChatBackend *chat_backend,
671 const SubgameSpec &gamespec, // Used for local game
672 bool simple_singleplayer_mode);
679 void extendedResourceCleanup();
681 // Basic initialisation
682 bool init(const std::string &map_dir, std::string *address,
684 const SubgameSpec &gamespec);
686 bool createSingleplayerServer(const std::string &map_dir,
687 const SubgameSpec &gamespec, u16 port, std::string *address);
690 bool createClient(const std::string &playername,
691 const std::string &password, std::string *address, u16 port);
695 bool connectToServer(const std::string &playername,
696 const std::string &password, std::string *address, u16 port,
697 bool *connect_ok, bool *aborted);
698 bool getServerContent(bool *aborted);
702 void updateInteractTimers(f32 dtime);
703 bool checkConnection();
704 bool handleCallbacks();
705 void processQueues();
706 void updateProfilers(const RunStats &stats, const FpsControl &draw_times, f32 dtime);
707 void updateStats(RunStats *stats, const FpsControl &draw_times, f32 dtime);
708 void updateProfilerGraphs(ProfilerGraph *graph);
711 void processUserInput(f32 dtime);
712 void processKeyInput();
713 void processItemSelection(u16 *new_playeritem);
715 void dropSelectedItem(bool single_item = false);
716 void openInventory();
717 void openConsole(float scale, const wchar_t *line=NULL);
718 void toggleFreeMove();
719 void toggleFreeMoveAlt();
720 void togglePitchMove();
723 void toggleCinematic();
724 void toggleAutoforward();
726 void toggleMinimap(bool shift_pressed);
729 void toggleUpdateCamera();
731 void increaseViewRange();
732 void decreaseViewRange();
733 void toggleFullViewRange();
734 void checkZoomEnabled();
736 void updateCameraDirection(CameraOrientation *cam, float dtime);
737 void updateCameraOrientation(CameraOrientation *cam, float dtime);
738 void updatePlayerControl(const CameraOrientation &cam);
739 void step(f32 *dtime);
740 void processClientEvents(CameraOrientation *cam);
741 void updateCamera(u32 busy_time, f32 dtime);
742 void updateSound(f32 dtime);
743 void processPlayerInteraction(f32 dtime, bool show_hud, bool show_debug);
745 * Returns the object or node the player is pointing at.
746 * Also updates the selected thing in the Hud.
748 * @param[in] shootline the shootline, starting from
749 * the camera position. This also gives the maximal distance
751 * @param[in] liquids_pointable if false, liquids are ignored
752 * @param[in] look_for_object if false, objects are ignored
753 * @param[in] camera_offset offset of the camera
754 * @param[out] selected_object the selected object or
757 PointedThing updatePointedThing(
758 const core::line3d<f32> &shootline, bool liquids_pointable,
759 bool look_for_object, const v3s16 &camera_offset);
760 void handlePointingAtNothing(const ItemStack &playerItem);
761 void handlePointingAtNode(const PointedThing &pointed,
762 const ItemStack &selected_item, const ItemStack &hand_item, f32 dtime);
763 void handlePointingAtObject(const PointedThing &pointed, const ItemStack &playeritem,
764 const v3f &player_position, bool show_debug);
765 void handleDigging(const PointedThing &pointed, const v3s16 &nodepos,
766 const ItemStack &selected_item, const ItemStack &hand_item, f32 dtime);
767 void updateFrame(ProfilerGraph *graph, RunStats *stats, f32 dtime,
768 const CameraOrientation &cam);
771 void limitFps(FpsControl *fps_timings, f32 *dtime);
773 void showOverlayMessage(const char *msg, float dtime, int percent,
774 bool draw_clouds = true);
776 static void settingChangedCallback(const std::string &setting_name, void *data);
779 inline bool isKeyDown(GameKeyType k)
781 return input->isKeyDown(k);
783 inline bool wasKeyDown(GameKeyType k)
785 return input->wasKeyDown(k);
789 void handleAndroidChatInput();
794 bool force_fog_off = false;
795 bool disable_camera_update = false;
798 void showDeathFormspec();
799 void showPauseMenu();
801 // ClientEvent handlers
802 void handleClientEvent_None(ClientEvent *event, CameraOrientation *cam);
803 void handleClientEvent_PlayerDamage(ClientEvent *event, CameraOrientation *cam);
804 void handleClientEvent_PlayerForceMove(ClientEvent *event, CameraOrientation *cam);
805 void handleClientEvent_Deathscreen(ClientEvent *event, CameraOrientation *cam);
806 void handleClientEvent_ShowFormSpec(ClientEvent *event, CameraOrientation *cam);
807 void handleClientEvent_ShowLocalFormSpec(ClientEvent *event, CameraOrientation *cam);
808 void handleClientEvent_HandleParticleEvent(ClientEvent *event,
809 CameraOrientation *cam);
810 void handleClientEvent_HudAdd(ClientEvent *event, CameraOrientation *cam);
811 void handleClientEvent_HudRemove(ClientEvent *event, CameraOrientation *cam);
812 void handleClientEvent_HudChange(ClientEvent *event, CameraOrientation *cam);
813 void handleClientEvent_SetSky(ClientEvent *event, CameraOrientation *cam);
814 void handleClientEvent_SetSun(ClientEvent *event, CameraOrientation *cam);
815 void handleClientEvent_SetMoon(ClientEvent *event, CameraOrientation *cam);
816 void handleClientEvent_SetStars(ClientEvent *event, CameraOrientation *cam);
817 void handleClientEvent_OverrideDayNigthRatio(ClientEvent *event,
818 CameraOrientation *cam);
819 void handleClientEvent_CloudParams(ClientEvent *event, CameraOrientation *cam);
821 void updateChat(f32 dtime, const v2u32 &screensize);
823 bool nodePlacement(const ItemDefinition &selected_def, const ItemStack &selected_item,
824 const v3s16 &nodepos, const v3s16 &neighbourpos, const PointedThing &pointed,
825 const NodeMetadata *meta);
826 static const ClientEventHandler clientEventHandler[CLIENTEVENT_MAX];
828 InputHandler *input = nullptr;
830 Client *client = nullptr;
831 Server *server = nullptr;
833 IWritableTextureSource *texture_src = nullptr;
834 IWritableShaderSource *shader_src = nullptr;
836 // When created, these will be filled with data received from the server
837 IWritableItemDefManager *itemdef_manager = nullptr;
838 NodeDefManager *nodedef_manager = nullptr;
840 GameOnDemandSoundFetcher soundfetcher; // useful when testing
841 ISoundManager *sound = nullptr;
842 bool sound_is_dummy = false;
843 SoundMaker *soundmaker = nullptr;
845 ChatBackend *chat_backend = nullptr;
847 EventManager *eventmgr = nullptr;
848 QuicktuneShortcutter *quicktune = nullptr;
849 bool registration_confirmation_shown = false;
851 std::unique_ptr<GameUI> m_game_ui;
852 GUIChatConsole *gui_chat_console = nullptr; // Free using ->Drop()
853 MapDrawControl *draw_control = nullptr;
854 Camera *camera = nullptr;
855 Clouds *clouds = nullptr; // Free using ->Drop()
856 Sky *sky = nullptr; // Free using ->Drop()
858 Minimap *mapper = nullptr;
864 This class does take ownership/responsibily for cleaning up etc of any of
865 these items (e.g. device)
867 IrrlichtDevice *device;
868 video::IVideoDriver *driver;
869 scene::ISceneManager *smgr;
871 std::string *error_message;
872 bool *reconnect_requested;
873 scene::ISceneNode *skybox;
876 bool simple_singleplayer_mode;
879 /* Pre-calculated values
881 int crack_animation_length;
883 IntervalLimiter profiler_interval;
886 * TODO: Local caching of settings is not optimal and should at some stage
887 * be updated to use a global settings object for getting thse values
888 * (as opposed to the this local caching). This can be addressed in
891 bool m_cache_doubletap_jump;
892 bool m_cache_enable_clouds;
893 bool m_cache_enable_joysticks;
894 bool m_cache_enable_particles;
895 bool m_cache_enable_fog;
896 bool m_cache_enable_noclip;
897 bool m_cache_enable_free_move;
898 f32 m_cache_mouse_sensitivity;
899 f32 m_cache_joystick_frustum_sensitivity;
900 f32 m_repeat_right_click_time;
901 f32 m_cache_cam_smoothing;
902 f32 m_cache_fog_start;
904 bool m_invert_mouse = false;
905 bool m_first_loop_after_window_activation = false;
906 bool m_camera_offset_changed = false;
908 bool m_does_lost_focus_pause_game = false;
911 bool m_cache_hold_aux1;
912 bool m_android_chat_open;
917 m_game_ui(new GameUI())
919 g_settings->registerChangedCallback("doubletap_jump",
920 &settingChangedCallback, this);
921 g_settings->registerChangedCallback("enable_clouds",
922 &settingChangedCallback, this);
923 g_settings->registerChangedCallback("doubletap_joysticks",
924 &settingChangedCallback, this);
925 g_settings->registerChangedCallback("enable_particles",
926 &settingChangedCallback, this);
927 g_settings->registerChangedCallback("enable_fog",
928 &settingChangedCallback, this);
929 g_settings->registerChangedCallback("mouse_sensitivity",
930 &settingChangedCallback, this);
931 g_settings->registerChangedCallback("joystick_frustum_sensitivity",
932 &settingChangedCallback, this);
933 g_settings->registerChangedCallback("repeat_rightclick_time",
934 &settingChangedCallback, this);
935 g_settings->registerChangedCallback("noclip",
936 &settingChangedCallback, this);
937 g_settings->registerChangedCallback("free_move",
938 &settingChangedCallback, this);
939 g_settings->registerChangedCallback("cinematic",
940 &settingChangedCallback, this);
941 g_settings->registerChangedCallback("cinematic_camera_smoothing",
942 &settingChangedCallback, this);
943 g_settings->registerChangedCallback("camera_smoothing",
944 &settingChangedCallback, this);
949 m_cache_hold_aux1 = false; // This is initialised properly later
956 /****************************************************************************
958 ****************************************************************************/
967 delete server; // deleted first to stop all server threads
975 delete nodedef_manager;
976 delete itemdef_manager;
979 extendedResourceCleanup();
981 g_settings->deregisterChangedCallback("doubletap_jump",
982 &settingChangedCallback, this);
983 g_settings->deregisterChangedCallback("enable_clouds",
984 &settingChangedCallback, this);
985 g_settings->deregisterChangedCallback("enable_particles",
986 &settingChangedCallback, this);
987 g_settings->deregisterChangedCallback("enable_fog",
988 &settingChangedCallback, this);
989 g_settings->deregisterChangedCallback("mouse_sensitivity",
990 &settingChangedCallback, this);
991 g_settings->deregisterChangedCallback("repeat_rightclick_time",
992 &settingChangedCallback, this);
993 g_settings->deregisterChangedCallback("noclip",
994 &settingChangedCallback, this);
995 g_settings->deregisterChangedCallback("free_move",
996 &settingChangedCallback, this);
997 g_settings->deregisterChangedCallback("cinematic",
998 &settingChangedCallback, this);
999 g_settings->deregisterChangedCallback("cinematic_camera_smoothing",
1000 &settingChangedCallback, this);
1001 g_settings->deregisterChangedCallback("camera_smoothing",
1002 &settingChangedCallback, this);
1005 bool Game::startup(bool *kill,
1007 InputHandler *input,
1008 const std::string &map_dir,
1009 const std::string &playername,
1010 const std::string &password,
1011 std::string *address, // can change if simple_singleplayer_mode
1013 std::string &error_message,
1015 ChatBackend *chat_backend,
1016 const SubgameSpec &gamespec,
1017 bool simple_singleplayer_mode)
1020 this->device = RenderingEngine::get_raw_device();
1022 this->error_message = &error_message;
1023 this->reconnect_requested = reconnect;
1024 this->random_input = random_input;
1025 this->input = input;
1026 this->chat_backend = chat_backend;
1027 this->simple_singleplayer_mode = simple_singleplayer_mode;
1029 input->keycache.populate();
1031 driver = device->getVideoDriver();
1032 smgr = RenderingEngine::get_scene_manager();
1034 RenderingEngine::get_scene_manager()->getParameters()->
1035 setAttribute(scene::OBJ_LOADER_IGNORE_MATERIAL_FILES, true);
1038 runData = GameRunData();
1039 runData.time_from_last_punch = 10.0;
1041 m_game_ui->initFlags();
1043 m_invert_mouse = g_settings->getBool("invert_mouse");
1044 m_first_loop_after_window_activation = true;
1046 g_translations->clear();
1048 if (!init(map_dir, address, port, gamespec))
1051 if (!createClient(playername, password, address, port))
1054 RenderingEngine::initialize(client, hud);
1062 ProfilerGraph graph;
1063 RunStats stats = { 0 };
1064 CameraOrientation cam_view_target = { 0 };
1065 CameraOrientation cam_view = { 0 };
1066 FpsControl draw_times = { 0 };
1067 f32 dtime; // in seconds
1069 /* Clear the profiler */
1070 Profiler::GraphValues dummyvalues;
1071 g_profiler->graphGet(dummyvalues);
1073 draw_times.last_time = RenderingEngine::get_timer_time();
1075 set_light_table(g_settings->getFloat("display_gamma"));
1078 m_cache_hold_aux1 = g_settings->getBool("fast_move")
1079 && client->checkPrivilege("fast");
1082 irr::core::dimension2d<u32> previous_screen_size(g_settings->getU16("screen_w"),
1083 g_settings->getU16("screen_h"));
1085 while (RenderingEngine::run()
1086 && !(*kill || g_gamecallback->shutdown_requested
1087 || (server && server->isShutdownRequested()))) {
1089 const irr::core::dimension2d<u32> ¤t_screen_size =
1090 RenderingEngine::get_video_driver()->getScreenSize();
1091 // Verify if window size has changed and save it if it's the case
1092 // Ensure evaluating settings->getBool after verifying screensize
1093 // First condition is cheaper
1094 if (previous_screen_size != current_screen_size &&
1095 current_screen_size != irr::core::dimension2d<u32>(0,0) &&
1096 g_settings->getBool("autosave_screensize")) {
1097 g_settings->setU16("screen_w", current_screen_size.Width);
1098 g_settings->setU16("screen_h", current_screen_size.Height);
1099 previous_screen_size = current_screen_size;
1102 // Calculate dtime =
1103 // RenderingEngine::run() from this iteration
1104 // + Sleep time until the wanted FPS are reached
1105 limitFps(&draw_times, &dtime);
1107 // Prepare render data for next iteration
1109 updateStats(&stats, draw_times, dtime);
1110 updateInteractTimers(dtime);
1112 if (!checkConnection())
1114 if (!handleCallbacks())
1119 m_game_ui->clearInfoText();
1120 hud->resizeHotbar();
1122 updateProfilers(stats, draw_times, dtime);
1123 processUserInput(dtime);
1124 // Update camera before player movement to avoid camera lag of one frame
1125 updateCameraDirection(&cam_view_target, dtime);
1126 cam_view.camera_yaw += (cam_view_target.camera_yaw -
1127 cam_view.camera_yaw) * m_cache_cam_smoothing;
1128 cam_view.camera_pitch += (cam_view_target.camera_pitch -
1129 cam_view.camera_pitch) * m_cache_cam_smoothing;
1130 updatePlayerControl(cam_view);
1132 processClientEvents(&cam_view_target);
1133 updateCamera(draw_times.busy_time, dtime);
1135 processPlayerInteraction(dtime, m_game_ui->m_flags.show_hud,
1136 m_game_ui->m_flags.show_debug);
1137 updateFrame(&graph, &stats, dtime, cam_view);
1138 updateProfilerGraphs(&graph);
1140 // Update if minimap has been disabled by the server
1141 m_game_ui->m_flags.show_minimap &= client->shouldShowMinimap();
1143 if (m_does_lost_focus_pause_game && !device->isWindowFocused() && !isMenuActive()) {
1150 void Game::shutdown()
1152 RenderingEngine::finalize();
1153 #if IRRLICHT_VERSION_MAJOR == 1 && IRRLICHT_VERSION_MINOR <= 8
1154 if (g_settings->get("3d_mode") == "pageflip") {
1155 driver->setRenderTarget(irr::video::ERT_STEREO_BOTH_BUFFERS);
1158 auto formspec = m_game_ui->getFormspecGUI();
1160 formspec->quitMenu();
1162 showOverlayMessage(N_("Shutting down..."), 0, 0, false);
1167 if (gui_chat_console)
1168 gui_chat_console->drop();
1174 while (g_menumgr.menuCount() > 0) {
1175 g_menumgr.m_stack.front()->setVisible(false);
1176 g_menumgr.deletingMenu(g_menumgr.m_stack.front());
1179 m_game_ui->deleteFormspec();
1181 chat_backend->addMessage(L"", L"# Disconnected.");
1182 chat_backend->addMessage(L"", L"");
1186 while (!client->isShutdown()) {
1187 assert(texture_src != NULL);
1188 assert(shader_src != NULL);
1189 texture_src->processQueue();
1190 shader_src->processQueue();
1197 /****************************************************************************/
1198 /****************************************************************************
1200 ****************************************************************************/
1201 /****************************************************************************/
1204 const std::string &map_dir,
1205 std::string *address,
1207 const SubgameSpec &gamespec)
1209 texture_src = createTextureSource();
1211 showOverlayMessage(N_("Loading..."), 0, 0);
1213 shader_src = createShaderSource();
1215 itemdef_manager = createItemDefManager();
1216 nodedef_manager = createNodeDefManager();
1218 eventmgr = new EventManager();
1219 quicktune = new QuicktuneShortcutter();
1221 if (!(texture_src && shader_src && itemdef_manager && nodedef_manager
1222 && eventmgr && quicktune))
1228 // Create a server if not connecting to an existing one
1229 if (address->empty()) {
1230 if (!createSingleplayerServer(map_dir, gamespec, port, address))
1237 bool Game::initSound()
1240 if (g_settings->getBool("enable_sound")) {
1241 infostream << "Attempting to use OpenAL audio" << std::endl;
1242 sound = createOpenALSoundManager(g_sound_manager_singleton.get(), &soundfetcher);
1244 infostream << "Failed to initialize OpenAL audio" << std::endl;
1246 infostream << "Sound disabled." << std::endl;
1250 infostream << "Using dummy audio." << std::endl;
1251 sound = &dummySoundManager;
1252 sound_is_dummy = true;
1255 soundmaker = new SoundMaker(sound, nodedef_manager);
1259 soundmaker->registerReceiver(eventmgr);
1264 bool Game::createSingleplayerServer(const std::string &map_dir,
1265 const SubgameSpec &gamespec, u16 port, std::string *address)
1267 showOverlayMessage(N_("Creating server..."), 0, 5);
1269 std::string bind_str = g_settings->get("bind_address");
1270 Address bind_addr(0, 0, 0, 0, port);
1272 if (g_settings->getBool("ipv6_server")) {
1273 bind_addr.setAddress((IPv6AddressBytes *) NULL);
1277 bind_addr.Resolve(bind_str.c_str());
1278 } catch (ResolveError &e) {
1279 infostream << "Resolving bind address \"" << bind_str
1280 << "\" failed: " << e.what()
1281 << " -- Listening on all addresses." << std::endl;
1284 if (bind_addr.isIPv6() && !g_settings->getBool("enable_ipv6")) {
1285 *error_message = "Unable to listen on " +
1286 bind_addr.serializeString() +
1287 " because IPv6 is disabled";
1288 errorstream << *error_message << std::endl;
1292 server = new Server(map_dir, gamespec, simple_singleplayer_mode, bind_addr, false);
1299 bool Game::createClient(const std::string &playername,
1300 const std::string &password, std::string *address, u16 port)
1302 showOverlayMessage(N_("Creating client..."), 0, 10);
1304 draw_control = new MapDrawControl;
1308 bool could_connect, connect_aborted;
1309 #ifdef HAVE_TOUCHSCREENGUI
1310 if (g_touchscreengui) {
1311 g_touchscreengui->init(texture_src);
1312 g_touchscreengui->hide();
1315 if (!connectToServer(playername, password, address, port,
1316 &could_connect, &connect_aborted))
1319 if (!could_connect) {
1320 if (error_message->empty() && !connect_aborted) {
1321 // Should not happen if error messages are set properly
1322 *error_message = "Connection failed for unknown reason";
1323 errorstream << *error_message << std::endl;
1328 if (!getServerContent(&connect_aborted)) {
1329 if (error_message->empty() && !connect_aborted) {
1330 // Should not happen if error messages are set properly
1331 *error_message = "Connection failed for unknown reason";
1332 errorstream << *error_message << std::endl;
1337 GameGlobalShaderConstantSetterFactory *scsf = new GameGlobalShaderConstantSetterFactory(
1338 &m_flags.force_fog_off, &runData.fog_range, client);
1339 shader_src->addShaderConstantSetterFactory(scsf);
1341 // Update cached textures, meshes and materials
1342 client->afterContentReceived();
1346 camera = new Camera(*draw_control, client);
1347 if (!camera || !camera->successfullyCreated(*error_message))
1349 client->setCamera(camera);
1353 if (m_cache_enable_clouds) {
1354 clouds = new Clouds(smgr, -1, time(0));
1356 *error_message = "Memory allocation error (clouds)";
1357 errorstream << *error_message << std::endl;
1364 sky = new Sky(-1, texture_src);
1366 skybox = NULL; // This is used/set later on in the main run loop
1369 *error_message = "Memory allocation error sky";
1370 errorstream << *error_message << std::endl;
1374 /* Pre-calculated values
1376 video::ITexture *t = texture_src->getTexture("crack_anylength.png");
1378 v2u32 size = t->getOriginalSize();
1379 crack_animation_length = size.Y / size.X;
1381 crack_animation_length = 5;
1387 /* Set window caption
1389 std::wstring str = utf8_to_wide(PROJECT_NAME_C);
1391 str += utf8_to_wide(g_version_hash);
1393 str += driver->getName();
1395 device->setWindowCaption(str.c_str());
1397 LocalPlayer *player = client->getEnv().getLocalPlayer();
1398 player->hurt_tilt_timer = 0;
1399 player->hurt_tilt_strength = 0;
1401 hud = new Hud(guienv, client, player, &player->inventory);
1404 *error_message = "Memory error: could not create HUD";
1405 errorstream << *error_message << std::endl;
1409 mapper = client->getMinimap();
1411 mapper->setMinimapMode(MINIMAP_MODE_OFF);
1416 bool Game::initGui()
1420 // Remove stale "recent" chat messages from previous connections
1421 chat_backend->clearRecentChat();
1423 // Make sure the size of the recent messages buffer is right
1424 chat_backend->applySettings();
1426 // Chat backend and console
1427 gui_chat_console = new GUIChatConsole(guienv, guienv->getRootGUIElement(),
1428 -1, chat_backend, client, &g_menumgr);
1429 if (!gui_chat_console) {
1430 *error_message = "Could not allocate memory for chat console";
1431 errorstream << *error_message << std::endl;
1435 #ifdef HAVE_TOUCHSCREENGUI
1437 if (g_touchscreengui)
1438 g_touchscreengui->show();
1445 bool Game::connectToServer(const std::string &playername,
1446 const std::string &password, std::string *address, u16 port,
1447 bool *connect_ok, bool *connection_aborted)
1449 *connect_ok = false; // Let's not be overly optimistic
1450 *connection_aborted = false;
1451 bool local_server_mode = false;
1453 showOverlayMessage(N_("Resolving address..."), 0, 15);
1455 Address connect_address(0, 0, 0, 0, port);
1458 connect_address.Resolve(address->c_str());
1460 if (connect_address.isZero()) { // i.e. INADDR_ANY, IN6ADDR_ANY
1461 //connect_address.Resolve("localhost");
1462 if (connect_address.isIPv6()) {
1463 IPv6AddressBytes addr_bytes;
1464 addr_bytes.bytes[15] = 1;
1465 connect_address.setAddress(&addr_bytes);
1467 connect_address.setAddress(127, 0, 0, 1);
1469 local_server_mode = true;
1471 } catch (ResolveError &e) {
1472 *error_message = std::string("Couldn't resolve address: ") + e.what();
1473 errorstream << *error_message << std::endl;
1477 if (connect_address.isIPv6() && !g_settings->getBool("enable_ipv6")) {
1478 *error_message = "Unable to connect to " +
1479 connect_address.serializeString() +
1480 " because IPv6 is disabled";
1481 errorstream << *error_message << std::endl;
1485 client = new Client(playername.c_str(), password, *address,
1486 *draw_control, texture_src, shader_src,
1487 itemdef_manager, nodedef_manager, sound, eventmgr,
1488 connect_address.isIPv6(), m_game_ui.get());
1493 client->m_simple_singleplayer_mode = simple_singleplayer_mode;
1495 infostream << "Connecting to server at ";
1496 connect_address.print(&infostream);
1497 infostream << std::endl;
1499 client->connect(connect_address,
1500 simple_singleplayer_mode || local_server_mode);
1503 Wait for server to accept connection
1509 FpsControl fps_control = { 0 };
1511 f32 wait_time = 0; // in seconds
1513 fps_control.last_time = RenderingEngine::get_timer_time();
1515 while (RenderingEngine::run()) {
1517 limitFps(&fps_control, &dtime);
1519 // Update client and server
1520 client->step(dtime);
1523 server->step(dtime);
1526 if (client->getState() == LC_Init) {
1532 if (*connection_aborted)
1535 if (client->accessDenied()) {
1536 *error_message = "Access denied. Reason: "
1537 + client->accessDeniedReason();
1538 *reconnect_requested = client->reconnectRequested();
1539 errorstream << *error_message << std::endl;
1543 if (input->cancelPressed()) {
1544 *connection_aborted = true;
1545 infostream << "Connect aborted [Escape]" << std::endl;
1549 if (client->m_is_registration_confirmation_state) {
1550 if (registration_confirmation_shown) {
1551 // Keep drawing the GUI
1552 RenderingEngine::draw_menu_scene(guienv, dtime, true);
1554 registration_confirmation_shown = true;
1555 (new GUIConfirmRegistration(guienv, guienv->getRootGUIElement(), -1,
1556 &g_menumgr, client, playername, password, connection_aborted))->drop();
1560 // Only time out if we aren't waiting for the server we started
1561 if (!address->empty() && wait_time > 10) {
1562 *error_message = "Connection timed out.";
1563 errorstream << *error_message << std::endl;
1568 showOverlayMessage(N_("Connecting to server..."), dtime, 20);
1571 } catch (con::PeerNotFoundException &e) {
1572 // TODO: Should something be done here? At least an info/error
1580 bool Game::getServerContent(bool *aborted)
1584 FpsControl fps_control = { 0 };
1585 f32 dtime; // in seconds
1587 fps_control.last_time = RenderingEngine::get_timer_time();
1589 while (RenderingEngine::run()) {
1591 limitFps(&fps_control, &dtime);
1593 // Update client and server
1594 client->step(dtime);
1597 server->step(dtime);
1600 if (client->mediaReceived() && client->itemdefReceived() &&
1601 client->nodedefReceived()) {
1606 if (!checkConnection())
1609 if (client->getState() < LC_Init) {
1610 *error_message = "Client disconnected";
1611 errorstream << *error_message << std::endl;
1615 if (input->cancelPressed()) {
1617 infostream << "Connect aborted [Escape]" << std::endl;
1624 if (!client->itemdefReceived()) {
1625 const wchar_t *text = wgettext("Item definitions...");
1627 RenderingEngine::draw_load_screen(text, guienv, texture_src,
1630 } else if (!client->nodedefReceived()) {
1631 const wchar_t *text = wgettext("Node definitions...");
1633 RenderingEngine::draw_load_screen(text, guienv, texture_src,
1637 std::stringstream message;
1638 std::fixed(message);
1639 message.precision(0);
1640 message << gettext("Media...") << " " << (client->mediaReceiveProgress()*100) << "%";
1641 message.precision(2);
1643 if ((USE_CURL == 0) ||
1644 (!g_settings->getBool("enable_remote_media_server"))) {
1645 float cur = client->getCurRate();
1646 std::string cur_unit = gettext("KiB/s");
1650 cur_unit = gettext("MiB/s");
1653 message << " (" << cur << ' ' << cur_unit << ")";
1656 progress = 30 + client->mediaReceiveProgress() * 35 + 0.5;
1657 RenderingEngine::draw_load_screen(utf8_to_wide(message.str()), guienv,
1658 texture_src, dtime, progress);
1666 /****************************************************************************/
1667 /****************************************************************************
1669 ****************************************************************************/
1670 /****************************************************************************/
1672 inline void Game::updateInteractTimers(f32 dtime)
1674 if (runData.nodig_delay_timer >= 0)
1675 runData.nodig_delay_timer -= dtime;
1677 if (runData.object_hit_delay_timer >= 0)
1678 runData.object_hit_delay_timer -= dtime;
1680 runData.time_from_last_punch += dtime;
1684 /* returns false if game should exit, otherwise true
1686 inline bool Game::checkConnection()
1688 if (client->accessDenied()) {
1689 *error_message = "Access denied. Reason: "
1690 + client->accessDeniedReason();
1691 *reconnect_requested = client->reconnectRequested();
1692 errorstream << *error_message << std::endl;
1700 /* returns false if game should exit, otherwise true
1702 inline bool Game::handleCallbacks()
1704 if (g_gamecallback->disconnect_requested) {
1705 g_gamecallback->disconnect_requested = false;
1709 if (g_gamecallback->changepassword_requested) {
1710 (new GUIPasswordChange(guienv, guiroot, -1,
1711 &g_menumgr, client))->drop();
1712 g_gamecallback->changepassword_requested = false;
1715 if (g_gamecallback->changevolume_requested) {
1716 (new GUIVolumeChange(guienv, guiroot, -1,
1717 &g_menumgr))->drop();
1718 g_gamecallback->changevolume_requested = false;
1721 if (g_gamecallback->keyconfig_requested) {
1722 (new GUIKeyChangeMenu(guienv, guiroot, -1,
1723 &g_menumgr))->drop();
1724 g_gamecallback->keyconfig_requested = false;
1727 if (g_gamecallback->keyconfig_changed) {
1728 input->keycache.populate(); // update the cache with new settings
1729 g_gamecallback->keyconfig_changed = false;
1736 void Game::processQueues()
1738 texture_src->processQueue();
1739 itemdef_manager->processQueue(client);
1740 shader_src->processQueue();
1744 void Game::updateProfilers(const RunStats &stats, const FpsControl &draw_times,
1747 float profiler_print_interval =
1748 g_settings->getFloat("profiler_print_interval");
1749 bool print_to_log = true;
1751 if (profiler_print_interval == 0) {
1752 print_to_log = false;
1753 profiler_print_interval = 3;
1756 if (profiler_interval.step(dtime, profiler_print_interval)) {
1758 infostream << "Profiler:" << std::endl;
1759 g_profiler->print(infostream);
1762 m_game_ui->updateProfiler();
1763 g_profiler->clear();
1766 // Update update graphs
1767 g_profiler->graphAdd("Time non-rendering [ms]",
1768 draw_times.busy_time - stats.drawtime);
1770 g_profiler->graphAdd("Sleep [ms]", draw_times.sleep_time);
1771 g_profiler->graphAdd("FPS", 1.0f / dtime);
1774 void Game::updateStats(RunStats *stats, const FpsControl &draw_times,
1781 /* Time average and jitter calculation
1783 jp = &stats->dtime_jitter;
1784 jp->avg = jp->avg * 0.96 + dtime * 0.04;
1786 jitter = dtime - jp->avg;
1788 if (jitter > jp->max)
1791 jp->counter += dtime;
1793 if (jp->counter > 0.0) {
1795 jp->max_sample = jp->max;
1796 jp->max_fraction = jp->max_sample / (jp->avg + 0.001);
1800 /* Busytime average and jitter calculation
1802 jp = &stats->busy_time_jitter;
1803 jp->avg = jp->avg + draw_times.busy_time * 0.02;
1805 jitter = draw_times.busy_time - jp->avg;
1807 if (jitter > jp->max)
1809 if (jitter < jp->min)
1812 jp->counter += dtime;
1814 if (jp->counter > 0.0) {
1816 jp->max_sample = jp->max;
1817 jp->min_sample = jp->min;
1825 /****************************************************************************
1827 ****************************************************************************/
1829 void Game::processUserInput(f32 dtime)
1831 // Reset input if window not active or some menu is active
1832 if (!device->isWindowActive() || isMenuActive() || guienv->hasFocus(gui_chat_console)) {
1834 #ifdef HAVE_TOUCHSCREENGUI
1835 g_touchscreengui->hide();
1838 #ifdef HAVE_TOUCHSCREENGUI
1839 else if (g_touchscreengui) {
1840 /* on touchscreengui step may generate own input events which ain't
1841 * what we want in case we just did clear them */
1842 g_touchscreengui->step(dtime);
1846 if (!guienv->hasFocus(gui_chat_console) && gui_chat_console->isOpen()) {
1847 gui_chat_console->closeConsoleAtOnce();
1850 // Input handler step() (used by the random input generator)
1854 auto formspec = m_game_ui->getFormspecGUI();
1856 formspec->getAndroidUIInput();
1858 handleAndroidChatInput();
1861 // Increase timer for double tap of "keymap_jump"
1862 if (m_cache_doubletap_jump && runData.jump_timer <= 0.2f)
1863 runData.jump_timer += dtime;
1866 processItemSelection(&runData.new_playeritem);
1870 void Game::processKeyInput()
1872 if (wasKeyDown(KeyType::DROP)) {
1873 dropSelectedItem(isKeyDown(KeyType::SNEAK));
1874 } else if (wasKeyDown(KeyType::AUTOFORWARD)) {
1875 toggleAutoforward();
1876 } else if (wasKeyDown(KeyType::BACKWARD)) {
1877 if (g_settings->getBool("continuous_forward"))
1878 toggleAutoforward();
1879 } else if (wasKeyDown(KeyType::INVENTORY)) {
1881 } else if (input->cancelPressed()) {
1883 m_android_chat_open = false;
1885 if (!gui_chat_console->isOpenInhibited()) {
1888 } else if (wasKeyDown(KeyType::CHAT)) {
1889 openConsole(0.2, L"");
1890 } else if (wasKeyDown(KeyType::CMD)) {
1891 openConsole(0.2, L"/");
1892 } else if (wasKeyDown(KeyType::CMD_LOCAL)) {
1893 if (client->modsLoaded())
1894 openConsole(0.2, L".");
1896 m_game_ui->showStatusText(wgettext("Client side scripting is disabled"));
1897 } else if (wasKeyDown(KeyType::CONSOLE)) {
1898 openConsole(core::clamp(g_settings->getFloat("console_height"), 0.1f, 1.0f));
1899 } else if (wasKeyDown(KeyType::FREEMOVE)) {
1901 } else if (wasKeyDown(KeyType::JUMP)) {
1902 toggleFreeMoveAlt();
1903 } else if (wasKeyDown(KeyType::PITCHMOVE)) {
1905 } else if (wasKeyDown(KeyType::FASTMOVE)) {
1907 } else if (wasKeyDown(KeyType::NOCLIP)) {
1909 } else if (wasKeyDown(KeyType::MUTE)) {
1910 bool new_mute_sound = !g_settings->getBool("mute_sound");
1911 g_settings->setBool("mute_sound", new_mute_sound);
1913 m_game_ui->showTranslatedStatusText("Sound muted");
1915 m_game_ui->showTranslatedStatusText("Sound unmuted");
1916 } else if (wasKeyDown(KeyType::INC_VOLUME)) {
1917 float new_volume = rangelim(g_settings->getFloat("sound_volume") + 0.1f, 0.0f, 1.0f);
1919 g_settings->setFloat("sound_volume", new_volume);
1920 const wchar_t *str = wgettext("Volume changed to %d%%");
1921 swprintf(buf, sizeof(buf) / sizeof(wchar_t), str, myround(new_volume * 100));
1923 m_game_ui->showStatusText(buf);
1924 } else if (wasKeyDown(KeyType::DEC_VOLUME)) {
1925 float new_volume = rangelim(g_settings->getFloat("sound_volume") - 0.1f, 0.0f, 1.0f);
1927 g_settings->setFloat("sound_volume", new_volume);
1928 const wchar_t *str = wgettext("Volume changed to %d%%");
1929 swprintf(buf, sizeof(buf) / sizeof(wchar_t), str, myround(new_volume * 100));
1931 m_game_ui->showStatusText(buf);
1932 } else if (wasKeyDown(KeyType::CINEMATIC)) {
1934 } else if (wasKeyDown(KeyType::SCREENSHOT)) {
1935 client->makeScreenshot();
1936 } else if (wasKeyDown(KeyType::TOGGLE_HUD)) {
1937 m_game_ui->toggleHud();
1938 } else if (wasKeyDown(KeyType::MINIMAP)) {
1939 toggleMinimap(isKeyDown(KeyType::SNEAK));
1940 } else if (wasKeyDown(KeyType::TOGGLE_CHAT)) {
1941 m_game_ui->toggleChat();
1942 } else if (wasKeyDown(KeyType::TOGGLE_FOG)) {
1944 } else if (wasKeyDown(KeyType::TOGGLE_UPDATE_CAMERA)) {
1945 toggleUpdateCamera();
1946 } else if (wasKeyDown(KeyType::TOGGLE_DEBUG)) {
1948 } else if (wasKeyDown(KeyType::TOGGLE_PROFILER)) {
1949 m_game_ui->toggleProfiler();
1950 } else if (wasKeyDown(KeyType::INCREASE_VIEWING_RANGE)) {
1951 increaseViewRange();
1952 } else if (wasKeyDown(KeyType::DECREASE_VIEWING_RANGE)) {
1953 decreaseViewRange();
1954 } else if (wasKeyDown(KeyType::RANGESELECT)) {
1955 toggleFullViewRange();
1956 } else if (wasKeyDown(KeyType::ZOOM)) {
1958 } else if (wasKeyDown(KeyType::QUICKTUNE_NEXT)) {
1960 } else if (wasKeyDown(KeyType::QUICKTUNE_PREV)) {
1962 } else if (wasKeyDown(KeyType::QUICKTUNE_INC)) {
1964 } else if (wasKeyDown(KeyType::QUICKTUNE_DEC)) {
1968 if (!isKeyDown(KeyType::JUMP) && runData.reset_jump_timer) {
1969 runData.reset_jump_timer = false;
1970 runData.jump_timer = 0.0f;
1973 if (quicktune->hasMessage()) {
1974 m_game_ui->showStatusText(utf8_to_wide(quicktune->getMessage()));
1978 void Game::processItemSelection(u16 *new_playeritem)
1980 LocalPlayer *player = client->getEnv().getLocalPlayer();
1982 /* Item selection using mouse wheel
1984 *new_playeritem = player->getWieldIndex();
1986 s32 wheel = input->getMouseWheel();
1987 u16 max_item = MYMIN(PLAYER_INVENTORY_SIZE - 1,
1988 player->hud_hotbar_itemcount - 1);
1992 if (input->joystick.wasKeyDown(KeyType::SCROLL_DOWN) ||
1993 wasKeyDown(KeyType::HOTBAR_NEXT)) {
1997 if (input->joystick.wasKeyDown(KeyType::SCROLL_UP) ||
1998 wasKeyDown(KeyType::HOTBAR_PREV)) {
2003 *new_playeritem = *new_playeritem < max_item ? *new_playeritem + 1 : 0;
2005 *new_playeritem = *new_playeritem > 0 ? *new_playeritem - 1 : max_item;
2008 /* Item selection using hotbar slot keys
2010 for (u16 i = 0; i <= max_item; i++) {
2011 if (wasKeyDown((GameKeyType) (KeyType::SLOT_1 + i))) {
2012 *new_playeritem = i;
2013 infostream << "Selected item: " << new_playeritem << std::endl;
2020 void Game::dropSelectedItem(bool single_item)
2022 IDropAction *a = new IDropAction();
2023 a->count = single_item ? 1 : 0;
2024 a->from_inv.setCurrentPlayer();
2025 a->from_list = "main";
2026 a->from_i = client->getEnv().getLocalPlayer()->getWieldIndex();
2027 client->inventoryAction(a);
2031 void Game::openInventory()
2034 * Don't permit to open inventory is CAO or player doesn't exists.
2035 * This prevent showing an empty inventory at player load
2038 LocalPlayer *player = client->getEnv().getLocalPlayer();
2039 if (!player || !player->getCAO())
2042 infostream << "the_game: " << "Launching inventory" << std::endl;
2044 PlayerInventoryFormSource *fs_src = new PlayerInventoryFormSource(client);
2046 InventoryLocation inventoryloc;
2047 inventoryloc.setCurrentPlayer();
2049 if (!client->modsLoaded()
2050 || !client->getScript()->on_inventory_open(fs_src->m_client->getInventory(inventoryloc))) {
2051 TextDest *txt_dst = new TextDestPlayerInventory(client);
2052 auto *&formspec = m_game_ui->updateFormspec("");
2053 GUIFormSpecMenu::create(formspec, client, &input->joystick, fs_src,
2054 txt_dst, client->getFormspecPrepend());
2056 formspec->setFormSpec(fs_src->getForm(), inventoryloc);
2061 void Game::openConsole(float scale, const wchar_t *line)
2063 assert(scale > 0.0f && scale <= 1.0f);
2066 porting::showInputDialog(gettext("ok"), "", "", 2);
2067 m_android_chat_open = true;
2069 if (gui_chat_console->isOpenInhibited())
2071 gui_chat_console->openConsole(scale);
2073 gui_chat_console->setCloseOnEnter(true);
2074 gui_chat_console->replaceAndAddToHistory(line);
2080 void Game::handleAndroidChatInput()
2082 if (m_android_chat_open && porting::getInputDialogState() == 0) {
2083 std::string text = porting::getInputDialogValue();
2084 client->typeChatMessage(utf8_to_wide(text));
2085 m_android_chat_open = false;
2091 void Game::toggleFreeMove()
2093 bool free_move = !g_settings->getBool("free_move");
2094 g_settings->set("free_move", bool_to_cstr(free_move));
2097 if (client->checkPrivilege("fly")) {
2098 m_game_ui->showTranslatedStatusText("Fly mode enabled");
2100 m_game_ui->showTranslatedStatusText("Fly mode enabled (note: no 'fly' privilege)");
2103 m_game_ui->showTranslatedStatusText("Fly mode disabled");
2107 void Game::toggleFreeMoveAlt()
2109 if (m_cache_doubletap_jump && runData.jump_timer < 0.2f)
2112 runData.reset_jump_timer = true;
2116 void Game::togglePitchMove()
2118 bool pitch_move = !g_settings->getBool("pitch_move");
2119 g_settings->set("pitch_move", bool_to_cstr(pitch_move));
2122 m_game_ui->showTranslatedStatusText("Pitch move mode enabled");
2124 m_game_ui->showTranslatedStatusText("Pitch move mode disabled");
2129 void Game::toggleFast()
2131 bool fast_move = !g_settings->getBool("fast_move");
2132 bool has_fast_privs = client->checkPrivilege("fast");
2133 g_settings->set("fast_move", bool_to_cstr(fast_move));
2136 if (has_fast_privs) {
2137 m_game_ui->showTranslatedStatusText("Fast mode enabled");
2139 m_game_ui->showTranslatedStatusText("Fast mode enabled (note: no 'fast' privilege)");
2142 m_game_ui->showTranslatedStatusText("Fast mode disabled");
2146 m_cache_hold_aux1 = fast_move && has_fast_privs;
2151 void Game::toggleNoClip()
2153 bool noclip = !g_settings->getBool("noclip");
2154 g_settings->set("noclip", bool_to_cstr(noclip));
2157 if (client->checkPrivilege("noclip")) {
2158 m_game_ui->showTranslatedStatusText("Noclip mode enabled");
2160 m_game_ui->showTranslatedStatusText("Noclip mode enabled (note: no 'noclip' privilege)");
2163 m_game_ui->showTranslatedStatusText("Noclip mode disabled");
2167 void Game::toggleCinematic()
2169 bool cinematic = !g_settings->getBool("cinematic");
2170 g_settings->set("cinematic", bool_to_cstr(cinematic));
2173 m_game_ui->showTranslatedStatusText("Cinematic mode enabled");
2175 m_game_ui->showTranslatedStatusText("Cinematic mode disabled");
2178 // Autoforward by toggling continuous forward.
2179 void Game::toggleAutoforward()
2181 bool autorun_enabled = !g_settings->getBool("continuous_forward");
2182 g_settings->set("continuous_forward", bool_to_cstr(autorun_enabled));
2184 if (autorun_enabled)
2185 m_game_ui->showTranslatedStatusText("Automatic forward enabled");
2187 m_game_ui->showTranslatedStatusText("Automatic forward disabled");
2190 void Game::toggleMinimap(bool shift_pressed)
2192 if (!mapper || !m_game_ui->m_flags.show_hud || !g_settings->getBool("enable_minimap"))
2195 if (shift_pressed) {
2196 mapper->toggleMinimapShape();
2200 u32 hud_flags = client->getEnv().getLocalPlayer()->hud_flags;
2202 MinimapMode mode = MINIMAP_MODE_OFF;
2203 if (hud_flags & HUD_FLAG_MINIMAP_VISIBLE) {
2204 mode = mapper->getMinimapMode();
2205 mode = (MinimapMode)((int)mode + 1);
2206 // If radar is disabled and in, or switching to, radar mode
2207 if (!(hud_flags & HUD_FLAG_MINIMAP_RADAR_VISIBLE) && mode > 3)
2208 mode = MINIMAP_MODE_OFF;
2211 m_game_ui->m_flags.show_minimap = true;
2213 case MINIMAP_MODE_SURFACEx1:
2214 m_game_ui->showTranslatedStatusText("Minimap in surface mode, Zoom x1");
2216 case MINIMAP_MODE_SURFACEx2:
2217 m_game_ui->showTranslatedStatusText("Minimap in surface mode, Zoom x2");
2219 case MINIMAP_MODE_SURFACEx4:
2220 m_game_ui->showTranslatedStatusText("Minimap in surface mode, Zoom x4");
2222 case MINIMAP_MODE_RADARx1:
2223 m_game_ui->showTranslatedStatusText("Minimap in radar mode, Zoom x1");
2225 case MINIMAP_MODE_RADARx2:
2226 m_game_ui->showTranslatedStatusText("Minimap in radar mode, Zoom x2");
2228 case MINIMAP_MODE_RADARx4:
2229 m_game_ui->showTranslatedStatusText("Minimap in radar mode, Zoom x4");
2232 mode = MINIMAP_MODE_OFF;
2233 m_game_ui->m_flags.show_minimap = false;
2234 if (hud_flags & HUD_FLAG_MINIMAP_VISIBLE)
2235 m_game_ui->showTranslatedStatusText("Minimap hidden");
2237 m_game_ui->showTranslatedStatusText("Minimap currently disabled by game or mod");
2240 mapper->setMinimapMode(mode);
2243 void Game::toggleFog()
2245 bool fog_enabled = g_settings->getBool("enable_fog");
2246 g_settings->setBool("enable_fog", !fog_enabled);
2248 m_game_ui->showTranslatedStatusText("Fog disabled");
2250 m_game_ui->showTranslatedStatusText("Fog enabled");
2254 void Game::toggleDebug()
2256 // Initial / 4x toggle: Chat only
2257 // 1x toggle: Debug text with chat
2258 // 2x toggle: Debug text with profiler graph
2259 // 3x toggle: Debug text and wireframe
2260 if (!m_game_ui->m_flags.show_debug) {
2261 m_game_ui->m_flags.show_debug = true;
2262 m_game_ui->m_flags.show_profiler_graph = false;
2263 draw_control->show_wireframe = false;
2264 m_game_ui->showTranslatedStatusText("Debug info shown");
2265 } else if (!m_game_ui->m_flags.show_profiler_graph && !draw_control->show_wireframe) {
2266 m_game_ui->m_flags.show_profiler_graph = true;
2267 m_game_ui->showTranslatedStatusText("Profiler graph shown");
2268 } else if (!draw_control->show_wireframe && client->checkPrivilege("debug")) {
2269 m_game_ui->m_flags.show_profiler_graph = false;
2270 draw_control->show_wireframe = true;
2271 m_game_ui->showTranslatedStatusText("Wireframe shown");
2273 m_game_ui->m_flags.show_debug = false;
2274 m_game_ui->m_flags.show_profiler_graph = false;
2275 draw_control->show_wireframe = false;
2276 if (client->checkPrivilege("debug")) {
2277 m_game_ui->showTranslatedStatusText("Debug info, profiler graph, and wireframe hidden");
2279 m_game_ui->showTranslatedStatusText("Debug info and profiler graph hidden");
2285 void Game::toggleUpdateCamera()
2287 m_flags.disable_camera_update = !m_flags.disable_camera_update;
2288 if (m_flags.disable_camera_update)
2289 m_game_ui->showTranslatedStatusText("Camera update disabled");
2291 m_game_ui->showTranslatedStatusText("Camera update enabled");
2295 void Game::increaseViewRange()
2297 s16 range = g_settings->getS16("viewing_range");
2298 s16 range_new = range + 10;
2302 if (range_new > 4000) {
2304 str = wgettext("Viewing range is at maximum: %d");
2305 swprintf(buf, sizeof(buf) / sizeof(wchar_t), str, range_new);
2307 m_game_ui->showStatusText(buf);
2310 str = wgettext("Viewing range changed to %d");
2311 swprintf(buf, sizeof(buf) / sizeof(wchar_t), str, range_new);
2313 m_game_ui->showStatusText(buf);
2315 g_settings->set("viewing_range", itos(range_new));
2319 void Game::decreaseViewRange()
2321 s16 range = g_settings->getS16("viewing_range");
2322 s16 range_new = range - 10;
2326 if (range_new < 20) {
2328 str = wgettext("Viewing range is at minimum: %d");
2329 swprintf(buf, sizeof(buf) / sizeof(wchar_t), str, range_new);
2331 m_game_ui->showStatusText(buf);
2333 str = wgettext("Viewing range changed to %d");
2334 swprintf(buf, sizeof(buf) / sizeof(wchar_t), str, range_new);
2336 m_game_ui->showStatusText(buf);
2338 g_settings->set("viewing_range", itos(range_new));
2342 void Game::toggleFullViewRange()
2344 draw_control->range_all = !draw_control->range_all;
2345 if (draw_control->range_all)
2346 m_game_ui->showTranslatedStatusText("Enabled unlimited viewing range");
2348 m_game_ui->showTranslatedStatusText("Disabled unlimited viewing range");
2352 void Game::checkZoomEnabled()
2354 LocalPlayer *player = client->getEnv().getLocalPlayer();
2355 if (player->getZoomFOV() < 0.001f || player->getFov().fov > 0.0f)
2356 m_game_ui->showTranslatedStatusText("Zoom currently disabled by game or mod");
2360 void Game::updateCameraDirection(CameraOrientation *cam, float dtime)
2362 if ((device->isWindowActive() && device->isWindowFocused()
2363 && !isMenuActive()) || random_input) {
2366 if (!random_input) {
2367 // Mac OSX gets upset if this is set every frame
2368 if (device->getCursorControl()->isVisible())
2369 device->getCursorControl()->setVisible(false);
2373 if (m_first_loop_after_window_activation) {
2374 m_first_loop_after_window_activation = false;
2376 input->setMousePos(driver->getScreenSize().Width / 2,
2377 driver->getScreenSize().Height / 2);
2379 updateCameraOrientation(cam, dtime);
2385 // Mac OSX gets upset if this is set every frame
2386 if (!device->getCursorControl()->isVisible())
2387 device->getCursorControl()->setVisible(true);
2390 m_first_loop_after_window_activation = true;
2395 void Game::updateCameraOrientation(CameraOrientation *cam, float dtime)
2397 #ifdef HAVE_TOUCHSCREENGUI
2398 if (g_touchscreengui) {
2399 cam->camera_yaw += g_touchscreengui->getYawChange();
2400 cam->camera_pitch = g_touchscreengui->getPitch();
2403 v2s32 center(driver->getScreenSize().Width / 2, driver->getScreenSize().Height / 2);
2404 v2s32 dist = input->getMousePos() - center;
2406 if (m_invert_mouse || camera->getCameraMode() == CAMERA_MODE_THIRD_FRONT) {
2410 cam->camera_yaw -= dist.X * m_cache_mouse_sensitivity;
2411 cam->camera_pitch += dist.Y * m_cache_mouse_sensitivity;
2413 if (dist.X != 0 || dist.Y != 0)
2414 input->setMousePos(center.X, center.Y);
2415 #ifdef HAVE_TOUCHSCREENGUI
2419 if (m_cache_enable_joysticks) {
2420 f32 c = m_cache_joystick_frustum_sensitivity * (1.f / 32767.f) * dtime;
2421 cam->camera_yaw -= input->joystick.getAxisWithoutDead(JA_FRUSTUM_HORIZONTAL) * c;
2422 cam->camera_pitch += input->joystick.getAxisWithoutDead(JA_FRUSTUM_VERTICAL) * c;
2425 cam->camera_pitch = rangelim(cam->camera_pitch, -89.5, 89.5);
2429 void Game::updatePlayerControl(const CameraOrientation &cam)
2431 //TimeTaker tt("update player control", NULL, PRECISION_NANO);
2433 // DO NOT use the isKeyDown method for the forward, backward, left, right
2434 // buttons, as the code that uses the controls needs to be able to
2435 // distinguish between the two in order to know when to use joysticks.
2437 PlayerControl control(
2438 input->isKeyDown(KeyType::FORWARD),
2439 input->isKeyDown(KeyType::BACKWARD),
2440 input->isKeyDown(KeyType::LEFT),
2441 input->isKeyDown(KeyType::RIGHT),
2442 isKeyDown(KeyType::JUMP),
2443 isKeyDown(KeyType::SPECIAL1),
2444 isKeyDown(KeyType::SNEAK),
2445 isKeyDown(KeyType::ZOOM),
2446 input->getLeftState(),
2447 input->getRightState(),
2450 input->joystick.getAxisWithoutDead(JA_SIDEWARD_MOVE),
2451 input->joystick.getAxisWithoutDead(JA_FORWARD_MOVE)
2455 ( (u32)(isKeyDown(KeyType::FORWARD) & 0x1) << 0) |
2456 ( (u32)(isKeyDown(KeyType::BACKWARD) & 0x1) << 1) |
2457 ( (u32)(isKeyDown(KeyType::LEFT) & 0x1) << 2) |
2458 ( (u32)(isKeyDown(KeyType::RIGHT) & 0x1) << 3) |
2459 ( (u32)(isKeyDown(KeyType::JUMP) & 0x1) << 4) |
2460 ( (u32)(isKeyDown(KeyType::SPECIAL1) & 0x1) << 5) |
2461 ( (u32)(isKeyDown(KeyType::SNEAK) & 0x1) << 6) |
2462 ( (u32)(input->getLeftState() & 0x1) << 7) |
2463 ( (u32)(input->getRightState() & 0x1) << 8
2467 /* For Android, simulate holding down AUX1 (fast move) if the user has
2468 * the fast_move setting toggled on. If there is an aux1 key defined for
2469 * Android then its meaning is inverted (i.e. holding aux1 means walk and
2472 if (m_cache_hold_aux1) {
2473 control.aux1 = control.aux1 ^ true;
2474 keypress_bits ^= ((u32)(1U << 5));
2478 LocalPlayer *player = client->getEnv().getLocalPlayer();
2480 // autojump if set: simulate "jump" key
2481 if (player->getAutojump()) {
2482 control.jump = true;
2483 keypress_bits |= 1U << 4;
2486 // autoforward if set: simulate "up" key
2487 if (player->getPlayerSettings().continuous_forward &&
2488 client->activeObjectsReceived() && !player->isDead()) {
2490 keypress_bits |= 1U << 0;
2493 client->setPlayerControl(control);
2494 player->keyPressed = keypress_bits;
2500 inline void Game::step(f32 *dtime)
2502 bool can_be_and_is_paused =
2503 (simple_singleplayer_mode && g_menumgr.pausesGame());
2505 if (can_be_and_is_paused) { // This is for a singleplayer server
2506 *dtime = 0; // No time passes
2509 server->step(*dtime);
2511 client->step(*dtime);
2515 const ClientEventHandler Game::clientEventHandler[CLIENTEVENT_MAX] = {
2516 {&Game::handleClientEvent_None},
2517 {&Game::handleClientEvent_PlayerDamage},
2518 {&Game::handleClientEvent_PlayerForceMove},
2519 {&Game::handleClientEvent_Deathscreen},
2520 {&Game::handleClientEvent_ShowFormSpec},
2521 {&Game::handleClientEvent_ShowLocalFormSpec},
2522 {&Game::handleClientEvent_HandleParticleEvent},
2523 {&Game::handleClientEvent_HandleParticleEvent},
2524 {&Game::handleClientEvent_HandleParticleEvent},
2525 {&Game::handleClientEvent_HudAdd},
2526 {&Game::handleClientEvent_HudRemove},
2527 {&Game::handleClientEvent_HudChange},
2528 {&Game::handleClientEvent_SetSky},
2529 {&Game::handleClientEvent_SetSun},
2530 {&Game::handleClientEvent_SetMoon},
2531 {&Game::handleClientEvent_SetStars},
2532 {&Game::handleClientEvent_OverrideDayNigthRatio},
2533 {&Game::handleClientEvent_CloudParams},
2536 void Game::handleClientEvent_None(ClientEvent *event, CameraOrientation *cam)
2538 FATAL_ERROR("ClientEvent type None received");
2541 void Game::handleClientEvent_PlayerDamage(ClientEvent *event, CameraOrientation *cam)
2543 if (client->modsLoaded())
2544 client->getScript()->on_damage_taken(event->player_damage.amount);
2546 // Damage flash and hurt tilt are not used at death
2547 if (client->getHP() > 0) {
2548 runData.damage_flash += 95.0f + 3.2f * event->player_damage.amount;
2549 runData.damage_flash = MYMIN(runData.damage_flash, 127.0f);
2551 LocalPlayer *player = client->getEnv().getLocalPlayer();
2553 player->hurt_tilt_timer = 1.5f;
2554 player->hurt_tilt_strength =
2555 rangelim(event->player_damage.amount / 4.0f, 1.0f, 4.0f);
2558 // Play damage sound
2559 client->getEventManager()->put(new SimpleTriggerEvent(MtEvent::PLAYER_DAMAGE));
2562 void Game::handleClientEvent_PlayerForceMove(ClientEvent *event, CameraOrientation *cam)
2564 cam->camera_yaw = event->player_force_move.yaw;
2565 cam->camera_pitch = event->player_force_move.pitch;
2568 void Game::handleClientEvent_Deathscreen(ClientEvent *event, CameraOrientation *cam)
2570 // If client scripting is enabled, deathscreen is handled by CSM code in
2571 // builtin/client/init.lua
2572 if (client->modsLoaded())
2573 client->getScript()->on_death();
2575 showDeathFormspec();
2577 /* Handle visualization */
2578 LocalPlayer *player = client->getEnv().getLocalPlayer();
2579 runData.damage_flash = 0;
2580 player->hurt_tilt_timer = 0;
2581 player->hurt_tilt_strength = 0;
2584 void Game::handleClientEvent_ShowFormSpec(ClientEvent *event, CameraOrientation *cam)
2586 if (event->show_formspec.formspec->empty()) {
2587 auto formspec = m_game_ui->getFormspecGUI();
2588 if (formspec && (event->show_formspec.formname->empty()
2589 || *(event->show_formspec.formname) == m_game_ui->getFormspecName())) {
2590 formspec->quitMenu();
2593 FormspecFormSource *fs_src =
2594 new FormspecFormSource(*(event->show_formspec.formspec));
2595 TextDestPlayerInventory *txt_dst =
2596 new TextDestPlayerInventory(client, *(event->show_formspec.formname));
2598 auto *&formspec = m_game_ui->updateFormspec(*(event->show_formspec.formname));
2599 GUIFormSpecMenu::create(formspec, client, &input->joystick,
2600 fs_src, txt_dst, client->getFormspecPrepend());
2603 delete event->show_formspec.formspec;
2604 delete event->show_formspec.formname;
2607 void Game::handleClientEvent_ShowLocalFormSpec(ClientEvent *event, CameraOrientation *cam)
2609 FormspecFormSource *fs_src = new FormspecFormSource(*event->show_formspec.formspec);
2610 LocalFormspecHandler *txt_dst =
2611 new LocalFormspecHandler(*event->show_formspec.formname, client);
2612 GUIFormSpecMenu::create(m_game_ui->getFormspecGUI(), client, &input->joystick,
2613 fs_src, txt_dst, client->getFormspecPrepend());
2615 delete event->show_formspec.formspec;
2616 delete event->show_formspec.formname;
2619 void Game::handleClientEvent_HandleParticleEvent(ClientEvent *event,
2620 CameraOrientation *cam)
2622 LocalPlayer *player = client->getEnv().getLocalPlayer();
2623 client->getParticleManager()->handleParticleEvent(event, client, player);
2626 void Game::handleClientEvent_HudAdd(ClientEvent *event, CameraOrientation *cam)
2628 LocalPlayer *player = client->getEnv().getLocalPlayer();
2629 auto &hud_server_to_client = client->getHUDTranslationMap();
2631 u32 server_id = event->hudadd.server_id;
2632 // ignore if we already have a HUD with that ID
2633 auto i = hud_server_to_client.find(server_id);
2634 if (i != hud_server_to_client.end()) {
2635 delete event->hudadd.pos;
2636 delete event->hudadd.name;
2637 delete event->hudadd.scale;
2638 delete event->hudadd.text;
2639 delete event->hudadd.align;
2640 delete event->hudadd.offset;
2641 delete event->hudadd.world_pos;
2642 delete event->hudadd.size;
2646 HudElement *e = new HudElement;
2647 e->type = (HudElementType)event->hudadd.type;
2648 e->pos = *event->hudadd.pos;
2649 e->name = *event->hudadd.name;
2650 e->scale = *event->hudadd.scale;
2651 e->text = *event->hudadd.text;
2652 e->number = event->hudadd.number;
2653 e->item = event->hudadd.item;
2654 e->dir = event->hudadd.dir;
2655 e->align = *event->hudadd.align;
2656 e->offset = *event->hudadd.offset;
2657 e->world_pos = *event->hudadd.world_pos;
2658 e->size = *event->hudadd.size;
2659 e->z_index = event->hudadd.z_index;
2660 hud_server_to_client[server_id] = player->addHud(e);
2662 delete event->hudadd.pos;
2663 delete event->hudadd.name;
2664 delete event->hudadd.scale;
2665 delete event->hudadd.text;
2666 delete event->hudadd.align;
2667 delete event->hudadd.offset;
2668 delete event->hudadd.world_pos;
2669 delete event->hudadd.size;
2672 void Game::handleClientEvent_HudRemove(ClientEvent *event, CameraOrientation *cam)
2674 LocalPlayer *player = client->getEnv().getLocalPlayer();
2675 HudElement *e = player->removeHud(event->hudrm.id);
2679 void Game::handleClientEvent_HudChange(ClientEvent *event, CameraOrientation *cam)
2681 LocalPlayer *player = client->getEnv().getLocalPlayer();
2683 u32 id = event->hudchange.id;
2684 HudElement *e = player->getHud(id);
2687 delete event->hudchange.v3fdata;
2688 delete event->hudchange.v2fdata;
2689 delete event->hudchange.sdata;
2690 delete event->hudchange.v2s32data;
2694 switch (event->hudchange.stat) {
2696 e->pos = *event->hudchange.v2fdata;
2700 e->name = *event->hudchange.sdata;
2703 case HUD_STAT_SCALE:
2704 e->scale = *event->hudchange.v2fdata;
2708 e->text = *event->hudchange.sdata;
2711 case HUD_STAT_NUMBER:
2712 e->number = event->hudchange.data;
2716 e->item = event->hudchange.data;
2720 e->dir = event->hudchange.data;
2723 case HUD_STAT_ALIGN:
2724 e->align = *event->hudchange.v2fdata;
2727 case HUD_STAT_OFFSET:
2728 e->offset = *event->hudchange.v2fdata;
2731 case HUD_STAT_WORLD_POS:
2732 e->world_pos = *event->hudchange.v3fdata;
2736 e->size = *event->hudchange.v2s32data;
2739 case HUD_STAT_Z_INDEX:
2740 e->z_index = event->hudchange.data;
2744 delete event->hudchange.v3fdata;
2745 delete event->hudchange.v2fdata;
2746 delete event->hudchange.sdata;
2747 delete event->hudchange.v2s32data;
2750 void Game::handleClientEvent_SetSky(ClientEvent *event, CameraOrientation *cam)
2752 sky->setVisible(false);
2753 // Whether clouds are visible in front of a custom skybox.
2754 sky->setCloudsEnabled(event->set_sky->clouds);
2760 // Clear the old textures out in case we switch rendering type.
2761 sky->clearSkyboxTextures();
2762 // Handle according to type
2763 if (event->set_sky->type == "regular") {
2764 // Shows the mesh skybox
2765 sky->setVisible(true);
2766 // Update mesh based skybox colours if applicable.
2767 sky->setSkyColors(*event->set_sky);
2768 sky->setHorizonTint(
2769 event->set_sky->sun_tint,
2770 event->set_sky->moon_tint,
2771 event->set_sky->tint_type
2773 } else if (event->set_sky->type == "skybox" &&
2774 event->set_sky->textures.size() == 6) {
2775 // Disable the dyanmic mesh skybox:
2776 sky->setVisible(false);
2778 sky->setFallbackBgColor(event->set_sky->bgcolor);
2779 // Set sunrise and sunset fog tinting:
2780 sky->setHorizonTint(
2781 event->set_sky->sun_tint,
2782 event->set_sky->moon_tint,
2783 event->set_sky->tint_type
2785 // Add textures to skybox.
2786 for (int i = 0; i < 6; i++)
2787 sky->addTextureToSkybox(event->set_sky->textures[i], i, texture_src);
2789 // Handle everything else as plain color.
2790 if (event->set_sky->type != "plain")
2791 infostream << "Unknown sky type: "
2792 << (event->set_sky->type) << std::endl;
2793 sky->setVisible(false);
2794 sky->setFallbackBgColor(event->set_sky->bgcolor);
2795 // Disable directional sun/moon tinting on plain or invalid skyboxes.
2796 sky->setHorizonTint(
2797 event->set_sky->bgcolor,
2798 event->set_sky->bgcolor,
2802 delete event->set_sky;
2805 void Game::handleClientEvent_SetSun(ClientEvent *event, CameraOrientation *cam)
2807 sky->setSunVisible(event->sun_params->visible);
2808 sky->setSunTexture(event->sun_params->texture,
2809 event->sun_params->tonemap, texture_src);
2810 sky->setSunScale(event->sun_params->scale);
2811 sky->setSunriseVisible(event->sun_params->sunrise_visible);
2812 sky->setSunriseTexture(event->sun_params->sunrise, texture_src);
2813 delete event->sun_params;
2816 void Game::handleClientEvent_SetMoon(ClientEvent *event, CameraOrientation *cam)
2818 sky->setMoonVisible(event->moon_params->visible);
2819 sky->setMoonTexture(event->moon_params->texture,
2820 event->moon_params->tonemap, texture_src);
2821 sky->setMoonScale(event->moon_params->scale);
2822 delete event->moon_params;
2825 void Game::handleClientEvent_SetStars(ClientEvent *event, CameraOrientation *cam)
2827 sky->setStarsVisible(event->star_params->visible);
2828 sky->setStarCount(event->star_params->count, false);
2829 sky->setStarColor(event->star_params->starcolor);
2830 sky->setStarScale(event->star_params->scale);
2831 delete event->star_params;
2834 void Game::handleClientEvent_OverrideDayNigthRatio(ClientEvent *event,
2835 CameraOrientation *cam)
2837 client->getEnv().setDayNightRatioOverride(
2838 event->override_day_night_ratio.do_override,
2839 event->override_day_night_ratio.ratio_f * 1000.0f);
2842 void Game::handleClientEvent_CloudParams(ClientEvent *event, CameraOrientation *cam)
2847 clouds->setDensity(event->cloud_params.density);
2848 clouds->setColorBright(video::SColor(event->cloud_params.color_bright));
2849 clouds->setColorAmbient(video::SColor(event->cloud_params.color_ambient));
2850 clouds->setHeight(event->cloud_params.height);
2851 clouds->setThickness(event->cloud_params.thickness);
2852 clouds->setSpeed(v2f(event->cloud_params.speed_x, event->cloud_params.speed_y));
2855 void Game::processClientEvents(CameraOrientation *cam)
2857 while (client->hasClientEvents()) {
2858 std::unique_ptr<ClientEvent> event(client->getClientEvent());
2859 FATAL_ERROR_IF(event->type >= CLIENTEVENT_MAX, "Invalid clientevent type");
2860 const ClientEventHandler& evHandler = clientEventHandler[event->type];
2861 (this->*evHandler.handler)(event.get(), cam);
2865 void Game::updateChat(f32 dtime, const v2u32 &screensize)
2867 // Add chat log output for errors to be shown in chat
2868 static LogOutputBuffer chat_log_error_buf(g_logger, LL_ERROR);
2870 // Get new messages from error log buffer
2871 while (!chat_log_error_buf.empty()) {
2872 std::wstring error_message = utf8_to_wide(chat_log_error_buf.get());
2873 if (!g_settings->getBool("disable_escape_sequences")) {
2874 error_message.insert(0, L"\x1b(c@red)");
2875 error_message.append(L"\x1b(c@white)");
2877 chat_backend->addMessage(L"", error_message);
2880 // Get new messages from client
2881 std::wstring message;
2882 while (client->getChatMessage(message)) {
2883 chat_backend->addUnparsedMessage(message);
2886 // Remove old messages
2887 chat_backend->step(dtime);
2889 // Display all messages in a static text element
2890 m_game_ui->setChatText(chat_backend->getRecentChat(),
2891 chat_backend->getRecentBuffer().getLineCount());
2894 void Game::updateCamera(u32 busy_time, f32 dtime)
2896 LocalPlayer *player = client->getEnv().getLocalPlayer();
2899 For interaction purposes, get info about the held item
2901 - Is it a usable item?
2902 - Can it point to liquids?
2904 ItemStack playeritem;
2906 ItemStack selected, hand;
2907 playeritem = player->getWieldedItem(&selected, &hand);
2910 ToolCapabilities playeritem_toolcap =
2911 playeritem.getToolCapabilities(itemdef_manager);
2913 v3s16 old_camera_offset = camera->getOffset();
2915 if (wasKeyDown(KeyType::CAMERA_MODE)) {
2916 GenericCAO *playercao = player->getCAO();
2918 // If playercao not loaded, don't change camera
2922 camera->toggleCameraMode();
2924 playercao->setVisible(camera->getCameraMode() > CAMERA_MODE_FIRST);
2925 playercao->setChildrenVisible(camera->getCameraMode() > CAMERA_MODE_FIRST);
2928 float full_punch_interval = playeritem_toolcap.full_punch_interval;
2929 float tool_reload_ratio = runData.time_from_last_punch / full_punch_interval;
2931 tool_reload_ratio = MYMIN(tool_reload_ratio, 1.0);
2932 camera->update(player, dtime, busy_time / 1000.0f, tool_reload_ratio);
2933 camera->step(dtime);
2935 v3f camera_position = camera->getPosition();
2936 v3f camera_direction = camera->getDirection();
2937 f32 camera_fov = camera->getFovMax();
2938 v3s16 camera_offset = camera->getOffset();
2940 m_camera_offset_changed = (camera_offset != old_camera_offset);
2942 if (!m_flags.disable_camera_update) {
2943 client->getEnv().getClientMap().updateCamera(camera_position,
2944 camera_direction, camera_fov, camera_offset);
2946 if (m_camera_offset_changed) {
2947 client->updateCameraOffset(camera_offset);
2948 client->getEnv().updateCameraOffset(camera_offset);
2951 clouds->updateCameraOffset(camera_offset);
2957 void Game::updateSound(f32 dtime)
2959 // Update sound listener
2960 v3s16 camera_offset = camera->getOffset();
2961 sound->updateListener(camera->getCameraNode()->getPosition() + intToFloat(camera_offset, BS),
2962 v3f(0, 0, 0), // velocity
2963 camera->getDirection(),
2964 camera->getCameraNode()->getUpVector());
2966 bool mute_sound = g_settings->getBool("mute_sound");
2968 sound->setListenerGain(0.0f);
2970 // Check if volume is in the proper range, else fix it.
2971 float old_volume = g_settings->getFloat("sound_volume");
2972 float new_volume = rangelim(old_volume, 0.0f, 1.0f);
2973 sound->setListenerGain(new_volume);
2975 if (old_volume != new_volume) {
2976 g_settings->setFloat("sound_volume", new_volume);
2980 LocalPlayer *player = client->getEnv().getLocalPlayer();
2982 // Tell the sound maker whether to make footstep sounds
2983 soundmaker->makes_footstep_sound = player->makes_footstep_sound;
2985 // Update sound maker
2986 if (player->makes_footstep_sound)
2987 soundmaker->step(dtime);
2989 ClientMap &map = client->getEnv().getClientMap();
2990 MapNode n = map.getNode(player->getFootstepNodePos());
2991 soundmaker->m_player_step_sound = nodedef_manager->get(n).sound_footstep;
2995 void Game::processPlayerInteraction(f32 dtime, bool show_hud, bool show_debug)
2997 LocalPlayer *player = client->getEnv().getLocalPlayer();
2999 v3f player_position = player->getPosition();
3000 v3f player_eye_position = player->getEyePosition();
3001 v3f camera_position = camera->getPosition();
3002 v3f camera_direction = camera->getDirection();
3003 v3s16 camera_offset = camera->getOffset();
3005 if (camera->getCameraMode() == CAMERA_MODE_FIRST)
3006 player_eye_position += player->eye_offset_first;
3008 player_eye_position += player->eye_offset_third;
3011 Calculate what block is the crosshair pointing to
3014 ItemStack selected_item, hand_item;
3015 const ItemStack &tool_item = player->getWieldedItem(&selected_item, &hand_item);
3017 const ItemDefinition &selected_def = selected_item.getDefinition(itemdef_manager);
3018 f32 d = getToolRange(selected_def, hand_item.getDefinition(itemdef_manager));
3020 core::line3d<f32> shootline;
3022 if (camera->getCameraMode() != CAMERA_MODE_THIRD_FRONT) {
3023 shootline = core::line3d<f32>(player_eye_position,
3024 player_eye_position + camera_direction * BS * d);
3026 // prevent player pointing anything in front-view
3027 shootline = core::line3d<f32>(camera_position, camera_position);
3030 #ifdef HAVE_TOUCHSCREENGUI
3032 if ((g_settings->getBool("touchtarget")) && (g_touchscreengui)) {
3033 shootline = g_touchscreengui->getShootline();
3034 // Scale shootline to the acual distance the player can reach
3035 shootline.end = shootline.start
3036 + shootline.getVector().normalize() * BS * d;
3037 shootline.start += intToFloat(camera_offset, BS);
3038 shootline.end += intToFloat(camera_offset, BS);
3043 PointedThing pointed = updatePointedThing(shootline,
3044 selected_def.liquids_pointable,
3045 !runData.ldown_for_dig,
3048 if (pointed != runData.pointed_old) {
3049 infostream << "Pointing at " << pointed.dump() << std::endl;
3050 hud->updateSelectionMesh(camera_offset);
3053 if (runData.digging_blocked && !input->getLeftState()) {
3054 // allow digging again if button is not pressed
3055 runData.digging_blocked = false;
3060 - releasing left mouse button
3061 - pointing away from node
3063 if (runData.digging) {
3064 if (input->getLeftReleased()) {
3065 infostream << "Left button released"
3066 << " (stopped digging)" << std::endl;
3067 runData.digging = false;
3068 } else if (pointed != runData.pointed_old) {
3069 if (pointed.type == POINTEDTHING_NODE
3070 && runData.pointed_old.type == POINTEDTHING_NODE
3071 && pointed.node_undersurface
3072 == runData.pointed_old.node_undersurface) {
3073 // Still pointing to the same node, but a different face.
3076 infostream << "Pointing away from node"
3077 << " (stopped digging)" << std::endl;
3078 runData.digging = false;
3079 hud->updateSelectionMesh(camera_offset);
3083 if (!runData.digging) {
3084 client->interact(INTERACT_STOP_DIGGING, runData.pointed_old);
3085 client->setCrack(-1, v3s16(0, 0, 0));
3086 runData.dig_time = 0.0;
3088 } else if (runData.dig_instantly && input->getLeftReleased()) {
3089 // Remove e.g. torches faster when clicking instead of holding LMB
3090 runData.nodig_delay_timer = 0;
3091 runData.dig_instantly = false;
3094 if (!runData.digging && runData.ldown_for_dig && !input->getLeftState()) {
3095 runData.ldown_for_dig = false;
3098 runData.left_punch = false;
3100 soundmaker->m_player_leftpunch_sound.name = "";
3102 // Prepare for repeating, unless we're not supposed to
3103 if (input->getRightState() && !g_settings->getBool("safe_dig_and_place"))
3104 runData.repeat_rightclick_timer += dtime;
3106 runData.repeat_rightclick_timer = 0;
3108 if (selected_def.usable && input->getLeftState()) {
3109 if (input->getLeftClicked() && (!client->modsLoaded()
3110 || !client->getScript()->on_item_use(selected_item, pointed)))
3111 client->interact(INTERACT_USE, pointed);
3112 } else if (pointed.type == POINTEDTHING_NODE) {
3113 handlePointingAtNode(pointed, selected_item, hand_item, dtime);
3114 } else if (pointed.type == POINTEDTHING_OBJECT) {
3115 handlePointingAtObject(pointed, tool_item, player_position, show_debug);
3116 } else if (input->getLeftState()) {
3117 // When button is held down in air, show continuous animation
3118 runData.left_punch = true;
3119 // Run callback even though item is not usable
3120 if (input->getLeftClicked() && client->modsLoaded())
3121 client->getScript()->on_item_use(selected_item, pointed);
3122 } else if (input->getRightClicked()) {
3123 handlePointingAtNothing(selected_item);
3126 runData.pointed_old = pointed;
3128 if (runData.left_punch || input->getLeftClicked())
3129 camera->setDigging(0); // left click animation
3131 input->resetLeftClicked();
3132 input->resetRightClicked();
3134 input->resetLeftReleased();
3135 input->resetRightReleased();
3139 PointedThing Game::updatePointedThing(
3140 const core::line3d<f32> &shootline,
3141 bool liquids_pointable,
3142 bool look_for_object,
3143 const v3s16 &camera_offset)
3145 std::vector<aabb3f> *selectionboxes = hud->getSelectionBoxes();
3146 selectionboxes->clear();
3147 hud->setSelectedFaceNormal(v3f(0.0, 0.0, 0.0));
3148 static thread_local const bool show_entity_selectionbox = g_settings->getBool(
3149 "show_entity_selectionbox");
3151 ClientEnvironment &env = client->getEnv();
3152 ClientMap &map = env.getClientMap();
3153 const NodeDefManager *nodedef = map.getNodeDefManager();
3155 runData.selected_object = NULL;
3157 RaycastState s(shootline, look_for_object, liquids_pointable);
3158 PointedThing result;
3159 env.continueRaycast(&s, &result);
3160 if (result.type == POINTEDTHING_OBJECT) {
3161 runData.selected_object = client->getEnv().getActiveObject(result.object_id);
3162 aabb3f selection_box;
3163 if (show_entity_selectionbox && runData.selected_object->doShowSelectionBox() &&
3164 runData.selected_object->getSelectionBox(&selection_box)) {
3165 v3f pos = runData.selected_object->getPosition();
3166 selectionboxes->push_back(aabb3f(selection_box));
3167 hud->setSelectionPos(pos, camera_offset);
3169 } else if (result.type == POINTEDTHING_NODE) {
3170 // Update selection boxes
3171 MapNode n = map.getNode(result.node_undersurface);
3172 std::vector<aabb3f> boxes;
3173 n.getSelectionBoxes(nodedef, &boxes,
3174 n.getNeighbors(result.node_undersurface, &map));
3177 for (std::vector<aabb3f>::const_iterator i = boxes.begin();
3178 i != boxes.end(); ++i) {
3180 box.MinEdge -= v3f(d, d, d);
3181 box.MaxEdge += v3f(d, d, d);
3182 selectionboxes->push_back(box);
3184 hud->setSelectionPos(intToFloat(result.node_undersurface, BS),
3186 hud->setSelectedFaceNormal(v3f(
3187 result.intersection_normal.X,
3188 result.intersection_normal.Y,
3189 result.intersection_normal.Z));
3192 // Update selection mesh light level and vertex colors
3193 if (!selectionboxes->empty()) {
3194 v3f pf = hud->getSelectionPos();
3195 v3s16 p = floatToInt(pf, BS);
3197 // Get selection mesh light level
3198 MapNode n = map.getNode(p);
3199 u16 node_light = getInteriorLight(n, -1, nodedef);
3200 u16 light_level = node_light;
3202 for (const v3s16 &dir : g_6dirs) {
3203 n = map.getNode(p + dir);
3204 node_light = getInteriorLight(n, -1, nodedef);
3205 if (node_light > light_level)
3206 light_level = node_light;
3209 u32 daynight_ratio = client->getEnv().getDayNightRatio();
3211 final_color_blend(&c, light_level, daynight_ratio);
3213 // Modify final color a bit with time
3214 u32 timer = porting::getTimeMs() % 5000;
3215 float timerf = (float) (irr::core::PI * ((timer / 2500.0) - 0.5));
3216 float sin_r = 0.08f * std::sin(timerf);
3217 float sin_g = 0.08f * std::sin(timerf + irr::core::PI * 0.5f);
3218 float sin_b = 0.08f * std::sin(timerf + irr::core::PI);
3219 c.setRed(core::clamp(core::round32(c.getRed() * (0.8 + sin_r)), 0, 255));
3220 c.setGreen(core::clamp(core::round32(c.getGreen() * (0.8 + sin_g)), 0, 255));
3221 c.setBlue(core::clamp(core::round32(c.getBlue() * (0.8 + sin_b)), 0, 255));
3223 // Set mesh final color
3224 hud->setSelectionMeshColor(c);
3230 void Game::handlePointingAtNothing(const ItemStack &playerItem)
3232 infostream << "Right Clicked in Air" << std::endl;
3233 PointedThing fauxPointed;
3234 fauxPointed.type = POINTEDTHING_NOTHING;
3235 client->interact(INTERACT_ACTIVATE, fauxPointed);
3239 void Game::handlePointingAtNode(const PointedThing &pointed,
3240 const ItemStack &selected_item, const ItemStack &hand_item, f32 dtime)
3242 v3s16 nodepos = pointed.node_undersurface;
3243 v3s16 neighbourpos = pointed.node_abovesurface;
3246 Check information text of node
3249 ClientMap &map = client->getEnv().getClientMap();
3251 if (runData.nodig_delay_timer <= 0.0 && input->getLeftState()
3252 && !runData.digging_blocked
3253 && client->checkPrivilege("interact")) {
3254 handleDigging(pointed, nodepos, selected_item, hand_item, dtime);
3257 // This should be done after digging handling
3258 NodeMetadata *meta = map.getNodeMetadata(nodepos);
3261 m_game_ui->setInfoText(unescape_translate(utf8_to_wide(
3262 meta->getString("infotext"))));
3264 MapNode n = map.getNode(nodepos);
3266 if (nodedef_manager->get(n).tiledef[0].name == "unknown_node.png") {
3267 m_game_ui->setInfoText(L"Unknown node: " +
3268 utf8_to_wide(nodedef_manager->get(n).name));
3272 if ((input->getRightClicked() ||
3273 runData.repeat_rightclick_timer >= m_repeat_right_click_time) &&
3274 client->checkPrivilege("interact")) {
3275 runData.repeat_rightclick_timer = 0;
3276 infostream << "Ground right-clicked" << std::endl;
3278 camera->setDigging(1); // right click animation (always shown for feedback)
3280 soundmaker->m_player_rightpunch_sound = SimpleSoundSpec();
3282 // If the wielded item has node placement prediction,
3284 // And also set the sound and send the interact
3285 // But first check for meta formspec and rightclickable
3286 auto &def = selected_item.getDefinition(itemdef_manager);
3287 bool placed = nodePlacement(def, selected_item, nodepos, neighbourpos,
3290 if (placed && client->modsLoaded())
3291 client->getScript()->on_placenode(pointed, def);
3295 bool Game::nodePlacement(const ItemDefinition &selected_def,
3296 const ItemStack &selected_item, const v3s16 &nodepos, const v3s16 &neighbourpos,
3297 const PointedThing &pointed, const NodeMetadata *meta)
3299 std::string prediction = selected_def.node_placement_prediction;
3300 const NodeDefManager *nodedef = client->ndef();
3301 ClientMap &map = client->getEnv().getClientMap();
3303 bool is_valid_position;
3305 node = map.getNode(nodepos, &is_valid_position);
3306 if (!is_valid_position) {
3307 soundmaker->m_player_rightpunch_sound = selected_def.sound_place_failed;
3312 if (meta && !meta->getString("formspec").empty() && !random_input
3313 && !isKeyDown(KeyType::SNEAK)) {
3314 // on_rightclick callbacks are called anyway
3315 if (nodedef_manager->get(map.getNode(nodepos)).rightclickable)
3316 client->interact(INTERACT_PLACE, pointed);
3318 infostream << "Launching custom inventory view" << std::endl;
3320 InventoryLocation inventoryloc;
3321 inventoryloc.setNodeMeta(nodepos);
3323 NodeMetadataFormSource *fs_src = new NodeMetadataFormSource(
3324 &client->getEnv().getClientMap(), nodepos);
3325 TextDest *txt_dst = new TextDestNodeMetadata(nodepos, client);
3327 auto *&formspec = m_game_ui->updateFormspec("");
3328 GUIFormSpecMenu::create(formspec, client, &input->joystick, fs_src,
3329 txt_dst, client->getFormspecPrepend());
3331 formspec->setFormSpec(meta->getString("formspec"), inventoryloc);
3335 // on_rightclick callback
3336 if (prediction.empty() || (nodedef->get(node).rightclickable &&
3337 !isKeyDown(KeyType::SNEAK))) {
3339 client->interact(INTERACT_PLACE, pointed);
3343 verbosestream << "Node placement prediction for "
3344 << selected_def.name << " is "
3345 << prediction << std::endl;
3346 v3s16 p = neighbourpos;
3348 // Place inside node itself if buildable_to
3349 MapNode n_under = map.getNode(nodepos, &is_valid_position);
3350 if (is_valid_position) {
3351 if (nodedef->get(n_under).buildable_to) {
3354 node = map.getNode(p, &is_valid_position);
3355 if (is_valid_position && !nodedef->get(node).buildable_to) {
3357 client->interact(INTERACT_PLACE, pointed);
3363 // Find id of predicted node
3365 bool found = nodedef->getId(prediction, id);
3368 errorstream << "Node placement prediction failed for "
3369 << selected_def.name << " (places "
3371 << ") - Name not known" << std::endl;
3372 // Handle this as if prediction was empty
3374 client->interact(INTERACT_PLACE, pointed);
3378 const ContentFeatures &predicted_f = nodedef->get(id);
3380 // Predict param2 for facedir and wallmounted nodes
3383 if (predicted_f.param_type_2 == CPT2_WALLMOUNTED ||
3384 predicted_f.param_type_2 == CPT2_COLORED_WALLMOUNTED) {
3385 v3s16 dir = nodepos - neighbourpos;
3387 if (abs(dir.Y) > MYMAX(abs(dir.X), abs(dir.Z))) {
3388 param2 = dir.Y < 0 ? 1 : 0;
3389 } else if (abs(dir.X) > abs(dir.Z)) {
3390 param2 = dir.X < 0 ? 3 : 2;
3392 param2 = dir.Z < 0 ? 5 : 4;
3396 if (predicted_f.param_type_2 == CPT2_FACEDIR ||
3397 predicted_f.param_type_2 == CPT2_COLORED_FACEDIR) {
3398 v3s16 dir = nodepos - floatToInt(client->getEnv().getLocalPlayer()->getPosition(), BS);
3400 if (abs(dir.X) > abs(dir.Z)) {
3401 param2 = dir.X < 0 ? 3 : 1;
3403 param2 = dir.Z < 0 ? 2 : 0;
3407 assert(param2 <= 5);
3409 //Check attachment if node is in group attached_node
3410 if (((ItemGroupList) predicted_f.groups)["attached_node"] != 0) {
3411 static v3s16 wallmounted_dirs[8] = {
3421 if (predicted_f.param_type_2 == CPT2_WALLMOUNTED ||
3422 predicted_f.param_type_2 == CPT2_COLORED_WALLMOUNTED)
3423 pp = p + wallmounted_dirs[param2];
3425 pp = p + v3s16(0, -1, 0);
3427 if (!nodedef->get(map.getNode(pp)).walkable) {
3429 client->interact(INTERACT_PLACE, pointed);
3435 if ((predicted_f.param_type_2 == CPT2_COLOR
3436 || predicted_f.param_type_2 == CPT2_COLORED_FACEDIR
3437 || predicted_f.param_type_2 == CPT2_COLORED_WALLMOUNTED)) {
3438 const std::string &indexstr = selected_item.metadata.getString(
3439 "palette_index", 0);
3440 if (!indexstr.empty()) {
3441 s32 index = mystoi(indexstr);
3442 if (predicted_f.param_type_2 == CPT2_COLOR) {
3444 } else if (predicted_f.param_type_2 == CPT2_COLORED_WALLMOUNTED) {
3445 // param2 = pure palette index + other
3446 param2 = (index & 0xf8) | (param2 & 0x07);
3447 } else if (predicted_f.param_type_2 == CPT2_COLORED_FACEDIR) {
3448 // param2 = pure palette index + other
3449 param2 = (index & 0xe0) | (param2 & 0x1f);
3454 // Add node to client map
3455 MapNode n(id, 0, param2);
3458 LocalPlayer *player = client->getEnv().getLocalPlayer();
3460 // Dont place node when player would be inside new node
3461 // NOTE: This is to be eventually implemented by a mod as client-side Lua
3462 if (!nodedef->get(n).walkable ||
3463 g_settings->getBool("enable_build_where_you_stand") ||
3464 (client->checkPrivilege("noclip") && g_settings->getBool("noclip")) ||
3465 (nodedef->get(n).walkable &&
3466 neighbourpos != player->getStandingNodePos() + v3s16(0, 1, 0) &&
3467 neighbourpos != player->getStandingNodePos() + v3s16(0, 2, 0))) {
3468 // This triggers the required mesh update too
3469 client->addNode(p, n);
3471 client->interact(INTERACT_PLACE, pointed);
3472 // A node is predicted, also play a sound
3473 soundmaker->m_player_rightpunch_sound = selected_def.sound_place;
3476 soundmaker->m_player_rightpunch_sound = selected_def.sound_place_failed;
3479 } catch (InvalidPositionException &e) {
3480 errorstream << "Node placement prediction failed for "
3481 << selected_def.name << " (places "
3483 << ") - Position not loaded" << std::endl;
3484 soundmaker->m_player_rightpunch_sound = selected_def.sound_place_failed;
3489 void Game::handlePointingAtObject(const PointedThing &pointed,
3490 const ItemStack &tool_item, const v3f &player_position, bool show_debug)
3492 std::wstring infotext = unescape_translate(
3493 utf8_to_wide(runData.selected_object->infoText()));
3496 if (!infotext.empty()) {
3499 infotext += utf8_to_wide(runData.selected_object->debugInfoText());
3502 m_game_ui->setInfoText(infotext);
3504 if (input->getLeftState()) {
3505 bool do_punch = false;
3506 bool do_punch_damage = false;
3508 if (runData.object_hit_delay_timer <= 0.0) {
3510 do_punch_damage = true;
3511 runData.object_hit_delay_timer = object_hit_delay;
3514 if (input->getLeftClicked())
3518 infostream << "Left-clicked object" << std::endl;
3519 runData.left_punch = true;
3522 if (do_punch_damage) {
3523 // Report direct punch
3524 v3f objpos = runData.selected_object->getPosition();
3525 v3f dir = (objpos - player_position).normalize();
3527 bool disable_send = runData.selected_object->directReportPunch(
3528 dir, &tool_item, runData.time_from_last_punch);
3529 runData.time_from_last_punch = 0;
3532 client->interact(INTERACT_START_DIGGING, pointed);
3534 } else if (input->getRightClicked()) {
3535 infostream << "Right-clicked object" << std::endl;
3536 client->interact(INTERACT_PLACE, pointed); // place
3541 void Game::handleDigging(const PointedThing &pointed, const v3s16 &nodepos,
3542 const ItemStack &selected_item, const ItemStack &hand_item, f32 dtime)
3544 // See also: serverpackethandle.cpp, action == 2
3545 LocalPlayer *player = client->getEnv().getLocalPlayer();
3546 ClientMap &map = client->getEnv().getClientMap();
3547 MapNode n = client->getEnv().getClientMap().getNode(nodepos);
3549 // NOTE: Similar piece of code exists on the server side for
3551 // Get digging parameters
3552 DigParams params = getDigParams(nodedef_manager->get(n).groups,
3553 &selected_item.getToolCapabilities(itemdef_manager));
3555 // If can't dig, try hand
3556 if (!params.diggable) {
3557 params = getDigParams(nodedef_manager->get(n).groups,
3558 &hand_item.getToolCapabilities(itemdef_manager));
3561 if (!params.diggable) {
3562 // I guess nobody will wait for this long
3563 runData.dig_time_complete = 10000000.0;
3565 runData.dig_time_complete = params.time;
3567 if (m_cache_enable_particles) {
3568 const ContentFeatures &features = client->getNodeDefManager()->get(n);
3569 client->getParticleManager()->addNodeParticle(client,
3570 player, nodepos, n, features);
3574 if (!runData.digging) {
3575 infostream << "Started digging" << std::endl;
3576 runData.dig_instantly = runData.dig_time_complete == 0;
3577 if (client->modsLoaded() && client->getScript()->on_punchnode(nodepos, n))
3579 client->interact(INTERACT_START_DIGGING, pointed);
3580 runData.digging = true;
3581 runData.ldown_for_dig = true;
3584 if (!runData.dig_instantly) {
3585 runData.dig_index = (float)crack_animation_length
3587 / runData.dig_time_complete;
3589 // This is for e.g. torches
3590 runData.dig_index = crack_animation_length;
3593 SimpleSoundSpec sound_dig = nodedef_manager->get(n).sound_dig;
3595 if (sound_dig.exists() && params.diggable) {
3596 if (sound_dig.name == "__group") {
3597 if (!params.main_group.empty()) {
3598 soundmaker->m_player_leftpunch_sound.gain = 0.5;
3599 soundmaker->m_player_leftpunch_sound.name =
3600 std::string("default_dig_") +
3604 soundmaker->m_player_leftpunch_sound = sound_dig;
3608 // Don't show cracks if not diggable
3609 if (runData.dig_time_complete >= 100000.0) {
3610 } else if (runData.dig_index < crack_animation_length) {
3611 //TimeTaker timer("client.setTempMod");
3612 //infostream<<"dig_index="<<dig_index<<std::endl;
3613 client->setCrack(runData.dig_index, nodepos);
3615 infostream << "Digging completed" << std::endl;
3616 client->setCrack(-1, v3s16(0, 0, 0));
3618 runData.dig_time = 0;
3619 runData.digging = false;
3620 // we successfully dug, now block it from repeating if we want to be safe
3621 if (g_settings->getBool("safe_dig_and_place"))
3622 runData.digging_blocked = true;
3624 runData.nodig_delay_timer =
3625 runData.dig_time_complete / (float)crack_animation_length;
3627 // We don't want a corresponding delay to very time consuming nodes
3628 // and nodes without digging time (e.g. torches) get a fixed delay.
3629 if (runData.nodig_delay_timer > 0.3)
3630 runData.nodig_delay_timer = 0.3;
3631 else if (runData.dig_instantly)
3632 runData.nodig_delay_timer = 0.15;
3634 bool is_valid_position;
3635 MapNode wasnode = map.getNode(nodepos, &is_valid_position);
3636 if (is_valid_position) {
3637 if (client->modsLoaded() &&
3638 client->getScript()->on_dignode(nodepos, wasnode)) {
3642 const ContentFeatures &f = client->ndef()->get(wasnode);
3643 if (f.node_dig_prediction == "air") {
3644 client->removeNode(nodepos);
3645 } else if (!f.node_dig_prediction.empty()) {
3647 bool found = client->ndef()->getId(f.node_dig_prediction, id);
3649 client->addNode(nodepos, id, true);
3651 // implicit else: no prediction
3654 client->interact(INTERACT_DIGGING_COMPLETED, pointed);
3656 if (m_cache_enable_particles) {
3657 const ContentFeatures &features =
3658 client->getNodeDefManager()->get(wasnode);
3659 client->getParticleManager()->addDiggingParticles(client,
3660 player, nodepos, wasnode, features);
3664 // Send event to trigger sound
3665 client->getEventManager()->put(new NodeDugEvent(nodepos, wasnode));
3668 if (runData.dig_time_complete < 100000.0) {
3669 runData.dig_time += dtime;
3671 runData.dig_time = 0;
3672 client->setCrack(-1, nodepos);
3675 camera->setDigging(0); // left click animation
3679 void Game::updateFrame(ProfilerGraph *graph, RunStats *stats, f32 dtime,
3680 const CameraOrientation &cam)
3682 TimeTaker tt_update("Game::updateFrame()");
3683 LocalPlayer *player = client->getEnv().getLocalPlayer();
3689 if (draw_control->range_all) {
3690 runData.fog_range = 100000 * BS;
3692 runData.fog_range = draw_control->wanted_range * BS;
3696 Calculate general brightness
3698 u32 daynight_ratio = client->getEnv().getDayNightRatio();
3699 float time_brightness = decode_light_f((float)daynight_ratio / 1000.0);
3700 float direct_brightness;
3703 if (m_cache_enable_noclip && m_cache_enable_free_move) {
3704 direct_brightness = time_brightness;
3705 sunlight_seen = true;
3707 float old_brightness = sky->getBrightness();
3708 direct_brightness = client->getEnv().getClientMap()
3709 .getBackgroundBrightness(MYMIN(runData.fog_range * 1.2, 60 * BS),
3710 daynight_ratio, (int)(old_brightness * 255.5), &sunlight_seen)
3714 float time_of_day_smooth = runData.time_of_day_smooth;
3715 float time_of_day = client->getEnv().getTimeOfDayF();
3717 static const float maxsm = 0.05f;
3718 static const float todsm = 0.05f;
3720 if (std::fabs(time_of_day - time_of_day_smooth) > maxsm &&
3721 std::fabs(time_of_day - time_of_day_smooth + 1.0) > maxsm &&
3722 std::fabs(time_of_day - time_of_day_smooth - 1.0) > maxsm)
3723 time_of_day_smooth = time_of_day;
3725 if (time_of_day_smooth > 0.8 && time_of_day < 0.2)
3726 time_of_day_smooth = time_of_day_smooth * (1.0 - todsm)
3727 + (time_of_day + 1.0) * todsm;
3729 time_of_day_smooth = time_of_day_smooth * (1.0 - todsm)
3730 + time_of_day * todsm;
3732 runData.time_of_day_smooth = time_of_day_smooth;
3734 sky->update(time_of_day_smooth, time_brightness, direct_brightness,
3735 sunlight_seen, camera->getCameraMode(), player->getYaw(),
3736 player->getPitch());
3742 if (sky->getCloudsVisible()) {
3743 clouds->setVisible(true);
3744 clouds->step(dtime);
3745 // camera->getPosition is not enough for 3rd person views
3746 v3f camera_node_position = camera->getCameraNode()->getPosition();
3747 v3s16 camera_offset = camera->getOffset();
3748 camera_node_position.X = camera_node_position.X + camera_offset.X * BS;
3749 camera_node_position.Y = camera_node_position.Y + camera_offset.Y * BS;
3750 camera_node_position.Z = camera_node_position.Z + camera_offset.Z * BS;
3751 clouds->update(camera_node_position,
3752 sky->getCloudColor());
3753 if (clouds->isCameraInsideCloud() && m_cache_enable_fog) {
3754 // if inside clouds, and fog enabled, use that as sky
3756 video::SColor clouds_dark = clouds->getColor()
3757 .getInterpolated(video::SColor(255, 0, 0, 0), 0.9);
3758 sky->overrideColors(clouds_dark, clouds->getColor());
3759 sky->setInClouds(true);
3760 runData.fog_range = std::fmin(runData.fog_range * 0.5f, 32.0f * BS);
3761 // do not draw clouds after all
3762 clouds->setVisible(false);
3765 clouds->setVisible(false);
3772 client->getParticleManager()->step(dtime);
3778 if (m_cache_enable_fog) {
3781 video::EFT_FOG_LINEAR,
3782 runData.fog_range * m_cache_fog_start,
3783 runData.fog_range * 1.0,
3791 video::EFT_FOG_LINEAR,
3801 Get chat messages from client
3804 v2u32 screensize = driver->getScreenSize();
3806 updateChat(dtime, screensize);
3812 if (player->getWieldIndex() != runData.new_playeritem)
3813 client->setPlayerItem(runData.new_playeritem);
3815 if (client->updateWieldedItem()) {
3816 // Update wielded tool
3817 ItemStack selected_item, hand_item;
3818 ItemStack &tool_item = player->getWieldedItem(&selected_item, &hand_item);
3819 camera->wield(tool_item);
3823 Update block draw list every 200ms or when camera direction has
3826 runData.update_draw_list_timer += dtime;
3828 v3f camera_direction = camera->getDirection();
3829 if (runData.update_draw_list_timer >= 0.2
3830 || runData.update_draw_list_last_cam_dir.getDistanceFrom(camera_direction) > 0.2
3831 || m_camera_offset_changed) {
3832 runData.update_draw_list_timer = 0;
3833 client->getEnv().getClientMap().updateDrawList();
3834 runData.update_draw_list_last_cam_dir = camera_direction;
3837 m_game_ui->update(*stats, client, draw_control, cam, runData.pointed_old, gui_chat_console, dtime);
3840 make sure menu is on top
3841 1. Delete formspec menu reference if menu was removed
3842 2. Else, make sure formspec menu is on top
3844 auto formspec = m_game_ui->getFormspecGUI();
3845 do { // breakable. only runs for one iteration
3849 if (formspec->getReferenceCount() == 1) {
3850 m_game_ui->deleteFormspec();
3854 auto &loc = formspec->getFormspecLocation();
3855 if (loc.type == InventoryLocation::NODEMETA) {
3856 NodeMetadata *meta = client->getEnv().getClientMap().getNodeMetadata(loc.p);
3857 if (!meta || meta->getString("formspec").empty()) {
3858 formspec->quitMenu();
3864 guiroot->bringToFront(formspec);
3870 const video::SColor &skycolor = sky->getSkyColor();
3872 TimeTaker tt_draw("Draw scene");
3873 driver->beginScene(true, true, skycolor);
3875 bool draw_wield_tool = (m_game_ui->m_flags.show_hud &&
3876 (player->hud_flags & HUD_FLAG_WIELDITEM_VISIBLE) &&
3877 (camera->getCameraMode() == CAMERA_MODE_FIRST));
3878 bool draw_crosshair = (
3879 (player->hud_flags & HUD_FLAG_CROSSHAIR_VISIBLE) &&
3880 (camera->getCameraMode() != CAMERA_MODE_THIRD_FRONT));
3881 #ifdef HAVE_TOUCHSCREENGUI
3883 draw_crosshair = !g_settings->getBool("touchtarget");
3884 } catch (SettingNotFoundException) {
3887 RenderingEngine::draw_scene(skycolor, m_game_ui->m_flags.show_hud,
3888 m_game_ui->m_flags.show_minimap, draw_wield_tool, draw_crosshair);
3893 if (m_game_ui->m_flags.show_profiler_graph)
3894 graph->draw(10, screensize.Y - 10, driver, g_fontengine->getFont());
3899 if (runData.damage_flash > 0.0f) {
3900 video::SColor color(runData.damage_flash, 180, 0, 0);
3901 driver->draw2DRectangle(color,
3902 core::rect<s32>(0, 0, screensize.X, screensize.Y),
3905 runData.damage_flash -= 384.0f * dtime;
3911 if (player->hurt_tilt_timer > 0.0f) {
3912 player->hurt_tilt_timer -= dtime * 6.0f;
3914 if (player->hurt_tilt_timer < 0.0f)
3915 player->hurt_tilt_strength = 0.0f;
3919 Update minimap pos and rotation
3921 if (mapper && m_game_ui->m_flags.show_minimap && m_game_ui->m_flags.show_hud) {
3922 mapper->setPos(floatToInt(player->getPosition(), BS));
3923 mapper->setAngle(player->getYaw());
3931 stats->drawtime = tt_draw.stop(true);
3932 g_profiler->avg("Game::updateFrame(): draw scene [ms]", stats->drawtime);
3933 g_profiler->graphAdd("Update frame [ms]", tt_update.stop(true));
3936 /* Log times and stuff for visualization */
3937 inline void Game::updateProfilerGraphs(ProfilerGraph *graph)
3939 Profiler::GraphValues values;
3940 g_profiler->graphGet(values);
3946 /****************************************************************************
3948 ****************************************************************************/
3950 /* On some computers framerate doesn't seem to be automatically limited
3952 inline void Game::limitFps(FpsControl *fps_timings, f32 *dtime)
3954 // not using getRealTime is necessary for wine
3955 device->getTimer()->tick(); // Maker sure device time is up-to-date
3956 u32 time = device->getTimer()->getTime();
3957 u32 last_time = fps_timings->last_time;
3959 if (time > last_time) // Make sure time hasn't overflowed
3960 fps_timings->busy_time = time - last_time;
3962 fps_timings->busy_time = 0;
3964 u32 frametime_min = 1000 / (g_menumgr.pausesGame()
3965 ? g_settings->getFloat("pause_fps_max")
3966 : g_settings->getFloat("fps_max"));
3968 if (fps_timings->busy_time < frametime_min) {
3969 fps_timings->sleep_time = frametime_min - fps_timings->busy_time;
3970 device->sleep(fps_timings->sleep_time);
3972 fps_timings->sleep_time = 0;
3975 /* Get the new value of the device timer. Note that device->sleep() may
3976 * not sleep for the entire requested time as sleep may be interrupted and
3977 * therefore it is arguably more accurate to get the new time from the
3978 * device rather than calculating it by adding sleep_time to time.
3981 device->getTimer()->tick(); // Update device timer
3982 time = device->getTimer()->getTime();
3984 if (time > last_time) // Make sure last_time hasn't overflowed
3985 *dtime = (time - last_time) / 1000.0;
3989 fps_timings->last_time = time;
3992 void Game::showOverlayMessage(const char *msg, float dtime, int percent, bool draw_clouds)
3994 const wchar_t *wmsg = wgettext(msg);
3995 RenderingEngine::draw_load_screen(wmsg, guienv, texture_src, dtime, percent,
4000 void Game::settingChangedCallback(const std::string &setting_name, void *data)
4002 ((Game *)data)->readSettings();
4005 void Game::readSettings()
4007 m_cache_doubletap_jump = g_settings->getBool("doubletap_jump");
4008 m_cache_enable_clouds = g_settings->getBool("enable_clouds");
4009 m_cache_enable_joysticks = g_settings->getBool("enable_joysticks");
4010 m_cache_enable_particles = g_settings->getBool("enable_particles");
4011 m_cache_enable_fog = g_settings->getBool("enable_fog");
4012 m_cache_mouse_sensitivity = g_settings->getFloat("mouse_sensitivity");
4013 m_cache_joystick_frustum_sensitivity = g_settings->getFloat("joystick_frustum_sensitivity");
4014 m_repeat_right_click_time = g_settings->getFloat("repeat_rightclick_time");
4016 m_cache_enable_noclip = g_settings->getBool("noclip");
4017 m_cache_enable_free_move = g_settings->getBool("free_move");
4019 m_cache_fog_start = g_settings->getFloat("fog_start");
4021 m_cache_cam_smoothing = 0;
4022 if (g_settings->getBool("cinematic"))
4023 m_cache_cam_smoothing = 1 - g_settings->getFloat("cinematic_camera_smoothing");
4025 m_cache_cam_smoothing = 1 - g_settings->getFloat("camera_smoothing");
4027 m_cache_fog_start = rangelim(m_cache_fog_start, 0.0f, 0.99f);
4028 m_cache_cam_smoothing = rangelim(m_cache_cam_smoothing, 0.01f, 1.0f);
4029 m_cache_mouse_sensitivity = rangelim(m_cache_mouse_sensitivity, 0.001, 100.0);
4031 m_does_lost_focus_pause_game = g_settings->getBool("pause_on_lost_focus");
4034 /****************************************************************************/
4035 /****************************************************************************
4037 ****************************************************************************/
4038 /****************************************************************************/
4040 void Game::extendedResourceCleanup()
4042 // Extended resource accounting
4043 infostream << "Irrlicht resources after cleanup:" << std::endl;
4044 infostream << "\tRemaining meshes : "
4045 << RenderingEngine::get_mesh_cache()->getMeshCount() << std::endl;
4046 infostream << "\tRemaining textures : "
4047 << driver->getTextureCount() << std::endl;
4049 for (unsigned int i = 0; i < driver->getTextureCount(); i++) {
4050 irr::video::ITexture *texture = driver->getTextureByIndex(i);
4051 infostream << "\t\t" << i << ":" << texture->getName().getPath().c_str()
4055 clearTextureNameCache();
4056 infostream << "\tRemaining materials: "
4057 << driver-> getMaterialRendererCount()
4058 << " (note: irrlicht doesn't support removing renderers)" << std::endl;
4061 void Game::showDeathFormspec()
4063 static std::string formspec_str =
4064 std::string("formspec_version[1]") +
4066 "bgcolor[#320000b4;true]"
4067 "label[4.85,1.35;" + gettext("You died") + "]"
4068 "button_exit[4,3;3,0.5;btn_respawn;" + gettext("Respawn") + "]"
4072 /* Note: FormspecFormSource and LocalFormspecHandler *
4073 * are deleted by guiFormSpecMenu */
4074 FormspecFormSource *fs_src = new FormspecFormSource(formspec_str);
4075 LocalFormspecHandler *txt_dst = new LocalFormspecHandler("MT_DEATH_SCREEN", client);
4077 auto *&formspec = m_game_ui->getFormspecGUI();
4078 GUIFormSpecMenu::create(formspec, client, &input->joystick,
4079 fs_src, txt_dst, client->getFormspecPrepend());
4080 formspec->setFocus("btn_respawn");
4083 #define GET_KEY_NAME(KEY) gettext(getKeySetting(#KEY).name())
4084 void Game::showPauseMenu()
4087 static const std::string control_text = strgettext("Default Controls:\n"
4088 "No menu visible:\n"
4089 "- single tap: button activate\n"
4090 "- double tap: place/use\n"
4091 "- slide finger: look around\n"
4092 "Menu/Inventory visible:\n"
4093 "- double tap (outside):\n"
4095 "- touch stack, touch slot:\n"
4097 "- touch&drag, tap 2nd finger\n"
4098 " --> place single item to slot\n"
4101 static const std::string control_text_template = strgettext("Controls:\n"
4102 "- %s: move forwards\n"
4103 "- %s: move backwards\n"
4105 "- %s: move right\n"
4106 "- %s: jump/climb\n"
4107 "- %s: sneak/go down\n"
4110 "- Mouse: turn/look\n"
4111 "- Mouse left: dig/punch\n"
4112 "- Mouse right: place/use\n"
4113 "- Mouse wheel: select item\n"
4117 char control_text_buf[600];
4119 porting::mt_snprintf(control_text_buf, sizeof(control_text_buf), control_text_template.c_str(),
4120 GET_KEY_NAME(keymap_forward),
4121 GET_KEY_NAME(keymap_backward),
4122 GET_KEY_NAME(keymap_left),
4123 GET_KEY_NAME(keymap_right),
4124 GET_KEY_NAME(keymap_jump),
4125 GET_KEY_NAME(keymap_sneak),
4126 GET_KEY_NAME(keymap_drop),
4127 GET_KEY_NAME(keymap_inventory),
4128 GET_KEY_NAME(keymap_chat)
4131 std::string control_text = std::string(control_text_buf);
4132 str_formspec_escape(control_text);
4135 float ypos = simple_singleplayer_mode ? 0.7f : 0.1f;
4136 std::ostringstream os;
4138 os << "formspec_version[1]" << SIZE_TAG
4139 << "button_exit[4," << (ypos++) << ";3,0.5;btn_continue;"
4140 << strgettext("Continue") << "]";
4142 if (!simple_singleplayer_mode) {
4143 os << "button_exit[4," << (ypos++) << ";3,0.5;btn_change_password;"
4144 << strgettext("Change Password") << "]";
4146 os << "field[4.95,0;5,1.5;;" << strgettext("Game paused") << ";]";
4150 os << "button_exit[4," << (ypos++) << ";3,0.5;btn_sound;"
4151 << strgettext("Sound Volume") << "]";
4152 os << "button_exit[4," << (ypos++) << ";3,0.5;btn_key_config;"
4153 << strgettext("Change Keys") << "]";
4155 os << "button_exit[4," << (ypos++) << ";3,0.5;btn_exit_menu;"
4156 << strgettext("Exit to Menu") << "]";
4157 os << "button_exit[4," << (ypos++) << ";3,0.5;btn_exit_os;"
4158 << strgettext("Exit to OS") << "]"
4159 << "textarea[7.5,0.25;3.9,6.25;;" << control_text << ";]"
4160 << "textarea[0.4,0.25;3.9,6.25;;" << PROJECT_NAME_C " " VERSION_STRING "\n"
4162 << strgettext("Game info:") << "\n";
4163 const std::string &address = client->getAddressName();
4164 static const std::string mode = strgettext("- Mode: ");
4165 if (!simple_singleplayer_mode) {
4166 Address serverAddress = client->getServerAddress();
4167 if (!address.empty()) {
4168 os << mode << strgettext("Remote server") << "\n"
4169 << strgettext("- Address: ") << address;
4171 os << mode << strgettext("Hosting server");
4173 os << "\n" << strgettext("- Port: ") << serverAddress.getPort() << "\n";
4175 os << mode << strgettext("Singleplayer") << "\n";
4177 if (simple_singleplayer_mode || address.empty()) {
4178 static const std::string on = strgettext("On");
4179 static const std::string off = strgettext("Off");
4180 const std::string &damage = g_settings->getBool("enable_damage") ? on : off;
4181 const std::string &creative = g_settings->getBool("creative_mode") ? on : off;
4182 const std::string &announced = g_settings->getBool("server_announce") ? on : off;
4183 os << strgettext("- Damage: ") << damage << "\n"
4184 << strgettext("- Creative Mode: ") << creative << "\n";
4185 if (!simple_singleplayer_mode) {
4186 const std::string &pvp = g_settings->getBool("enable_pvp") ? on : off;
4187 os << strgettext("- PvP: ") << pvp << "\n"
4188 << strgettext("- Public: ") << announced << "\n";
4189 std::string server_name = g_settings->get("server_name");
4190 str_formspec_escape(server_name);
4191 if (announced == on && !server_name.empty())
4192 os << strgettext("- Server Name: ") << server_name;
4199 /* Note: FormspecFormSource and LocalFormspecHandler *
4200 * are deleted by guiFormSpecMenu */
4201 FormspecFormSource *fs_src = new FormspecFormSource(os.str());
4202 LocalFormspecHandler *txt_dst = new LocalFormspecHandler("MT_PAUSE_MENU");
4204 auto *&formspec = m_game_ui->getFormspecGUI();
4205 GUIFormSpecMenu::create(formspec, client, &input->joystick,
4206 fs_src, txt_dst, client->getFormspecPrepend());
4207 formspec->setFocus("btn_continue");
4208 formspec->doPause = true;
4211 /****************************************************************************/
4212 /****************************************************************************
4213 extern function for launching the game
4214 ****************************************************************************/
4215 /****************************************************************************/
4217 void the_game(bool *kill,
4219 InputHandler *input,
4220 const std::string &map_dir,
4221 const std::string &playername,
4222 const std::string &password,
4223 const std::string &address, // If empty local server is created
4226 std::string &error_message,
4227 ChatBackend &chat_backend,
4228 bool *reconnect_requested,
4229 const SubgameSpec &gamespec, // Used for local game
4230 bool simple_singleplayer_mode)
4234 /* Make a copy of the server address because if a local singleplayer server
4235 * is created then this is updated and we don't want to change the value
4236 * passed to us by the calling function
4238 std::string server_address = address;
4242 if (game.startup(kill, random_input, input, map_dir,
4243 playername, password, &server_address, port, error_message,
4244 reconnect_requested, &chat_backend, gamespec,
4245 simple_singleplayer_mode)) {
4250 } catch (SerializationError &e) {
4251 error_message = std::string("A serialization error occurred:\n")
4252 + e.what() + "\n\nThe server is probably "
4253 " running a different version of " PROJECT_NAME_C ".";
4254 errorstream << error_message << std::endl;
4255 } catch (ServerError &e) {
4256 error_message = e.what();
4257 errorstream << "ServerError: " << error_message << std::endl;
4258 } catch (ModError &e) {
4259 error_message = std::string("ModError: ") + e.what() +
4260 strgettext("\nCheck debug.txt for details.");
4261 errorstream << error_message << std::endl;