3 Copyright (C) 2010-2013 celeron55, Perttu Ahola <celeron55@gmail.com>
5 This program is free software; you can redistribute it and/or modify
6 it under the terms of the GNU Lesser General Public License as published by
7 the Free Software Foundation; either version 2.1 of the License, or
8 (at your option) any later version.
10 This program is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 GNU Lesser General Public License for more details.
15 You should have received a copy of the GNU Lesser General Public License along
16 with this program; if not, write to the Free Software Foundation, Inc.,
17 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
24 #include "client/renderingengine.h"
27 #include "client/clientevent.h"
28 #include "client/gameui.h"
29 #include "client/inputhandler.h"
30 #include "client/tile.h" // For TextureSource
31 #include "client/keys.h"
32 #include "client/joystick_controller.h"
33 #include "clientmap.h"
36 #include "content_cao.h"
37 #include "client/event_manager.h"
38 #include "fontengine.h"
43 #include "gui/guiChatConsole.h"
44 #include "gui/guiConfirmRegistration.h"
45 #include "gui/guiFormSpecMenu.h"
46 #include "gui/guiKeyChangeMenu.h"
47 #include "gui/guiPasswordChange.h"
48 #include "gui/guiVolumeChange.h"
49 #include "gui/mainmenumanager.h"
50 #include "gui/profilergraph.h"
53 #include "nodedef.h" // Needed for determining pointing to nodes
54 #include "nodemetadata.h"
55 #include "particles.h"
58 #include "quicktune_shortcutter.h"
64 #include "translation.h"
65 #include "util/basic_macros.h"
66 #include "util/directiontables.h"
67 #include "util/pointedthing.h"
68 #include "irrlicht_changes/static_text.h"
70 #include "script/scripting_client.h"
74 #include "client/sound_openal.h"
76 #include "client/sound.h"
82 struct TextDestNodeMetadata : public TextDest
84 TextDestNodeMetadata(v3s16 p, Client *client)
89 // This is deprecated I guess? -celeron55
90 void gotText(const std::wstring &text)
92 std::string ntext = wide_to_utf8(text);
93 infostream << "Submitting 'text' field of node at (" << m_p.X << ","
94 << m_p.Y << "," << m_p.Z << "): " << ntext << std::endl;
96 fields["text"] = ntext;
97 m_client->sendNodemetaFields(m_p, "", fields);
99 void gotText(const StringMap &fields)
101 m_client->sendNodemetaFields(m_p, "", fields);
108 struct TextDestPlayerInventory : public TextDest
110 TextDestPlayerInventory(Client *client)
115 TextDestPlayerInventory(Client *client, const std::string &formname)
118 m_formname = formname;
120 void gotText(const StringMap &fields)
122 m_client->sendInventoryFields(m_formname, fields);
128 struct LocalFormspecHandler : public TextDest
130 LocalFormspecHandler(const std::string &formname)
132 m_formname = formname;
135 LocalFormspecHandler(const std::string &formname, Client *client):
138 m_formname = formname;
141 void gotText(const StringMap &fields)
143 if (m_formname == "MT_PAUSE_MENU") {
144 if (fields.find("btn_sound") != fields.end()) {
145 g_gamecallback->changeVolume();
149 if (fields.find("btn_key_config") != fields.end()) {
150 g_gamecallback->keyConfig();
154 if (fields.find("btn_exit_menu") != fields.end()) {
155 g_gamecallback->disconnect();
159 if (fields.find("btn_exit_os") != fields.end()) {
160 g_gamecallback->exitToOS();
162 RenderingEngine::get_raw_device()->closeDevice();
167 if (fields.find("btn_change_password") != fields.end()) {
168 g_gamecallback->changePassword();
172 if (fields.find("quit") != fields.end()) {
176 if (fields.find("btn_continue") != fields.end()) {
181 if (m_formname == "MT_DEATH_SCREEN") {
182 assert(m_client != 0);
183 m_client->sendRespawn();
187 if (m_client && m_client->moddingEnabled())
188 m_client->getScript()->on_formspec_input(m_formname, fields);
191 Client *m_client = nullptr;
194 /* Form update callback */
196 class NodeMetadataFormSource: public IFormSource
199 NodeMetadataFormSource(ClientMap *map, v3s16 p):
204 const std::string &getForm() const
206 static const std::string empty_string = "";
207 NodeMetadata *meta = m_map->getNodeMetadata(m_p);
212 return meta->getString("formspec");
215 virtual std::string resolveText(const std::string &str)
217 NodeMetadata *meta = m_map->getNodeMetadata(m_p);
222 return meta->resolveString(str);
229 class PlayerInventoryFormSource: public IFormSource
232 PlayerInventoryFormSource(Client *client):
237 const std::string &getForm() const
239 LocalPlayer *player = m_client->getEnv().getLocalPlayer();
240 return player->inventory_formspec;
246 class NodeDugEvent: public MtEvent
252 NodeDugEvent(v3s16 p, MapNode n):
256 MtEvent::Type getType() const
258 return MtEvent::NODE_DUG;
264 ISoundManager *m_sound;
265 const NodeDefManager *m_ndef;
267 bool makes_footstep_sound;
268 float m_player_step_timer;
270 SimpleSoundSpec m_player_step_sound;
271 SimpleSoundSpec m_player_leftpunch_sound;
272 SimpleSoundSpec m_player_rightpunch_sound;
274 SoundMaker(ISoundManager *sound, const NodeDefManager *ndef):
277 makes_footstep_sound(true),
278 m_player_step_timer(0)
282 void playPlayerStep()
284 if (m_player_step_timer <= 0 && m_player_step_sound.exists()) {
285 m_player_step_timer = 0.03;
286 if (makes_footstep_sound)
287 m_sound->playSound(m_player_step_sound, false);
291 static void viewBobbingStep(MtEvent *e, void *data)
293 SoundMaker *sm = (SoundMaker *)data;
294 sm->playPlayerStep();
297 static void playerRegainGround(MtEvent *e, void *data)
299 SoundMaker *sm = (SoundMaker *)data;
300 sm->playPlayerStep();
303 static void playerJump(MtEvent *e, void *data)
305 //SoundMaker *sm = (SoundMaker*)data;
308 static void cameraPunchLeft(MtEvent *e, void *data)
310 SoundMaker *sm = (SoundMaker *)data;
311 sm->m_sound->playSound(sm->m_player_leftpunch_sound, false);
314 static void cameraPunchRight(MtEvent *e, void *data)
316 SoundMaker *sm = (SoundMaker *)data;
317 sm->m_sound->playSound(sm->m_player_rightpunch_sound, false);
320 static void nodeDug(MtEvent *e, void *data)
322 SoundMaker *sm = (SoundMaker *)data;
323 NodeDugEvent *nde = (NodeDugEvent *)e;
324 sm->m_sound->playSound(sm->m_ndef->get(nde->n).sound_dug, false);
327 static void playerDamage(MtEvent *e, void *data)
329 SoundMaker *sm = (SoundMaker *)data;
330 sm->m_sound->playSound(SimpleSoundSpec("player_damage", 0.5), false);
333 static void playerFallingDamage(MtEvent *e, void *data)
335 SoundMaker *sm = (SoundMaker *)data;
336 sm->m_sound->playSound(SimpleSoundSpec("player_falling_damage", 0.5), false);
339 void registerReceiver(MtEventManager *mgr)
341 mgr->reg(MtEvent::VIEW_BOBBING_STEP, SoundMaker::viewBobbingStep, this);
342 mgr->reg(MtEvent::PLAYER_REGAIN_GROUND, SoundMaker::playerRegainGround, this);
343 mgr->reg(MtEvent::PLAYER_JUMP, SoundMaker::playerJump, this);
344 mgr->reg(MtEvent::CAMERA_PUNCH_LEFT, SoundMaker::cameraPunchLeft, this);
345 mgr->reg(MtEvent::CAMERA_PUNCH_RIGHT, SoundMaker::cameraPunchRight, this);
346 mgr->reg(MtEvent::NODE_DUG, SoundMaker::nodeDug, this);
347 mgr->reg(MtEvent::PLAYER_DAMAGE, SoundMaker::playerDamage, this);
348 mgr->reg(MtEvent::PLAYER_FALLING_DAMAGE, SoundMaker::playerFallingDamage, this);
351 void step(float dtime)
353 m_player_step_timer -= dtime;
357 // Locally stored sounds don't need to be preloaded because of this
358 class GameOnDemandSoundFetcher: public OnDemandSoundFetcher
360 std::set<std::string> m_fetched;
362 void paths_insert(std::set<std::string> &dst_paths,
363 const std::string &base,
364 const std::string &name)
366 dst_paths.insert(base + DIR_DELIM + "sounds" + DIR_DELIM + name + ".ogg");
367 dst_paths.insert(base + DIR_DELIM + "sounds" + DIR_DELIM + name + ".0.ogg");
368 dst_paths.insert(base + DIR_DELIM + "sounds" + DIR_DELIM + name + ".1.ogg");
369 dst_paths.insert(base + DIR_DELIM + "sounds" + DIR_DELIM + name + ".2.ogg");
370 dst_paths.insert(base + DIR_DELIM + "sounds" + DIR_DELIM + name + ".3.ogg");
371 dst_paths.insert(base + DIR_DELIM + "sounds" + DIR_DELIM + name + ".4.ogg");
372 dst_paths.insert(base + DIR_DELIM + "sounds" + DIR_DELIM + name + ".5.ogg");
373 dst_paths.insert(base + DIR_DELIM + "sounds" + DIR_DELIM + name + ".6.ogg");
374 dst_paths.insert(base + DIR_DELIM + "sounds" + DIR_DELIM + name + ".7.ogg");
375 dst_paths.insert(base + DIR_DELIM + "sounds" + DIR_DELIM + name + ".8.ogg");
376 dst_paths.insert(base + DIR_DELIM + "sounds" + DIR_DELIM + name + ".9.ogg");
379 void fetchSounds(const std::string &name,
380 std::set<std::string> &dst_paths,
381 std::set<std::string> &dst_datas)
383 if (m_fetched.count(name))
386 m_fetched.insert(name);
388 paths_insert(dst_paths, porting::path_share, name);
389 paths_insert(dst_paths, porting::path_user, name);
394 // before 1.8 there isn't a "integer interface", only float
395 #if (IRRLICHT_VERSION_MAJOR == 1 && IRRLICHT_VERSION_MINOR < 8)
396 typedef f32 SamplerLayer_t;
398 typedef s32 SamplerLayer_t;
402 class GameGlobalShaderConstantSetter : public IShaderConstantSetter
405 bool *m_force_fog_off;
408 CachedPixelShaderSetting<float, 4> m_sky_bg_color;
409 CachedPixelShaderSetting<float> m_fog_distance;
410 CachedVertexShaderSetting<float> m_animation_timer_vertex;
411 CachedPixelShaderSetting<float> m_animation_timer_pixel;
412 CachedPixelShaderSetting<float, 3> m_day_light;
413 CachedPixelShaderSetting<float, 3> m_eye_position_pixel;
414 CachedVertexShaderSetting<float, 3> m_eye_position_vertex;
415 CachedPixelShaderSetting<float, 3> m_minimap_yaw;
416 CachedPixelShaderSetting<SamplerLayer_t> m_base_texture;
417 CachedPixelShaderSetting<SamplerLayer_t> m_normal_texture;
418 CachedPixelShaderSetting<SamplerLayer_t> m_texture_flags;
422 void onSettingsChange(const std::string &name)
424 if (name == "enable_fog")
425 m_fog_enabled = g_settings->getBool("enable_fog");
428 static void settingsCallback(const std::string &name, void *userdata)
430 reinterpret_cast<GameGlobalShaderConstantSetter*>(userdata)->onSettingsChange(name);
433 void setSky(Sky *sky) { m_sky = sky; }
435 GameGlobalShaderConstantSetter(Sky *sky, bool *force_fog_off,
436 f32 *fog_range, Client *client) :
438 m_force_fog_off(force_fog_off),
439 m_fog_range(fog_range),
440 m_sky_bg_color("skyBgColor"),
441 m_fog_distance("fogDistance"),
442 m_animation_timer_vertex("animationTimer"),
443 m_animation_timer_pixel("animationTimer"),
444 m_day_light("dayLight"),
445 m_eye_position_pixel("eyePosition"),
446 m_eye_position_vertex("eyePosition"),
447 m_minimap_yaw("yawVec"),
448 m_base_texture("baseTexture"),
449 m_normal_texture("normalTexture"),
450 m_texture_flags("textureFlags"),
453 g_settings->registerChangedCallback("enable_fog", settingsCallback, this);
454 m_fog_enabled = g_settings->getBool("enable_fog");
457 ~GameGlobalShaderConstantSetter()
459 g_settings->deregisterChangedCallback("enable_fog", settingsCallback, this);
462 virtual void onSetConstants(video::IMaterialRendererServices *services,
469 video::SColor bgcolor = m_sky->getBgColor();
470 video::SColorf bgcolorf(bgcolor);
471 float bgcolorfa[4] = {
477 m_sky_bg_color.set(bgcolorfa, services);
480 float fog_distance = 10000 * BS;
482 if (m_fog_enabled && !*m_force_fog_off)
483 fog_distance = *m_fog_range;
485 m_fog_distance.set(&fog_distance, services);
487 u32 daynight_ratio = (float)m_client->getEnv().getDayNightRatio();
488 video::SColorf sunlight;
489 get_sunlight_color(&sunlight, daynight_ratio);
494 m_day_light.set(dnc, services);
496 u32 animation_timer = porting::getTimeMs() % 100000;
497 float animation_timer_f = (float)animation_timer / 100000.f;
498 m_animation_timer_vertex.set(&animation_timer_f, services);
499 m_animation_timer_pixel.set(&animation_timer_f, services);
501 float eye_position_array[3];
502 v3f epos = m_client->getEnv().getLocalPlayer()->getEyePosition();
503 #if (IRRLICHT_VERSION_MAJOR == 1 && IRRLICHT_VERSION_MINOR < 8)
504 eye_position_array[0] = epos.X;
505 eye_position_array[1] = epos.Y;
506 eye_position_array[2] = epos.Z;
508 epos.getAs3Values(eye_position_array);
510 m_eye_position_pixel.set(eye_position_array, services);
511 m_eye_position_vertex.set(eye_position_array, services);
513 if (m_client->getMinimap()) {
514 float minimap_yaw_array[3];
515 v3f minimap_yaw = m_client->getMinimap()->getYawVec();
516 #if (IRRLICHT_VERSION_MAJOR == 1 && IRRLICHT_VERSION_MINOR < 8)
517 minimap_yaw_array[0] = minimap_yaw.X;
518 minimap_yaw_array[1] = minimap_yaw.Y;
519 minimap_yaw_array[2] = minimap_yaw.Z;
521 minimap_yaw.getAs3Values(minimap_yaw_array);
523 m_minimap_yaw.set(minimap_yaw_array, services);
526 SamplerLayer_t base_tex = 0,
529 m_base_texture.set(&base_tex, services);
530 m_normal_texture.set(&normal_tex, services);
531 m_texture_flags.set(&flags_tex, services);
536 class GameGlobalShaderConstantSetterFactory : public IShaderConstantSetterFactory
539 bool *m_force_fog_off;
542 std::vector<GameGlobalShaderConstantSetter *> created_nosky;
544 GameGlobalShaderConstantSetterFactory(bool *force_fog_off,
545 f32 *fog_range, Client *client) :
547 m_force_fog_off(force_fog_off),
548 m_fog_range(fog_range),
552 void setSky(Sky *sky) {
554 for (GameGlobalShaderConstantSetter *ggscs : created_nosky) {
555 ggscs->setSky(m_sky);
557 created_nosky.clear();
560 virtual IShaderConstantSetter* create()
562 GameGlobalShaderConstantSetter *scs = new GameGlobalShaderConstantSetter(
563 m_sky, m_force_fog_off, m_fog_range, m_client);
565 created_nosky.push_back(scs);
571 #define SIZE_TAG "size[11,5.5]"
573 #define SIZE_TAG "size[11,5.5,true]" // Fixed size on desktop
576 /****************************************************************************
578 ****************************************************************************/
580 const float object_hit_delay = 0.2;
583 u32 last_time, busy_time, sleep_time;
587 /* The reason the following structs are not anonymous structs within the
588 * class is that they are not used by the majority of member functions and
589 * many functions that do require objects of thse types do not modify them
590 * (so they can be passed as a const qualified parameter)
596 PointedThing pointed_old;
600 bool digging_blocked;
602 bool update_wielded_item_trigger;
603 bool reset_jump_timer;
604 float nodig_delay_timer;
606 float dig_time_complete;
607 float repeat_rightclick_timer;
608 float object_hit_delay_timer;
609 float time_from_last_punch;
610 ClientActiveObject *selected_object;
614 float update_draw_list_timer;
618 v3f update_draw_list_last_cam_dir;
620 float time_of_day_smooth;
625 struct ClientEventHandler
627 void (Game::*handler)(ClientEvent *, CameraOrientation *);
630 /****************************************************************************
632 ****************************************************************************/
634 /* This is not intended to be a public class. If a public class becomes
635 * desirable then it may be better to create another 'wrapper' class that
636 * hides most of the stuff in this class (nothing in this class is required
637 * by any other file) but exposes the public methods/data only.
644 bool startup(bool *kill,
647 const std::string &map_dir,
648 const std::string &playername,
649 const std::string &password,
650 // If address is "", local server is used and address is updated
651 std::string *address,
653 std::string &error_message,
655 ChatBackend *chat_backend,
656 const SubgameSpec &gamespec, // Used for local game
657 bool simple_singleplayer_mode);
664 void extendedResourceCleanup();
666 // Basic initialisation
667 bool init(const std::string &map_dir, std::string *address,
669 const SubgameSpec &gamespec);
671 bool createSingleplayerServer(const std::string &map_dir,
672 const SubgameSpec &gamespec, u16 port, std::string *address);
675 bool createClient(const std::string &playername,
676 const std::string &password, std::string *address, u16 port);
680 bool connectToServer(const std::string &playername,
681 const std::string &password, std::string *address, u16 port,
682 bool *connect_ok, bool *aborted);
683 bool getServerContent(bool *aborted);
687 void updateInteractTimers(f32 dtime);
688 bool checkConnection();
689 bool handleCallbacks();
690 void processQueues();
691 void updateProfilers(const RunStats &stats, const FpsControl &draw_times, f32 dtime);
692 void addProfilerGraphs(const RunStats &stats, const FpsControl &draw_times, f32 dtime);
693 void updateStats(RunStats *stats, const FpsControl &draw_times, f32 dtime);
696 void processUserInput(f32 dtime);
697 void processKeyInput();
698 void processItemSelection(u16 *new_playeritem);
700 void dropSelectedItem(bool single_item = false);
701 void openInventory();
702 void openConsole(float scale, const wchar_t *line=NULL);
703 void toggleFreeMove();
704 void toggleFreeMoveAlt();
705 void togglePitchFly();
708 void toggleCinematic();
709 void toggleAutoforward();
711 void toggleMinimap(bool shift_pressed);
714 void toggleUpdateCamera();
716 void increaseViewRange();
717 void decreaseViewRange();
718 void toggleFullViewRange();
719 void checkZoomEnabled();
721 void updateCameraDirection(CameraOrientation *cam, float dtime);
722 void updateCameraOrientation(CameraOrientation *cam, float dtime);
723 void updatePlayerControl(const CameraOrientation &cam);
724 void step(f32 *dtime);
725 void processClientEvents(CameraOrientation *cam);
726 void updateCamera(u32 busy_time, f32 dtime);
727 void updateSound(f32 dtime);
728 void processPlayerInteraction(f32 dtime, bool show_hud, bool show_debug);
730 * Returns the object or node the player is pointing at.
731 * Also updates the selected thing in the Hud.
733 * @param[in] shootline the shootline, starting from
734 * the camera position. This also gives the maximal distance
736 * @param[in] liquids_pointable if false, liquids are ignored
737 * @param[in] look_for_object if false, objects are ignored
738 * @param[in] camera_offset offset of the camera
739 * @param[out] selected_object the selected object or
742 PointedThing updatePointedThing(
743 const core::line3d<f32> &shootline, bool liquids_pointable,
744 bool look_for_object, const v3s16 &camera_offset);
745 void handlePointingAtNothing(const ItemStack &playerItem);
746 void handlePointingAtNode(const PointedThing &pointed,
747 const ItemDefinition &playeritem_def, const ItemStack &playeritem,
748 const ToolCapabilities &playeritem_toolcap, f32 dtime);
749 void handlePointingAtObject(const PointedThing &pointed, const ItemStack &playeritem,
750 const v3f &player_position, bool show_debug);
751 void handleDigging(const PointedThing &pointed, const v3s16 &nodepos,
752 const ToolCapabilities &playeritem_toolcap, f32 dtime);
753 void updateFrame(ProfilerGraph *graph, RunStats *stats, f32 dtime,
754 const CameraOrientation &cam);
755 void updateProfilerGraphs(ProfilerGraph *graph);
758 void limitFps(FpsControl *fps_timings, f32 *dtime);
760 void showOverlayMessage(const char *msg, float dtime, int percent,
761 bool draw_clouds = true);
763 static void settingChangedCallback(const std::string &setting_name, void *data);
766 inline bool isKeyDown(GameKeyType k)
768 return input->isKeyDown(k);
770 inline bool wasKeyDown(GameKeyType k)
772 return input->wasKeyDown(k);
776 void handleAndroidChatInput();
781 bool force_fog_off = false;
782 bool disable_camera_update = false;
785 void showDeathFormspec();
786 void showPauseMenu();
788 // ClientEvent handlers
789 void handleClientEvent_None(ClientEvent *event, CameraOrientation *cam);
790 void handleClientEvent_PlayerDamage(ClientEvent *event, CameraOrientation *cam);
791 void handleClientEvent_PlayerForceMove(ClientEvent *event, CameraOrientation *cam);
792 void handleClientEvent_Deathscreen(ClientEvent *event, CameraOrientation *cam);
793 void handleClientEvent_ShowFormSpec(ClientEvent *event, CameraOrientation *cam);
794 void handleClientEvent_ShowLocalFormSpec(ClientEvent *event, CameraOrientation *cam);
795 void handleClientEvent_HandleParticleEvent(ClientEvent *event,
796 CameraOrientation *cam);
797 void handleClientEvent_HudAdd(ClientEvent *event, CameraOrientation *cam);
798 void handleClientEvent_HudRemove(ClientEvent *event, CameraOrientation *cam);
799 void handleClientEvent_HudChange(ClientEvent *event, CameraOrientation *cam);
800 void handleClientEvent_SetSky(ClientEvent *event, CameraOrientation *cam);
801 void handleClientEvent_OverrideDayNigthRatio(ClientEvent *event,
802 CameraOrientation *cam);
803 void handleClientEvent_CloudParams(ClientEvent *event, CameraOrientation *cam);
805 void updateChat(f32 dtime, const v2u32 &screensize);
807 bool nodePlacementPrediction(const ItemDefinition &playeritem_def,
808 const ItemStack &playeritem, const v3s16 &nodepos, const v3s16 &neighbourpos);
809 static const ClientEventHandler clientEventHandler[CLIENTEVENT_MAX];
811 InputHandler *input = nullptr;
813 Client *client = nullptr;
814 Server *server = nullptr;
816 IWritableTextureSource *texture_src = nullptr;
817 IWritableShaderSource *shader_src = nullptr;
819 // When created, these will be filled with data received from the server
820 IWritableItemDefManager *itemdef_manager = nullptr;
821 NodeDefManager *nodedef_manager = nullptr;
823 GameOnDemandSoundFetcher soundfetcher; // useful when testing
824 ISoundManager *sound = nullptr;
825 bool sound_is_dummy = false;
826 SoundMaker *soundmaker = nullptr;
828 ChatBackend *chat_backend = nullptr;
830 GUIFormSpecMenu *current_formspec = nullptr;
831 //default: "". If other than "", empty show_formspec packets will only close the formspec when the formname matches
832 std::string cur_formname;
834 EventManager *eventmgr = nullptr;
835 QuicktuneShortcutter *quicktune = nullptr;
836 bool registration_confirmation_shown = false;
838 std::unique_ptr<GameUI> m_game_ui;
839 GUIChatConsole *gui_chat_console = nullptr; // Free using ->Drop()
840 MapDrawControl *draw_control = nullptr;
841 Camera *camera = nullptr;
842 Clouds *clouds = nullptr; // Free using ->Drop()
843 Sky *sky = nullptr; // Free using ->Drop()
844 Inventory *local_inventory = nullptr;
846 Minimap *mapper = nullptr;
852 This class does take ownership/responsibily for cleaning up etc of any of
853 these items (e.g. device)
855 IrrlichtDevice *device;
856 video::IVideoDriver *driver;
857 scene::ISceneManager *smgr;
859 std::string *error_message;
860 bool *reconnect_requested;
861 scene::ISceneNode *skybox;
864 bool simple_singleplayer_mode;
867 /* Pre-calculated values
869 int crack_animation_length;
871 IntervalLimiter profiler_interval;
874 * TODO: Local caching of settings is not optimal and should at some stage
875 * be updated to use a global settings object for getting thse values
876 * (as opposed to the this local caching). This can be addressed in
879 bool m_cache_doubletap_jump;
880 bool m_cache_enable_clouds;
881 bool m_cache_enable_joysticks;
882 bool m_cache_enable_particles;
883 bool m_cache_enable_fog;
884 bool m_cache_enable_noclip;
885 bool m_cache_enable_free_move;
886 f32 m_cache_mouse_sensitivity;
887 f32 m_cache_joystick_frustum_sensitivity;
888 f32 m_repeat_right_click_time;
889 f32 m_cache_cam_smoothing;
890 f32 m_cache_fog_start;
892 bool m_invert_mouse = false;
893 bool m_first_loop_after_window_activation = false;
894 bool m_camera_offset_changed = false;
896 bool m_does_lost_focus_pause_game = false;
899 bool m_cache_hold_aux1;
900 bool m_android_chat_open;
905 m_game_ui(new GameUI())
907 g_settings->registerChangedCallback("doubletap_jump",
908 &settingChangedCallback, this);
909 g_settings->registerChangedCallback("enable_clouds",
910 &settingChangedCallback, this);
911 g_settings->registerChangedCallback("doubletap_joysticks",
912 &settingChangedCallback, this);
913 g_settings->registerChangedCallback("enable_particles",
914 &settingChangedCallback, this);
915 g_settings->registerChangedCallback("enable_fog",
916 &settingChangedCallback, this);
917 g_settings->registerChangedCallback("mouse_sensitivity",
918 &settingChangedCallback, this);
919 g_settings->registerChangedCallback("joystick_frustum_sensitivity",
920 &settingChangedCallback, this);
921 g_settings->registerChangedCallback("repeat_rightclick_time",
922 &settingChangedCallback, this);
923 g_settings->registerChangedCallback("noclip",
924 &settingChangedCallback, this);
925 g_settings->registerChangedCallback("free_move",
926 &settingChangedCallback, this);
927 g_settings->registerChangedCallback("cinematic",
928 &settingChangedCallback, this);
929 g_settings->registerChangedCallback("cinematic_camera_smoothing",
930 &settingChangedCallback, this);
931 g_settings->registerChangedCallback("camera_smoothing",
932 &settingChangedCallback, this);
937 m_cache_hold_aux1 = false; // This is initialised properly later
944 /****************************************************************************
946 ****************************************************************************/
955 delete server; // deleted first to stop all server threads
958 delete local_inventory;
964 delete nodedef_manager;
965 delete itemdef_manager;
968 extendedResourceCleanup();
970 g_settings->deregisterChangedCallback("doubletap_jump",
971 &settingChangedCallback, this);
972 g_settings->deregisterChangedCallback("enable_clouds",
973 &settingChangedCallback, this);
974 g_settings->deregisterChangedCallback("enable_particles",
975 &settingChangedCallback, this);
976 g_settings->deregisterChangedCallback("enable_fog",
977 &settingChangedCallback, this);
978 g_settings->deregisterChangedCallback("mouse_sensitivity",
979 &settingChangedCallback, this);
980 g_settings->deregisterChangedCallback("repeat_rightclick_time",
981 &settingChangedCallback, this);
982 g_settings->deregisterChangedCallback("noclip",
983 &settingChangedCallback, this);
984 g_settings->deregisterChangedCallback("free_move",
985 &settingChangedCallback, this);
986 g_settings->deregisterChangedCallback("cinematic",
987 &settingChangedCallback, this);
988 g_settings->deregisterChangedCallback("cinematic_camera_smoothing",
989 &settingChangedCallback, this);
990 g_settings->deregisterChangedCallback("camera_smoothing",
991 &settingChangedCallback, this);
994 bool Game::startup(bool *kill,
997 const std::string &map_dir,
998 const std::string &playername,
999 const std::string &password,
1000 std::string *address, // can change if simple_singleplayer_mode
1002 std::string &error_message,
1004 ChatBackend *chat_backend,
1005 const SubgameSpec &gamespec,
1006 bool simple_singleplayer_mode)
1009 this->device = RenderingEngine::get_raw_device();
1011 this->error_message = &error_message;
1012 this->reconnect_requested = reconnect;
1013 this->random_input = random_input;
1014 this->input = input;
1015 this->chat_backend = chat_backend;
1016 this->simple_singleplayer_mode = simple_singleplayer_mode;
1018 input->keycache.populate();
1020 driver = device->getVideoDriver();
1021 smgr = RenderingEngine::get_scene_manager();
1023 RenderingEngine::get_scene_manager()->getParameters()->
1024 setAttribute(scene::OBJ_LOADER_IGNORE_MATERIAL_FILES, true);
1027 runData = GameRunData();
1028 runData.time_from_last_punch = 10.0;
1029 runData.update_wielded_item_trigger = true;
1031 m_game_ui->initFlags();
1033 m_invert_mouse = g_settings->getBool("invert_mouse");
1034 m_first_loop_after_window_activation = true;
1036 g_translations->clear();
1038 if (!init(map_dir, address, port, gamespec))
1041 if (!createClient(playername, password, address, port))
1044 RenderingEngine::initialize(client, hud);
1052 ProfilerGraph graph;
1053 RunStats stats = { 0 };
1054 CameraOrientation cam_view_target = { 0 };
1055 CameraOrientation cam_view = { 0 };
1056 FpsControl draw_times = { 0 };
1057 f32 dtime; // in seconds
1059 /* Clear the profiler */
1060 Profiler::GraphValues dummyvalues;
1061 g_profiler->graphGet(dummyvalues);
1063 draw_times.last_time = RenderingEngine::get_timer_time();
1065 set_light_table(g_settings->getFloat("display_gamma"));
1068 m_cache_hold_aux1 = g_settings->getBool("fast_move")
1069 && client->checkPrivilege("fast");
1072 irr::core::dimension2d<u32> previous_screen_size(g_settings->getU16("screen_w"),
1073 g_settings->getU16("screen_h"));
1075 while (RenderingEngine::run()
1076 && !(*kill || g_gamecallback->shutdown_requested
1077 || (server && server->isShutdownRequested()))) {
1079 const irr::core::dimension2d<u32> ¤t_screen_size =
1080 RenderingEngine::get_video_driver()->getScreenSize();
1081 // Verify if window size has changed and save it if it's the case
1082 // Ensure evaluating settings->getBool after verifying screensize
1083 // First condition is cheaper
1084 if (previous_screen_size != current_screen_size &&
1085 current_screen_size != irr::core::dimension2d<u32>(0,0) &&
1086 g_settings->getBool("autosave_screensize")) {
1087 g_settings->setU16("screen_w", current_screen_size.Width);
1088 g_settings->setU16("screen_h", current_screen_size.Height);
1089 previous_screen_size = current_screen_size;
1092 /* Must be called immediately after a device->run() call because it
1093 * uses device->getTimer()->getTime()
1095 limitFps(&draw_times, &dtime);
1097 updateStats(&stats, draw_times, dtime);
1098 updateInteractTimers(dtime);
1100 if (!checkConnection())
1102 if (!handleCallbacks())
1107 m_game_ui->clearInfoText();
1108 hud->resizeHotbar();
1110 updateProfilers(stats, draw_times, dtime);
1111 processUserInput(dtime);
1112 // Update camera before player movement to avoid camera lag of one frame
1113 updateCameraDirection(&cam_view_target, dtime);
1114 cam_view.camera_yaw += (cam_view_target.camera_yaw -
1115 cam_view.camera_yaw) * m_cache_cam_smoothing;
1116 cam_view.camera_pitch += (cam_view_target.camera_pitch -
1117 cam_view.camera_pitch) * m_cache_cam_smoothing;
1118 updatePlayerControl(cam_view);
1120 processClientEvents(&cam_view_target);
1121 updateCamera(draw_times.busy_time, dtime);
1123 processPlayerInteraction(dtime, m_game_ui->m_flags.show_hud,
1124 m_game_ui->m_flags.show_debug);
1125 updateFrame(&graph, &stats, dtime, cam_view);
1126 updateProfilerGraphs(&graph);
1128 // Update if minimap has been disabled by the server
1129 m_game_ui->m_flags.show_minimap &= client->shouldShowMinimap();
1131 if (m_does_lost_focus_pause_game && !device->isWindowFocused() && !isMenuActive()) {
1138 void Game::shutdown()
1140 RenderingEngine::finalize();
1141 #if IRRLICHT_VERSION_MAJOR == 1 && IRRLICHT_VERSION_MINOR <= 8
1142 if (g_settings->get("3d_mode") == "pageflip") {
1143 driver->setRenderTarget(irr::video::ERT_STEREO_BOTH_BUFFERS);
1146 if (current_formspec)
1147 current_formspec->quitMenu();
1149 showOverlayMessage("Shutting down...", 0, 0, false);
1154 if (gui_chat_console)
1155 gui_chat_console->drop();
1161 while (g_menumgr.menuCount() > 0) {
1162 g_menumgr.m_stack.front()->setVisible(false);
1163 g_menumgr.deletingMenu(g_menumgr.m_stack.front());
1166 if (current_formspec) {
1167 current_formspec->drop();
1168 current_formspec = NULL;
1171 chat_backend->addMessage(L"", L"# Disconnected.");
1172 chat_backend->addMessage(L"", L"");
1176 while (!client->isShutdown()) {
1177 assert(texture_src != NULL);
1178 assert(shader_src != NULL);
1179 texture_src->processQueue();
1180 shader_src->processQueue();
1187 /****************************************************************************/
1188 /****************************************************************************
1190 ****************************************************************************/
1191 /****************************************************************************/
1194 const std::string &map_dir,
1195 std::string *address,
1197 const SubgameSpec &gamespec)
1199 texture_src = createTextureSource();
1201 showOverlayMessage("Loading...", 0, 0);
1203 shader_src = createShaderSource();
1205 itemdef_manager = createItemDefManager();
1206 nodedef_manager = createNodeDefManager();
1208 eventmgr = new EventManager();
1209 quicktune = new QuicktuneShortcutter();
1211 if (!(texture_src && shader_src && itemdef_manager && nodedef_manager
1212 && eventmgr && quicktune))
1218 // Create a server if not connecting to an existing one
1219 if (address->empty()) {
1220 if (!createSingleplayerServer(map_dir, gamespec, port, address))
1227 bool Game::initSound()
1230 if (g_settings->getBool("enable_sound")) {
1231 infostream << "Attempting to use OpenAL audio" << std::endl;
1232 sound = createOpenALSoundManager(g_sound_manager_singleton.get(), &soundfetcher);
1234 infostream << "Failed to initialize OpenAL audio" << std::endl;
1236 infostream << "Sound disabled." << std::endl;
1240 infostream << "Using dummy audio." << std::endl;
1241 sound = &dummySoundManager;
1242 sound_is_dummy = true;
1245 soundmaker = new SoundMaker(sound, nodedef_manager);
1249 soundmaker->registerReceiver(eventmgr);
1254 bool Game::createSingleplayerServer(const std::string &map_dir,
1255 const SubgameSpec &gamespec, u16 port, std::string *address)
1257 showOverlayMessage("Creating server...", 0, 5);
1259 std::string bind_str = g_settings->get("bind_address");
1260 Address bind_addr(0, 0, 0, 0, port);
1262 if (g_settings->getBool("ipv6_server")) {
1263 bind_addr.setAddress((IPv6AddressBytes *) NULL);
1267 bind_addr.Resolve(bind_str.c_str());
1268 } catch (ResolveError &e) {
1269 infostream << "Resolving bind address \"" << bind_str
1270 << "\" failed: " << e.what()
1271 << " -- Listening on all addresses." << std::endl;
1274 if (bind_addr.isIPv6() && !g_settings->getBool("enable_ipv6")) {
1275 *error_message = "Unable to listen on " +
1276 bind_addr.serializeString() +
1277 " because IPv6 is disabled";
1278 errorstream << *error_message << std::endl;
1282 server = new Server(map_dir, gamespec, simple_singleplayer_mode, bind_addr, false);
1289 bool Game::createClient(const std::string &playername,
1290 const std::string &password, std::string *address, u16 port)
1292 showOverlayMessage("Creating client...", 0, 10);
1294 draw_control = new MapDrawControl;
1298 bool could_connect, connect_aborted;
1299 #ifdef HAVE_TOUCHSCREENGUI
1300 if (g_touchscreengui) {
1301 g_touchscreengui->init(texture_src);
1302 g_touchscreengui->hide();
1305 if (!connectToServer(playername, password, address, port,
1306 &could_connect, &connect_aborted))
1309 if (!could_connect) {
1310 if (error_message->empty() && !connect_aborted) {
1311 // Should not happen if error messages are set properly
1312 *error_message = "Connection failed for unknown reason";
1313 errorstream << *error_message << std::endl;
1318 if (!getServerContent(&connect_aborted)) {
1319 if (error_message->empty() && !connect_aborted) {
1320 // Should not happen if error messages are set properly
1321 *error_message = "Connection failed for unknown reason";
1322 errorstream << *error_message << std::endl;
1327 GameGlobalShaderConstantSetterFactory *scsf = new GameGlobalShaderConstantSetterFactory(
1328 &m_flags.force_fog_off, &runData.fog_range, client);
1329 shader_src->addShaderConstantSetterFactory(scsf);
1331 // Update cached textures, meshes and materials
1332 client->afterContentReceived();
1336 camera = new Camera(*draw_control, client);
1337 if (!camera || !camera->successfullyCreated(*error_message))
1339 client->setCamera(camera);
1343 if (m_cache_enable_clouds) {
1344 clouds = new Clouds(smgr, -1, time(0));
1346 *error_message = "Memory allocation error (clouds)";
1347 errorstream << *error_message << std::endl;
1354 sky = new Sky(-1, texture_src);
1356 skybox = NULL; // This is used/set later on in the main run loop
1358 local_inventory = new Inventory(itemdef_manager);
1360 if (!(sky && local_inventory)) {
1361 *error_message = "Memory allocation error (sky or local inventory)";
1362 errorstream << *error_message << std::endl;
1366 /* Pre-calculated values
1368 video::ITexture *t = texture_src->getTexture("crack_anylength.png");
1370 v2u32 size = t->getOriginalSize();
1371 crack_animation_length = size.Y / size.X;
1373 crack_animation_length = 5;
1379 /* Set window caption
1381 std::wstring str = utf8_to_wide(PROJECT_NAME_C);
1383 str += utf8_to_wide(g_version_hash);
1385 str += driver->getName();
1387 device->setWindowCaption(str.c_str());
1389 LocalPlayer *player = client->getEnv().getLocalPlayer();
1390 player->hurt_tilt_timer = 0;
1391 player->hurt_tilt_strength = 0;
1393 hud = new Hud(guienv, client, player, local_inventory);
1396 *error_message = "Memory error: could not create HUD";
1397 errorstream << *error_message << std::endl;
1401 mapper = client->getMinimap();
1403 mapper->setMinimapMode(MINIMAP_MODE_OFF);
1408 bool Game::initGui()
1412 // Remove stale "recent" chat messages from previous connections
1413 chat_backend->clearRecentChat();
1415 // Make sure the size of the recent messages buffer is right
1416 chat_backend->applySettings();
1418 // Chat backend and console
1419 gui_chat_console = new GUIChatConsole(guienv, guienv->getRootGUIElement(),
1420 -1, chat_backend, client, &g_menumgr);
1421 if (!gui_chat_console) {
1422 *error_message = "Could not allocate memory for chat console";
1423 errorstream << *error_message << std::endl;
1427 #ifdef HAVE_TOUCHSCREENGUI
1429 if (g_touchscreengui)
1430 g_touchscreengui->show();
1437 bool Game::connectToServer(const std::string &playername,
1438 const std::string &password, std::string *address, u16 port,
1439 bool *connect_ok, bool *connection_aborted)
1441 *connect_ok = false; // Let's not be overly optimistic
1442 *connection_aborted = false;
1443 bool local_server_mode = false;
1445 showOverlayMessage("Resolving address...", 0, 15);
1447 Address connect_address(0, 0, 0, 0, port);
1450 connect_address.Resolve(address->c_str());
1452 if (connect_address.isZero()) { // i.e. INADDR_ANY, IN6ADDR_ANY
1453 //connect_address.Resolve("localhost");
1454 if (connect_address.isIPv6()) {
1455 IPv6AddressBytes addr_bytes;
1456 addr_bytes.bytes[15] = 1;
1457 connect_address.setAddress(&addr_bytes);
1459 connect_address.setAddress(127, 0, 0, 1);
1461 local_server_mode = true;
1463 } catch (ResolveError &e) {
1464 *error_message = std::string("Couldn't resolve address: ") + e.what();
1465 errorstream << *error_message << std::endl;
1469 if (connect_address.isIPv6() && !g_settings->getBool("enable_ipv6")) {
1470 *error_message = "Unable to connect to " +
1471 connect_address.serializeString() +
1472 " because IPv6 is disabled";
1473 errorstream << *error_message << std::endl;
1477 client = new Client(playername.c_str(), password, *address,
1478 *draw_control, texture_src, shader_src,
1479 itemdef_manager, nodedef_manager, sound, eventmgr,
1480 connect_address.isIPv6(), m_game_ui.get());
1485 client->m_simple_singleplayer_mode = simple_singleplayer_mode;
1487 infostream << "Connecting to server at ";
1488 connect_address.print(&infostream);
1489 infostream << std::endl;
1491 client->connect(connect_address,
1492 simple_singleplayer_mode || local_server_mode);
1495 Wait for server to accept connection
1501 FpsControl fps_control = { 0 };
1503 f32 wait_time = 0; // in seconds
1505 fps_control.last_time = RenderingEngine::get_timer_time();
1507 while (RenderingEngine::run()) {
1509 limitFps(&fps_control, &dtime);
1511 // Update client and server
1512 client->step(dtime);
1515 server->step(dtime);
1518 if (client->getState() == LC_Init) {
1524 if (*connection_aborted)
1527 if (client->accessDenied()) {
1528 *error_message = "Access denied. Reason: "
1529 + client->accessDeniedReason();
1530 *reconnect_requested = client->reconnectRequested();
1531 errorstream << *error_message << std::endl;
1535 if (input->cancelPressed()) {
1536 *connection_aborted = true;
1537 infostream << "Connect aborted [Escape]" << std::endl;
1541 if (client->m_is_registration_confirmation_state) {
1542 if (registration_confirmation_shown) {
1543 // Keep drawing the GUI
1544 RenderingEngine::draw_menu_scene(guienv, dtime, true);
1546 registration_confirmation_shown = true;
1547 (new GUIConfirmRegistration(guienv, guienv->getRootGUIElement(), -1,
1548 &g_menumgr, client, playername, password, *address, connection_aborted))->drop();
1552 // Only time out if we aren't waiting for the server we started
1553 if (!address->empty() && wait_time > 10) {
1554 *error_message = "Connection timed out.";
1555 errorstream << *error_message << std::endl;
1560 showOverlayMessage("Connecting to server...", dtime, 20);
1563 } catch (con::PeerNotFoundException &e) {
1564 // TODO: Should something be done here? At least an info/error
1572 bool Game::getServerContent(bool *aborted)
1576 FpsControl fps_control = { 0 };
1577 f32 dtime; // in seconds
1579 fps_control.last_time = RenderingEngine::get_timer_time();
1581 while (RenderingEngine::run()) {
1583 limitFps(&fps_control, &dtime);
1585 // Update client and server
1586 client->step(dtime);
1589 server->step(dtime);
1592 if (client->mediaReceived() && client->itemdefReceived() &&
1593 client->nodedefReceived()) {
1598 if (!checkConnection())
1601 if (client->getState() < LC_Init) {
1602 *error_message = "Client disconnected";
1603 errorstream << *error_message << std::endl;
1607 if (input->cancelPressed()) {
1609 infostream << "Connect aborted [Escape]" << std::endl;
1616 if (!client->itemdefReceived()) {
1617 const wchar_t *text = wgettext("Item definitions...");
1619 RenderingEngine::draw_load_screen(text, guienv, texture_src,
1622 } else if (!client->nodedefReceived()) {
1623 const wchar_t *text = wgettext("Node definitions...");
1625 RenderingEngine::draw_load_screen(text, guienv, texture_src,
1629 std::stringstream message;
1630 std::fixed(message);
1631 message.precision(0);
1632 message << gettext("Media...") << " " << (client->mediaReceiveProgress()*100) << "%";
1633 message.precision(2);
1635 if ((USE_CURL == 0) ||
1636 (!g_settings->getBool("enable_remote_media_server"))) {
1637 float cur = client->getCurRate();
1638 std::string cur_unit = gettext("KiB/s");
1642 cur_unit = gettext("MiB/s");
1645 message << " (" << cur << ' ' << cur_unit << ")";
1648 progress = 30 + client->mediaReceiveProgress() * 35 + 0.5;
1649 RenderingEngine::draw_load_screen(utf8_to_wide(message.str()), guienv,
1650 texture_src, dtime, progress);
1658 /****************************************************************************/
1659 /****************************************************************************
1661 ****************************************************************************/
1662 /****************************************************************************/
1664 inline void Game::updateInteractTimers(f32 dtime)
1666 if (runData.nodig_delay_timer >= 0)
1667 runData.nodig_delay_timer -= dtime;
1669 if (runData.object_hit_delay_timer >= 0)
1670 runData.object_hit_delay_timer -= dtime;
1672 runData.time_from_last_punch += dtime;
1676 /* returns false if game should exit, otherwise true
1678 inline bool Game::checkConnection()
1680 if (client->accessDenied()) {
1681 *error_message = "Access denied. Reason: "
1682 + client->accessDeniedReason();
1683 *reconnect_requested = client->reconnectRequested();
1684 errorstream << *error_message << std::endl;
1692 /* returns false if game should exit, otherwise true
1694 inline bool Game::handleCallbacks()
1696 if (g_gamecallback->disconnect_requested) {
1697 g_gamecallback->disconnect_requested = false;
1701 if (g_gamecallback->changepassword_requested) {
1702 (new GUIPasswordChange(guienv, guiroot, -1,
1703 &g_menumgr, client))->drop();
1704 g_gamecallback->changepassword_requested = false;
1707 if (g_gamecallback->changevolume_requested) {
1708 (new GUIVolumeChange(guienv, guiroot, -1,
1709 &g_menumgr))->drop();
1710 g_gamecallback->changevolume_requested = false;
1713 if (g_gamecallback->keyconfig_requested) {
1714 (new GUIKeyChangeMenu(guienv, guiroot, -1,
1715 &g_menumgr))->drop();
1716 g_gamecallback->keyconfig_requested = false;
1719 if (g_gamecallback->keyconfig_changed) {
1720 input->keycache.populate(); // update the cache with new settings
1721 g_gamecallback->keyconfig_changed = false;
1728 void Game::processQueues()
1730 texture_src->processQueue();
1731 itemdef_manager->processQueue(client);
1732 shader_src->processQueue();
1736 void Game::updateProfilers(const RunStats &stats, const FpsControl &draw_times, f32 dtime)
1738 float profiler_print_interval =
1739 g_settings->getFloat("profiler_print_interval");
1740 bool print_to_log = true;
1742 if (profiler_print_interval == 0) {
1743 print_to_log = false;
1744 profiler_print_interval = 5;
1747 if (profiler_interval.step(dtime, profiler_print_interval)) {
1749 infostream << "Profiler:" << std::endl;
1750 g_profiler->print(infostream);
1753 m_game_ui->updateProfiler();
1754 g_profiler->clear();
1757 addProfilerGraphs(stats, draw_times, dtime);
1761 void Game::addProfilerGraphs(const RunStats &stats,
1762 const FpsControl &draw_times, f32 dtime)
1764 g_profiler->graphAdd("mainloop_other",
1765 draw_times.busy_time / 1000.0f - stats.drawtime / 1000.0f);
1767 if (draw_times.sleep_time != 0)
1768 g_profiler->graphAdd("mainloop_sleep", draw_times.sleep_time / 1000.0f);
1769 g_profiler->graphAdd("mainloop_dtime", dtime);
1771 g_profiler->add("Elapsed time", dtime);
1772 g_profiler->avg("FPS", 1. / dtime);
1776 void Game::updateStats(RunStats *stats, const FpsControl &draw_times,
1783 /* Time average and jitter calculation
1785 jp = &stats->dtime_jitter;
1786 jp->avg = jp->avg * 0.96 + dtime * 0.04;
1788 jitter = dtime - jp->avg;
1790 if (jitter > jp->max)
1793 jp->counter += dtime;
1795 if (jp->counter > 0.0) {
1797 jp->max_sample = jp->max;
1798 jp->max_fraction = jp->max_sample / (jp->avg + 0.001);
1802 /* Busytime average and jitter calculation
1804 jp = &stats->busy_time_jitter;
1805 jp->avg = jp->avg + draw_times.busy_time * 0.02;
1807 jitter = draw_times.busy_time - jp->avg;
1809 if (jitter > jp->max)
1811 if (jitter < jp->min)
1814 jp->counter += dtime;
1816 if (jp->counter > 0.0) {
1818 jp->max_sample = jp->max;
1819 jp->min_sample = jp->min;
1827 /****************************************************************************
1829 ****************************************************************************/
1831 void Game::processUserInput(f32 dtime)
1833 // Reset input if window not active or some menu is active
1834 if (!device->isWindowActive() || isMenuActive() || guienv->hasFocus(gui_chat_console)) {
1836 #ifdef HAVE_TOUCHSCREENGUI
1837 g_touchscreengui->hide();
1840 #ifdef HAVE_TOUCHSCREENGUI
1841 else if (g_touchscreengui) {
1842 /* on touchscreengui step may generate own input events which ain't
1843 * what we want in case we just did clear them */
1844 g_touchscreengui->step(dtime);
1848 if (!guienv->hasFocus(gui_chat_console) && gui_chat_console->isOpen()) {
1849 gui_chat_console->closeConsoleAtOnce();
1852 // Input handler step() (used by the random input generator)
1856 if (current_formspec != NULL)
1857 current_formspec->getAndroidUIInput();
1859 handleAndroidChatInput();
1862 // Increase timer for double tap of "keymap_jump"
1863 if (m_cache_doubletap_jump && runData.jump_timer <= 0.2f)
1864 runData.jump_timer += dtime;
1867 processItemSelection(&runData.new_playeritem);
1871 void Game::processKeyInput()
1873 if (wasKeyDown(KeyType::DROP)) {
1874 dropSelectedItem(isKeyDown(KeyType::SNEAK));
1875 } else if (wasKeyDown(KeyType::AUTOFORWARD)) {
1876 toggleAutoforward();
1877 } else if (wasKeyDown(KeyType::BACKWARD)) {
1878 if (g_settings->getBool("continuous_forward"))
1879 toggleAutoforward();
1880 } else if (wasKeyDown(KeyType::INVENTORY)) {
1882 } else if (input->cancelPressed()) {
1883 if (!gui_chat_console->isOpenInhibited()) {
1886 } else if (wasKeyDown(KeyType::CHAT)) {
1887 openConsole(0.2, L"");
1888 } else if (wasKeyDown(KeyType::CMD)) {
1889 openConsole(0.2, L"/");
1890 } else if (wasKeyDown(KeyType::CMD_LOCAL)) {
1891 if (client->moddingEnabled())
1892 openConsole(0.2, L".");
1894 m_game_ui->showStatusText(wgettext("CSM is disabled"));
1895 } else if (wasKeyDown(KeyType::CONSOLE)) {
1896 openConsole(core::clamp(g_settings->getFloat("console_height"), 0.1f, 1.0f));
1897 } else if (wasKeyDown(KeyType::FREEMOVE)) {
1899 } else if (wasKeyDown(KeyType::JUMP)) {
1900 toggleFreeMoveAlt();
1901 } else if (wasKeyDown(KeyType::PITCHFLY)) {
1903 } else if (wasKeyDown(KeyType::FASTMOVE)) {
1905 } else if (wasKeyDown(KeyType::NOCLIP)) {
1907 } else if (wasKeyDown(KeyType::MUTE)) {
1908 bool new_mute_sound = !g_settings->getBool("mute_sound");
1909 g_settings->setBool("mute_sound", new_mute_sound);
1911 m_game_ui->showTranslatedStatusText("Sound muted");
1913 m_game_ui->showTranslatedStatusText("Sound unmuted");
1914 } else if (wasKeyDown(KeyType::INC_VOLUME)) {
1915 float new_volume = rangelim(g_settings->getFloat("sound_volume") + 0.1f, 0.0f, 1.0f);
1917 g_settings->setFloat("sound_volume", new_volume);
1918 const wchar_t *str = wgettext("Volume changed to %d%%");
1919 swprintf(buf, sizeof(buf) / sizeof(wchar_t), str, myround(new_volume * 100));
1921 m_game_ui->showStatusText(buf);
1922 } else if (wasKeyDown(KeyType::DEC_VOLUME)) {
1923 float new_volume = rangelim(g_settings->getFloat("sound_volume") - 0.1f, 0.0f, 1.0f);
1925 g_settings->setFloat("sound_volume", new_volume);
1926 const wchar_t *str = wgettext("Volume changed to %d%%");
1927 swprintf(buf, sizeof(buf) / sizeof(wchar_t), str, myround(new_volume * 100));
1929 m_game_ui->showStatusText(buf);
1930 } else if (wasKeyDown(KeyType::CINEMATIC)) {
1932 } else if (wasKeyDown(KeyType::SCREENSHOT)) {
1933 client->makeScreenshot();
1934 } else if (wasKeyDown(KeyType::TOGGLE_HUD)) {
1935 m_game_ui->toggleHud();
1936 } else if (wasKeyDown(KeyType::MINIMAP)) {
1937 toggleMinimap(isKeyDown(KeyType::SNEAK));
1938 } else if (wasKeyDown(KeyType::TOGGLE_CHAT)) {
1939 m_game_ui->toggleChat();
1940 } else if (wasKeyDown(KeyType::TOGGLE_FOG)) {
1942 } else if (wasKeyDown(KeyType::TOGGLE_UPDATE_CAMERA)) {
1943 toggleUpdateCamera();
1944 } else if (wasKeyDown(KeyType::TOGGLE_DEBUG)) {
1946 } else if (wasKeyDown(KeyType::TOGGLE_PROFILER)) {
1947 m_game_ui->toggleProfiler();
1948 } else if (wasKeyDown(KeyType::INCREASE_VIEWING_RANGE)) {
1949 increaseViewRange();
1950 } else if (wasKeyDown(KeyType::DECREASE_VIEWING_RANGE)) {
1951 decreaseViewRange();
1952 } else if (wasKeyDown(KeyType::RANGESELECT)) {
1953 toggleFullViewRange();
1954 } else if (wasKeyDown(KeyType::ZOOM)) {
1956 } else if (wasKeyDown(KeyType::QUICKTUNE_NEXT)) {
1958 } else if (wasKeyDown(KeyType::QUICKTUNE_PREV)) {
1960 } else if (wasKeyDown(KeyType::QUICKTUNE_INC)) {
1962 } else if (wasKeyDown(KeyType::QUICKTUNE_DEC)) {
1966 if (!isKeyDown(KeyType::JUMP) && runData.reset_jump_timer) {
1967 runData.reset_jump_timer = false;
1968 runData.jump_timer = 0.0f;
1971 if (quicktune->hasMessage()) {
1972 m_game_ui->showStatusText(utf8_to_wide(quicktune->getMessage()));
1976 void Game::processItemSelection(u16 *new_playeritem)
1978 LocalPlayer *player = client->getEnv().getLocalPlayer();
1980 /* Item selection using mouse wheel
1982 *new_playeritem = client->getPlayerItem();
1984 s32 wheel = input->getMouseWheel();
1985 u16 max_item = MYMIN(PLAYER_INVENTORY_SIZE - 1,
1986 player->hud_hotbar_itemcount - 1);
1990 if (input->joystick.wasKeyDown(KeyType::SCROLL_DOWN) ||
1991 wasKeyDown(KeyType::HOTBAR_NEXT)) {
1995 if (input->joystick.wasKeyDown(KeyType::SCROLL_UP) ||
1996 wasKeyDown(KeyType::HOTBAR_PREV)) {
2001 *new_playeritem = *new_playeritem < max_item ? *new_playeritem + 1 : 0;
2003 *new_playeritem = *new_playeritem > 0 ? *new_playeritem - 1 : max_item;
2006 /* Item selection using hotbar slot keys
2008 for (u16 i = 0; i <= max_item; i++) {
2009 if (wasKeyDown((GameKeyType) (KeyType::SLOT_1 + i))) {
2010 *new_playeritem = i;
2011 infostream << "Selected item: " << new_playeritem << std::endl;
2018 void Game::dropSelectedItem(bool single_item)
2020 IDropAction *a = new IDropAction();
2021 a->count = single_item ? 1 : 0;
2022 a->from_inv.setCurrentPlayer();
2023 a->from_list = "main";
2024 a->from_i = client->getPlayerItem();
2025 client->inventoryAction(a);
2029 void Game::openInventory()
2032 * Don't permit to open inventory is CAO or player doesn't exists.
2033 * This prevent showing an empty inventory at player load
2036 LocalPlayer *player = client->getEnv().getLocalPlayer();
2037 if (!player || !player->getCAO())
2040 infostream << "the_game: " << "Launching inventory" << std::endl;
2042 PlayerInventoryFormSource *fs_src = new PlayerInventoryFormSource(client);
2044 InventoryLocation inventoryloc;
2045 inventoryloc.setCurrentPlayer();
2047 if (!client->moddingEnabled()
2048 || !client->getScript()->on_inventory_open(fs_src->m_client->getInventory(inventoryloc))) {
2049 TextDest *txt_dst = new TextDestPlayerInventory(client);
2050 GUIFormSpecMenu::create(current_formspec, client, &input->joystick, fs_src,
2051 txt_dst, client->getFormspecPrepend());
2053 current_formspec->setFormSpec(fs_src->getForm(), inventoryloc);
2058 void Game::openConsole(float scale, const wchar_t *line)
2060 assert(scale > 0.0f && scale <= 1.0f);
2063 porting::showInputDialog(gettext("ok"), "", "", 2);
2064 m_android_chat_open = true;
2066 if (gui_chat_console->isOpenInhibited())
2068 gui_chat_console->openConsole(scale);
2070 gui_chat_console->setCloseOnEnter(true);
2071 gui_chat_console->replaceAndAddToHistory(line);
2077 void Game::handleAndroidChatInput()
2079 if (m_android_chat_open && porting::getInputDialogState() == 0) {
2080 std::string text = porting::getInputDialogValue();
2081 client->typeChatMessage(utf8_to_wide(text));
2087 void Game::toggleFreeMove()
2089 bool free_move = !g_settings->getBool("free_move");
2090 g_settings->set("free_move", bool_to_cstr(free_move));
2093 if (client->checkPrivilege("fly")) {
2094 m_game_ui->showTranslatedStatusText("Fly mode enabled");
2096 m_game_ui->showTranslatedStatusText("Fly mode enabled (note: no 'fly' privilege)");
2099 m_game_ui->showTranslatedStatusText("Fly mode disabled");
2103 void Game::toggleFreeMoveAlt()
2105 if (m_cache_doubletap_jump && runData.jump_timer < 0.2f)
2108 runData.reset_jump_timer = true;
2112 void Game::togglePitchFly()
2114 bool pitch_fly = !g_settings->getBool("pitch_fly");
2115 g_settings->set("pitch_fly", bool_to_cstr(pitch_fly));
2118 m_game_ui->showTranslatedStatusText("Pitch fly mode enabled");
2120 m_game_ui->showTranslatedStatusText("Pitch fly mode disabled");
2125 void Game::toggleFast()
2127 bool fast_move = !g_settings->getBool("fast_move");
2128 bool has_fast_privs = client->checkPrivilege("fast");
2129 g_settings->set("fast_move", bool_to_cstr(fast_move));
2132 if (has_fast_privs) {
2133 m_game_ui->showTranslatedStatusText("Fast mode enabled");
2135 m_game_ui->showTranslatedStatusText("Fast mode enabled (note: no 'fast' privilege)");
2138 m_game_ui->showTranslatedStatusText("Fast mode disabled");
2142 m_cache_hold_aux1 = fast_move && has_fast_privs;
2147 void Game::toggleNoClip()
2149 bool noclip = !g_settings->getBool("noclip");
2150 g_settings->set("noclip", bool_to_cstr(noclip));
2153 if (client->checkPrivilege("noclip")) {
2154 m_game_ui->showTranslatedStatusText("Noclip mode enabled");
2156 m_game_ui->showTranslatedStatusText("Noclip mode enabled (note: no 'noclip' privilege)");
2159 m_game_ui->showTranslatedStatusText("Noclip mode disabled");
2163 void Game::toggleCinematic()
2165 bool cinematic = !g_settings->getBool("cinematic");
2166 g_settings->set("cinematic", bool_to_cstr(cinematic));
2169 m_game_ui->showTranslatedStatusText("Cinematic mode enabled");
2171 m_game_ui->showTranslatedStatusText("Cinematic mode disabled");
2174 // Autoforward by toggling continuous forward.
2175 void Game::toggleAutoforward()
2177 bool autorun_enabled = !g_settings->getBool("continuous_forward");
2178 g_settings->set("continuous_forward", bool_to_cstr(autorun_enabled));
2180 if (autorun_enabled)
2181 m_game_ui->showTranslatedStatusText("Automatic forwards enabled");
2183 m_game_ui->showTranslatedStatusText("Automatic forwards disabled");
2186 void Game::toggleMinimap(bool shift_pressed)
2188 if (!mapper || !m_game_ui->m_flags.show_hud || !g_settings->getBool("enable_minimap"))
2191 if (shift_pressed) {
2192 mapper->toggleMinimapShape();
2196 u32 hud_flags = client->getEnv().getLocalPlayer()->hud_flags;
2198 MinimapMode mode = MINIMAP_MODE_OFF;
2199 if (hud_flags & HUD_FLAG_MINIMAP_VISIBLE) {
2200 mode = mapper->getMinimapMode();
2201 mode = (MinimapMode)((int)mode + 1);
2202 // If radar is disabled and in, or switching to, radar mode
2203 if (!(hud_flags & HUD_FLAG_MINIMAP_RADAR_VISIBLE) && mode > 3)
2204 mode = MINIMAP_MODE_OFF;
2207 m_game_ui->m_flags.show_minimap = true;
2209 case MINIMAP_MODE_SURFACEx1:
2210 m_game_ui->showTranslatedStatusText("Minimap in surface mode, Zoom x1");
2212 case MINIMAP_MODE_SURFACEx2:
2213 m_game_ui->showTranslatedStatusText("Minimap in surface mode, Zoom x2");
2215 case MINIMAP_MODE_SURFACEx4:
2216 m_game_ui->showTranslatedStatusText("Minimap in surface mode, Zoom x4");
2218 case MINIMAP_MODE_RADARx1:
2219 m_game_ui->showTranslatedStatusText("Minimap in radar mode, Zoom x1");
2221 case MINIMAP_MODE_RADARx2:
2222 m_game_ui->showTranslatedStatusText("Minimap in radar mode, Zoom x2");
2224 case MINIMAP_MODE_RADARx4:
2225 m_game_ui->showTranslatedStatusText("Minimap in radar mode, Zoom x4");
2228 mode = MINIMAP_MODE_OFF;
2229 m_game_ui->m_flags.show_minimap = false;
2230 if (hud_flags & HUD_FLAG_MINIMAP_VISIBLE)
2231 m_game_ui->showTranslatedStatusText("Minimap hidden");
2233 m_game_ui->showTranslatedStatusText("Minimap currently disabled by game or mod");
2236 mapper->setMinimapMode(mode);
2239 void Game::toggleFog()
2241 bool fog_enabled = g_settings->getBool("enable_fog");
2242 g_settings->setBool("enable_fog", !fog_enabled);
2244 m_game_ui->showTranslatedStatusText("Fog disabled");
2246 m_game_ui->showTranslatedStatusText("Fog enabled");
2250 void Game::toggleDebug()
2252 // Initial / 4x toggle: Chat only
2253 // 1x toggle: Debug text with chat
2254 // 2x toggle: Debug text with profiler graph
2255 // 3x toggle: Debug text and wireframe
2256 if (!m_game_ui->m_flags.show_debug) {
2257 m_game_ui->m_flags.show_debug = true;
2258 m_game_ui->m_flags.show_profiler_graph = false;
2259 draw_control->show_wireframe = false;
2260 m_game_ui->showTranslatedStatusText("Debug info shown");
2261 } else if (!m_game_ui->m_flags.show_profiler_graph && !draw_control->show_wireframe) {
2262 m_game_ui->m_flags.show_profiler_graph = true;
2263 m_game_ui->showTranslatedStatusText("Profiler graph shown");
2264 } else if (!draw_control->show_wireframe && client->checkPrivilege("debug")) {
2265 m_game_ui->m_flags.show_profiler_graph = false;
2266 draw_control->show_wireframe = true;
2267 m_game_ui->showTranslatedStatusText("Wireframe shown");
2269 m_game_ui->m_flags.show_debug = false;
2270 m_game_ui->m_flags.show_profiler_graph = false;
2271 draw_control->show_wireframe = false;
2272 if (client->checkPrivilege("debug")) {
2273 m_game_ui->showTranslatedStatusText("Debug info, profiler graph, and wireframe hidden");
2275 m_game_ui->showTranslatedStatusText("Debug info and profiler graph hidden");
2281 void Game::toggleUpdateCamera()
2283 m_flags.disable_camera_update = !m_flags.disable_camera_update;
2284 if (m_flags.disable_camera_update)
2285 m_game_ui->showTranslatedStatusText("Camera update disabled");
2287 m_game_ui->showTranslatedStatusText("Camera update enabled");
2291 void Game::increaseViewRange()
2293 s16 range = g_settings->getS16("viewing_range");
2294 s16 range_new = range + 10;
2298 if (range_new > 4000) {
2300 str = wgettext("Viewing range is at maximum: %d");
2301 swprintf(buf, sizeof(buf) / sizeof(wchar_t), str, range_new);
2303 m_game_ui->showStatusText(buf);
2306 str = wgettext("Viewing range changed to %d");
2307 swprintf(buf, sizeof(buf) / sizeof(wchar_t), str, range_new);
2309 m_game_ui->showStatusText(buf);
2311 g_settings->set("viewing_range", itos(range_new));
2315 void Game::decreaseViewRange()
2317 s16 range = g_settings->getS16("viewing_range");
2318 s16 range_new = range - 10;
2322 if (range_new < 20) {
2324 str = wgettext("Viewing range is at minimum: %d");
2325 swprintf(buf, sizeof(buf) / sizeof(wchar_t), str, range_new);
2327 m_game_ui->showStatusText(buf);
2329 str = wgettext("Viewing range changed to %d");
2330 swprintf(buf, sizeof(buf) / sizeof(wchar_t), str, range_new);
2332 m_game_ui->showStatusText(buf);
2334 g_settings->set("viewing_range", itos(range_new));
2338 void Game::toggleFullViewRange()
2340 draw_control->range_all = !draw_control->range_all;
2341 if (draw_control->range_all)
2342 m_game_ui->showTranslatedStatusText("Enabled unlimited viewing range");
2344 m_game_ui->showTranslatedStatusText("Disabled unlimited viewing range");
2348 void Game::checkZoomEnabled()
2350 LocalPlayer *player = client->getEnv().getLocalPlayer();
2351 if (player->getZoomFOV() < 0.001f)
2352 m_game_ui->showTranslatedStatusText("Zoom currently disabled by game or mod");
2356 void Game::updateCameraDirection(CameraOrientation *cam, float dtime)
2358 if ((device->isWindowActive() && device->isWindowFocused()
2359 && !isMenuActive()) || random_input) {
2362 if (!random_input) {
2363 // Mac OSX gets upset if this is set every frame
2364 if (device->getCursorControl()->isVisible())
2365 device->getCursorControl()->setVisible(false);
2369 if (m_first_loop_after_window_activation) {
2370 m_first_loop_after_window_activation = false;
2372 input->setMousePos(driver->getScreenSize().Width / 2,
2373 driver->getScreenSize().Height / 2);
2375 updateCameraOrientation(cam, dtime);
2381 // Mac OSX gets upset if this is set every frame
2382 if (!device->getCursorControl()->isVisible())
2383 device->getCursorControl()->setVisible(true);
2386 m_first_loop_after_window_activation = true;
2391 void Game::updateCameraOrientation(CameraOrientation *cam, float dtime)
2393 #ifdef HAVE_TOUCHSCREENGUI
2394 if (g_touchscreengui) {
2395 cam->camera_yaw += g_touchscreengui->getYawChange();
2396 cam->camera_pitch = g_touchscreengui->getPitch();
2399 v2s32 center(driver->getScreenSize().Width / 2, driver->getScreenSize().Height / 2);
2400 v2s32 dist = input->getMousePos() - center;
2402 if (m_invert_mouse || camera->getCameraMode() == CAMERA_MODE_THIRD_FRONT) {
2406 cam->camera_yaw -= dist.X * m_cache_mouse_sensitivity;
2407 cam->camera_pitch += dist.Y * m_cache_mouse_sensitivity;
2409 if (dist.X != 0 || dist.Y != 0)
2410 input->setMousePos(center.X, center.Y);
2411 #ifdef HAVE_TOUCHSCREENGUI
2415 if (m_cache_enable_joysticks) {
2416 f32 c = m_cache_joystick_frustum_sensitivity * (1.f / 32767.f) * dtime;
2417 cam->camera_yaw -= input->joystick.getAxisWithoutDead(JA_FRUSTUM_HORIZONTAL) * c;
2418 cam->camera_pitch += input->joystick.getAxisWithoutDead(JA_FRUSTUM_VERTICAL) * c;
2421 cam->camera_pitch = rangelim(cam->camera_pitch, -89.5, 89.5);
2425 void Game::updatePlayerControl(const CameraOrientation &cam)
2427 //TimeTaker tt("update player control", NULL, PRECISION_NANO);
2429 // DO NOT use the isKeyDown method for the forward, backward, left, right
2430 // buttons, as the code that uses the controls needs to be able to
2431 // distinguish between the two in order to know when to use joysticks.
2433 PlayerControl control(
2434 input->isKeyDown(KeyType::FORWARD),
2435 input->isKeyDown(KeyType::BACKWARD),
2436 input->isKeyDown(KeyType::LEFT),
2437 input->isKeyDown(KeyType::RIGHT),
2438 isKeyDown(KeyType::JUMP),
2439 isKeyDown(KeyType::SPECIAL1),
2440 isKeyDown(KeyType::SNEAK),
2441 isKeyDown(KeyType::ZOOM),
2442 input->getLeftState(),
2443 input->getRightState(),
2446 input->joystick.getAxisWithoutDead(JA_SIDEWARD_MOVE),
2447 input->joystick.getAxisWithoutDead(JA_FORWARD_MOVE)
2451 ( (u32)(isKeyDown(KeyType::FORWARD) & 0x1) << 0) |
2452 ( (u32)(isKeyDown(KeyType::BACKWARD) & 0x1) << 1) |
2453 ( (u32)(isKeyDown(KeyType::LEFT) & 0x1) << 2) |
2454 ( (u32)(isKeyDown(KeyType::RIGHT) & 0x1) << 3) |
2455 ( (u32)(isKeyDown(KeyType::JUMP) & 0x1) << 4) |
2456 ( (u32)(isKeyDown(KeyType::SPECIAL1) & 0x1) << 5) |
2457 ( (u32)(isKeyDown(KeyType::SNEAK) & 0x1) << 6) |
2458 ( (u32)(input->getLeftState() & 0x1) << 7) |
2459 ( (u32)(input->getRightState() & 0x1) << 8
2463 /* For Android, simulate holding down AUX1 (fast move) if the user has
2464 * the fast_move setting toggled on. If there is an aux1 key defined for
2465 * Android then its meaning is inverted (i.e. holding aux1 means walk and
2468 if (m_cache_hold_aux1) {
2469 control.aux1 = control.aux1 ^ true;
2470 keypress_bits ^= ((u32)(1U << 5));
2474 LocalPlayer *player = client->getEnv().getLocalPlayer();
2476 // autojump if set: simulate "jump" key
2477 if (player->getAutojump()) {
2478 control.jump = true;
2479 keypress_bits |= 1U << 4;
2482 client->setPlayerControl(control);
2483 player->keyPressed = keypress_bits;
2489 inline void Game::step(f32 *dtime)
2491 bool can_be_and_is_paused =
2492 (simple_singleplayer_mode && g_menumgr.pausesGame());
2494 if (can_be_and_is_paused) { // This is for a singleplayer server
2495 *dtime = 0; // No time passes
2498 server->step(*dtime);
2500 client->step(*dtime);
2504 const ClientEventHandler Game::clientEventHandler[CLIENTEVENT_MAX] = {
2505 {&Game::handleClientEvent_None},
2506 {&Game::handleClientEvent_PlayerDamage},
2507 {&Game::handleClientEvent_PlayerForceMove},
2508 {&Game::handleClientEvent_Deathscreen},
2509 {&Game::handleClientEvent_ShowFormSpec},
2510 {&Game::handleClientEvent_ShowLocalFormSpec},
2511 {&Game::handleClientEvent_HandleParticleEvent},
2512 {&Game::handleClientEvent_HandleParticleEvent},
2513 {&Game::handleClientEvent_HandleParticleEvent},
2514 {&Game::handleClientEvent_HudAdd},
2515 {&Game::handleClientEvent_HudRemove},
2516 {&Game::handleClientEvent_HudChange},
2517 {&Game::handleClientEvent_SetSky},
2518 {&Game::handleClientEvent_OverrideDayNigthRatio},
2519 {&Game::handleClientEvent_CloudParams},
2522 void Game::handleClientEvent_None(ClientEvent *event, CameraOrientation *cam)
2524 FATAL_ERROR("ClientEvent type None received");
2527 void Game::handleClientEvent_PlayerDamage(ClientEvent *event, CameraOrientation *cam)
2529 if (client->moddingEnabled()) {
2530 client->getScript()->on_damage_taken(event->player_damage.amount);
2533 // Damage flash and hurt tilt are not used at death
2534 if (client->getHP() > 0) {
2535 runData.damage_flash += 95.0f + 3.2f * event->player_damage.amount;
2536 runData.damage_flash = MYMIN(runData.damage_flash, 127.0f);
2538 LocalPlayer *player = client->getEnv().getLocalPlayer();
2540 player->hurt_tilt_timer = 1.5f;
2541 player->hurt_tilt_strength =
2542 rangelim(event->player_damage.amount / 4.0f, 1.0f, 4.0f);
2545 // Play damage sound
2546 client->getEventManager()->put(new SimpleTriggerEvent(MtEvent::PLAYER_DAMAGE));
2549 void Game::handleClientEvent_PlayerForceMove(ClientEvent *event, CameraOrientation *cam)
2551 cam->camera_yaw = event->player_force_move.yaw;
2552 cam->camera_pitch = event->player_force_move.pitch;
2555 void Game::handleClientEvent_Deathscreen(ClientEvent *event, CameraOrientation *cam)
2557 // If CSM enabled, deathscreen is handled by CSM code in
2558 // builtin/client/init.lua
2559 if (client->moddingEnabled())
2560 client->getScript()->on_death();
2562 showDeathFormspec();
2564 /* Handle visualization */
2565 LocalPlayer *player = client->getEnv().getLocalPlayer();
2566 runData.damage_flash = 0;
2567 player->hurt_tilt_timer = 0;
2568 player->hurt_tilt_strength = 0;
2571 void Game::handleClientEvent_ShowFormSpec(ClientEvent *event, CameraOrientation *cam)
2573 if (event->show_formspec.formspec->empty()) {
2574 if (current_formspec && (event->show_formspec.formname->empty()
2575 || *(event->show_formspec.formname) == cur_formname)) {
2576 current_formspec->quitMenu();
2579 FormspecFormSource *fs_src =
2580 new FormspecFormSource(*(event->show_formspec.formspec));
2581 TextDestPlayerInventory *txt_dst =
2582 new TextDestPlayerInventory(client, *(event->show_formspec.formname));
2584 GUIFormSpecMenu::create(current_formspec, client, &input->joystick,
2585 fs_src, txt_dst, client->getFormspecPrepend());
2586 cur_formname = *(event->show_formspec.formname);
2589 delete event->show_formspec.formspec;
2590 delete event->show_formspec.formname;
2593 void Game::handleClientEvent_ShowLocalFormSpec(ClientEvent *event, CameraOrientation *cam)
2595 FormspecFormSource *fs_src = new FormspecFormSource(*event->show_formspec.formspec);
2596 LocalFormspecHandler *txt_dst =
2597 new LocalFormspecHandler(*event->show_formspec.formname, client);
2598 GUIFormSpecMenu::create(current_formspec, client, &input->joystick,
2599 fs_src, txt_dst, client->getFormspecPrepend());
2601 delete event->show_formspec.formspec;
2602 delete event->show_formspec.formname;
2605 void Game::handleClientEvent_HandleParticleEvent(ClientEvent *event,
2606 CameraOrientation *cam)
2608 LocalPlayer *player = client->getEnv().getLocalPlayer();
2609 client->getParticleManager()->handleParticleEvent(event, client, player);
2612 void Game::handleClientEvent_HudAdd(ClientEvent *event, CameraOrientation *cam)
2614 LocalPlayer *player = client->getEnv().getLocalPlayer();
2615 auto &hud_server_to_client = client->getHUDTranslationMap();
2617 u32 server_id = event->hudadd.server_id;
2618 // ignore if we already have a HUD with that ID
2619 auto i = hud_server_to_client.find(server_id);
2620 if (i != hud_server_to_client.end()) {
2621 delete event->hudadd.pos;
2622 delete event->hudadd.name;
2623 delete event->hudadd.scale;
2624 delete event->hudadd.text;
2625 delete event->hudadd.align;
2626 delete event->hudadd.offset;
2627 delete event->hudadd.world_pos;
2628 delete event->hudadd.size;
2632 HudElement *e = new HudElement;
2633 e->type = (HudElementType)event->hudadd.type;
2634 e->pos = *event->hudadd.pos;
2635 e->name = *event->hudadd.name;
2636 e->scale = *event->hudadd.scale;
2637 e->text = *event->hudadd.text;
2638 e->number = event->hudadd.number;
2639 e->item = event->hudadd.item;
2640 e->dir = event->hudadd.dir;
2641 e->align = *event->hudadd.align;
2642 e->offset = *event->hudadd.offset;
2643 e->world_pos = *event->hudadd.world_pos;
2644 e->size = *event->hudadd.size;
2645 hud_server_to_client[server_id] = player->addHud(e);
2647 delete event->hudadd.pos;
2648 delete event->hudadd.name;
2649 delete event->hudadd.scale;
2650 delete event->hudadd.text;
2651 delete event->hudadd.align;
2652 delete event->hudadd.offset;
2653 delete event->hudadd.world_pos;
2654 delete event->hudadd.size;
2657 void Game::handleClientEvent_HudRemove(ClientEvent *event, CameraOrientation *cam)
2659 LocalPlayer *player = client->getEnv().getLocalPlayer();
2660 HudElement *e = player->removeHud(event->hudrm.id);
2664 void Game::handleClientEvent_HudChange(ClientEvent *event, CameraOrientation *cam)
2666 LocalPlayer *player = client->getEnv().getLocalPlayer();
2668 u32 id = event->hudchange.id;
2669 HudElement *e = player->getHud(id);
2672 delete event->hudchange.v3fdata;
2673 delete event->hudchange.v2fdata;
2674 delete event->hudchange.sdata;
2675 delete event->hudchange.v2s32data;
2679 switch (event->hudchange.stat) {
2681 e->pos = *event->hudchange.v2fdata;
2685 e->name = *event->hudchange.sdata;
2688 case HUD_STAT_SCALE:
2689 e->scale = *event->hudchange.v2fdata;
2693 e->text = *event->hudchange.sdata;
2696 case HUD_STAT_NUMBER:
2697 e->number = event->hudchange.data;
2701 e->item = event->hudchange.data;
2705 e->dir = event->hudchange.data;
2708 case HUD_STAT_ALIGN:
2709 e->align = *event->hudchange.v2fdata;
2712 case HUD_STAT_OFFSET:
2713 e->offset = *event->hudchange.v2fdata;
2716 case HUD_STAT_WORLD_POS:
2717 e->world_pos = *event->hudchange.v3fdata;
2721 e->size = *event->hudchange.v2s32data;
2725 delete event->hudchange.v3fdata;
2726 delete event->hudchange.v2fdata;
2727 delete event->hudchange.sdata;
2728 delete event->hudchange.v2s32data;
2731 void Game::handleClientEvent_SetSky(ClientEvent *event, CameraOrientation *cam)
2733 sky->setVisible(false);
2734 // Whether clouds are visible in front of a custom skybox
2735 sky->setCloudsEnabled(event->set_sky.clouds);
2742 // Handle according to type
2743 if (*event->set_sky.type == "regular") {
2744 sky->setVisible(true);
2745 sky->setCloudsEnabled(true);
2746 } else if (*event->set_sky.type == "skybox" &&
2747 event->set_sky.params->size() == 6) {
2748 sky->setFallbackBgColor(*event->set_sky.bgcolor);
2749 skybox = RenderingEngine::get_scene_manager()->addSkyBoxSceneNode(
2750 texture_src->getTextureForMesh((*event->set_sky.params)[0]),
2751 texture_src->getTextureForMesh((*event->set_sky.params)[1]),
2752 texture_src->getTextureForMesh((*event->set_sky.params)[2]),
2753 texture_src->getTextureForMesh((*event->set_sky.params)[3]),
2754 texture_src->getTextureForMesh((*event->set_sky.params)[4]),
2755 texture_src->getTextureForMesh((*event->set_sky.params)[5]));
2757 // Handle everything else as plain color
2759 if (*event->set_sky.type != "plain")
2760 infostream << "Unknown sky type: "
2761 << (*event->set_sky.type) << std::endl;
2763 sky->setFallbackBgColor(*event->set_sky.bgcolor);
2766 delete event->set_sky.bgcolor;
2767 delete event->set_sky.type;
2768 delete event->set_sky.params;
2771 void Game::handleClientEvent_OverrideDayNigthRatio(ClientEvent *event,
2772 CameraOrientation *cam)
2774 client->getEnv().setDayNightRatioOverride(
2775 event->override_day_night_ratio.do_override,
2776 event->override_day_night_ratio.ratio_f * 1000.0f);
2779 void Game::handleClientEvent_CloudParams(ClientEvent *event, CameraOrientation *cam)
2784 clouds->setDensity(event->cloud_params.density);
2785 clouds->setColorBright(video::SColor(event->cloud_params.color_bright));
2786 clouds->setColorAmbient(video::SColor(event->cloud_params.color_ambient));
2787 clouds->setHeight(event->cloud_params.height);
2788 clouds->setThickness(event->cloud_params.thickness);
2789 clouds->setSpeed(v2f(event->cloud_params.speed_x, event->cloud_params.speed_y));
2792 void Game::processClientEvents(CameraOrientation *cam)
2794 while (client->hasClientEvents()) {
2795 std::unique_ptr<ClientEvent> event(client->getClientEvent());
2796 FATAL_ERROR_IF(event->type >= CLIENTEVENT_MAX, "Invalid clientevent type");
2797 const ClientEventHandler& evHandler = clientEventHandler[event->type];
2798 (this->*evHandler.handler)(event.get(), cam);
2802 void Game::updateChat(f32 dtime, const v2u32 &screensize)
2804 // Add chat log output for errors to be shown in chat
2805 static LogOutputBuffer chat_log_error_buf(g_logger, LL_ERROR);
2807 // Get new messages from error log buffer
2808 while (!chat_log_error_buf.empty()) {
2809 std::wstring error_message = utf8_to_wide(chat_log_error_buf.get());
2810 if (!g_settings->getBool("disable_escape_sequences")) {
2811 error_message.insert(0, L"\x1b(c@red)");
2812 error_message.append(L"\x1b(c@white)");
2814 chat_backend->addMessage(L"", error_message);
2817 // Get new messages from client
2818 std::wstring message;
2819 while (client->getChatMessage(message)) {
2820 chat_backend->addUnparsedMessage(message);
2823 // Remove old messages
2824 chat_backend->step(dtime);
2826 // Display all messages in a static text element
2827 m_game_ui->setChatText(chat_backend->getRecentChat(),
2828 chat_backend->getRecentBuffer().getLineCount());
2831 void Game::updateCamera(u32 busy_time, f32 dtime)
2833 LocalPlayer *player = client->getEnv().getLocalPlayer();
2836 For interaction purposes, get info about the held item
2838 - Is it a usable item?
2839 - Can it point to liquids?
2841 ItemStack playeritem;
2843 InventoryList *mlist = local_inventory->getList("main");
2845 if (mlist && client->getPlayerItem() < mlist->getSize())
2846 playeritem = mlist->getItem(client->getPlayerItem());
2849 if (playeritem.getDefinition(itemdef_manager).name.empty()) { // override the hand
2850 InventoryList *hlist = local_inventory->getList("hand");
2852 playeritem = hlist->getItem(0);
2856 ToolCapabilities playeritem_toolcap =
2857 playeritem.getToolCapabilities(itemdef_manager);
2859 v3s16 old_camera_offset = camera->getOffset();
2861 if (wasKeyDown(KeyType::CAMERA_MODE)) {
2862 GenericCAO *playercao = player->getCAO();
2864 // If playercao not loaded, don't change camera
2868 camera->toggleCameraMode();
2870 playercao->setVisible(camera->getCameraMode() > CAMERA_MODE_FIRST);
2871 playercao->setChildrenVisible(camera->getCameraMode() > CAMERA_MODE_FIRST);
2874 float full_punch_interval = playeritem_toolcap.full_punch_interval;
2875 float tool_reload_ratio = runData.time_from_last_punch / full_punch_interval;
2877 tool_reload_ratio = MYMIN(tool_reload_ratio, 1.0);
2878 camera->update(player, dtime, busy_time / 1000.0f, tool_reload_ratio);
2879 camera->step(dtime);
2881 v3f camera_position = camera->getPosition();
2882 v3f camera_direction = camera->getDirection();
2883 f32 camera_fov = camera->getFovMax();
2884 v3s16 camera_offset = camera->getOffset();
2886 m_camera_offset_changed = (camera_offset != old_camera_offset);
2888 if (!m_flags.disable_camera_update) {
2889 client->getEnv().getClientMap().updateCamera(camera_position,
2890 camera_direction, camera_fov, camera_offset);
2892 if (m_camera_offset_changed) {
2893 client->updateCameraOffset(camera_offset);
2894 client->getEnv().updateCameraOffset(camera_offset);
2897 clouds->updateCameraOffset(camera_offset);
2903 void Game::updateSound(f32 dtime)
2905 // Update sound listener
2906 v3s16 camera_offset = camera->getOffset();
2907 sound->updateListener(camera->getCameraNode()->getPosition() + intToFloat(camera_offset, BS),
2908 v3f(0, 0, 0), // velocity
2909 camera->getDirection(),
2910 camera->getCameraNode()->getUpVector());
2912 bool mute_sound = g_settings->getBool("mute_sound");
2914 sound->setListenerGain(0.0f);
2916 // Check if volume is in the proper range, else fix it.
2917 float old_volume = g_settings->getFloat("sound_volume");
2918 float new_volume = rangelim(old_volume, 0.0f, 1.0f);
2919 sound->setListenerGain(new_volume);
2921 if (old_volume != new_volume) {
2922 g_settings->setFloat("sound_volume", new_volume);
2926 LocalPlayer *player = client->getEnv().getLocalPlayer();
2928 // Tell the sound maker whether to make footstep sounds
2929 soundmaker->makes_footstep_sound = player->makes_footstep_sound;
2931 // Update sound maker
2932 if (player->makes_footstep_sound)
2933 soundmaker->step(dtime);
2935 ClientMap &map = client->getEnv().getClientMap();
2936 MapNode n = map.getNodeNoEx(player->getFootstepNodePos());
2937 soundmaker->m_player_step_sound = nodedef_manager->get(n).sound_footstep;
2941 void Game::processPlayerInteraction(f32 dtime, bool show_hud, bool show_debug)
2943 LocalPlayer *player = client->getEnv().getLocalPlayer();
2945 ItemStack playeritem;
2947 InventoryList *mlist = local_inventory->getList("main");
2949 if (mlist && client->getPlayerItem() < mlist->getSize())
2950 playeritem = mlist->getItem(client->getPlayerItem());
2953 const ItemDefinition &playeritem_def =
2954 playeritem.getDefinition(itemdef_manager);
2955 InventoryList *hlist = local_inventory->getList("hand");
2956 const ItemDefinition &hand_def =
2957 hlist ? hlist->getItem(0).getDefinition(itemdef_manager) : itemdef_manager->get("");
2959 v3f player_position = player->getPosition();
2960 v3f camera_position = camera->getPosition();
2961 v3f camera_direction = camera->getDirection();
2962 v3s16 camera_offset = camera->getOffset();
2966 Calculate what block is the crosshair pointing to
2969 f32 d = playeritem_def.range; // max. distance
2970 f32 d_hand = hand_def.range;
2972 if (d < 0 && d_hand >= 0)
2977 core::line3d<f32> shootline;
2979 if (camera->getCameraMode() != CAMERA_MODE_THIRD_FRONT) {
2980 shootline = core::line3d<f32>(camera_position,
2981 camera_position + camera_direction * BS * d);
2983 // prevent player pointing anything in front-view
2984 shootline = core::line3d<f32>(camera_position,camera_position);
2987 #ifdef HAVE_TOUCHSCREENGUI
2989 if ((g_settings->getBool("touchtarget")) && (g_touchscreengui)) {
2990 shootline = g_touchscreengui->getShootline();
2991 // Scale shootline to the acual distance the player can reach
2992 shootline.end = shootline.start
2993 + shootline.getVector().normalize() * BS * d;
2994 shootline.start += intToFloat(camera_offset, BS);
2995 shootline.end += intToFloat(camera_offset, BS);
3000 PointedThing pointed = updatePointedThing(shootline,
3001 playeritem_def.liquids_pointable,
3002 !runData.ldown_for_dig,
3005 if (pointed != runData.pointed_old) {
3006 infostream << "Pointing at " << pointed.dump() << std::endl;
3007 hud->updateSelectionMesh(camera_offset);
3010 if (runData.digging_blocked && !input->getLeftState()) {
3011 // allow digging again if button is not pressed
3012 runData.digging_blocked = false;
3017 - releasing left mouse button
3018 - pointing away from node
3020 if (runData.digging) {
3021 if (input->getLeftReleased()) {
3022 infostream << "Left button released"
3023 << " (stopped digging)" << std::endl;
3024 runData.digging = false;
3025 } else if (pointed != runData.pointed_old) {
3026 if (pointed.type == POINTEDTHING_NODE
3027 && runData.pointed_old.type == POINTEDTHING_NODE
3028 && pointed.node_undersurface
3029 == runData.pointed_old.node_undersurface) {
3030 // Still pointing to the same node, but a different face.
3033 infostream << "Pointing away from node"
3034 << " (stopped digging)" << std::endl;
3035 runData.digging = false;
3036 hud->updateSelectionMesh(camera_offset);
3040 if (!runData.digging) {
3041 client->interact(1, runData.pointed_old);
3042 client->setCrack(-1, v3s16(0, 0, 0));
3043 runData.dig_time = 0.0;
3045 } else if (runData.dig_instantly && input->getLeftReleased()) {
3046 // Remove e.g. torches faster when clicking instead of holding LMB
3047 runData.nodig_delay_timer = 0;
3048 runData.dig_instantly = false;
3051 if (!runData.digging && runData.ldown_for_dig && !input->getLeftState()) {
3052 runData.ldown_for_dig = false;
3055 runData.left_punch = false;
3057 soundmaker->m_player_leftpunch_sound.name = "";
3059 // Prepare for repeating, unless we're not supposed to
3060 if (input->getRightState() && !g_settings->getBool("safe_dig_and_place"))
3061 runData.repeat_rightclick_timer += dtime;
3063 runData.repeat_rightclick_timer = 0;
3065 if (playeritem_def.usable && input->getLeftState()) {
3066 if (input->getLeftClicked() && (!client->moddingEnabled()
3067 || !client->getScript()->on_item_use(playeritem, pointed)))
3068 client->interact(4, pointed);
3069 } else if (pointed.type == POINTEDTHING_NODE) {
3070 ToolCapabilities playeritem_toolcap =
3071 playeritem.getToolCapabilities(itemdef_manager);
3072 if (playeritem.name.empty()) {
3073 const ToolCapabilities *handToolcap = hlist
3074 ? &hlist->getItem(0).getToolCapabilities(itemdef_manager)
3075 : itemdef_manager->get("").tool_capabilities;
3077 if (handToolcap != nullptr)
3078 playeritem_toolcap = *handToolcap;
3080 handlePointingAtNode(pointed, playeritem_def, playeritem,
3081 playeritem_toolcap, dtime);
3082 } else if (pointed.type == POINTEDTHING_OBJECT) {
3083 handlePointingAtObject(pointed, playeritem, player_position, show_debug);
3084 } else if (input->getLeftState()) {
3085 // When button is held down in air, show continuous animation
3086 runData.left_punch = true;
3087 } else if (input->getRightClicked()) {
3088 handlePointingAtNothing(playeritem);
3091 runData.pointed_old = pointed;
3093 if (runData.left_punch || input->getLeftClicked())
3094 camera->setDigging(0); // left click animation
3096 input->resetLeftClicked();
3097 input->resetRightClicked();
3099 input->resetLeftReleased();
3100 input->resetRightReleased();
3104 PointedThing Game::updatePointedThing(
3105 const core::line3d<f32> &shootline,
3106 bool liquids_pointable,
3107 bool look_for_object,
3108 const v3s16 &camera_offset)
3110 std::vector<aabb3f> *selectionboxes = hud->getSelectionBoxes();
3111 selectionboxes->clear();
3112 hud->setSelectedFaceNormal(v3f(0.0, 0.0, 0.0));
3113 static thread_local const bool show_entity_selectionbox = g_settings->getBool(
3114 "show_entity_selectionbox");
3116 ClientEnvironment &env = client->getEnv();
3117 ClientMap &map = env.getClientMap();
3118 const NodeDefManager *nodedef = map.getNodeDefManager();
3120 runData.selected_object = NULL;
3122 RaycastState s(shootline, look_for_object, liquids_pointable);
3123 PointedThing result;
3124 env.continueRaycast(&s, &result);
3125 if (result.type == POINTEDTHING_OBJECT) {
3126 runData.selected_object = client->getEnv().getActiveObject(result.object_id);
3127 aabb3f selection_box;
3128 if (show_entity_selectionbox && runData.selected_object->doShowSelectionBox() &&
3129 runData.selected_object->getSelectionBox(&selection_box)) {
3130 v3f pos = runData.selected_object->getPosition();
3131 selectionboxes->push_back(aabb3f(selection_box));
3132 hud->setSelectionPos(pos, camera_offset);
3134 } else if (result.type == POINTEDTHING_NODE) {
3135 // Update selection boxes
3136 MapNode n = map.getNodeNoEx(result.node_undersurface);
3137 std::vector<aabb3f> boxes;
3138 n.getSelectionBoxes(nodedef, &boxes,
3139 n.getNeighbors(result.node_undersurface, &map));
3142 for (std::vector<aabb3f>::const_iterator i = boxes.begin();
3143 i != boxes.end(); ++i) {
3145 box.MinEdge -= v3f(d, d, d);
3146 box.MaxEdge += v3f(d, d, d);
3147 selectionboxes->push_back(box);
3149 hud->setSelectionPos(intToFloat(result.node_undersurface, BS),
3151 hud->setSelectedFaceNormal(v3f(
3152 result.intersection_normal.X,
3153 result.intersection_normal.Y,
3154 result.intersection_normal.Z));
3157 // Update selection mesh light level and vertex colors
3158 if (!selectionboxes->empty()) {
3159 v3f pf = hud->getSelectionPos();
3160 v3s16 p = floatToInt(pf, BS);
3162 // Get selection mesh light level
3163 MapNode n = map.getNodeNoEx(p);
3164 u16 node_light = getInteriorLight(n, -1, nodedef);
3165 u16 light_level = node_light;
3167 for (const v3s16 &dir : g_6dirs) {
3168 n = map.getNodeNoEx(p + dir);
3169 node_light = getInteriorLight(n, -1, nodedef);
3170 if (node_light > light_level)
3171 light_level = node_light;
3174 u32 daynight_ratio = client->getEnv().getDayNightRatio();
3176 final_color_blend(&c, light_level, daynight_ratio);
3178 // Modify final color a bit with time
3179 u32 timer = porting::getTimeMs() % 5000;
3180 float timerf = (float) (irr::core::PI * ((timer / 2500.0) - 0.5));
3181 float sin_r = 0.08f * std::sin(timerf);
3182 float sin_g = 0.08f * std::sin(timerf + irr::core::PI * 0.5f);
3183 float sin_b = 0.08f * std::sin(timerf + irr::core::PI);
3184 c.setRed(core::clamp(core::round32(c.getRed() * (0.8 + sin_r)), 0, 255));
3185 c.setGreen(core::clamp(core::round32(c.getGreen() * (0.8 + sin_g)), 0, 255));
3186 c.setBlue(core::clamp(core::round32(c.getBlue() * (0.8 + sin_b)), 0, 255));
3188 // Set mesh final color
3189 hud->setSelectionMeshColor(c);
3195 void Game::handlePointingAtNothing(const ItemStack &playerItem)
3197 infostream << "Right Clicked in Air" << std::endl;
3198 PointedThing fauxPointed;
3199 fauxPointed.type = POINTEDTHING_NOTHING;
3200 client->interact(5, fauxPointed);
3204 void Game::handlePointingAtNode(const PointedThing &pointed,
3205 const ItemDefinition &playeritem_def, const ItemStack &playeritem,
3206 const ToolCapabilities &playeritem_toolcap, f32 dtime)
3208 v3s16 nodepos = pointed.node_undersurface;
3209 v3s16 neighbourpos = pointed.node_abovesurface;
3212 Check information text of node
3215 ClientMap &map = client->getEnv().getClientMap();
3217 if (runData.nodig_delay_timer <= 0.0 && input->getLeftState()
3218 && !runData.digging_blocked
3219 && client->checkPrivilege("interact")) {
3220 handleDigging(pointed, nodepos, playeritem_toolcap, dtime);
3223 // This should be done after digging handling
3224 NodeMetadata *meta = map.getNodeMetadata(nodepos);
3227 m_game_ui->setInfoText(unescape_translate(utf8_to_wide(
3228 meta->getString("infotext"))));
3230 MapNode n = map.getNodeNoEx(nodepos);
3232 if (nodedef_manager->get(n).tiledef[0].name == "unknown_node.png") {
3233 m_game_ui->setInfoText(L"Unknown node: " +
3234 utf8_to_wide(nodedef_manager->get(n).name));
3238 if ((input->getRightClicked() ||
3239 runData.repeat_rightclick_timer >= m_repeat_right_click_time) &&
3240 client->checkPrivilege("interact")) {
3241 runData.repeat_rightclick_timer = 0;
3242 infostream << "Ground right-clicked" << std::endl;
3244 if (meta && !meta->getString("formspec").empty() && !random_input
3245 && !isKeyDown(KeyType::SNEAK)) {
3246 // Report right click to server
3247 if (nodedef_manager->get(map.getNodeNoEx(nodepos)).rightclickable) {
3248 client->interact(3, pointed);
3251 infostream << "Launching custom inventory view" << std::endl;
3253 InventoryLocation inventoryloc;
3254 inventoryloc.setNodeMeta(nodepos);
3256 NodeMetadataFormSource *fs_src = new NodeMetadataFormSource(
3257 &client->getEnv().getClientMap(), nodepos);
3258 TextDest *txt_dst = new TextDestNodeMetadata(nodepos, client);
3260 GUIFormSpecMenu::create(current_formspec, client, &input->joystick, fs_src,
3261 txt_dst, client->getFormspecPrepend());
3262 cur_formname.clear();
3264 current_formspec->setFormSpec(meta->getString("formspec"), inventoryloc);
3266 // Report right click to server
3268 camera->setDigging(1); // right click animation (always shown for feedback)
3270 // If the wielded item has node placement prediction,
3272 bool placed = nodePlacementPrediction(playeritem_def, playeritem, nodepos,
3277 client->interact(3, pointed);
3279 soundmaker->m_player_rightpunch_sound =
3280 playeritem_def.sound_place;
3282 if (client->moddingEnabled())
3283 client->getScript()->on_placenode(pointed, playeritem_def);
3285 soundmaker->m_player_rightpunch_sound =
3288 if (playeritem_def.node_placement_prediction.empty() ||
3289 nodedef_manager->get(map.getNodeNoEx(nodepos)).rightclickable) {
3290 client->interact(3, pointed); // Report to server
3292 soundmaker->m_player_rightpunch_sound =
3293 playeritem_def.sound_place_failed;
3300 bool Game::nodePlacementPrediction(const ItemDefinition &playeritem_def,
3301 const ItemStack &playeritem, const v3s16 &nodepos, const v3s16 &neighbourpos)
3303 std::string prediction = playeritem_def.node_placement_prediction;
3304 const NodeDefManager *nodedef = client->ndef();
3305 ClientMap &map = client->getEnv().getClientMap();
3307 bool is_valid_position;
3309 node = map.getNodeNoEx(nodepos, &is_valid_position);
3310 if (!is_valid_position)
3313 if (!prediction.empty() && !nodedef->get(node).rightclickable) {
3314 verbosestream << "Node placement prediction for "
3315 << playeritem_def.name << " is "
3316 << prediction << std::endl;
3317 v3s16 p = neighbourpos;
3319 // Place inside node itself if buildable_to
3320 MapNode n_under = map.getNodeNoEx(nodepos, &is_valid_position);
3321 if (is_valid_position)
3323 if (nodedef->get(n_under).buildable_to)
3326 node = map.getNodeNoEx(p, &is_valid_position);
3327 if (is_valid_position &&!nodedef->get(node).buildable_to)
3332 // Find id of predicted node
3334 bool found = nodedef->getId(prediction, id);
3337 errorstream << "Node placement prediction failed for "
3338 << playeritem_def.name << " (places "
3340 << ") - Name not known" << std::endl;
3344 const ContentFeatures &predicted_f = nodedef->get(id);
3346 // Predict param2 for facedir and wallmounted nodes
3349 if (predicted_f.param_type_2 == CPT2_WALLMOUNTED ||
3350 predicted_f.param_type_2 == CPT2_COLORED_WALLMOUNTED) {
3351 v3s16 dir = nodepos - neighbourpos;
3353 if (abs(dir.Y) > MYMAX(abs(dir.X), abs(dir.Z))) {
3354 param2 = dir.Y < 0 ? 1 : 0;
3355 } else if (abs(dir.X) > abs(dir.Z)) {
3356 param2 = dir.X < 0 ? 3 : 2;
3358 param2 = dir.Z < 0 ? 5 : 4;
3362 if (predicted_f.param_type_2 == CPT2_FACEDIR ||
3363 predicted_f.param_type_2 == CPT2_COLORED_FACEDIR) {
3364 v3s16 dir = nodepos - floatToInt(client->getEnv().getLocalPlayer()->getPosition(), BS);
3366 if (abs(dir.X) > abs(dir.Z)) {
3367 param2 = dir.X < 0 ? 3 : 1;
3369 param2 = dir.Z < 0 ? 2 : 0;
3373 assert(param2 <= 5);
3375 //Check attachment if node is in group attached_node
3376 if (((ItemGroupList) predicted_f.groups)["attached_node"] != 0) {
3377 static v3s16 wallmounted_dirs[8] = {
3387 if (predicted_f.param_type_2 == CPT2_WALLMOUNTED ||
3388 predicted_f.param_type_2 == CPT2_COLORED_WALLMOUNTED)
3389 pp = p + wallmounted_dirs[param2];
3391 pp = p + v3s16(0, -1, 0);
3393 if (!nodedef->get(map.getNodeNoEx(pp)).walkable)
3398 if ((predicted_f.param_type_2 == CPT2_COLOR
3399 || predicted_f.param_type_2 == CPT2_COLORED_FACEDIR
3400 || predicted_f.param_type_2 == CPT2_COLORED_WALLMOUNTED)) {
3401 const std::string &indexstr = playeritem.metadata.getString(
3402 "palette_index", 0);
3403 if (!indexstr.empty()) {
3404 s32 index = mystoi(indexstr);
3405 if (predicted_f.param_type_2 == CPT2_COLOR) {
3407 } else if (predicted_f.param_type_2
3408 == CPT2_COLORED_WALLMOUNTED) {
3409 // param2 = pure palette index + other
3410 param2 = (index & 0xf8) | (param2 & 0x07);
3411 } else if (predicted_f.param_type_2
3412 == CPT2_COLORED_FACEDIR) {
3413 // param2 = pure palette index + other
3414 param2 = (index & 0xe0) | (param2 & 0x1f);
3419 // Add node to client map
3420 MapNode n(id, 0, param2);
3423 LocalPlayer *player = client->getEnv().getLocalPlayer();
3425 // Dont place node when player would be inside new node
3426 // NOTE: This is to be eventually implemented by a mod as client-side Lua
3427 if (!nodedef->get(n).walkable ||
3428 g_settings->getBool("enable_build_where_you_stand") ||
3429 (client->checkPrivilege("noclip") && g_settings->getBool("noclip")) ||
3430 (nodedef->get(n).walkable &&
3431 neighbourpos != player->getStandingNodePos() + v3s16(0, 1, 0) &&
3432 neighbourpos != player->getStandingNodePos() + v3s16(0, 2, 0))) {
3434 // This triggers the required mesh update too
3435 client->addNode(p, n);
3438 } catch (InvalidPositionException &e) {
3439 errorstream << "Node placement prediction failed for "
3440 << playeritem_def.name << " (places "
3442 << ") - Position not loaded" << std::endl;
3449 void Game::handlePointingAtObject(const PointedThing &pointed, const ItemStack &playeritem,
3450 const v3f &player_position, bool show_debug)
3452 std::wstring infotext = unescape_translate(
3453 utf8_to_wide(runData.selected_object->infoText()));
3456 if (!infotext.empty()) {
3459 infotext += utf8_to_wide(runData.selected_object->debugInfoText());
3462 m_game_ui->setInfoText(infotext);
3464 if (input->getLeftState()) {
3465 bool do_punch = false;
3466 bool do_punch_damage = false;
3468 if (runData.object_hit_delay_timer <= 0.0) {
3470 do_punch_damage = true;
3471 runData.object_hit_delay_timer = object_hit_delay;
3474 if (input->getLeftClicked())
3478 infostream << "Left-clicked object" << std::endl;
3479 runData.left_punch = true;
3482 if (do_punch_damage) {
3483 // Report direct punch
3484 v3f objpos = runData.selected_object->getPosition();
3485 v3f dir = (objpos - player_position).normalize();
3486 ItemStack item = playeritem;
3487 if (playeritem.name.empty()) {
3488 InventoryList *hlist = local_inventory->getList("hand");
3490 item = hlist->getItem(0);
3494 bool disable_send = runData.selected_object->directReportPunch(
3495 dir, &item, runData.time_from_last_punch);
3496 runData.time_from_last_punch = 0;
3499 client->interact(0, pointed);
3501 } else if (input->getRightClicked()) {
3502 infostream << "Right-clicked object" << std::endl;
3503 client->interact(3, pointed); // place
3508 void Game::handleDigging(const PointedThing &pointed, const v3s16 &nodepos,
3509 const ToolCapabilities &playeritem_toolcap, f32 dtime)
3511 LocalPlayer *player = client->getEnv().getLocalPlayer();
3512 ClientMap &map = client->getEnv().getClientMap();
3513 MapNode n = client->getEnv().getClientMap().getNodeNoEx(nodepos);
3515 // NOTE: Similar piece of code exists on the server side for
3517 // Get digging parameters
3518 DigParams params = getDigParams(nodedef_manager->get(n).groups,
3519 &playeritem_toolcap);
3521 // If can't dig, try hand
3522 if (!params.diggable) {
3523 InventoryList *hlist = local_inventory->getList("hand");
3524 const ToolCapabilities *tp = hlist
3525 ? &hlist->getItem(0).getToolCapabilities(itemdef_manager)
3526 : itemdef_manager->get("").tool_capabilities;
3529 params = getDigParams(nodedef_manager->get(n).groups, tp);
3532 if (!params.diggable) {
3533 // I guess nobody will wait for this long
3534 runData.dig_time_complete = 10000000.0;
3536 runData.dig_time_complete = params.time;
3538 if (m_cache_enable_particles) {
3539 const ContentFeatures &features = client->getNodeDefManager()->get(n);
3540 client->getParticleManager()->addNodeParticle(client,
3541 player, nodepos, n, features);
3545 if (!runData.digging) {
3546 infostream << "Started digging" << std::endl;
3547 runData.dig_instantly = runData.dig_time_complete == 0;
3548 if (client->moddingEnabled() && client->getScript()->on_punchnode(nodepos, n))
3550 client->interact(0, pointed);
3551 runData.digging = true;
3552 runData.ldown_for_dig = true;
3555 if (!runData.dig_instantly) {
3556 runData.dig_index = (float)crack_animation_length
3558 / runData.dig_time_complete;
3560 // This is for e.g. torches
3561 runData.dig_index = crack_animation_length;
3564 SimpleSoundSpec sound_dig = nodedef_manager->get(n).sound_dig;
3566 if (sound_dig.exists() && params.diggable) {
3567 if (sound_dig.name == "__group") {
3568 if (!params.main_group.empty()) {
3569 soundmaker->m_player_leftpunch_sound.gain = 0.5;
3570 soundmaker->m_player_leftpunch_sound.name =
3571 std::string("default_dig_") +
3575 soundmaker->m_player_leftpunch_sound = sound_dig;
3579 // Don't show cracks if not diggable
3580 if (runData.dig_time_complete >= 100000.0) {
3581 } else if (runData.dig_index < crack_animation_length) {
3582 //TimeTaker timer("client.setTempMod");
3583 //infostream<<"dig_index="<<dig_index<<std::endl;
3584 client->setCrack(runData.dig_index, nodepos);
3586 infostream << "Digging completed" << std::endl;
3587 client->setCrack(-1, v3s16(0, 0, 0));
3589 runData.dig_time = 0;
3590 runData.digging = false;
3591 // we successfully dug, now block it from repeating if we want to be safe
3592 if (g_settings->getBool("safe_dig_and_place"))
3593 runData.digging_blocked = true;
3595 runData.nodig_delay_timer =
3596 runData.dig_time_complete / (float)crack_animation_length;
3598 // We don't want a corresponding delay to very time consuming nodes
3599 // and nodes without digging time (e.g. torches) get a fixed delay.
3600 if (runData.nodig_delay_timer > 0.3)
3601 runData.nodig_delay_timer = 0.3;
3602 else if (runData.dig_instantly)
3603 runData.nodig_delay_timer = 0.15;
3605 bool is_valid_position;
3606 MapNode wasnode = map.getNodeNoEx(nodepos, &is_valid_position);
3607 if (is_valid_position) {
3608 if (client->moddingEnabled() &&
3609 client->getScript()->on_dignode(nodepos, wasnode)) {
3613 const ContentFeatures &f = client->ndef()->get(wasnode);
3614 if (f.node_dig_prediction == "air") {
3615 client->removeNode(nodepos);
3616 } else if (!f.node_dig_prediction.empty()) {
3618 bool found = client->ndef()->getId(f.node_dig_prediction, id);
3620 client->addNode(nodepos, id, true);
3622 // implicit else: no prediction
3625 client->interact(2, pointed);
3627 if (m_cache_enable_particles) {
3628 const ContentFeatures &features =
3629 client->getNodeDefManager()->get(wasnode);
3630 client->getParticleManager()->addDiggingParticles(client,
3631 player, nodepos, wasnode, features);
3635 // Send event to trigger sound
3636 client->getEventManager()->put(new NodeDugEvent(nodepos, wasnode));
3639 if (runData.dig_time_complete < 100000.0) {
3640 runData.dig_time += dtime;
3642 runData.dig_time = 0;
3643 client->setCrack(-1, nodepos);
3646 camera->setDigging(0); // left click animation
3650 void Game::updateFrame(ProfilerGraph *graph, RunStats *stats, f32 dtime,
3651 const CameraOrientation &cam)
3653 LocalPlayer *player = client->getEnv().getLocalPlayer();
3659 if (draw_control->range_all) {
3660 runData.fog_range = 100000 * BS;
3662 runData.fog_range = draw_control->wanted_range * BS;
3666 Calculate general brightness
3668 u32 daynight_ratio = client->getEnv().getDayNightRatio();
3669 float time_brightness = decode_light_f((float)daynight_ratio / 1000.0);
3670 float direct_brightness;
3673 if (m_cache_enable_noclip && m_cache_enable_free_move) {
3674 direct_brightness = time_brightness;
3675 sunlight_seen = true;
3677 ScopeProfiler sp(g_profiler, "Detecting background light", SPT_AVG);
3678 float old_brightness = sky->getBrightness();
3679 direct_brightness = client->getEnv().getClientMap()
3680 .getBackgroundBrightness(MYMIN(runData.fog_range * 1.2, 60 * BS),
3681 daynight_ratio, (int)(old_brightness * 255.5), &sunlight_seen)
3685 float time_of_day_smooth = runData.time_of_day_smooth;
3686 float time_of_day = client->getEnv().getTimeOfDayF();
3688 static const float maxsm = 0.05f;
3689 static const float todsm = 0.05f;
3691 if (std::fabs(time_of_day - time_of_day_smooth) > maxsm &&
3692 std::fabs(time_of_day - time_of_day_smooth + 1.0) > maxsm &&
3693 std::fabs(time_of_day - time_of_day_smooth - 1.0) > maxsm)
3694 time_of_day_smooth = time_of_day;
3696 if (time_of_day_smooth > 0.8 && time_of_day < 0.2)
3697 time_of_day_smooth = time_of_day_smooth * (1.0 - todsm)
3698 + (time_of_day + 1.0) * todsm;
3700 time_of_day_smooth = time_of_day_smooth * (1.0 - todsm)
3701 + time_of_day * todsm;
3703 runData.time_of_day_smooth = time_of_day_smooth;
3705 sky->update(time_of_day_smooth, time_brightness, direct_brightness,
3706 sunlight_seen, camera->getCameraMode(), player->getYaw(),
3707 player->getPitch());
3713 if (sky->getCloudsVisible()) {
3714 clouds->setVisible(true);
3715 clouds->step(dtime);
3716 // camera->getPosition is not enough for 3rd person views
3717 v3f camera_node_position = camera->getCameraNode()->getPosition();
3718 v3s16 camera_offset = camera->getOffset();
3719 camera_node_position.X = camera_node_position.X + camera_offset.X * BS;
3720 camera_node_position.Y = camera_node_position.Y + camera_offset.Y * BS;
3721 camera_node_position.Z = camera_node_position.Z + camera_offset.Z * BS;
3722 clouds->update(camera_node_position,
3723 sky->getCloudColor());
3724 if (clouds->isCameraInsideCloud() && m_cache_enable_fog) {
3725 // if inside clouds, and fog enabled, use that as sky
3727 video::SColor clouds_dark = clouds->getColor()
3728 .getInterpolated(video::SColor(255, 0, 0, 0), 0.9);
3729 sky->overrideColors(clouds_dark, clouds->getColor());
3730 sky->setBodiesVisible(false);
3731 runData.fog_range = std::fmin(runData.fog_range * 0.5f, 32.0f * BS);
3732 // do not draw clouds after all
3733 clouds->setVisible(false);
3736 clouds->setVisible(false);
3743 client->getParticleManager()->step(dtime);
3749 if (m_cache_enable_fog) {
3752 video::EFT_FOG_LINEAR,
3753 runData.fog_range * m_cache_fog_start,
3754 runData.fog_range * 1.0,
3762 video::EFT_FOG_LINEAR,
3772 Get chat messages from client
3775 v2u32 screensize = driver->getScreenSize();
3777 updateChat(dtime, screensize);
3783 if (client->getPlayerItem() != runData.new_playeritem)
3784 client->selectPlayerItem(runData.new_playeritem);
3786 // Update local inventory if it has changed
3787 if (client->getLocalInventoryUpdated()) {
3788 //infostream<<"Updating local inventory"<<std::endl;
3789 client->getLocalInventory(*local_inventory);
3790 runData.update_wielded_item_trigger = true;
3793 if (runData.update_wielded_item_trigger) {
3794 // Update wielded tool
3795 InventoryList *mlist = local_inventory->getList("main");
3797 if (mlist && (client->getPlayerItem() < mlist->getSize())) {
3798 ItemStack item = mlist->getItem(client->getPlayerItem());
3799 if (item.getDefinition(itemdef_manager).name.empty()) { // override the hand
3800 InventoryList *hlist = local_inventory->getList("hand");
3802 item = hlist->getItem(0);
3804 camera->wield(item);
3807 runData.update_wielded_item_trigger = false;
3811 Update block draw list every 200ms or when camera direction has
3814 runData.update_draw_list_timer += dtime;
3816 v3f camera_direction = camera->getDirection();
3817 if (runData.update_draw_list_timer >= 0.2
3818 || runData.update_draw_list_last_cam_dir.getDistanceFrom(camera_direction) > 0.2
3819 || m_camera_offset_changed) {
3820 runData.update_draw_list_timer = 0;
3821 client->getEnv().getClientMap().updateDrawList();
3822 runData.update_draw_list_last_cam_dir = camera_direction;
3825 m_game_ui->update(*stats, client, draw_control, cam, runData.pointed_old, dtime);
3828 make sure menu is on top
3829 1. Delete formspec menu reference if menu was removed
3830 2. Else, make sure formspec menu is on top
3832 if (current_formspec) {
3833 if (current_formspec->getReferenceCount() == 1) {
3834 current_formspec->drop();
3835 current_formspec = NULL;
3836 } else if (isMenuActive()) {
3837 guiroot->bringToFront(current_formspec);
3844 const video::SColor &skycolor = sky->getSkyColor();
3846 TimeTaker tt_draw("mainloop: draw");
3847 driver->beginScene(true, true, skycolor);
3849 bool draw_wield_tool = (m_game_ui->m_flags.show_hud &&
3850 (player->hud_flags & HUD_FLAG_WIELDITEM_VISIBLE) &&
3851 (camera->getCameraMode() == CAMERA_MODE_FIRST));
3852 bool draw_crosshair = (
3853 (player->hud_flags & HUD_FLAG_CROSSHAIR_VISIBLE) &&
3854 (camera->getCameraMode() != CAMERA_MODE_THIRD_FRONT));
3855 #ifdef HAVE_TOUCHSCREENGUI
3857 draw_crosshair = !g_settings->getBool("touchtarget");
3858 } catch (SettingNotFoundException) {
3861 RenderingEngine::draw_scene(skycolor, m_game_ui->m_flags.show_hud,
3862 m_game_ui->m_flags.show_minimap, draw_wield_tool, draw_crosshair);
3867 if (m_game_ui->m_flags.show_profiler_graph)
3868 graph->draw(10, screensize.Y - 10, driver, g_fontengine->getFont());
3873 if (runData.damage_flash > 0.0f) {
3874 video::SColor color(runData.damage_flash, 180, 0, 0);
3875 driver->draw2DRectangle(color,
3876 core::rect<s32>(0, 0, screensize.X, screensize.Y),
3879 runData.damage_flash -= 384.0f * dtime;
3885 if (player->hurt_tilt_timer > 0.0f) {
3886 player->hurt_tilt_timer -= dtime * 6.0f;
3888 if (player->hurt_tilt_timer < 0.0f)
3889 player->hurt_tilt_strength = 0.0f;
3893 Update minimap pos and rotation
3895 if (mapper && m_game_ui->m_flags.show_minimap && m_game_ui->m_flags.show_hud) {
3896 mapper->setPos(floatToInt(player->getPosition(), BS));
3897 mapper->setAngle(player->getYaw());
3905 stats->drawtime = tt_draw.stop(true);
3906 g_profiler->graphAdd("mainloop_draw", stats->drawtime / 1000.0f);
3909 /* Log times and stuff for visualization */
3910 inline void Game::updateProfilerGraphs(ProfilerGraph *graph)
3912 Profiler::GraphValues values;
3913 g_profiler->graphGet(values);
3919 /****************************************************************************
3921 ****************************************************************************/
3923 /* On some computers framerate doesn't seem to be automatically limited
3925 inline void Game::limitFps(FpsControl *fps_timings, f32 *dtime)
3927 // not using getRealTime is necessary for wine
3928 device->getTimer()->tick(); // Maker sure device time is up-to-date
3929 u32 time = device->getTimer()->getTime();
3930 u32 last_time = fps_timings->last_time;
3932 if (time > last_time) // Make sure time hasn't overflowed
3933 fps_timings->busy_time = time - last_time;
3935 fps_timings->busy_time = 0;
3937 u32 frametime_min = 1000 / (g_menumgr.pausesGame()
3938 ? g_settings->getFloat("pause_fps_max")
3939 : g_settings->getFloat("fps_max"));
3941 if (fps_timings->busy_time < frametime_min) {
3942 fps_timings->sleep_time = frametime_min - fps_timings->busy_time;
3943 device->sleep(fps_timings->sleep_time);
3945 fps_timings->sleep_time = 0;
3948 /* Get the new value of the device timer. Note that device->sleep() may
3949 * not sleep for the entire requested time as sleep may be interrupted and
3950 * therefore it is arguably more accurate to get the new time from the
3951 * device rather than calculating it by adding sleep_time to time.
3954 device->getTimer()->tick(); // Update device timer
3955 time = device->getTimer()->getTime();
3957 if (time > last_time) // Make sure last_time hasn't overflowed
3958 *dtime = (time - last_time) / 1000.0;
3962 fps_timings->last_time = time;
3965 void Game::showOverlayMessage(const char *msg, float dtime, int percent, bool draw_clouds)
3967 const wchar_t *wmsg = wgettext(msg);
3968 RenderingEngine::draw_load_screen(wmsg, guienv, texture_src, dtime, percent,
3973 void Game::settingChangedCallback(const std::string &setting_name, void *data)
3975 ((Game *)data)->readSettings();
3978 void Game::readSettings()
3980 m_cache_doubletap_jump = g_settings->getBool("doubletap_jump");
3981 m_cache_enable_clouds = g_settings->getBool("enable_clouds");
3982 m_cache_enable_joysticks = g_settings->getBool("enable_joysticks");
3983 m_cache_enable_particles = g_settings->getBool("enable_particles");
3984 m_cache_enable_fog = g_settings->getBool("enable_fog");
3985 m_cache_mouse_sensitivity = g_settings->getFloat("mouse_sensitivity");
3986 m_cache_joystick_frustum_sensitivity = g_settings->getFloat("joystick_frustum_sensitivity");
3987 m_repeat_right_click_time = g_settings->getFloat("repeat_rightclick_time");
3989 m_cache_enable_noclip = g_settings->getBool("noclip");
3990 m_cache_enable_free_move = g_settings->getBool("free_move");
3992 m_cache_fog_start = g_settings->getFloat("fog_start");
3994 m_cache_cam_smoothing = 0;
3995 if (g_settings->getBool("cinematic"))
3996 m_cache_cam_smoothing = 1 - g_settings->getFloat("cinematic_camera_smoothing");
3998 m_cache_cam_smoothing = 1 - g_settings->getFloat("camera_smoothing");
4000 m_cache_fog_start = rangelim(m_cache_fog_start, 0.0f, 0.99f);
4001 m_cache_cam_smoothing = rangelim(m_cache_cam_smoothing, 0.01f, 1.0f);
4002 m_cache_mouse_sensitivity = rangelim(m_cache_mouse_sensitivity, 0.001, 100.0);
4004 m_does_lost_focus_pause_game = g_settings->getBool("pause_on_lost_focus");
4007 /****************************************************************************/
4008 /****************************************************************************
4010 ****************************************************************************/
4011 /****************************************************************************/
4013 void Game::extendedResourceCleanup()
4015 // Extended resource accounting
4016 infostream << "Irrlicht resources after cleanup:" << std::endl;
4017 infostream << "\tRemaining meshes : "
4018 << RenderingEngine::get_mesh_cache()->getMeshCount() << std::endl;
4019 infostream << "\tRemaining textures : "
4020 << driver->getTextureCount() << std::endl;
4022 for (unsigned int i = 0; i < driver->getTextureCount(); i++) {
4023 irr::video::ITexture *texture = driver->getTextureByIndex(i);
4024 infostream << "\t\t" << i << ":" << texture->getName().getPath().c_str()
4028 clearTextureNameCache();
4029 infostream << "\tRemaining materials: "
4030 << driver-> getMaterialRendererCount()
4031 << " (note: irrlicht doesn't support removing renderers)" << std::endl;
4034 void Game::showDeathFormspec()
4036 static std::string formspec =
4037 std::string(FORMSPEC_VERSION_STRING) +
4039 "bgcolor[#320000b4;true]"
4040 "label[4.85,1.35;" + gettext("You died") + "]"
4041 "button_exit[4,3;3,0.5;btn_respawn;" + gettext("Respawn") + "]"
4045 /* Note: FormspecFormSource and LocalFormspecHandler *
4046 * are deleted by guiFormSpecMenu */
4047 FormspecFormSource *fs_src = new FormspecFormSource(formspec);
4048 LocalFormspecHandler *txt_dst = new LocalFormspecHandler("MT_DEATH_SCREEN", client);
4050 GUIFormSpecMenu::create(current_formspec, client, &input->joystick, fs_src,
4051 txt_dst, client->getFormspecPrepend());
4052 current_formspec->setFocus("btn_respawn");
4055 #define GET_KEY_NAME(KEY) gettext(getKeySetting(#KEY).name())
4056 void Game::showPauseMenu()
4059 static const std::string control_text = strgettext("Default Controls:\n"
4060 "No menu visible:\n"
4061 "- single tap: button activate\n"
4062 "- double tap: place/use\n"
4063 "- slide finger: look around\n"
4064 "Menu/Inventory visible:\n"
4065 "- double tap (outside):\n"
4067 "- touch stack, touch slot:\n"
4069 "- touch&drag, tap 2nd finger\n"
4070 " --> place single item to slot\n"
4073 static const std::string control_text_template = strgettext("Controls:\n"
4074 "- %s: move forwards\n"
4075 "- %s: move backwards\n"
4077 "- %s: move right\n"
4078 "- %s: jump/climb\n"
4079 "- %s: sneak/go down\n"
4082 "- Mouse: turn/look\n"
4083 "- Mouse left: dig/punch\n"
4084 "- Mouse right: place/use\n"
4085 "- Mouse wheel: select item\n"
4089 char control_text_buf[600];
4091 porting::mt_snprintf(control_text_buf, sizeof(control_text_buf), control_text_template.c_str(),
4092 GET_KEY_NAME(keymap_forward),
4093 GET_KEY_NAME(keymap_backward),
4094 GET_KEY_NAME(keymap_left),
4095 GET_KEY_NAME(keymap_right),
4096 GET_KEY_NAME(keymap_jump),
4097 GET_KEY_NAME(keymap_sneak),
4098 GET_KEY_NAME(keymap_drop),
4099 GET_KEY_NAME(keymap_inventory),
4100 GET_KEY_NAME(keymap_chat)
4103 std::string control_text = std::string(control_text_buf);
4104 str_formspec_escape(control_text);
4107 float ypos = simple_singleplayer_mode ? 0.7f : 0.1f;
4108 std::ostringstream os;
4110 os << FORMSPEC_VERSION_STRING << SIZE_TAG
4111 << "button_exit[4," << (ypos++) << ";3,0.5;btn_continue;"
4112 << strgettext("Continue") << "]";
4114 if (!simple_singleplayer_mode) {
4115 os << "button_exit[4," << (ypos++) << ";3,0.5;btn_change_password;"
4116 << strgettext("Change Password") << "]";
4118 os << "field[4.95,0;5,1.5;;" << strgettext("Game paused") << ";]";
4122 os << "button_exit[4," << (ypos++) << ";3,0.5;btn_sound;"
4123 << strgettext("Sound Volume") << "]";
4124 os << "button_exit[4," << (ypos++) << ";3,0.5;btn_key_config;"
4125 << strgettext("Change Keys") << "]";
4127 os << "button_exit[4," << (ypos++) << ";3,0.5;btn_exit_menu;"
4128 << strgettext("Exit to Menu") << "]";
4129 os << "button_exit[4," << (ypos++) << ";3,0.5;btn_exit_os;"
4130 << strgettext("Exit to OS") << "]"
4131 << "textarea[7.5,0.25;3.9,6.25;;" << control_text << ";]"
4132 << "textarea[0.4,0.25;3.9,6.25;;" << PROJECT_NAME_C " " VERSION_STRING "\n"
4134 << strgettext("Game info:") << "\n";
4135 const std::string &address = client->getAddressName();
4136 static const std::string mode = strgettext("- Mode: ");
4137 if (!simple_singleplayer_mode) {
4138 Address serverAddress = client->getServerAddress();
4139 if (!address.empty()) {
4140 os << mode << strgettext("Remote server") << "\n"
4141 << strgettext("- Address: ") << address;
4143 os << mode << strgettext("Hosting server");
4145 os << "\n" << strgettext("- Port: ") << serverAddress.getPort() << "\n";
4147 os << mode << strgettext("Singleplayer") << "\n";
4149 if (simple_singleplayer_mode || address.empty()) {
4150 static const std::string on = strgettext("On");
4151 static const std::string off = strgettext("Off");
4152 const std::string &damage = g_settings->getBool("enable_damage") ? on : off;
4153 const std::string &creative = g_settings->getBool("creative_mode") ? on : off;
4154 const std::string &announced = g_settings->getBool("server_announce") ? on : off;
4155 os << strgettext("- Damage: ") << damage << "\n"
4156 << strgettext("- Creative Mode: ") << creative << "\n";
4157 if (!simple_singleplayer_mode) {
4158 const std::string &pvp = g_settings->getBool("enable_pvp") ? on : off;
4159 os << strgettext("- PvP: ") << pvp << "\n"
4160 << strgettext("- Public: ") << announced << "\n";
4161 std::string server_name = g_settings->get("server_name");
4162 str_formspec_escape(server_name);
4163 if (announced == on && !server_name.empty())
4164 os << strgettext("- Server Name: ") << server_name;
4171 /* Note: FormspecFormSource and LocalFormspecHandler *
4172 * are deleted by guiFormSpecMenu */
4173 FormspecFormSource *fs_src = new FormspecFormSource(os.str());
4174 LocalFormspecHandler *txt_dst = new LocalFormspecHandler("MT_PAUSE_MENU");
4176 GUIFormSpecMenu::create(current_formspec, client, &input->joystick,
4177 fs_src, txt_dst, client->getFormspecPrepend());
4178 current_formspec->setFocus("btn_continue");
4179 current_formspec->doPause = true;
4182 /****************************************************************************/
4183 /****************************************************************************
4184 extern function for launching the game
4185 ****************************************************************************/
4186 /****************************************************************************/
4188 void the_game(bool *kill,
4190 InputHandler *input,
4191 const std::string &map_dir,
4192 const std::string &playername,
4193 const std::string &password,
4194 const std::string &address, // If empty local server is created
4197 std::string &error_message,
4198 ChatBackend &chat_backend,
4199 bool *reconnect_requested,
4200 const SubgameSpec &gamespec, // Used for local game
4201 bool simple_singleplayer_mode)
4205 /* Make a copy of the server address because if a local singleplayer server
4206 * is created then this is updated and we don't want to change the value
4207 * passed to us by the calling function
4209 std::string server_address = address;
4213 if (game.startup(kill, random_input, input, map_dir,
4214 playername, password, &server_address, port, error_message,
4215 reconnect_requested, &chat_backend, gamespec,
4216 simple_singleplayer_mode)) {
4221 } catch (SerializationError &e) {
4222 error_message = std::string("A serialization error occurred:\n")
4223 + e.what() + "\n\nThe server is probably "
4224 " running a different version of " PROJECT_NAME_C ".";
4225 errorstream << error_message << std::endl;
4226 } catch (ServerError &e) {
4227 error_message = e.what();
4228 errorstream << "ServerError: " << error_message << std::endl;
4229 } catch (ModError &e) {
4230 error_message = e.what() + strgettext("\nCheck debug.txt for details.");
4231 errorstream << "ModError: " << error_message << std::endl;