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"
73 #include "client/sound_openal.h"
75 #include "client/sound.h"
81 struct TextDestNodeMetadata : public TextDest
83 TextDestNodeMetadata(v3s16 p, Client *client)
88 // This is deprecated I guess? -celeron55
89 void gotText(const std::wstring &text)
91 std::string ntext = wide_to_utf8(text);
92 infostream << "Submitting 'text' field of node at (" << m_p.X << ","
93 << m_p.Y << "," << m_p.Z << "): " << ntext << std::endl;
95 fields["text"] = ntext;
96 m_client->sendNodemetaFields(m_p, "", fields);
98 void gotText(const StringMap &fields)
100 m_client->sendNodemetaFields(m_p, "", fields);
107 struct TextDestPlayerInventory : public TextDest
109 TextDestPlayerInventory(Client *client)
114 TextDestPlayerInventory(Client *client, const std::string &formname)
117 m_formname = formname;
119 void gotText(const StringMap &fields)
121 m_client->sendInventoryFields(m_formname, fields);
127 struct LocalFormspecHandler : public TextDest
129 LocalFormspecHandler(const std::string &formname)
131 m_formname = formname;
134 LocalFormspecHandler(const std::string &formname, Client *client):
137 m_formname = formname;
140 void gotText(const StringMap &fields)
142 if (m_formname == "MT_PAUSE_MENU") {
143 if (fields.find("btn_sound") != fields.end()) {
144 g_gamecallback->changeVolume();
148 if (fields.find("btn_key_config") != fields.end()) {
149 g_gamecallback->keyConfig();
153 if (fields.find("btn_exit_menu") != fields.end()) {
154 g_gamecallback->disconnect();
158 if (fields.find("btn_exit_os") != fields.end()) {
159 g_gamecallback->exitToOS();
161 RenderingEngine::get_raw_device()->closeDevice();
166 if (fields.find("btn_change_password") != fields.end()) {
167 g_gamecallback->changePassword();
171 if (fields.find("quit") != fields.end()) {
175 if (fields.find("btn_continue") != fields.end()) {
180 // Don't disable this part when modding is disabled, it's used in builtin
181 if (m_client && m_client->getScript())
182 m_client->getScript()->on_formspec_input(m_formname, fields);
185 Client *m_client = nullptr;
188 /* Form update callback */
190 class NodeMetadataFormSource: public IFormSource
193 NodeMetadataFormSource(ClientMap *map, v3s16 p):
198 const std::string &getForm() const
200 static const std::string empty_string = "";
201 NodeMetadata *meta = m_map->getNodeMetadata(m_p);
206 return meta->getString("formspec");
209 virtual std::string resolveText(const std::string &str)
211 NodeMetadata *meta = m_map->getNodeMetadata(m_p);
216 return meta->resolveString(str);
223 class PlayerInventoryFormSource: public IFormSource
226 PlayerInventoryFormSource(Client *client):
231 const std::string &getForm() const
233 LocalPlayer *player = m_client->getEnv().getLocalPlayer();
234 return player->inventory_formspec;
240 class NodeDugEvent: public MtEvent
246 NodeDugEvent(v3s16 p, MapNode n):
250 MtEvent::Type getType() const
252 return MtEvent::NODE_DUG;
258 ISoundManager *m_sound;
259 const NodeDefManager *m_ndef;
261 bool makes_footstep_sound;
262 float m_player_step_timer;
264 SimpleSoundSpec m_player_step_sound;
265 SimpleSoundSpec m_player_leftpunch_sound;
266 SimpleSoundSpec m_player_rightpunch_sound;
268 SoundMaker(ISoundManager *sound, const NodeDefManager *ndef):
271 makes_footstep_sound(true),
272 m_player_step_timer(0)
276 void playPlayerStep()
278 if (m_player_step_timer <= 0 && m_player_step_sound.exists()) {
279 m_player_step_timer = 0.03;
280 if (makes_footstep_sound)
281 m_sound->playSound(m_player_step_sound, false);
285 static void viewBobbingStep(MtEvent *e, void *data)
287 SoundMaker *sm = (SoundMaker *)data;
288 sm->playPlayerStep();
291 static void playerRegainGround(MtEvent *e, void *data)
293 SoundMaker *sm = (SoundMaker *)data;
294 sm->playPlayerStep();
297 static void playerJump(MtEvent *e, void *data)
299 //SoundMaker *sm = (SoundMaker*)data;
302 static void cameraPunchLeft(MtEvent *e, void *data)
304 SoundMaker *sm = (SoundMaker *)data;
305 sm->m_sound->playSound(sm->m_player_leftpunch_sound, false);
308 static void cameraPunchRight(MtEvent *e, void *data)
310 SoundMaker *sm = (SoundMaker *)data;
311 sm->m_sound->playSound(sm->m_player_rightpunch_sound, false);
314 static void nodeDug(MtEvent *e, void *data)
316 SoundMaker *sm = (SoundMaker *)data;
317 NodeDugEvent *nde = (NodeDugEvent *)e;
318 sm->m_sound->playSound(sm->m_ndef->get(nde->n).sound_dug, false);
321 static void playerDamage(MtEvent *e, void *data)
323 SoundMaker *sm = (SoundMaker *)data;
324 sm->m_sound->playSound(SimpleSoundSpec("player_damage", 0.5), false);
327 static void playerFallingDamage(MtEvent *e, void *data)
329 SoundMaker *sm = (SoundMaker *)data;
330 sm->m_sound->playSound(SimpleSoundSpec("player_falling_damage", 0.5), false);
333 void registerReceiver(MtEventManager *mgr)
335 mgr->reg(MtEvent::VIEW_BOBBING_STEP, SoundMaker::viewBobbingStep, this);
336 mgr->reg(MtEvent::PLAYER_REGAIN_GROUND, SoundMaker::playerRegainGround, this);
337 mgr->reg(MtEvent::PLAYER_JUMP, SoundMaker::playerJump, this);
338 mgr->reg(MtEvent::CAMERA_PUNCH_LEFT, SoundMaker::cameraPunchLeft, this);
339 mgr->reg(MtEvent::CAMERA_PUNCH_RIGHT, SoundMaker::cameraPunchRight, this);
340 mgr->reg(MtEvent::NODE_DUG, SoundMaker::nodeDug, this);
341 mgr->reg(MtEvent::PLAYER_DAMAGE, SoundMaker::playerDamage, this);
342 mgr->reg(MtEvent::PLAYER_FALLING_DAMAGE, SoundMaker::playerFallingDamage, this);
345 void step(float dtime)
347 m_player_step_timer -= dtime;
351 // Locally stored sounds don't need to be preloaded because of this
352 class GameOnDemandSoundFetcher: public OnDemandSoundFetcher
354 std::set<std::string> m_fetched;
356 void paths_insert(std::set<std::string> &dst_paths,
357 const std::string &base,
358 const std::string &name)
360 dst_paths.insert(base + DIR_DELIM + "sounds" + DIR_DELIM + name + ".ogg");
361 dst_paths.insert(base + DIR_DELIM + "sounds" + DIR_DELIM + name + ".0.ogg");
362 dst_paths.insert(base + DIR_DELIM + "sounds" + DIR_DELIM + name + ".1.ogg");
363 dst_paths.insert(base + DIR_DELIM + "sounds" + DIR_DELIM + name + ".2.ogg");
364 dst_paths.insert(base + DIR_DELIM + "sounds" + DIR_DELIM + name + ".3.ogg");
365 dst_paths.insert(base + DIR_DELIM + "sounds" + DIR_DELIM + name + ".4.ogg");
366 dst_paths.insert(base + DIR_DELIM + "sounds" + DIR_DELIM + name + ".5.ogg");
367 dst_paths.insert(base + DIR_DELIM + "sounds" + DIR_DELIM + name + ".6.ogg");
368 dst_paths.insert(base + DIR_DELIM + "sounds" + DIR_DELIM + name + ".7.ogg");
369 dst_paths.insert(base + DIR_DELIM + "sounds" + DIR_DELIM + name + ".8.ogg");
370 dst_paths.insert(base + DIR_DELIM + "sounds" + DIR_DELIM + name + ".9.ogg");
373 void fetchSounds(const std::string &name,
374 std::set<std::string> &dst_paths,
375 std::set<std::string> &dst_datas)
377 if (m_fetched.count(name))
380 m_fetched.insert(name);
382 paths_insert(dst_paths, porting::path_share, name);
383 paths_insert(dst_paths, porting::path_user, name);
388 // before 1.8 there isn't a "integer interface", only float
389 #if (IRRLICHT_VERSION_MAJOR == 1 && IRRLICHT_VERSION_MINOR < 8)
390 typedef f32 SamplerLayer_t;
392 typedef s32 SamplerLayer_t;
396 class GameGlobalShaderConstantSetter : public IShaderConstantSetter
399 bool *m_force_fog_off;
402 CachedPixelShaderSetting<float, 4> m_sky_bg_color;
403 CachedPixelShaderSetting<float> m_fog_distance;
404 CachedVertexShaderSetting<float> m_animation_timer_vertex;
405 CachedPixelShaderSetting<float> m_animation_timer_pixel;
406 CachedPixelShaderSetting<float, 3> m_day_light;
407 CachedPixelShaderSetting<float, 3> m_eye_position_pixel;
408 CachedVertexShaderSetting<float, 3> m_eye_position_vertex;
409 CachedPixelShaderSetting<float, 3> m_minimap_yaw;
410 CachedPixelShaderSetting<SamplerLayer_t> m_base_texture;
411 CachedPixelShaderSetting<SamplerLayer_t> m_normal_texture;
412 CachedPixelShaderSetting<SamplerLayer_t> m_texture_flags;
416 void onSettingsChange(const std::string &name)
418 if (name == "enable_fog")
419 m_fog_enabled = g_settings->getBool("enable_fog");
422 static void settingsCallback(const std::string &name, void *userdata)
424 reinterpret_cast<GameGlobalShaderConstantSetter*>(userdata)->onSettingsChange(name);
427 void setSky(Sky *sky) { m_sky = sky; }
429 GameGlobalShaderConstantSetter(Sky *sky, bool *force_fog_off,
430 f32 *fog_range, Client *client) :
432 m_force_fog_off(force_fog_off),
433 m_fog_range(fog_range),
434 m_sky_bg_color("skyBgColor"),
435 m_fog_distance("fogDistance"),
436 m_animation_timer_vertex("animationTimer"),
437 m_animation_timer_pixel("animationTimer"),
438 m_day_light("dayLight"),
439 m_eye_position_pixel("eyePosition"),
440 m_eye_position_vertex("eyePosition"),
441 m_minimap_yaw("yawVec"),
442 m_base_texture("baseTexture"),
443 m_normal_texture("normalTexture"),
444 m_texture_flags("textureFlags"),
447 g_settings->registerChangedCallback("enable_fog", settingsCallback, this);
448 m_fog_enabled = g_settings->getBool("enable_fog");
451 ~GameGlobalShaderConstantSetter()
453 g_settings->deregisterChangedCallback("enable_fog", settingsCallback, this);
456 virtual void onSetConstants(video::IMaterialRendererServices *services,
463 video::SColor bgcolor = m_sky->getBgColor();
464 video::SColorf bgcolorf(bgcolor);
465 float bgcolorfa[4] = {
471 m_sky_bg_color.set(bgcolorfa, services);
474 float fog_distance = 10000 * BS;
476 if (m_fog_enabled && !*m_force_fog_off)
477 fog_distance = *m_fog_range;
479 m_fog_distance.set(&fog_distance, services);
481 u32 daynight_ratio = (float)m_client->getEnv().getDayNightRatio();
482 video::SColorf sunlight;
483 get_sunlight_color(&sunlight, daynight_ratio);
488 m_day_light.set(dnc, services);
490 u32 animation_timer = porting::getTimeMs() % 100000;
491 float animation_timer_f = (float)animation_timer / 100000.f;
492 m_animation_timer_vertex.set(&animation_timer_f, services);
493 m_animation_timer_pixel.set(&animation_timer_f, services);
495 float eye_position_array[3];
496 v3f epos = m_client->getEnv().getLocalPlayer()->getEyePosition();
497 #if (IRRLICHT_VERSION_MAJOR == 1 && IRRLICHT_VERSION_MINOR < 8)
498 eye_position_array[0] = epos.X;
499 eye_position_array[1] = epos.Y;
500 eye_position_array[2] = epos.Z;
502 epos.getAs3Values(eye_position_array);
504 m_eye_position_pixel.set(eye_position_array, services);
505 m_eye_position_vertex.set(eye_position_array, services);
507 if (m_client->getMinimap()) {
508 float minimap_yaw_array[3];
509 v3f minimap_yaw = m_client->getMinimap()->getYawVec();
510 #if (IRRLICHT_VERSION_MAJOR == 1 && IRRLICHT_VERSION_MINOR < 8)
511 minimap_yaw_array[0] = minimap_yaw.X;
512 minimap_yaw_array[1] = minimap_yaw.Y;
513 minimap_yaw_array[2] = minimap_yaw.Z;
515 minimap_yaw.getAs3Values(minimap_yaw_array);
517 m_minimap_yaw.set(minimap_yaw_array, services);
520 SamplerLayer_t base_tex = 0,
523 m_base_texture.set(&base_tex, services);
524 m_normal_texture.set(&normal_tex, services);
525 m_texture_flags.set(&flags_tex, services);
530 class GameGlobalShaderConstantSetterFactory : public IShaderConstantSetterFactory
533 bool *m_force_fog_off;
536 std::vector<GameGlobalShaderConstantSetter *> created_nosky;
538 GameGlobalShaderConstantSetterFactory(bool *force_fog_off,
539 f32 *fog_range, Client *client) :
541 m_force_fog_off(force_fog_off),
542 m_fog_range(fog_range),
546 void setSky(Sky *sky) {
548 for (GameGlobalShaderConstantSetter *ggscs : created_nosky) {
549 ggscs->setSky(m_sky);
551 created_nosky.clear();
554 virtual IShaderConstantSetter* create()
556 GameGlobalShaderConstantSetter *scs = new GameGlobalShaderConstantSetter(
557 m_sky, m_force_fog_off, m_fog_range, m_client);
559 created_nosky.push_back(scs);
565 #define SIZE_TAG "size[11,5.5]"
567 #define SIZE_TAG "size[11,5.5,true]" // Fixed size on desktop
570 /****************************************************************************
572 ****************************************************************************/
574 const float object_hit_delay = 0.2;
577 u32 last_time, busy_time, sleep_time;
581 /* The reason the following structs are not anonymous structs within the
582 * class is that they are not used by the majority of member functions and
583 * many functions that do require objects of thse types do not modify them
584 * (so they can be passed as a const qualified parameter)
590 PointedThing pointed_old;
594 bool digging_blocked;
596 bool update_wielded_item_trigger;
597 bool reset_jump_timer;
598 float nodig_delay_timer;
600 float dig_time_complete;
601 float repeat_rightclick_timer;
602 float object_hit_delay_timer;
603 float time_from_last_punch;
604 ClientActiveObject *selected_object;
608 float update_draw_list_timer;
612 v3f update_draw_list_last_cam_dir;
614 float time_of_day_smooth;
619 struct ClientEventHandler
621 void (Game::*handler)(ClientEvent *, CameraOrientation *);
624 /****************************************************************************
626 ****************************************************************************/
628 /* This is not intended to be a public class. If a public class becomes
629 * desirable then it may be better to create another 'wrapper' class that
630 * hides most of the stuff in this class (nothing in this class is required
631 * by any other file) but exposes the public methods/data only.
638 bool startup(bool *kill,
641 const std::string &map_dir,
642 const std::string &playername,
643 const std::string &password,
644 // If address is "", local server is used and address is updated
645 std::string *address,
647 std::string &error_message,
649 ChatBackend *chat_backend,
650 const SubgameSpec &gamespec, // Used for local game
651 bool simple_singleplayer_mode);
658 void extendedResourceCleanup();
660 // Basic initialisation
661 bool init(const std::string &map_dir, std::string *address,
663 const SubgameSpec &gamespec);
665 bool createSingleplayerServer(const std::string &map_dir,
666 const SubgameSpec &gamespec, u16 port, std::string *address);
669 bool createClient(const std::string &playername,
670 const std::string &password, std::string *address, u16 port);
674 bool connectToServer(const std::string &playername,
675 const std::string &password, std::string *address, u16 port,
676 bool *connect_ok, bool *aborted);
677 bool getServerContent(bool *aborted);
681 void updateInteractTimers(f32 dtime);
682 bool checkConnection();
683 bool handleCallbacks();
684 void processQueues();
685 void updateProfilers(const RunStats &stats, const FpsControl &draw_times, f32 dtime);
686 void addProfilerGraphs(const RunStats &stats, const FpsControl &draw_times, f32 dtime);
687 void updateStats(RunStats *stats, const FpsControl &draw_times, f32 dtime);
690 void processUserInput(f32 dtime);
691 void processKeyInput();
692 void processItemSelection(u16 *new_playeritem);
694 void dropSelectedItem(bool single_item = false);
695 void openInventory();
696 void openConsole(float scale, const wchar_t *line=NULL);
697 void toggleFreeMove();
698 void toggleFreeMoveAlt();
701 void toggleCinematic();
702 void toggleAutoforward();
704 void toggleMinimap(bool shift_pressed);
707 void toggleUpdateCamera();
709 void increaseViewRange();
710 void decreaseViewRange();
711 void toggleFullViewRange();
712 void checkZoomEnabled();
714 void updateCameraDirection(CameraOrientation *cam, float dtime);
715 void updateCameraOrientation(CameraOrientation *cam, float dtime);
716 void updatePlayerControl(const CameraOrientation &cam);
717 void step(f32 *dtime);
718 void processClientEvents(CameraOrientation *cam);
719 void updateCamera(u32 busy_time, f32 dtime);
720 void updateSound(f32 dtime);
721 void processPlayerInteraction(f32 dtime, bool show_hud, bool show_debug);
723 * Returns the object or node the player is pointing at.
724 * Also updates the selected thing in the Hud.
726 * @param[in] shootline the shootline, starting from
727 * the camera position. This also gives the maximal distance
729 * @param[in] liquids_pointable if false, liquids are ignored
730 * @param[in] look_for_object if false, objects are ignored
731 * @param[in] camera_offset offset of the camera
732 * @param[out] selected_object the selected object or
735 PointedThing updatePointedThing(
736 const core::line3d<f32> &shootline, bool liquids_pointable,
737 bool look_for_object, const v3s16 &camera_offset);
738 void handlePointingAtNothing(const ItemStack &playerItem);
739 void handlePointingAtNode(const PointedThing &pointed,
740 const ItemDefinition &playeritem_def, const ItemStack &playeritem,
741 const ToolCapabilities &playeritem_toolcap, f32 dtime);
742 void handlePointingAtObject(const PointedThing &pointed, const ItemStack &playeritem,
743 const v3f &player_position, bool show_debug);
744 void handleDigging(const PointedThing &pointed, const v3s16 &nodepos,
745 const ToolCapabilities &playeritem_toolcap, f32 dtime);
746 void updateFrame(ProfilerGraph *graph, RunStats *stats, f32 dtime,
747 const CameraOrientation &cam);
748 void updateProfilerGraphs(ProfilerGraph *graph);
751 void limitFps(FpsControl *fps_timings, f32 *dtime);
753 void showOverlayMessage(const char *msg, float dtime, int percent,
754 bool draw_clouds = true);
756 static void settingChangedCallback(const std::string &setting_name, void *data);
759 inline bool isKeyDown(GameKeyType k)
761 return input->isKeyDown(k);
763 inline bool wasKeyDown(GameKeyType k)
765 return input->wasKeyDown(k);
769 void handleAndroidChatInput();
774 bool force_fog_off = false;
775 bool disable_camera_update = false;
778 void showPauseMenu();
780 // ClientEvent handlers
781 void handleClientEvent_None(ClientEvent *event, CameraOrientation *cam);
782 void handleClientEvent_PlayerDamage(ClientEvent *event, CameraOrientation *cam);
783 void handleClientEvent_PlayerForceMove(ClientEvent *event, CameraOrientation *cam);
784 void handleClientEvent_Deathscreen(ClientEvent *event, CameraOrientation *cam);
785 void handleClientEvent_ShowFormSpec(ClientEvent *event, CameraOrientation *cam);
786 void handleClientEvent_ShowLocalFormSpec(ClientEvent *event, CameraOrientation *cam);
787 void handleClientEvent_HandleParticleEvent(ClientEvent *event,
788 CameraOrientation *cam);
789 void handleClientEvent_HudAdd(ClientEvent *event, CameraOrientation *cam);
790 void handleClientEvent_HudRemove(ClientEvent *event, CameraOrientation *cam);
791 void handleClientEvent_HudChange(ClientEvent *event, CameraOrientation *cam);
792 void handleClientEvent_SetSky(ClientEvent *event, CameraOrientation *cam);
793 void handleClientEvent_OverrideDayNigthRatio(ClientEvent *event,
794 CameraOrientation *cam);
795 void handleClientEvent_CloudParams(ClientEvent *event, CameraOrientation *cam);
797 void updateChat(f32 dtime, const v2u32 &screensize);
799 bool nodePlacementPrediction(const ItemDefinition &playeritem_def,
800 const ItemStack &playeritem, const v3s16 &nodepos, const v3s16 &neighbourpos);
801 static const ClientEventHandler clientEventHandler[CLIENTEVENT_MAX];
803 InputHandler *input = nullptr;
805 Client *client = nullptr;
806 Server *server = nullptr;
808 IWritableTextureSource *texture_src = nullptr;
809 IWritableShaderSource *shader_src = nullptr;
811 // When created, these will be filled with data received from the server
812 IWritableItemDefManager *itemdef_manager = nullptr;
813 NodeDefManager *nodedef_manager = nullptr;
815 GameOnDemandSoundFetcher soundfetcher; // useful when testing
816 ISoundManager *sound = nullptr;
817 bool sound_is_dummy = false;
818 SoundMaker *soundmaker = nullptr;
820 ChatBackend *chat_backend = nullptr;
822 GUIFormSpecMenu *current_formspec = nullptr;
823 //default: "". If other than "", empty show_formspec packets will only close the formspec when the formname matches
824 std::string cur_formname;
826 EventManager *eventmgr = nullptr;
827 QuicktuneShortcutter *quicktune = nullptr;
828 bool registration_confirmation_shown = false;
830 std::unique_ptr<GameUI> m_game_ui;
831 GUIChatConsole *gui_chat_console = nullptr; // Free using ->Drop()
832 MapDrawControl *draw_control = nullptr;
833 Camera *camera = nullptr;
834 Clouds *clouds = nullptr; // Free using ->Drop()
835 Sky *sky = nullptr; // Free using ->Drop()
836 Inventory *local_inventory = nullptr;
838 Minimap *mapper = nullptr;
844 This class does take ownership/responsibily for cleaning up etc of any of
845 these items (e.g. device)
847 IrrlichtDevice *device;
848 video::IVideoDriver *driver;
849 scene::ISceneManager *smgr;
851 std::string *error_message;
852 bool *reconnect_requested;
853 scene::ISceneNode *skybox;
856 bool simple_singleplayer_mode;
859 /* Pre-calculated values
861 int crack_animation_length;
863 IntervalLimiter profiler_interval;
866 * TODO: Local caching of settings is not optimal and should at some stage
867 * be updated to use a global settings object for getting thse values
868 * (as opposed to the this local caching). This can be addressed in
871 bool m_cache_doubletap_jump;
872 bool m_cache_enable_clouds;
873 bool m_cache_enable_joysticks;
874 bool m_cache_enable_particles;
875 bool m_cache_enable_fog;
876 bool m_cache_enable_noclip;
877 bool m_cache_enable_free_move;
878 f32 m_cache_mouse_sensitivity;
879 f32 m_cache_joystick_frustum_sensitivity;
880 f32 m_repeat_right_click_time;
881 f32 m_cache_cam_smoothing;
882 f32 m_cache_fog_start;
884 bool m_invert_mouse = false;
885 bool m_first_loop_after_window_activation = false;
886 bool m_camera_offset_changed = false;
888 bool m_does_lost_focus_pause_game = false;
891 bool m_cache_hold_aux1;
892 bool m_android_chat_open;
897 m_game_ui(new GameUI())
899 g_settings->registerChangedCallback("doubletap_jump",
900 &settingChangedCallback, this);
901 g_settings->registerChangedCallback("enable_clouds",
902 &settingChangedCallback, this);
903 g_settings->registerChangedCallback("doubletap_joysticks",
904 &settingChangedCallback, this);
905 g_settings->registerChangedCallback("enable_particles",
906 &settingChangedCallback, this);
907 g_settings->registerChangedCallback("enable_fog",
908 &settingChangedCallback, this);
909 g_settings->registerChangedCallback("mouse_sensitivity",
910 &settingChangedCallback, this);
911 g_settings->registerChangedCallback("joystick_frustum_sensitivity",
912 &settingChangedCallback, this);
913 g_settings->registerChangedCallback("repeat_rightclick_time",
914 &settingChangedCallback, this);
915 g_settings->registerChangedCallback("noclip",
916 &settingChangedCallback, this);
917 g_settings->registerChangedCallback("free_move",
918 &settingChangedCallback, this);
919 g_settings->registerChangedCallback("cinematic",
920 &settingChangedCallback, this);
921 g_settings->registerChangedCallback("cinematic_camera_smoothing",
922 &settingChangedCallback, this);
923 g_settings->registerChangedCallback("camera_smoothing",
924 &settingChangedCallback, this);
929 m_cache_hold_aux1 = false; // This is initialised properly later
936 /****************************************************************************
938 ****************************************************************************/
947 delete server; // deleted first to stop all server threads
950 delete local_inventory;
956 delete nodedef_manager;
957 delete itemdef_manager;
960 extendedResourceCleanup();
962 g_settings->deregisterChangedCallback("doubletap_jump",
963 &settingChangedCallback, this);
964 g_settings->deregisterChangedCallback("enable_clouds",
965 &settingChangedCallback, this);
966 g_settings->deregisterChangedCallback("enable_particles",
967 &settingChangedCallback, this);
968 g_settings->deregisterChangedCallback("enable_fog",
969 &settingChangedCallback, this);
970 g_settings->deregisterChangedCallback("mouse_sensitivity",
971 &settingChangedCallback, this);
972 g_settings->deregisterChangedCallback("repeat_rightclick_time",
973 &settingChangedCallback, this);
974 g_settings->deregisterChangedCallback("noclip",
975 &settingChangedCallback, this);
976 g_settings->deregisterChangedCallback("free_move",
977 &settingChangedCallback, this);
978 g_settings->deregisterChangedCallback("cinematic",
979 &settingChangedCallback, this);
980 g_settings->deregisterChangedCallback("cinematic_camera_smoothing",
981 &settingChangedCallback, this);
982 g_settings->deregisterChangedCallback("camera_smoothing",
983 &settingChangedCallback, this);
986 bool Game::startup(bool *kill,
989 const std::string &map_dir,
990 const std::string &playername,
991 const std::string &password,
992 std::string *address, // can change if simple_singleplayer_mode
994 std::string &error_message,
996 ChatBackend *chat_backend,
997 const SubgameSpec &gamespec,
998 bool simple_singleplayer_mode)
1001 this->device = RenderingEngine::get_raw_device();
1003 this->error_message = &error_message;
1004 this->reconnect_requested = reconnect;
1005 this->random_input = random_input;
1006 this->input = input;
1007 this->chat_backend = chat_backend;
1008 this->simple_singleplayer_mode = simple_singleplayer_mode;
1010 input->keycache.populate();
1012 driver = device->getVideoDriver();
1013 smgr = RenderingEngine::get_scene_manager();
1015 RenderingEngine::get_scene_manager()->getParameters()->
1016 setAttribute(scene::OBJ_LOADER_IGNORE_MATERIAL_FILES, true);
1019 runData = GameRunData();
1020 runData.time_from_last_punch = 10.0;
1021 runData.update_wielded_item_trigger = true;
1023 m_game_ui->initFlags();
1025 m_invert_mouse = g_settings->getBool("invert_mouse");
1026 m_first_loop_after_window_activation = true;
1028 g_translations->clear();
1030 if (!init(map_dir, address, port, gamespec))
1033 if (!createClient(playername, password, address, port))
1036 RenderingEngine::initialize(client, hud);
1044 ProfilerGraph graph;
1045 RunStats stats = { 0 };
1046 CameraOrientation cam_view_target = { 0 };
1047 CameraOrientation cam_view = { 0 };
1048 FpsControl draw_times = { 0 };
1049 f32 dtime; // in seconds
1051 /* Clear the profiler */
1052 Profiler::GraphValues dummyvalues;
1053 g_profiler->graphGet(dummyvalues);
1055 draw_times.last_time = RenderingEngine::get_timer_time();
1057 set_light_table(g_settings->getFloat("display_gamma"));
1060 m_cache_hold_aux1 = g_settings->getBool("fast_move")
1061 && client->checkPrivilege("fast");
1064 irr::core::dimension2d<u32> previous_screen_size(g_settings->getU16("screen_w"),
1065 g_settings->getU16("screen_h"));
1067 while (RenderingEngine::run()
1068 && !(*kill || g_gamecallback->shutdown_requested
1069 || (server && server->isShutdownRequested()))) {
1071 const irr::core::dimension2d<u32> ¤t_screen_size =
1072 RenderingEngine::get_video_driver()->getScreenSize();
1073 // Verify if window size has changed and save it if it's the case
1074 // Ensure evaluating settings->getBool after verifying screensize
1075 // First condition is cheaper
1076 if (previous_screen_size != current_screen_size &&
1077 current_screen_size != irr::core::dimension2d<u32>(0,0) &&
1078 g_settings->getBool("autosave_screensize")) {
1079 g_settings->setU16("screen_w", current_screen_size.Width);
1080 g_settings->setU16("screen_h", current_screen_size.Height);
1081 previous_screen_size = current_screen_size;
1084 /* Must be called immediately after a device->run() call because it
1085 * uses device->getTimer()->getTime()
1087 limitFps(&draw_times, &dtime);
1089 updateStats(&stats, draw_times, dtime);
1090 updateInteractTimers(dtime);
1092 if (!checkConnection())
1094 if (!handleCallbacks())
1099 m_game_ui->clearInfoText();
1100 hud->resizeHotbar();
1102 updateProfilers(stats, draw_times, dtime);
1103 processUserInput(dtime);
1104 // Update camera before player movement to avoid camera lag of one frame
1105 updateCameraDirection(&cam_view_target, dtime);
1106 cam_view.camera_yaw += (cam_view_target.camera_yaw -
1107 cam_view.camera_yaw) * m_cache_cam_smoothing;
1108 cam_view.camera_pitch += (cam_view_target.camera_pitch -
1109 cam_view.camera_pitch) * m_cache_cam_smoothing;
1110 updatePlayerControl(cam_view);
1112 processClientEvents(&cam_view_target);
1113 updateCamera(draw_times.busy_time, dtime);
1115 processPlayerInteraction(dtime, m_game_ui->m_flags.show_hud,
1116 m_game_ui->m_flags.show_debug);
1117 updateFrame(&graph, &stats, dtime, cam_view);
1118 updateProfilerGraphs(&graph);
1120 // Update if minimap has been disabled by the server
1121 m_game_ui->m_flags.show_minimap &= client->shouldShowMinimap();
1123 if (m_does_lost_focus_pause_game && !device->isWindowFocused() && !isMenuActive()) {
1130 void Game::shutdown()
1132 RenderingEngine::finalize();
1133 #if IRRLICHT_VERSION_MAJOR == 1 && IRRLICHT_VERSION_MINOR <= 8
1134 if (g_settings->get("3d_mode") == "pageflip") {
1135 driver->setRenderTarget(irr::video::ERT_STEREO_BOTH_BUFFERS);
1138 if (current_formspec)
1139 current_formspec->quitMenu();
1141 showOverlayMessage("Shutting down...", 0, 0, false);
1146 if (gui_chat_console)
1147 gui_chat_console->drop();
1153 while (g_menumgr.menuCount() > 0) {
1154 g_menumgr.m_stack.front()->setVisible(false);
1155 g_menumgr.deletingMenu(g_menumgr.m_stack.front());
1158 if (current_formspec) {
1159 current_formspec->drop();
1160 current_formspec = NULL;
1163 chat_backend->addMessage(L"", L"# Disconnected.");
1164 chat_backend->addMessage(L"", L"");
1168 while (!client->isShutdown()) {
1169 assert(texture_src != NULL);
1170 assert(shader_src != NULL);
1171 texture_src->processQueue();
1172 shader_src->processQueue();
1179 /****************************************************************************/
1180 /****************************************************************************
1182 ****************************************************************************/
1183 /****************************************************************************/
1186 const std::string &map_dir,
1187 std::string *address,
1189 const SubgameSpec &gamespec)
1191 texture_src = createTextureSource();
1193 showOverlayMessage("Loading...", 0, 0);
1195 shader_src = createShaderSource();
1197 itemdef_manager = createItemDefManager();
1198 nodedef_manager = createNodeDefManager();
1200 eventmgr = new EventManager();
1201 quicktune = new QuicktuneShortcutter();
1203 if (!(texture_src && shader_src && itemdef_manager && nodedef_manager
1204 && eventmgr && quicktune))
1210 // Create a server if not connecting to an existing one
1211 if (address->empty()) {
1212 if (!createSingleplayerServer(map_dir, gamespec, port, address))
1219 bool Game::initSound()
1222 if (g_settings->getBool("enable_sound")) {
1223 infostream << "Attempting to use OpenAL audio" << std::endl;
1224 sound = createOpenALSoundManager(g_sound_manager_singleton.get(), &soundfetcher);
1226 infostream << "Failed to initialize OpenAL audio" << std::endl;
1228 infostream << "Sound disabled." << std::endl;
1232 infostream << "Using dummy audio." << std::endl;
1233 sound = &dummySoundManager;
1234 sound_is_dummy = true;
1237 soundmaker = new SoundMaker(sound, nodedef_manager);
1241 soundmaker->registerReceiver(eventmgr);
1246 bool Game::createSingleplayerServer(const std::string &map_dir,
1247 const SubgameSpec &gamespec, u16 port, std::string *address)
1249 showOverlayMessage("Creating server...", 0, 5);
1251 std::string bind_str = g_settings->get("bind_address");
1252 Address bind_addr(0, 0, 0, 0, port);
1254 if (g_settings->getBool("ipv6_server")) {
1255 bind_addr.setAddress((IPv6AddressBytes *) NULL);
1259 bind_addr.Resolve(bind_str.c_str());
1260 } catch (ResolveError &e) {
1261 infostream << "Resolving bind address \"" << bind_str
1262 << "\" failed: " << e.what()
1263 << " -- Listening on all addresses." << std::endl;
1266 if (bind_addr.isIPv6() && !g_settings->getBool("enable_ipv6")) {
1267 *error_message = "Unable to listen on " +
1268 bind_addr.serializeString() +
1269 " because IPv6 is disabled";
1270 errorstream << *error_message << std::endl;
1274 server = new Server(map_dir, gamespec, simple_singleplayer_mode, bind_addr, false);
1281 bool Game::createClient(const std::string &playername,
1282 const std::string &password, std::string *address, u16 port)
1284 showOverlayMessage("Creating client...", 0, 10);
1286 draw_control = new MapDrawControl;
1290 bool could_connect, connect_aborted;
1291 #ifdef HAVE_TOUCHSCREENGUI
1292 if (g_touchscreengui) {
1293 g_touchscreengui->init(texture_src);
1294 g_touchscreengui->hide();
1297 if (!connectToServer(playername, password, address, port,
1298 &could_connect, &connect_aborted))
1301 if (!could_connect) {
1302 if (error_message->empty() && !connect_aborted) {
1303 // Should not happen if error messages are set properly
1304 *error_message = "Connection failed for unknown reason";
1305 errorstream << *error_message << std::endl;
1310 if (!getServerContent(&connect_aborted)) {
1311 if (error_message->empty() && !connect_aborted) {
1312 // Should not happen if error messages are set properly
1313 *error_message = "Connection failed for unknown reason";
1314 errorstream << *error_message << std::endl;
1319 GameGlobalShaderConstantSetterFactory *scsf = new GameGlobalShaderConstantSetterFactory(
1320 &m_flags.force_fog_off, &runData.fog_range, client);
1321 shader_src->addShaderConstantSetterFactory(scsf);
1323 // Update cached textures, meshes and materials
1324 client->afterContentReceived();
1328 camera = new Camera(*draw_control, client);
1329 if (!camera || !camera->successfullyCreated(*error_message))
1331 client->setCamera(camera);
1335 if (m_cache_enable_clouds) {
1336 clouds = new Clouds(smgr, -1, time(0));
1338 *error_message = "Memory allocation error (clouds)";
1339 errorstream << *error_message << std::endl;
1346 sky = new Sky(-1, texture_src);
1348 skybox = NULL; // This is used/set later on in the main run loop
1350 local_inventory = new Inventory(itemdef_manager);
1352 if (!(sky && local_inventory)) {
1353 *error_message = "Memory allocation error (sky or local inventory)";
1354 errorstream << *error_message << std::endl;
1358 /* Pre-calculated values
1360 video::ITexture *t = texture_src->getTexture("crack_anylength.png");
1362 v2u32 size = t->getOriginalSize();
1363 crack_animation_length = size.Y / size.X;
1365 crack_animation_length = 5;
1371 /* Set window caption
1373 std::wstring str = utf8_to_wide(PROJECT_NAME_C);
1375 str += utf8_to_wide(g_version_hash);
1377 str += driver->getName();
1379 device->setWindowCaption(str.c_str());
1381 LocalPlayer *player = client->getEnv().getLocalPlayer();
1382 player->hurt_tilt_timer = 0;
1383 player->hurt_tilt_strength = 0;
1385 hud = new Hud(guienv, client, player, local_inventory);
1388 *error_message = "Memory error: could not create HUD";
1389 errorstream << *error_message << std::endl;
1393 mapper = client->getMinimap();
1395 mapper->setMinimapMode(MINIMAP_MODE_OFF);
1400 bool Game::initGui()
1404 // Remove stale "recent" chat messages from previous connections
1405 chat_backend->clearRecentChat();
1407 // Make sure the size of the recent messages buffer is right
1408 chat_backend->applySettings();
1410 // Chat backend and console
1411 gui_chat_console = new GUIChatConsole(guienv, guienv->getRootGUIElement(),
1412 -1, chat_backend, client, &g_menumgr);
1413 if (!gui_chat_console) {
1414 *error_message = "Could not allocate memory for chat console";
1415 errorstream << *error_message << std::endl;
1419 #ifdef HAVE_TOUCHSCREENGUI
1421 if (g_touchscreengui)
1422 g_touchscreengui->show();
1429 bool Game::connectToServer(const std::string &playername,
1430 const std::string &password, std::string *address, u16 port,
1431 bool *connect_ok, bool *connection_aborted)
1433 *connect_ok = false; // Let's not be overly optimistic
1434 *connection_aborted = false;
1435 bool local_server_mode = false;
1437 showOverlayMessage("Resolving address...", 0, 15);
1439 Address connect_address(0, 0, 0, 0, port);
1442 connect_address.Resolve(address->c_str());
1444 if (connect_address.isZero()) { // i.e. INADDR_ANY, IN6ADDR_ANY
1445 //connect_address.Resolve("localhost");
1446 if (connect_address.isIPv6()) {
1447 IPv6AddressBytes addr_bytes;
1448 addr_bytes.bytes[15] = 1;
1449 connect_address.setAddress(&addr_bytes);
1451 connect_address.setAddress(127, 0, 0, 1);
1453 local_server_mode = true;
1455 } catch (ResolveError &e) {
1456 *error_message = std::string("Couldn't resolve address: ") + e.what();
1457 errorstream << *error_message << std::endl;
1461 if (connect_address.isIPv6() && !g_settings->getBool("enable_ipv6")) {
1462 *error_message = "Unable to connect to " +
1463 connect_address.serializeString() +
1464 " because IPv6 is disabled";
1465 errorstream << *error_message << std::endl;
1469 client = new Client(playername.c_str(), password, *address,
1470 *draw_control, texture_src, shader_src,
1471 itemdef_manager, nodedef_manager, sound, eventmgr,
1472 connect_address.isIPv6(), m_game_ui.get());
1477 client->m_simple_singleplayer_mode = simple_singleplayer_mode;
1479 infostream << "Connecting to server at ";
1480 connect_address.print(&infostream);
1481 infostream << std::endl;
1483 client->connect(connect_address,
1484 simple_singleplayer_mode || local_server_mode);
1487 Wait for server to accept connection
1493 FpsControl fps_control = { 0 };
1495 f32 wait_time = 0; // in seconds
1497 fps_control.last_time = RenderingEngine::get_timer_time();
1499 client->loadBuiltin();
1501 while (RenderingEngine::run()) {
1503 limitFps(&fps_control, &dtime);
1505 // Update client and server
1506 client->step(dtime);
1509 server->step(dtime);
1512 if (client->getState() == LC_Init) {
1518 if (*connection_aborted)
1521 if (client->accessDenied()) {
1522 *error_message = "Access denied. Reason: "
1523 + client->accessDeniedReason();
1524 *reconnect_requested = client->reconnectRequested();
1525 errorstream << *error_message << std::endl;
1529 if (input->cancelPressed()) {
1530 *connection_aborted = true;
1531 infostream << "Connect aborted [Escape]" << std::endl;
1535 if (client->m_is_registration_confirmation_state) {
1536 if (registration_confirmation_shown) {
1537 // Keep drawing the GUI
1538 RenderingEngine::draw_menu_scene(guienv, dtime, true);
1540 registration_confirmation_shown = true;
1541 (new GUIConfirmRegistration(guienv, guienv->getRootGUIElement(), -1,
1542 &g_menumgr, client, playername, password, *address, connection_aborted))->drop();
1546 // Only time out if we aren't waiting for the server we started
1547 if (!address->empty() && wait_time > 10) {
1548 *error_message = "Connection timed out.";
1549 errorstream << *error_message << std::endl;
1554 showOverlayMessage("Connecting to server...", dtime, 20);
1557 } catch (con::PeerNotFoundException &e) {
1558 // TODO: Should something be done here? At least an info/error
1566 bool Game::getServerContent(bool *aborted)
1570 FpsControl fps_control = { 0 };
1571 f32 dtime; // in seconds
1573 fps_control.last_time = RenderingEngine::get_timer_time();
1575 while (RenderingEngine::run()) {
1577 limitFps(&fps_control, &dtime);
1579 // Update client and server
1580 client->step(dtime);
1583 server->step(dtime);
1586 if (client->mediaReceived() && client->itemdefReceived() &&
1587 client->nodedefReceived()) {
1592 if (!checkConnection())
1595 if (client->getState() < LC_Init) {
1596 *error_message = "Client disconnected";
1597 errorstream << *error_message << std::endl;
1601 if (input->cancelPressed()) {
1603 infostream << "Connect aborted [Escape]" << std::endl;
1610 if (!client->itemdefReceived()) {
1611 const wchar_t *text = wgettext("Item definitions...");
1613 RenderingEngine::draw_load_screen(text, guienv, texture_src,
1616 } else if (!client->nodedefReceived()) {
1617 const wchar_t *text = wgettext("Node definitions...");
1619 RenderingEngine::draw_load_screen(text, guienv, texture_src,
1623 std::stringstream message;
1624 std::fixed(message);
1625 message.precision(0);
1626 message << gettext("Media...") << " " << (client->mediaReceiveProgress()*100) << "%";
1627 message.precision(2);
1629 if ((USE_CURL == 0) ||
1630 (!g_settings->getBool("enable_remote_media_server"))) {
1631 float cur = client->getCurRate();
1632 std::string cur_unit = gettext("KiB/s");
1636 cur_unit = gettext("MiB/s");
1639 message << " (" << cur << ' ' << cur_unit << ")";
1642 progress = 30 + client->mediaReceiveProgress() * 35 + 0.5;
1643 RenderingEngine::draw_load_screen(utf8_to_wide(message.str()), guienv,
1644 texture_src, dtime, progress);
1652 /****************************************************************************/
1653 /****************************************************************************
1655 ****************************************************************************/
1656 /****************************************************************************/
1658 inline void Game::updateInteractTimers(f32 dtime)
1660 if (runData.nodig_delay_timer >= 0)
1661 runData.nodig_delay_timer -= dtime;
1663 if (runData.object_hit_delay_timer >= 0)
1664 runData.object_hit_delay_timer -= dtime;
1666 runData.time_from_last_punch += dtime;
1670 /* returns false if game should exit, otherwise true
1672 inline bool Game::checkConnection()
1674 if (client->accessDenied()) {
1675 *error_message = "Access denied. Reason: "
1676 + client->accessDeniedReason();
1677 *reconnect_requested = client->reconnectRequested();
1678 errorstream << *error_message << std::endl;
1686 /* returns false if game should exit, otherwise true
1688 inline bool Game::handleCallbacks()
1690 if (g_gamecallback->disconnect_requested) {
1691 g_gamecallback->disconnect_requested = false;
1695 if (g_gamecallback->changepassword_requested) {
1696 (new GUIPasswordChange(guienv, guiroot, -1,
1697 &g_menumgr, client))->drop();
1698 g_gamecallback->changepassword_requested = false;
1701 if (g_gamecallback->changevolume_requested) {
1702 (new GUIVolumeChange(guienv, guiroot, -1,
1703 &g_menumgr))->drop();
1704 g_gamecallback->changevolume_requested = false;
1707 if (g_gamecallback->keyconfig_requested) {
1708 (new GUIKeyChangeMenu(guienv, guiroot, -1,
1709 &g_menumgr))->drop();
1710 g_gamecallback->keyconfig_requested = false;
1713 if (g_gamecallback->keyconfig_changed) {
1714 input->keycache.populate(); // update the cache with new settings
1715 g_gamecallback->keyconfig_changed = false;
1722 void Game::processQueues()
1724 texture_src->processQueue();
1725 itemdef_manager->processQueue(client);
1726 shader_src->processQueue();
1730 void Game::updateProfilers(const RunStats &stats, const FpsControl &draw_times, f32 dtime)
1732 float profiler_print_interval =
1733 g_settings->getFloat("profiler_print_interval");
1734 bool print_to_log = true;
1736 if (profiler_print_interval == 0) {
1737 print_to_log = false;
1738 profiler_print_interval = 5;
1741 if (profiler_interval.step(dtime, profiler_print_interval)) {
1743 infostream << "Profiler:" << std::endl;
1744 g_profiler->print(infostream);
1747 m_game_ui->updateProfiler();
1748 g_profiler->clear();
1751 addProfilerGraphs(stats, draw_times, dtime);
1755 void Game::addProfilerGraphs(const RunStats &stats,
1756 const FpsControl &draw_times, f32 dtime)
1758 g_profiler->graphAdd("mainloop_other",
1759 draw_times.busy_time / 1000.0f - stats.drawtime / 1000.0f);
1761 if (draw_times.sleep_time != 0)
1762 g_profiler->graphAdd("mainloop_sleep", draw_times.sleep_time / 1000.0f);
1763 g_profiler->graphAdd("mainloop_dtime", dtime);
1765 g_profiler->add("Elapsed time", dtime);
1766 g_profiler->avg("FPS", 1. / dtime);
1770 void Game::updateStats(RunStats *stats, const FpsControl &draw_times,
1777 /* Time average and jitter calculation
1779 jp = &stats->dtime_jitter;
1780 jp->avg = jp->avg * 0.96 + dtime * 0.04;
1782 jitter = dtime - jp->avg;
1784 if (jitter > jp->max)
1787 jp->counter += dtime;
1789 if (jp->counter > 0.0) {
1791 jp->max_sample = jp->max;
1792 jp->max_fraction = jp->max_sample / (jp->avg + 0.001);
1796 /* Busytime average and jitter calculation
1798 jp = &stats->busy_time_jitter;
1799 jp->avg = jp->avg + draw_times.busy_time * 0.02;
1801 jitter = draw_times.busy_time - jp->avg;
1803 if (jitter > jp->max)
1805 if (jitter < jp->min)
1808 jp->counter += dtime;
1810 if (jp->counter > 0.0) {
1812 jp->max_sample = jp->max;
1813 jp->min_sample = jp->min;
1821 /****************************************************************************
1823 ****************************************************************************/
1825 void Game::processUserInput(f32 dtime)
1827 // Reset input if window not active or some menu is active
1828 if (!device->isWindowActive() || isMenuActive() || guienv->hasFocus(gui_chat_console)) {
1830 #ifdef HAVE_TOUCHSCREENGUI
1831 g_touchscreengui->hide();
1834 #ifdef HAVE_TOUCHSCREENGUI
1835 else if (g_touchscreengui) {
1836 /* on touchscreengui step may generate own input events which ain't
1837 * what we want in case we just did clear them */
1838 g_touchscreengui->step(dtime);
1842 if (!guienv->hasFocus(gui_chat_console) && gui_chat_console->isOpen()) {
1843 gui_chat_console->closeConsoleAtOnce();
1846 // Input handler step() (used by the random input generator)
1850 if (current_formspec != NULL)
1851 current_formspec->getAndroidUIInput();
1853 handleAndroidChatInput();
1856 // Increase timer for double tap of "keymap_jump"
1857 if (m_cache_doubletap_jump && runData.jump_timer <= 0.2f)
1858 runData.jump_timer += dtime;
1861 processItemSelection(&runData.new_playeritem);
1865 void Game::processKeyInput()
1867 if (wasKeyDown(KeyType::DROP)) {
1868 dropSelectedItem(isKeyDown(KeyType::SNEAK));
1869 } else if (wasKeyDown(KeyType::AUTOFORWARD)) {
1870 toggleAutoforward();
1871 } else if (wasKeyDown(KeyType::BACKWARD)) {
1872 if (g_settings->getBool("continuous_forward"))
1873 toggleAutoforward();
1874 } else if (wasKeyDown(KeyType::INVENTORY)) {
1876 } else if (input->cancelPressed()) {
1877 if (!gui_chat_console->isOpenInhibited()) {
1880 } else if (wasKeyDown(KeyType::CHAT)) {
1881 openConsole(0.2, L"");
1882 } else if (wasKeyDown(KeyType::CMD)) {
1883 openConsole(0.2, L"/");
1884 } else if (wasKeyDown(KeyType::CMD_LOCAL)) {
1885 openConsole(0.2, L".");
1886 } else if (wasKeyDown(KeyType::CONSOLE)) {
1887 openConsole(core::clamp(g_settings->getFloat("console_height"), 0.1f, 1.0f));
1888 } else if (wasKeyDown(KeyType::FREEMOVE)) {
1890 } else if (wasKeyDown(KeyType::JUMP)) {
1891 toggleFreeMoveAlt();
1892 } else if (wasKeyDown(KeyType::FASTMOVE)) {
1894 } else if (wasKeyDown(KeyType::NOCLIP)) {
1896 } else if (wasKeyDown(KeyType::MUTE)) {
1897 bool new_mute_sound = !g_settings->getBool("mute_sound");
1898 g_settings->setBool("mute_sound", new_mute_sound);
1900 m_game_ui->showTranslatedStatusText("Sound muted");
1902 m_game_ui->showTranslatedStatusText("Sound unmuted");
1903 } else if (wasKeyDown(KeyType::INC_VOLUME)) {
1904 float new_volume = rangelim(g_settings->getFloat("sound_volume") + 0.1f, 0.0f, 1.0f);
1906 g_settings->setFloat("sound_volume", new_volume);
1907 const wchar_t *str = wgettext("Volume changed to %d%%");
1908 swprintf(buf, sizeof(buf) / sizeof(wchar_t), str, myround(new_volume * 100));
1910 m_game_ui->showStatusText(buf);
1911 } else if (wasKeyDown(KeyType::DEC_VOLUME)) {
1912 float new_volume = rangelim(g_settings->getFloat("sound_volume") - 0.1f, 0.0f, 1.0f);
1914 g_settings->setFloat("sound_volume", new_volume);
1915 const wchar_t *str = wgettext("Volume changed to %d%%");
1916 swprintf(buf, sizeof(buf) / sizeof(wchar_t), str, myround(new_volume * 100));
1918 m_game_ui->showStatusText(buf);
1919 } else if (wasKeyDown(KeyType::CINEMATIC)) {
1921 } else if (wasKeyDown(KeyType::SCREENSHOT)) {
1922 client->makeScreenshot();
1923 } else if (wasKeyDown(KeyType::TOGGLE_HUD)) {
1924 m_game_ui->toggleHud();
1925 } else if (wasKeyDown(KeyType::MINIMAP)) {
1926 toggleMinimap(isKeyDown(KeyType::SNEAK));
1927 } else if (wasKeyDown(KeyType::TOGGLE_CHAT)) {
1928 m_game_ui->toggleChat();
1929 } else if (wasKeyDown(KeyType::TOGGLE_FOG)) {
1931 } else if (wasKeyDown(KeyType::TOGGLE_UPDATE_CAMERA)) {
1932 toggleUpdateCamera();
1933 } else if (wasKeyDown(KeyType::TOGGLE_DEBUG)) {
1935 } else if (wasKeyDown(KeyType::TOGGLE_PROFILER)) {
1936 m_game_ui->toggleProfiler();
1937 } else if (wasKeyDown(KeyType::INCREASE_VIEWING_RANGE)) {
1938 increaseViewRange();
1939 } else if (wasKeyDown(KeyType::DECREASE_VIEWING_RANGE)) {
1940 decreaseViewRange();
1941 } else if (wasKeyDown(KeyType::RANGESELECT)) {
1942 toggleFullViewRange();
1943 } else if (wasKeyDown(KeyType::ZOOM)) {
1945 } else if (wasKeyDown(KeyType::QUICKTUNE_NEXT)) {
1947 } else if (wasKeyDown(KeyType::QUICKTUNE_PREV)) {
1949 } else if (wasKeyDown(KeyType::QUICKTUNE_INC)) {
1951 } else if (wasKeyDown(KeyType::QUICKTUNE_DEC)) {
1955 if (!isKeyDown(KeyType::JUMP) && runData.reset_jump_timer) {
1956 runData.reset_jump_timer = false;
1957 runData.jump_timer = 0.0f;
1960 if (quicktune->hasMessage()) {
1961 m_game_ui->showStatusText(utf8_to_wide(quicktune->getMessage()));
1965 void Game::processItemSelection(u16 *new_playeritem)
1967 LocalPlayer *player = client->getEnv().getLocalPlayer();
1969 /* Item selection using mouse wheel
1971 *new_playeritem = client->getPlayerItem();
1973 s32 wheel = input->getMouseWheel();
1974 u16 max_item = MYMIN(PLAYER_INVENTORY_SIZE - 1,
1975 player->hud_hotbar_itemcount - 1);
1979 if (input->joystick.wasKeyDown(KeyType::SCROLL_DOWN) ||
1980 wasKeyDown(KeyType::HOTBAR_NEXT)) {
1984 if (input->joystick.wasKeyDown(KeyType::SCROLL_UP) ||
1985 wasKeyDown(KeyType::HOTBAR_PREV)) {
1990 *new_playeritem = *new_playeritem < max_item ? *new_playeritem + 1 : 0;
1992 *new_playeritem = *new_playeritem > 0 ? *new_playeritem - 1 : max_item;
1995 /* Item selection using hotbar slot keys
1997 for (u16 i = 0; i < 23; i++) {
1998 if (wasKeyDown((GameKeyType) (KeyType::SLOT_1 + i))) {
1999 if (i < PLAYER_INVENTORY_SIZE && i < player->hud_hotbar_itemcount) {
2000 *new_playeritem = i;
2001 infostream << "Selected item: " << new_playeritem << std::endl;
2009 void Game::dropSelectedItem(bool single_item)
2011 IDropAction *a = new IDropAction();
2012 a->count = single_item ? 1 : 0;
2013 a->from_inv.setCurrentPlayer();
2014 a->from_list = "main";
2015 a->from_i = client->getPlayerItem();
2016 client->inventoryAction(a);
2020 void Game::openInventory()
2023 * Don't permit to open inventory is CAO or player doesn't exists.
2024 * This prevent showing an empty inventory at player load
2027 LocalPlayer *player = client->getEnv().getLocalPlayer();
2028 if (!player || !player->getCAO())
2031 infostream << "the_game: " << "Launching inventory" << std::endl;
2033 PlayerInventoryFormSource *fs_src = new PlayerInventoryFormSource(client);
2035 InventoryLocation inventoryloc;
2036 inventoryloc.setCurrentPlayer();
2038 if (!client->moddingEnabled()
2039 || !client->getScript()->on_inventory_open(fs_src->m_client->getInventory(inventoryloc))) {
2040 TextDest *txt_dst = new TextDestPlayerInventory(client);
2041 GUIFormSpecMenu::create(current_formspec, client, &input->joystick, fs_src,
2042 txt_dst, client->getFormspecPrepend());
2044 current_formspec->setFormSpec(fs_src->getForm(), inventoryloc);
2049 void Game::openConsole(float scale, const wchar_t *line)
2051 assert(scale > 0.0f && scale <= 1.0f);
2054 porting::showInputDialog(gettext("ok"), "", "", 2);
2055 m_android_chat_open = true;
2057 if (gui_chat_console->isOpenInhibited())
2059 gui_chat_console->openConsole(scale);
2061 gui_chat_console->setCloseOnEnter(true);
2062 gui_chat_console->replaceAndAddToHistory(line);
2068 void Game::handleAndroidChatInput()
2070 if (m_android_chat_open && porting::getInputDialogState() == 0) {
2071 std::string text = porting::getInputDialogValue();
2072 client->typeChatMessage(utf8_to_wide(text));
2078 void Game::toggleFreeMove()
2080 bool free_move = !g_settings->getBool("free_move");
2081 g_settings->set("free_move", bool_to_cstr(free_move));
2084 if (client->checkPrivilege("fly")) {
2085 m_game_ui->showTranslatedStatusText("Fly mode enabled");
2087 m_game_ui->showTranslatedStatusText("Fly mode enabled (note: no 'fly' privilege)");
2090 m_game_ui->showTranslatedStatusText("Fly mode disabled");
2094 void Game::toggleFreeMoveAlt()
2096 if (m_cache_doubletap_jump && runData.jump_timer < 0.2f)
2099 runData.reset_jump_timer = true;
2103 void Game::toggleFast()
2105 bool fast_move = !g_settings->getBool("fast_move");
2106 bool has_fast_privs = client->checkPrivilege("fast");
2107 g_settings->set("fast_move", bool_to_cstr(fast_move));
2110 if (has_fast_privs) {
2111 m_game_ui->showTranslatedStatusText("Fast mode enabled");
2113 m_game_ui->showTranslatedStatusText("Fast mode enabled (note: no 'fast' privilege)");
2116 m_game_ui->showTranslatedStatusText("Fast mode disabled");
2120 m_cache_hold_aux1 = fast_move && has_fast_privs;
2125 void Game::toggleNoClip()
2127 bool noclip = !g_settings->getBool("noclip");
2128 g_settings->set("noclip", bool_to_cstr(noclip));
2131 if (client->checkPrivilege("noclip")) {
2132 m_game_ui->showTranslatedStatusText("Noclip mode enabled");
2134 m_game_ui->showTranslatedStatusText("Noclip mode enabled (note: no 'noclip' privilege)");
2137 m_game_ui->showTranslatedStatusText("Noclip mode disabled");
2141 void Game::toggleCinematic()
2143 bool cinematic = !g_settings->getBool("cinematic");
2144 g_settings->set("cinematic", bool_to_cstr(cinematic));
2147 m_game_ui->showTranslatedStatusText("Cinematic mode enabled");
2149 m_game_ui->showTranslatedStatusText("Cinematic mode disabled");
2152 // Autoforward by toggling continuous forward.
2153 void Game::toggleAutoforward()
2155 bool autorun_enabled = !g_settings->getBool("continuous_forward");
2156 g_settings->set("continuous_forward", bool_to_cstr(autorun_enabled));
2158 if (autorun_enabled)
2159 m_game_ui->showTranslatedStatusText("Automatic forwards enabled");
2161 m_game_ui->showTranslatedStatusText("Automatic forwards disabled");
2164 void Game::toggleMinimap(bool shift_pressed)
2166 if (!mapper || !m_game_ui->m_flags.show_hud || !g_settings->getBool("enable_minimap"))
2169 if (shift_pressed) {
2170 mapper->toggleMinimapShape();
2174 u32 hud_flags = client->getEnv().getLocalPlayer()->hud_flags;
2176 MinimapMode mode = MINIMAP_MODE_OFF;
2177 if (hud_flags & HUD_FLAG_MINIMAP_VISIBLE) {
2178 mode = mapper->getMinimapMode();
2179 mode = (MinimapMode)((int)mode + 1);
2180 // If radar is disabled and in, or switching to, radar mode
2181 if (!(hud_flags & HUD_FLAG_MINIMAP_RADAR_VISIBLE) && mode > 3)
2182 mode = MINIMAP_MODE_OFF;
2185 m_game_ui->m_flags.show_minimap = true;
2187 case MINIMAP_MODE_SURFACEx1:
2188 m_game_ui->showTranslatedStatusText("Minimap in surface mode, Zoom x1");
2190 case MINIMAP_MODE_SURFACEx2:
2191 m_game_ui->showTranslatedStatusText("Minimap in surface mode, Zoom x2");
2193 case MINIMAP_MODE_SURFACEx4:
2194 m_game_ui->showTranslatedStatusText("Minimap in surface mode, Zoom x4");
2196 case MINIMAP_MODE_RADARx1:
2197 m_game_ui->showTranslatedStatusText("Minimap in radar mode, Zoom x1");
2199 case MINIMAP_MODE_RADARx2:
2200 m_game_ui->showTranslatedStatusText("Minimap in radar mode, Zoom x2");
2202 case MINIMAP_MODE_RADARx4:
2203 m_game_ui->showTranslatedStatusText("Minimap in radar mode, Zoom x4");
2206 mode = MINIMAP_MODE_OFF;
2207 m_game_ui->m_flags.show_minimap = false;
2208 if (hud_flags & HUD_FLAG_MINIMAP_VISIBLE)
2209 m_game_ui->showTranslatedStatusText("Minimap hidden");
2211 m_game_ui->showTranslatedStatusText("Minimap currently disabled by game or mod");
2214 mapper->setMinimapMode(mode);
2217 void Game::toggleFog()
2219 bool fog_enabled = g_settings->getBool("enable_fog");
2220 g_settings->setBool("enable_fog", !fog_enabled);
2222 m_game_ui->showTranslatedStatusText("Fog disabled");
2224 m_game_ui->showTranslatedStatusText("Fog enabled");
2228 void Game::toggleDebug()
2230 // Initial / 4x toggle: Chat only
2231 // 1x toggle: Debug text with chat
2232 // 2x toggle: Debug text with profiler graph
2233 // 3x toggle: Debug text and wireframe
2234 if (!m_game_ui->m_flags.show_debug) {
2235 m_game_ui->m_flags.show_debug = true;
2236 m_game_ui->m_flags.show_profiler_graph = false;
2237 draw_control->show_wireframe = false;
2238 m_game_ui->showTranslatedStatusText("Debug info shown");
2239 } else if (!m_game_ui->m_flags.show_profiler_graph && !draw_control->show_wireframe) {
2240 m_game_ui->m_flags.show_profiler_graph = true;
2241 m_game_ui->showTranslatedStatusText("Profiler graph shown");
2242 } else if (!draw_control->show_wireframe && client->checkPrivilege("debug")) {
2243 m_game_ui->m_flags.show_profiler_graph = false;
2244 draw_control->show_wireframe = true;
2245 m_game_ui->showTranslatedStatusText("Wireframe shown");
2247 m_game_ui->m_flags.show_debug = false;
2248 m_game_ui->m_flags.show_profiler_graph = false;
2249 draw_control->show_wireframe = false;
2250 if (client->checkPrivilege("debug")) {
2251 m_game_ui->showTranslatedStatusText("Debug info, profiler graph, and wireframe hidden");
2253 m_game_ui->showTranslatedStatusText("Debug info and profiler graph hidden");
2259 void Game::toggleUpdateCamera()
2261 m_flags.disable_camera_update = !m_flags.disable_camera_update;
2262 if (m_flags.disable_camera_update)
2263 m_game_ui->showTranslatedStatusText("Camera update disabled");
2265 m_game_ui->showTranslatedStatusText("Camera update enabled");
2269 void Game::increaseViewRange()
2271 s16 range = g_settings->getS16("viewing_range");
2272 s16 range_new = range + 10;
2276 if (range_new > 4000) {
2278 str = wgettext("Viewing range is at maximum: %d");
2279 swprintf(buf, sizeof(buf) / sizeof(wchar_t), str, range_new);
2281 m_game_ui->showStatusText(buf);
2284 str = wgettext("Viewing range changed to %d");
2285 swprintf(buf, sizeof(buf) / sizeof(wchar_t), str, range_new);
2287 m_game_ui->showStatusText(buf);
2289 g_settings->set("viewing_range", itos(range_new));
2293 void Game::decreaseViewRange()
2295 s16 range = g_settings->getS16("viewing_range");
2296 s16 range_new = range - 10;
2300 if (range_new < 20) {
2302 str = wgettext("Viewing range is at minimum: %d");
2303 swprintf(buf, sizeof(buf) / sizeof(wchar_t), str, range_new);
2305 m_game_ui->showStatusText(buf);
2307 str = wgettext("Viewing range changed to %d");
2308 swprintf(buf, sizeof(buf) / sizeof(wchar_t), str, range_new);
2310 m_game_ui->showStatusText(buf);
2312 g_settings->set("viewing_range", itos(range_new));
2316 void Game::toggleFullViewRange()
2318 draw_control->range_all = !draw_control->range_all;
2319 if (draw_control->range_all)
2320 m_game_ui->showTranslatedStatusText("Enabled unlimited viewing range");
2322 m_game_ui->showTranslatedStatusText("Disabled unlimited viewing range");
2326 void Game::checkZoomEnabled()
2328 LocalPlayer *player = client->getEnv().getLocalPlayer();
2329 if (player->getZoomFOV() < 0.001f)
2330 m_game_ui->showTranslatedStatusText("Zoom currently disabled by game or mod");
2334 void Game::updateCameraDirection(CameraOrientation *cam, float dtime)
2336 if ((device->isWindowActive() && device->isWindowFocused()
2337 && !isMenuActive()) || random_input) {
2340 if (!random_input) {
2341 // Mac OSX gets upset if this is set every frame
2342 if (device->getCursorControl()->isVisible())
2343 device->getCursorControl()->setVisible(false);
2347 if (m_first_loop_after_window_activation) {
2348 m_first_loop_after_window_activation = false;
2350 input->setMousePos(driver->getScreenSize().Width / 2,
2351 driver->getScreenSize().Height / 2);
2353 updateCameraOrientation(cam, dtime);
2359 // Mac OSX gets upset if this is set every frame
2360 if (!device->getCursorControl()->isVisible())
2361 device->getCursorControl()->setVisible(true);
2364 m_first_loop_after_window_activation = true;
2369 void Game::updateCameraOrientation(CameraOrientation *cam, float dtime)
2371 #ifdef HAVE_TOUCHSCREENGUI
2372 if (g_touchscreengui) {
2373 cam->camera_yaw += g_touchscreengui->getYawChange();
2374 cam->camera_pitch = g_touchscreengui->getPitch();
2377 v2s32 center(driver->getScreenSize().Width / 2, driver->getScreenSize().Height / 2);
2378 v2s32 dist = input->getMousePos() - center;
2380 if (m_invert_mouse || camera->getCameraMode() == CAMERA_MODE_THIRD_FRONT) {
2384 cam->camera_yaw -= dist.X * m_cache_mouse_sensitivity;
2385 cam->camera_pitch += dist.Y * m_cache_mouse_sensitivity;
2387 if (dist.X != 0 || dist.Y != 0)
2388 input->setMousePos(center.X, center.Y);
2389 #ifdef HAVE_TOUCHSCREENGUI
2393 if (m_cache_enable_joysticks) {
2394 f32 c = m_cache_joystick_frustum_sensitivity * (1.f / 32767.f) * dtime;
2395 cam->camera_yaw -= input->joystick.getAxisWithoutDead(JA_FRUSTUM_HORIZONTAL) * c;
2396 cam->camera_pitch += input->joystick.getAxisWithoutDead(JA_FRUSTUM_VERTICAL) * c;
2399 cam->camera_pitch = rangelim(cam->camera_pitch, -89.5, 89.5);
2403 void Game::updatePlayerControl(const CameraOrientation &cam)
2405 //TimeTaker tt("update player control", NULL, PRECISION_NANO);
2407 // DO NOT use the isKeyDown method for the forward, backward, left, right
2408 // buttons, as the code that uses the controls needs to be able to
2409 // distinguish between the two in order to know when to use joysticks.
2411 PlayerControl control(
2412 input->isKeyDown(KeyType::FORWARD),
2413 input->isKeyDown(KeyType::BACKWARD),
2414 input->isKeyDown(KeyType::LEFT),
2415 input->isKeyDown(KeyType::RIGHT),
2416 isKeyDown(KeyType::JUMP),
2417 isKeyDown(KeyType::SPECIAL1),
2418 isKeyDown(KeyType::SNEAK),
2419 isKeyDown(KeyType::ZOOM),
2420 input->getLeftState(),
2421 input->getRightState(),
2424 input->joystick.getAxisWithoutDead(JA_SIDEWARD_MOVE),
2425 input->joystick.getAxisWithoutDead(JA_FORWARD_MOVE)
2429 ( (u32)(isKeyDown(KeyType::FORWARD) & 0x1) << 0) |
2430 ( (u32)(isKeyDown(KeyType::BACKWARD) & 0x1) << 1) |
2431 ( (u32)(isKeyDown(KeyType::LEFT) & 0x1) << 2) |
2432 ( (u32)(isKeyDown(KeyType::RIGHT) & 0x1) << 3) |
2433 ( (u32)(isKeyDown(KeyType::JUMP) & 0x1) << 4) |
2434 ( (u32)(isKeyDown(KeyType::SPECIAL1) & 0x1) << 5) |
2435 ( (u32)(isKeyDown(KeyType::SNEAK) & 0x1) << 6) |
2436 ( (u32)(input->getLeftState() & 0x1) << 7) |
2437 ( (u32)(input->getRightState() & 0x1) << 8
2441 /* For Android, simulate holding down AUX1 (fast move) if the user has
2442 * the fast_move setting toggled on. If there is an aux1 key defined for
2443 * Android then its meaning is inverted (i.e. holding aux1 means walk and
2446 if (m_cache_hold_aux1) {
2447 control.aux1 = control.aux1 ^ true;
2448 keypress_bits ^= ((u32)(1U << 5));
2452 client->setPlayerControl(control);
2453 LocalPlayer *player = client->getEnv().getLocalPlayer();
2454 player->keyPressed = keypress_bits;
2460 inline void Game::step(f32 *dtime)
2462 bool can_be_and_is_paused =
2463 (simple_singleplayer_mode && g_menumgr.pausesGame());
2465 if (can_be_and_is_paused) { // This is for a singleplayer server
2466 *dtime = 0; // No time passes
2469 server->step(*dtime);
2471 client->step(*dtime);
2475 const ClientEventHandler Game::clientEventHandler[CLIENTEVENT_MAX] = {
2476 {&Game::handleClientEvent_None},
2477 {&Game::handleClientEvent_PlayerDamage},
2478 {&Game::handleClientEvent_PlayerForceMove},
2479 {&Game::handleClientEvent_Deathscreen},
2480 {&Game::handleClientEvent_ShowFormSpec},
2481 {&Game::handleClientEvent_ShowLocalFormSpec},
2482 {&Game::handleClientEvent_HandleParticleEvent},
2483 {&Game::handleClientEvent_HandleParticleEvent},
2484 {&Game::handleClientEvent_HandleParticleEvent},
2485 {&Game::handleClientEvent_HudAdd},
2486 {&Game::handleClientEvent_HudRemove},
2487 {&Game::handleClientEvent_HudChange},
2488 {&Game::handleClientEvent_SetSky},
2489 {&Game::handleClientEvent_OverrideDayNigthRatio},
2490 {&Game::handleClientEvent_CloudParams},
2493 void Game::handleClientEvent_None(ClientEvent *event, CameraOrientation *cam)
2495 FATAL_ERROR("ClientEvent type None received");
2498 void Game::handleClientEvent_PlayerDamage(ClientEvent *event, CameraOrientation *cam)
2500 if (client->moddingEnabled()) {
2501 client->getScript()->on_damage_taken(event->player_damage.amount);
2504 // Damage flash and hurt tilt are not used at death
2505 if (client->getHP() > 0) {
2506 runData.damage_flash += 95.0f + 3.2f * event->player_damage.amount;
2507 runData.damage_flash = MYMIN(runData.damage_flash, 127.0f);
2509 LocalPlayer *player = client->getEnv().getLocalPlayer();
2511 player->hurt_tilt_timer = 1.5f;
2512 player->hurt_tilt_strength =
2513 rangelim(event->player_damage.amount / 4.0f, 1.0f, 4.0f);
2516 // Play damage sound
2517 client->getEventManager()->put(new SimpleTriggerEvent(MtEvent::PLAYER_DAMAGE));
2520 void Game::handleClientEvent_PlayerForceMove(ClientEvent *event, CameraOrientation *cam)
2522 cam->camera_yaw = event->player_force_move.yaw;
2523 cam->camera_pitch = event->player_force_move.pitch;
2526 void Game::handleClientEvent_Deathscreen(ClientEvent *event, CameraOrientation *cam)
2528 // This should be enabled for death formspec in builtin
2529 client->getScript()->on_death();
2531 LocalPlayer *player = client->getEnv().getLocalPlayer();
2533 /* Handle visualization */
2534 runData.damage_flash = 0;
2535 player->hurt_tilt_timer = 0;
2536 player->hurt_tilt_strength = 0;
2539 void Game::handleClientEvent_ShowFormSpec(ClientEvent *event, CameraOrientation *cam)
2541 if (event->show_formspec.formspec->empty()) {
2542 if (current_formspec && (event->show_formspec.formname->empty()
2543 || *(event->show_formspec.formname) == cur_formname)) {
2544 current_formspec->quitMenu();
2547 FormspecFormSource *fs_src =
2548 new FormspecFormSource(*(event->show_formspec.formspec));
2549 TextDestPlayerInventory *txt_dst =
2550 new TextDestPlayerInventory(client, *(event->show_formspec.formname));
2552 GUIFormSpecMenu::create(current_formspec, client, &input->joystick,
2553 fs_src, txt_dst, client->getFormspecPrepend());
2554 cur_formname = *(event->show_formspec.formname);
2557 delete event->show_formspec.formspec;
2558 delete event->show_formspec.formname;
2561 void Game::handleClientEvent_ShowLocalFormSpec(ClientEvent *event, CameraOrientation *cam)
2563 FormspecFormSource *fs_src = new FormspecFormSource(*event->show_formspec.formspec);
2564 LocalFormspecHandler *txt_dst =
2565 new LocalFormspecHandler(*event->show_formspec.formname, client);
2566 GUIFormSpecMenu::create(current_formspec, client, &input->joystick,
2567 fs_src, txt_dst, client->getFormspecPrepend());
2569 delete event->show_formspec.formspec;
2570 delete event->show_formspec.formname;
2573 void Game::handleClientEvent_HandleParticleEvent(ClientEvent *event,
2574 CameraOrientation *cam)
2576 LocalPlayer *player = client->getEnv().getLocalPlayer();
2577 client->getParticleManager()->handleParticleEvent(event, client, player);
2580 void Game::handleClientEvent_HudAdd(ClientEvent *event, CameraOrientation *cam)
2582 LocalPlayer *player = client->getEnv().getLocalPlayer();
2583 auto &hud_server_to_client = client->getHUDTranslationMap();
2585 u32 server_id = event->hudadd.server_id;
2586 // ignore if we already have a HUD with that ID
2587 auto i = hud_server_to_client.find(server_id);
2588 if (i != hud_server_to_client.end()) {
2589 delete event->hudadd.pos;
2590 delete event->hudadd.name;
2591 delete event->hudadd.scale;
2592 delete event->hudadd.text;
2593 delete event->hudadd.align;
2594 delete event->hudadd.offset;
2595 delete event->hudadd.world_pos;
2596 delete event->hudadd.size;
2600 HudElement *e = new HudElement;
2601 e->type = (HudElementType)event->hudadd.type;
2602 e->pos = *event->hudadd.pos;
2603 e->name = *event->hudadd.name;
2604 e->scale = *event->hudadd.scale;
2605 e->text = *event->hudadd.text;
2606 e->number = event->hudadd.number;
2607 e->item = event->hudadd.item;
2608 e->dir = event->hudadd.dir;
2609 e->align = *event->hudadd.align;
2610 e->offset = *event->hudadd.offset;
2611 e->world_pos = *event->hudadd.world_pos;
2612 e->size = *event->hudadd.size;
2613 hud_server_to_client[server_id] = player->addHud(e);
2615 delete event->hudadd.pos;
2616 delete event->hudadd.name;
2617 delete event->hudadd.scale;
2618 delete event->hudadd.text;
2619 delete event->hudadd.align;
2620 delete event->hudadd.offset;
2621 delete event->hudadd.world_pos;
2622 delete event->hudadd.size;
2625 void Game::handleClientEvent_HudRemove(ClientEvent *event, CameraOrientation *cam)
2627 LocalPlayer *player = client->getEnv().getLocalPlayer();
2628 HudElement *e = player->removeHud(event->hudrm.id);
2632 void Game::handleClientEvent_HudChange(ClientEvent *event, CameraOrientation *cam)
2634 LocalPlayer *player = client->getEnv().getLocalPlayer();
2636 u32 id = event->hudchange.id;
2637 HudElement *e = player->getHud(id);
2640 delete event->hudchange.v3fdata;
2641 delete event->hudchange.v2fdata;
2642 delete event->hudchange.sdata;
2643 delete event->hudchange.v2s32data;
2647 switch (event->hudchange.stat) {
2649 e->pos = *event->hudchange.v2fdata;
2653 e->name = *event->hudchange.sdata;
2656 case HUD_STAT_SCALE:
2657 e->scale = *event->hudchange.v2fdata;
2661 e->text = *event->hudchange.sdata;
2664 case HUD_STAT_NUMBER:
2665 e->number = event->hudchange.data;
2669 e->item = event->hudchange.data;
2673 e->dir = event->hudchange.data;
2676 case HUD_STAT_ALIGN:
2677 e->align = *event->hudchange.v2fdata;
2680 case HUD_STAT_OFFSET:
2681 e->offset = *event->hudchange.v2fdata;
2684 case HUD_STAT_WORLD_POS:
2685 e->world_pos = *event->hudchange.v3fdata;
2689 e->size = *event->hudchange.v2s32data;
2693 delete event->hudchange.v3fdata;
2694 delete event->hudchange.v2fdata;
2695 delete event->hudchange.sdata;
2696 delete event->hudchange.v2s32data;
2699 void Game::handleClientEvent_SetSky(ClientEvent *event, CameraOrientation *cam)
2701 sky->setVisible(false);
2702 // Whether clouds are visible in front of a custom skybox
2703 sky->setCloudsEnabled(event->set_sky.clouds);
2710 // Handle according to type
2711 if (*event->set_sky.type == "regular") {
2712 sky->setVisible(true);
2713 sky->setCloudsEnabled(true);
2714 } else if (*event->set_sky.type == "skybox" &&
2715 event->set_sky.params->size() == 6) {
2716 sky->setFallbackBgColor(*event->set_sky.bgcolor);
2717 skybox = RenderingEngine::get_scene_manager()->addSkyBoxSceneNode(
2718 texture_src->getTextureForMesh((*event->set_sky.params)[0]),
2719 texture_src->getTextureForMesh((*event->set_sky.params)[1]),
2720 texture_src->getTextureForMesh((*event->set_sky.params)[2]),
2721 texture_src->getTextureForMesh((*event->set_sky.params)[3]),
2722 texture_src->getTextureForMesh((*event->set_sky.params)[4]),
2723 texture_src->getTextureForMesh((*event->set_sky.params)[5]));
2725 // Handle everything else as plain color
2727 if (*event->set_sky.type != "plain")
2728 infostream << "Unknown sky type: "
2729 << (*event->set_sky.type) << std::endl;
2731 sky->setFallbackBgColor(*event->set_sky.bgcolor);
2734 delete event->set_sky.bgcolor;
2735 delete event->set_sky.type;
2736 delete event->set_sky.params;
2739 void Game::handleClientEvent_OverrideDayNigthRatio(ClientEvent *event,
2740 CameraOrientation *cam)
2742 client->getEnv().setDayNightRatioOverride(
2743 event->override_day_night_ratio.do_override,
2744 event->override_day_night_ratio.ratio_f * 1000.0f);
2747 void Game::handleClientEvent_CloudParams(ClientEvent *event, CameraOrientation *cam)
2752 clouds->setDensity(event->cloud_params.density);
2753 clouds->setColorBright(video::SColor(event->cloud_params.color_bright));
2754 clouds->setColorAmbient(video::SColor(event->cloud_params.color_ambient));
2755 clouds->setHeight(event->cloud_params.height);
2756 clouds->setThickness(event->cloud_params.thickness);
2757 clouds->setSpeed(v2f(event->cloud_params.speed_x, event->cloud_params.speed_y));
2760 void Game::processClientEvents(CameraOrientation *cam)
2762 while (client->hasClientEvents()) {
2763 std::unique_ptr<ClientEvent> event(client->getClientEvent());
2764 FATAL_ERROR_IF(event->type >= CLIENTEVENT_MAX, "Invalid clientevent type");
2765 const ClientEventHandler& evHandler = clientEventHandler[event->type];
2766 (this->*evHandler.handler)(event.get(), cam);
2770 void Game::updateChat(f32 dtime, const v2u32 &screensize)
2772 // Add chat log output for errors to be shown in chat
2773 static LogOutputBuffer chat_log_error_buf(g_logger, LL_ERROR);
2775 // Get new messages from error log buffer
2776 while (!chat_log_error_buf.empty()) {
2777 std::wstring error_message = utf8_to_wide(chat_log_error_buf.get());
2778 if (!g_settings->getBool("disable_escape_sequences")) {
2779 error_message.insert(0, L"\x1b(c@red)");
2780 error_message.append(L"\x1b(c@white)");
2782 chat_backend->addMessage(L"", error_message);
2785 // Get new messages from client
2786 std::wstring message;
2787 while (client->getChatMessage(message)) {
2788 chat_backend->addUnparsedMessage(message);
2791 // Remove old messages
2792 chat_backend->step(dtime);
2794 // Display all messages in a static text element
2795 m_game_ui->setChatText(chat_backend->getRecentChat(),
2796 chat_backend->getRecentBuffer().getLineCount());
2799 void Game::updateCamera(u32 busy_time, f32 dtime)
2801 LocalPlayer *player = client->getEnv().getLocalPlayer();
2804 For interaction purposes, get info about the held item
2806 - Is it a usable item?
2807 - Can it point to liquids?
2809 ItemStack playeritem;
2811 InventoryList *mlist = local_inventory->getList("main");
2813 if (mlist && client->getPlayerItem() < mlist->getSize())
2814 playeritem = mlist->getItem(client->getPlayerItem());
2817 if (playeritem.getDefinition(itemdef_manager).name.empty()) { // override the hand
2818 InventoryList *hlist = local_inventory->getList("hand");
2820 playeritem = hlist->getItem(0);
2824 ToolCapabilities playeritem_toolcap =
2825 playeritem.getToolCapabilities(itemdef_manager);
2827 v3s16 old_camera_offset = camera->getOffset();
2829 if (wasKeyDown(KeyType::CAMERA_MODE)) {
2830 GenericCAO *playercao = player->getCAO();
2832 // If playercao not loaded, don't change camera
2836 camera->toggleCameraMode();
2838 playercao->setVisible(camera->getCameraMode() > CAMERA_MODE_FIRST);
2839 playercao->setChildrenVisible(camera->getCameraMode() > CAMERA_MODE_FIRST);
2842 float full_punch_interval = playeritem_toolcap.full_punch_interval;
2843 float tool_reload_ratio = runData.time_from_last_punch / full_punch_interval;
2845 tool_reload_ratio = MYMIN(tool_reload_ratio, 1.0);
2846 camera->update(player, dtime, busy_time / 1000.0f, tool_reload_ratio);
2847 camera->step(dtime);
2849 v3f camera_position = camera->getPosition();
2850 v3f camera_direction = camera->getDirection();
2851 f32 camera_fov = camera->getFovMax();
2852 v3s16 camera_offset = camera->getOffset();
2854 m_camera_offset_changed = (camera_offset != old_camera_offset);
2856 if (!m_flags.disable_camera_update) {
2857 client->getEnv().getClientMap().updateCamera(camera_position,
2858 camera_direction, camera_fov, camera_offset);
2860 if (m_camera_offset_changed) {
2861 client->updateCameraOffset(camera_offset);
2862 client->getEnv().updateCameraOffset(camera_offset);
2865 clouds->updateCameraOffset(camera_offset);
2871 void Game::updateSound(f32 dtime)
2873 // Update sound listener
2874 v3s16 camera_offset = camera->getOffset();
2875 sound->updateListener(camera->getCameraNode()->getPosition() + intToFloat(camera_offset, BS),
2876 v3f(0, 0, 0), // velocity
2877 camera->getDirection(),
2878 camera->getCameraNode()->getUpVector());
2880 bool mute_sound = g_settings->getBool("mute_sound");
2882 sound->setListenerGain(0.0f);
2884 // Check if volume is in the proper range, else fix it.
2885 float old_volume = g_settings->getFloat("sound_volume");
2886 float new_volume = rangelim(old_volume, 0.0f, 1.0f);
2887 sound->setListenerGain(new_volume);
2889 if (old_volume != new_volume) {
2890 g_settings->setFloat("sound_volume", new_volume);
2894 LocalPlayer *player = client->getEnv().getLocalPlayer();
2896 // Tell the sound maker whether to make footstep sounds
2897 soundmaker->makes_footstep_sound = player->makes_footstep_sound;
2899 // Update sound maker
2900 if (player->makes_footstep_sound)
2901 soundmaker->step(dtime);
2903 ClientMap &map = client->getEnv().getClientMap();
2904 MapNode n = map.getNodeNoEx(player->getFootstepNodePos());
2905 soundmaker->m_player_step_sound = nodedef_manager->get(n).sound_footstep;
2909 void Game::processPlayerInteraction(f32 dtime, bool show_hud, bool show_debug)
2911 LocalPlayer *player = client->getEnv().getLocalPlayer();
2913 ItemStack playeritem;
2915 InventoryList *mlist = local_inventory->getList("main");
2917 if (mlist && client->getPlayerItem() < mlist->getSize())
2918 playeritem = mlist->getItem(client->getPlayerItem());
2921 const ItemDefinition &playeritem_def =
2922 playeritem.getDefinition(itemdef_manager);
2923 InventoryList *hlist = local_inventory->getList("hand");
2924 const ItemDefinition &hand_def =
2925 hlist ? hlist->getItem(0).getDefinition(itemdef_manager) : itemdef_manager->get("");
2927 v3f player_position = player->getPosition();
2928 v3f camera_position = camera->getPosition();
2929 v3f camera_direction = camera->getDirection();
2930 v3s16 camera_offset = camera->getOffset();
2934 Calculate what block is the crosshair pointing to
2937 f32 d = playeritem_def.range; // max. distance
2938 f32 d_hand = hand_def.range;
2940 if (d < 0 && d_hand >= 0)
2945 core::line3d<f32> shootline;
2947 if (camera->getCameraMode() != CAMERA_MODE_THIRD_FRONT) {
2948 shootline = core::line3d<f32>(camera_position,
2949 camera_position + camera_direction * BS * d);
2951 // prevent player pointing anything in front-view
2952 shootline = core::line3d<f32>(camera_position,camera_position);
2955 #ifdef HAVE_TOUCHSCREENGUI
2957 if ((g_settings->getBool("touchtarget")) && (g_touchscreengui)) {
2958 shootline = g_touchscreengui->getShootline();
2959 // Scale shootline to the acual distance the player can reach
2960 shootline.end = shootline.start
2961 + shootline.getVector().normalize() * BS * d;
2962 shootline.start += intToFloat(camera_offset, BS);
2963 shootline.end += intToFloat(camera_offset, BS);
2968 PointedThing pointed = updatePointedThing(shootline,
2969 playeritem_def.liquids_pointable,
2970 !runData.ldown_for_dig,
2973 if (pointed != runData.pointed_old) {
2974 infostream << "Pointing at " << pointed.dump() << std::endl;
2975 hud->updateSelectionMesh(camera_offset);
2978 if (runData.digging_blocked && !input->getLeftState()) {
2979 // allow digging again if button is not pressed
2980 runData.digging_blocked = false;
2985 - releasing left mouse button
2986 - pointing away from node
2988 if (runData.digging) {
2989 if (input->getLeftReleased()) {
2990 infostream << "Left button released"
2991 << " (stopped digging)" << std::endl;
2992 runData.digging = false;
2993 } else if (pointed != runData.pointed_old) {
2994 if (pointed.type == POINTEDTHING_NODE
2995 && runData.pointed_old.type == POINTEDTHING_NODE
2996 && pointed.node_undersurface
2997 == runData.pointed_old.node_undersurface) {
2998 // Still pointing to the same node, but a different face.
3001 infostream << "Pointing away from node"
3002 << " (stopped digging)" << std::endl;
3003 runData.digging = false;
3004 hud->updateSelectionMesh(camera_offset);
3008 if (!runData.digging) {
3009 client->interact(1, runData.pointed_old);
3010 client->setCrack(-1, v3s16(0, 0, 0));
3011 runData.dig_time = 0.0;
3013 } else if (runData.dig_instantly && input->getLeftReleased()) {
3014 // Remove e.g. torches faster when clicking instead of holding LMB
3015 runData.nodig_delay_timer = 0;
3016 runData.dig_instantly = false;
3019 if (!runData.digging && runData.ldown_for_dig && !input->getLeftState()) {
3020 runData.ldown_for_dig = false;
3023 runData.left_punch = false;
3025 soundmaker->m_player_leftpunch_sound.name = "";
3027 // Prepare for repeating, unless we're not supposed to
3028 if (input->getRightState() && !g_settings->getBool("safe_dig_and_place"))
3029 runData.repeat_rightclick_timer += dtime;
3031 runData.repeat_rightclick_timer = 0;
3033 if (playeritem_def.usable && input->getLeftState()) {
3034 if (input->getLeftClicked() && (!client->moddingEnabled()
3035 || !client->getScript()->on_item_use(playeritem, pointed)))
3036 client->interact(4, pointed);
3037 } else if (pointed.type == POINTEDTHING_NODE) {
3038 ToolCapabilities playeritem_toolcap =
3039 playeritem.getToolCapabilities(itemdef_manager);
3040 if (playeritem.name.empty()) {
3041 const ToolCapabilities *handToolcap = hlist
3042 ? &hlist->getItem(0).getToolCapabilities(itemdef_manager)
3043 : itemdef_manager->get("").tool_capabilities;
3045 if (handToolcap != nullptr)
3046 playeritem_toolcap = *handToolcap;
3048 handlePointingAtNode(pointed, playeritem_def, playeritem,
3049 playeritem_toolcap, dtime);
3050 } else if (pointed.type == POINTEDTHING_OBJECT) {
3051 handlePointingAtObject(pointed, playeritem, player_position, show_debug);
3052 } else if (input->getLeftState()) {
3053 // When button is held down in air, show continuous animation
3054 runData.left_punch = true;
3055 } else if (input->getRightClicked()) {
3056 handlePointingAtNothing(playeritem);
3059 runData.pointed_old = pointed;
3061 if (runData.left_punch || input->getLeftClicked())
3062 camera->setDigging(0); // left click animation
3064 input->resetLeftClicked();
3065 input->resetRightClicked();
3067 input->resetLeftReleased();
3068 input->resetRightReleased();
3072 PointedThing Game::updatePointedThing(
3073 const core::line3d<f32> &shootline,
3074 bool liquids_pointable,
3075 bool look_for_object,
3076 const v3s16 &camera_offset)
3078 std::vector<aabb3f> *selectionboxes = hud->getSelectionBoxes();
3079 selectionboxes->clear();
3080 hud->setSelectedFaceNormal(v3f(0.0, 0.0, 0.0));
3081 static thread_local const bool show_entity_selectionbox = g_settings->getBool(
3082 "show_entity_selectionbox");
3084 ClientEnvironment &env = client->getEnv();
3085 ClientMap &map = env.getClientMap();
3086 const NodeDefManager *nodedef = map.getNodeDefManager();
3088 runData.selected_object = NULL;
3090 RaycastState s(shootline, look_for_object, liquids_pointable);
3091 PointedThing result;
3092 env.continueRaycast(&s, &result);
3093 if (result.type == POINTEDTHING_OBJECT) {
3094 runData.selected_object = client->getEnv().getActiveObject(result.object_id);
3095 aabb3f selection_box;
3096 if (show_entity_selectionbox && runData.selected_object->doShowSelectionBox() &&
3097 runData.selected_object->getSelectionBox(&selection_box)) {
3098 v3f pos = runData.selected_object->getPosition();
3099 selectionboxes->push_back(aabb3f(selection_box));
3100 hud->setSelectionPos(pos, camera_offset);
3102 } else if (result.type == POINTEDTHING_NODE) {
3103 // Update selection boxes
3104 MapNode n = map.getNodeNoEx(result.node_undersurface);
3105 std::vector<aabb3f> boxes;
3106 n.getSelectionBoxes(nodedef, &boxes,
3107 n.getNeighbors(result.node_undersurface, &map));
3110 for (std::vector<aabb3f>::const_iterator i = boxes.begin();
3111 i != boxes.end(); ++i) {
3113 box.MinEdge -= v3f(d, d, d);
3114 box.MaxEdge += v3f(d, d, d);
3115 selectionboxes->push_back(box);
3117 hud->setSelectionPos(intToFloat(result.node_undersurface, BS),
3119 hud->setSelectedFaceNormal(v3f(
3120 result.intersection_normal.X,
3121 result.intersection_normal.Y,
3122 result.intersection_normal.Z));
3125 // Update selection mesh light level and vertex colors
3126 if (!selectionboxes->empty()) {
3127 v3f pf = hud->getSelectionPos();
3128 v3s16 p = floatToInt(pf, BS);
3130 // Get selection mesh light level
3131 MapNode n = map.getNodeNoEx(p);
3132 u16 node_light = getInteriorLight(n, -1, nodedef);
3133 u16 light_level = node_light;
3135 for (const v3s16 &dir : g_6dirs) {
3136 n = map.getNodeNoEx(p + dir);
3137 node_light = getInteriorLight(n, -1, nodedef);
3138 if (node_light > light_level)
3139 light_level = node_light;
3142 u32 daynight_ratio = client->getEnv().getDayNightRatio();
3144 final_color_blend(&c, light_level, daynight_ratio);
3146 // Modify final color a bit with time
3147 u32 timer = porting::getTimeMs() % 5000;
3148 float timerf = (float) (irr::core::PI * ((timer / 2500.0) - 0.5));
3149 float sin_r = 0.08f * std::sin(timerf);
3150 float sin_g = 0.08f * std::sin(timerf + irr::core::PI * 0.5f);
3151 float sin_b = 0.08f * std::sin(timerf + irr::core::PI);
3152 c.setRed(core::clamp(core::round32(c.getRed() * (0.8 + sin_r)), 0, 255));
3153 c.setGreen(core::clamp(core::round32(c.getGreen() * (0.8 + sin_g)), 0, 255));
3154 c.setBlue(core::clamp(core::round32(c.getBlue() * (0.8 + sin_b)), 0, 255));
3156 // Set mesh final color
3157 hud->setSelectionMeshColor(c);
3163 void Game::handlePointingAtNothing(const ItemStack &playerItem)
3165 infostream << "Right Clicked in Air" << std::endl;
3166 PointedThing fauxPointed;
3167 fauxPointed.type = POINTEDTHING_NOTHING;
3168 client->interact(5, fauxPointed);
3172 void Game::handlePointingAtNode(const PointedThing &pointed,
3173 const ItemDefinition &playeritem_def, const ItemStack &playeritem,
3174 const ToolCapabilities &playeritem_toolcap, f32 dtime)
3176 v3s16 nodepos = pointed.node_undersurface;
3177 v3s16 neighbourpos = pointed.node_abovesurface;
3180 Check information text of node
3183 ClientMap &map = client->getEnv().getClientMap();
3185 if (runData.nodig_delay_timer <= 0.0 && input->getLeftState()
3186 && !runData.digging_blocked
3187 && client->checkPrivilege("interact")) {
3188 handleDigging(pointed, nodepos, playeritem_toolcap, dtime);
3191 // This should be done after digging handling
3192 NodeMetadata *meta = map.getNodeMetadata(nodepos);
3195 m_game_ui->setInfoText(unescape_translate(utf8_to_wide(
3196 meta->getString("infotext"))));
3198 MapNode n = map.getNodeNoEx(nodepos);
3200 if (nodedef_manager->get(n).tiledef[0].name == "unknown_node.png") {
3201 m_game_ui->setInfoText(L"Unknown node: " +
3202 utf8_to_wide(nodedef_manager->get(n).name));
3206 if ((input->getRightClicked() ||
3207 runData.repeat_rightclick_timer >= m_repeat_right_click_time) &&
3208 client->checkPrivilege("interact")) {
3209 runData.repeat_rightclick_timer = 0;
3210 infostream << "Ground right-clicked" << std::endl;
3212 if (meta && !meta->getString("formspec").empty() && !random_input
3213 && !isKeyDown(KeyType::SNEAK)) {
3214 // Report right click to server
3215 if (nodedef_manager->get(map.getNodeNoEx(nodepos)).rightclickable) {
3216 client->interact(3, pointed);
3219 infostream << "Launching custom inventory view" << std::endl;
3221 InventoryLocation inventoryloc;
3222 inventoryloc.setNodeMeta(nodepos);
3224 NodeMetadataFormSource *fs_src = new NodeMetadataFormSource(
3225 &client->getEnv().getClientMap(), nodepos);
3226 TextDest *txt_dst = new TextDestNodeMetadata(nodepos, client);
3228 GUIFormSpecMenu::create(current_formspec, client, &input->joystick, fs_src,
3229 txt_dst, client->getFormspecPrepend());
3230 cur_formname.clear();
3232 current_formspec->setFormSpec(meta->getString("formspec"), inventoryloc);
3234 // Report right click to server
3236 camera->setDigging(1); // right click animation (always shown for feedback)
3238 // If the wielded item has node placement prediction,
3240 bool placed = nodePlacementPrediction(playeritem_def, playeritem, nodepos,
3245 client->interact(3, pointed);
3247 soundmaker->m_player_rightpunch_sound =
3248 playeritem_def.sound_place;
3250 if (client->moddingEnabled())
3251 client->getScript()->on_placenode(pointed, playeritem_def);
3253 soundmaker->m_player_rightpunch_sound =
3256 if (playeritem_def.node_placement_prediction.empty() ||
3257 nodedef_manager->get(map.getNodeNoEx(nodepos)).rightclickable) {
3258 client->interact(3, pointed); // Report to server
3260 soundmaker->m_player_rightpunch_sound =
3261 playeritem_def.sound_place_failed;
3268 bool Game::nodePlacementPrediction(const ItemDefinition &playeritem_def,
3269 const ItemStack &playeritem, const v3s16 &nodepos, const v3s16 &neighbourpos)
3271 std::string prediction = playeritem_def.node_placement_prediction;
3272 const NodeDefManager *nodedef = client->ndef();
3273 ClientMap &map = client->getEnv().getClientMap();
3275 bool is_valid_position;
3277 node = map.getNodeNoEx(nodepos, &is_valid_position);
3278 if (!is_valid_position)
3281 if (!prediction.empty() && !nodedef->get(node).rightclickable) {
3282 verbosestream << "Node placement prediction for "
3283 << playeritem_def.name << " is "
3284 << prediction << std::endl;
3285 v3s16 p = neighbourpos;
3287 // Place inside node itself if buildable_to
3288 MapNode n_under = map.getNodeNoEx(nodepos, &is_valid_position);
3289 if (is_valid_position)
3291 if (nodedef->get(n_under).buildable_to)
3294 node = map.getNodeNoEx(p, &is_valid_position);
3295 if (is_valid_position &&!nodedef->get(node).buildable_to)
3300 // Find id of predicted node
3302 bool found = nodedef->getId(prediction, id);
3305 errorstream << "Node placement prediction failed for "
3306 << playeritem_def.name << " (places "
3308 << ") - Name not known" << std::endl;
3312 const ContentFeatures &predicted_f = nodedef->get(id);
3314 // Predict param2 for facedir and wallmounted nodes
3317 if (predicted_f.param_type_2 == CPT2_WALLMOUNTED ||
3318 predicted_f.param_type_2 == CPT2_COLORED_WALLMOUNTED) {
3319 v3s16 dir = nodepos - neighbourpos;
3321 if (abs(dir.Y) > MYMAX(abs(dir.X), abs(dir.Z))) {
3322 param2 = dir.Y < 0 ? 1 : 0;
3323 } else if (abs(dir.X) > abs(dir.Z)) {
3324 param2 = dir.X < 0 ? 3 : 2;
3326 param2 = dir.Z < 0 ? 5 : 4;
3330 if (predicted_f.param_type_2 == CPT2_FACEDIR ||
3331 predicted_f.param_type_2 == CPT2_COLORED_FACEDIR) {
3332 v3s16 dir = nodepos - floatToInt(client->getEnv().getLocalPlayer()->getPosition(), BS);
3334 if (abs(dir.X) > abs(dir.Z)) {
3335 param2 = dir.X < 0 ? 3 : 1;
3337 param2 = dir.Z < 0 ? 2 : 0;
3341 assert(param2 <= 5);
3343 //Check attachment if node is in group attached_node
3344 if (((ItemGroupList) predicted_f.groups)["attached_node"] != 0) {
3345 static v3s16 wallmounted_dirs[8] = {
3355 if (predicted_f.param_type_2 == CPT2_WALLMOUNTED ||
3356 predicted_f.param_type_2 == CPT2_COLORED_WALLMOUNTED)
3357 pp = p + wallmounted_dirs[param2];
3359 pp = p + v3s16(0, -1, 0);
3361 if (!nodedef->get(map.getNodeNoEx(pp)).walkable)
3366 if ((predicted_f.param_type_2 == CPT2_COLOR
3367 || predicted_f.param_type_2 == CPT2_COLORED_FACEDIR
3368 || predicted_f.param_type_2 == CPT2_COLORED_WALLMOUNTED)) {
3369 const std::string &indexstr = playeritem.metadata.getString(
3370 "palette_index", 0);
3371 if (!indexstr.empty()) {
3372 s32 index = mystoi(indexstr);
3373 if (predicted_f.param_type_2 == CPT2_COLOR) {
3375 } else if (predicted_f.param_type_2
3376 == CPT2_COLORED_WALLMOUNTED) {
3377 // param2 = pure palette index + other
3378 param2 = (index & 0xf8) | (param2 & 0x07);
3379 } else if (predicted_f.param_type_2
3380 == CPT2_COLORED_FACEDIR) {
3381 // param2 = pure palette index + other
3382 param2 = (index & 0xe0) | (param2 & 0x1f);
3387 // Add node to client map
3388 MapNode n(id, 0, param2);
3391 LocalPlayer *player = client->getEnv().getLocalPlayer();
3393 // Dont place node when player would be inside new node
3394 // NOTE: This is to be eventually implemented by a mod as client-side Lua
3395 if (!nodedef->get(n).walkable ||
3396 g_settings->getBool("enable_build_where_you_stand") ||
3397 (client->checkPrivilege("noclip") && g_settings->getBool("noclip")) ||
3398 (nodedef->get(n).walkable &&
3399 neighbourpos != player->getStandingNodePos() + v3s16(0, 1, 0) &&
3400 neighbourpos != player->getStandingNodePos() + v3s16(0, 2, 0))) {
3402 // This triggers the required mesh update too
3403 client->addNode(p, n);
3406 } catch (InvalidPositionException &e) {
3407 errorstream << "Node placement prediction failed for "
3408 << playeritem_def.name << " (places "
3410 << ") - Position not loaded" << std::endl;
3417 void Game::handlePointingAtObject(const PointedThing &pointed, const ItemStack &playeritem,
3418 const v3f &player_position, bool show_debug)
3420 std::wstring infotext = unescape_translate(
3421 utf8_to_wide(runData.selected_object->infoText()));
3424 if (!infotext.empty()) {
3427 infotext += utf8_to_wide(runData.selected_object->debugInfoText());
3430 m_game_ui->setInfoText(infotext);
3432 if (input->getLeftState()) {
3433 bool do_punch = false;
3434 bool do_punch_damage = false;
3436 if (runData.object_hit_delay_timer <= 0.0) {
3438 do_punch_damage = true;
3439 runData.object_hit_delay_timer = object_hit_delay;
3442 if (input->getLeftClicked())
3446 infostream << "Left-clicked object" << std::endl;
3447 runData.left_punch = true;
3450 if (do_punch_damage) {
3451 // Report direct punch
3452 v3f objpos = runData.selected_object->getPosition();
3453 v3f dir = (objpos - player_position).normalize();
3454 ItemStack item = playeritem;
3455 if (playeritem.name.empty()) {
3456 InventoryList *hlist = local_inventory->getList("hand");
3458 item = hlist->getItem(0);
3462 bool disable_send = runData.selected_object->directReportPunch(
3463 dir, &item, runData.time_from_last_punch);
3464 runData.time_from_last_punch = 0;
3467 client->interact(0, pointed);
3469 } else if (input->getRightClicked()) {
3470 infostream << "Right-clicked object" << std::endl;
3471 client->interact(3, pointed); // place
3476 void Game::handleDigging(const PointedThing &pointed, const v3s16 &nodepos,
3477 const ToolCapabilities &playeritem_toolcap, f32 dtime)
3479 LocalPlayer *player = client->getEnv().getLocalPlayer();
3480 ClientMap &map = client->getEnv().getClientMap();
3481 MapNode n = client->getEnv().getClientMap().getNodeNoEx(nodepos);
3483 // NOTE: Similar piece of code exists on the server side for
3485 // Get digging parameters
3486 DigParams params = getDigParams(nodedef_manager->get(n).groups,
3487 &playeritem_toolcap);
3489 // If can't dig, try hand
3490 if (!params.diggable) {
3491 InventoryList *hlist = local_inventory->getList("hand");
3492 const ToolCapabilities *tp = hlist
3493 ? &hlist->getItem(0).getToolCapabilities(itemdef_manager)
3494 : itemdef_manager->get("").tool_capabilities;
3497 params = getDigParams(nodedef_manager->get(n).groups, tp);
3500 if (!params.diggable) {
3501 // I guess nobody will wait for this long
3502 runData.dig_time_complete = 10000000.0;
3504 runData.dig_time_complete = params.time;
3506 if (m_cache_enable_particles) {
3507 const ContentFeatures &features = client->getNodeDefManager()->get(n);
3508 client->getParticleManager()->addNodeParticle(client,
3509 player, nodepos, n, features);
3513 if (!runData.digging) {
3514 infostream << "Started digging" << std::endl;
3515 runData.dig_instantly = runData.dig_time_complete == 0;
3516 if (client->moddingEnabled() && client->getScript()->on_punchnode(nodepos, n))
3518 client->interact(0, pointed);
3519 runData.digging = true;
3520 runData.ldown_for_dig = true;
3523 if (!runData.dig_instantly) {
3524 runData.dig_index = (float)crack_animation_length
3526 / runData.dig_time_complete;
3528 // This is for e.g. torches
3529 runData.dig_index = crack_animation_length;
3532 SimpleSoundSpec sound_dig = nodedef_manager->get(n).sound_dig;
3534 if (sound_dig.exists() && params.diggable) {
3535 if (sound_dig.name == "__group") {
3536 if (!params.main_group.empty()) {
3537 soundmaker->m_player_leftpunch_sound.gain = 0.5;
3538 soundmaker->m_player_leftpunch_sound.name =
3539 std::string("default_dig_") +
3543 soundmaker->m_player_leftpunch_sound = sound_dig;
3547 // Don't show cracks if not diggable
3548 if (runData.dig_time_complete >= 100000.0) {
3549 } else if (runData.dig_index < crack_animation_length) {
3550 //TimeTaker timer("client.setTempMod");
3551 //infostream<<"dig_index="<<dig_index<<std::endl;
3552 client->setCrack(runData.dig_index, nodepos);
3554 infostream << "Digging completed" << std::endl;
3555 client->setCrack(-1, v3s16(0, 0, 0));
3557 runData.dig_time = 0;
3558 runData.digging = false;
3559 // we successfully dug, now block it from repeating if we want to be safe
3560 if (g_settings->getBool("safe_dig_and_place"))
3561 runData.digging_blocked = true;
3563 runData.nodig_delay_timer =
3564 runData.dig_time_complete / (float)crack_animation_length;
3566 // We don't want a corresponding delay to very time consuming nodes
3567 // and nodes without digging time (e.g. torches) get a fixed delay.
3568 if (runData.nodig_delay_timer > 0.3)
3569 runData.nodig_delay_timer = 0.3;
3570 else if (runData.dig_instantly)
3571 runData.nodig_delay_timer = 0.15;
3573 bool is_valid_position;
3574 MapNode wasnode = map.getNodeNoEx(nodepos, &is_valid_position);
3575 if (is_valid_position) {
3576 if (client->moddingEnabled() &&
3577 client->getScript()->on_dignode(nodepos, wasnode)) {
3581 const ContentFeatures &f = client->ndef()->get(wasnode);
3582 if (f.node_dig_prediction == "air") {
3583 client->removeNode(nodepos);
3584 } else if (!f.node_dig_prediction.empty()) {
3586 bool found = client->ndef()->getId(f.node_dig_prediction, id);
3588 client->addNode(nodepos, id, true);
3590 // implicit else: no prediction
3593 client->interact(2, pointed);
3595 if (m_cache_enable_particles) {
3596 const ContentFeatures &features =
3597 client->getNodeDefManager()->get(wasnode);
3598 client->getParticleManager()->addDiggingParticles(client,
3599 player, nodepos, wasnode, features);
3603 // Send event to trigger sound
3604 client->getEventManager()->put(new NodeDugEvent(nodepos, wasnode));
3607 if (runData.dig_time_complete < 100000.0) {
3608 runData.dig_time += dtime;
3610 runData.dig_time = 0;
3611 client->setCrack(-1, nodepos);
3614 camera->setDigging(0); // left click animation
3618 void Game::updateFrame(ProfilerGraph *graph, RunStats *stats, f32 dtime,
3619 const CameraOrientation &cam)
3621 LocalPlayer *player = client->getEnv().getLocalPlayer();
3627 if (draw_control->range_all) {
3628 runData.fog_range = 100000 * BS;
3630 runData.fog_range = draw_control->wanted_range * BS;
3634 Calculate general brightness
3636 u32 daynight_ratio = client->getEnv().getDayNightRatio();
3637 float time_brightness = decode_light_f((float)daynight_ratio / 1000.0);
3638 float direct_brightness;
3641 if (m_cache_enable_noclip && m_cache_enable_free_move) {
3642 direct_brightness = time_brightness;
3643 sunlight_seen = true;
3645 ScopeProfiler sp(g_profiler, "Detecting background light", SPT_AVG);
3646 float old_brightness = sky->getBrightness();
3647 direct_brightness = client->getEnv().getClientMap()
3648 .getBackgroundBrightness(MYMIN(runData.fog_range * 1.2, 60 * BS),
3649 daynight_ratio, (int)(old_brightness * 255.5), &sunlight_seen)
3653 float time_of_day_smooth = runData.time_of_day_smooth;
3654 float time_of_day = client->getEnv().getTimeOfDayF();
3656 static const float maxsm = 0.05f;
3657 static const float todsm = 0.05f;
3659 if (std::fabs(time_of_day - time_of_day_smooth) > maxsm &&
3660 std::fabs(time_of_day - time_of_day_smooth + 1.0) > maxsm &&
3661 std::fabs(time_of_day - time_of_day_smooth - 1.0) > maxsm)
3662 time_of_day_smooth = time_of_day;
3664 if (time_of_day_smooth > 0.8 && time_of_day < 0.2)
3665 time_of_day_smooth = time_of_day_smooth * (1.0 - todsm)
3666 + (time_of_day + 1.0) * todsm;
3668 time_of_day_smooth = time_of_day_smooth * (1.0 - todsm)
3669 + time_of_day * todsm;
3671 runData.time_of_day_smooth = time_of_day_smooth;
3673 sky->update(time_of_day_smooth, time_brightness, direct_brightness,
3674 sunlight_seen, camera->getCameraMode(), player->getYaw(),
3675 player->getPitch());
3681 if (sky->getCloudsVisible()) {
3682 clouds->setVisible(true);
3683 clouds->step(dtime);
3684 // camera->getPosition is not enough for 3rd person views
3685 v3f camera_node_position = camera->getCameraNode()->getPosition();
3686 v3s16 camera_offset = camera->getOffset();
3687 camera_node_position.X = camera_node_position.X + camera_offset.X * BS;
3688 camera_node_position.Y = camera_node_position.Y + camera_offset.Y * BS;
3689 camera_node_position.Z = camera_node_position.Z + camera_offset.Z * BS;
3690 clouds->update(camera_node_position,
3691 sky->getCloudColor());
3692 if (clouds->isCameraInsideCloud() && m_cache_enable_fog) {
3693 // if inside clouds, and fog enabled, use that as sky
3695 video::SColor clouds_dark = clouds->getColor()
3696 .getInterpolated(video::SColor(255, 0, 0, 0), 0.9);
3697 sky->overrideColors(clouds_dark, clouds->getColor());
3698 sky->setBodiesVisible(false);
3699 runData.fog_range = std::fmin(runData.fog_range * 0.5f, 32.0f * BS);
3700 // do not draw clouds after all
3701 clouds->setVisible(false);
3704 clouds->setVisible(false);
3711 client->getParticleManager()->step(dtime);
3717 if (m_cache_enable_fog) {
3720 video::EFT_FOG_LINEAR,
3721 runData.fog_range * m_cache_fog_start,
3722 runData.fog_range * 1.0,
3730 video::EFT_FOG_LINEAR,
3740 Get chat messages from client
3743 v2u32 screensize = driver->getScreenSize();
3745 updateChat(dtime, screensize);
3751 if (client->getPlayerItem() != runData.new_playeritem)
3752 client->selectPlayerItem(runData.new_playeritem);
3754 // Update local inventory if it has changed
3755 if (client->getLocalInventoryUpdated()) {
3756 //infostream<<"Updating local inventory"<<std::endl;
3757 client->getLocalInventory(*local_inventory);
3758 runData.update_wielded_item_trigger = true;
3761 if (runData.update_wielded_item_trigger) {
3762 // Update wielded tool
3763 InventoryList *mlist = local_inventory->getList("main");
3765 if (mlist && (client->getPlayerItem() < mlist->getSize())) {
3766 ItemStack item = mlist->getItem(client->getPlayerItem());
3767 if (item.getDefinition(itemdef_manager).name.empty()) { // override the hand
3768 InventoryList *hlist = local_inventory->getList("hand");
3770 item = hlist->getItem(0);
3772 camera->wield(item);
3775 runData.update_wielded_item_trigger = false;
3779 Update block draw list every 200ms or when camera direction has
3782 runData.update_draw_list_timer += dtime;
3784 v3f camera_direction = camera->getDirection();
3785 if (runData.update_draw_list_timer >= 0.2
3786 || runData.update_draw_list_last_cam_dir.getDistanceFrom(camera_direction) > 0.2
3787 || m_camera_offset_changed) {
3788 runData.update_draw_list_timer = 0;
3789 client->getEnv().getClientMap().updateDrawList();
3790 runData.update_draw_list_last_cam_dir = camera_direction;
3793 m_game_ui->update(*stats, client, draw_control, cam, runData.pointed_old, dtime);
3796 make sure menu is on top
3797 1. Delete formspec menu reference if menu was removed
3798 2. Else, make sure formspec menu is on top
3800 if (current_formspec) {
3801 if (current_formspec->getReferenceCount() == 1) {
3802 current_formspec->drop();
3803 current_formspec = NULL;
3804 } else if (isMenuActive()) {
3805 guiroot->bringToFront(current_formspec);
3812 const video::SColor &skycolor = sky->getSkyColor();
3814 TimeTaker tt_draw("mainloop: draw");
3815 driver->beginScene(true, true, skycolor);
3817 bool draw_wield_tool = (m_game_ui->m_flags.show_hud &&
3818 (player->hud_flags & HUD_FLAG_WIELDITEM_VISIBLE) &&
3819 (camera->getCameraMode() == CAMERA_MODE_FIRST));
3820 bool draw_crosshair = (
3821 (player->hud_flags & HUD_FLAG_CROSSHAIR_VISIBLE) &&
3822 (camera->getCameraMode() != CAMERA_MODE_THIRD_FRONT));
3823 #ifdef HAVE_TOUCHSCREENGUI
3825 draw_crosshair = !g_settings->getBool("touchtarget");
3826 } catch (SettingNotFoundException) {
3829 RenderingEngine::draw_scene(skycolor, m_game_ui->m_flags.show_hud,
3830 m_game_ui->m_flags.show_minimap, draw_wield_tool, draw_crosshair);
3835 if (m_game_ui->m_flags.show_profiler_graph)
3836 graph->draw(10, screensize.Y - 10, driver, g_fontengine->getFont());
3841 if (runData.damage_flash > 0.0f) {
3842 video::SColor color(runData.damage_flash, 180, 0, 0);
3843 driver->draw2DRectangle(color,
3844 core::rect<s32>(0, 0, screensize.X, screensize.Y),
3847 runData.damage_flash -= 384.0f * dtime;
3853 if (player->hurt_tilt_timer > 0.0f) {
3854 player->hurt_tilt_timer -= dtime * 6.0f;
3856 if (player->hurt_tilt_timer < 0.0f)
3857 player->hurt_tilt_strength = 0.0f;
3861 Update minimap pos and rotation
3863 if (mapper && m_game_ui->m_flags.show_minimap && m_game_ui->m_flags.show_hud) {
3864 mapper->setPos(floatToInt(player->getPosition(), BS));
3865 mapper->setAngle(player->getYaw());
3873 stats->drawtime = tt_draw.stop(true);
3874 g_profiler->graphAdd("mainloop_draw", stats->drawtime / 1000.0f);
3877 /* Log times and stuff for visualization */
3878 inline void Game::updateProfilerGraphs(ProfilerGraph *graph)
3880 Profiler::GraphValues values;
3881 g_profiler->graphGet(values);
3887 /****************************************************************************
3889 ****************************************************************************/
3891 /* On some computers framerate doesn't seem to be automatically limited
3893 inline void Game::limitFps(FpsControl *fps_timings, f32 *dtime)
3895 // not using getRealTime is necessary for wine
3896 device->getTimer()->tick(); // Maker sure device time is up-to-date
3897 u32 time = device->getTimer()->getTime();
3898 u32 last_time = fps_timings->last_time;
3900 if (time > last_time) // Make sure time hasn't overflowed
3901 fps_timings->busy_time = time - last_time;
3903 fps_timings->busy_time = 0;
3905 u32 frametime_min = 1000 / (g_menumgr.pausesGame()
3906 ? g_settings->getFloat("pause_fps_max")
3907 : g_settings->getFloat("fps_max"));
3909 if (fps_timings->busy_time < frametime_min) {
3910 fps_timings->sleep_time = frametime_min - fps_timings->busy_time;
3911 device->sleep(fps_timings->sleep_time);
3913 fps_timings->sleep_time = 0;
3916 /* Get the new value of the device timer. Note that device->sleep() may
3917 * not sleep for the entire requested time as sleep may be interrupted and
3918 * therefore it is arguably more accurate to get the new time from the
3919 * device rather than calculating it by adding sleep_time to time.
3922 device->getTimer()->tick(); // Update device timer
3923 time = device->getTimer()->getTime();
3925 if (time > last_time) // Make sure last_time hasn't overflowed
3926 *dtime = (time - last_time) / 1000.0;
3930 fps_timings->last_time = time;
3933 void Game::showOverlayMessage(const char *msg, float dtime, int percent, bool draw_clouds)
3935 const wchar_t *wmsg = wgettext(msg);
3936 RenderingEngine::draw_load_screen(wmsg, guienv, texture_src, dtime, percent,
3941 void Game::settingChangedCallback(const std::string &setting_name, void *data)
3943 ((Game *)data)->readSettings();
3946 void Game::readSettings()
3948 m_cache_doubletap_jump = g_settings->getBool("doubletap_jump");
3949 m_cache_enable_clouds = g_settings->getBool("enable_clouds");
3950 m_cache_enable_joysticks = g_settings->getBool("enable_joysticks");
3951 m_cache_enable_particles = g_settings->getBool("enable_particles");
3952 m_cache_enable_fog = g_settings->getBool("enable_fog");
3953 m_cache_mouse_sensitivity = g_settings->getFloat("mouse_sensitivity");
3954 m_cache_joystick_frustum_sensitivity = g_settings->getFloat("joystick_frustum_sensitivity");
3955 m_repeat_right_click_time = g_settings->getFloat("repeat_rightclick_time");
3957 m_cache_enable_noclip = g_settings->getBool("noclip");
3958 m_cache_enable_free_move = g_settings->getBool("free_move");
3960 m_cache_fog_start = g_settings->getFloat("fog_start");
3962 m_cache_cam_smoothing = 0;
3963 if (g_settings->getBool("cinematic"))
3964 m_cache_cam_smoothing = 1 - g_settings->getFloat("cinematic_camera_smoothing");
3966 m_cache_cam_smoothing = 1 - g_settings->getFloat("camera_smoothing");
3968 m_cache_fog_start = rangelim(m_cache_fog_start, 0.0f, 0.99f);
3969 m_cache_cam_smoothing = rangelim(m_cache_cam_smoothing, 0.01f, 1.0f);
3970 m_cache_mouse_sensitivity = rangelim(m_cache_mouse_sensitivity, 0.001, 100.0);
3972 m_does_lost_focus_pause_game = g_settings->getBool("pause_on_lost_focus");
3975 /****************************************************************************/
3976 /****************************************************************************
3978 ****************************************************************************/
3979 /****************************************************************************/
3981 void Game::extendedResourceCleanup()
3983 // Extended resource accounting
3984 infostream << "Irrlicht resources after cleanup:" << std::endl;
3985 infostream << "\tRemaining meshes : "
3986 << RenderingEngine::get_mesh_cache()->getMeshCount() << std::endl;
3987 infostream << "\tRemaining textures : "
3988 << driver->getTextureCount() << std::endl;
3990 for (unsigned int i = 0; i < driver->getTextureCount(); i++) {
3991 irr::video::ITexture *texture = driver->getTextureByIndex(i);
3992 infostream << "\t\t" << i << ":" << texture->getName().getPath().c_str()
3996 clearTextureNameCache();
3997 infostream << "\tRemaining materials: "
3998 << driver-> getMaterialRendererCount()
3999 << " (note: irrlicht doesn't support removing renderers)" << std::endl;
4002 #define GET_KEY_NAME(KEY) gettext(getKeySetting(#KEY).name())
4003 void Game::showPauseMenu()
4006 static const std::string control_text = strgettext("Default Controls:\n"
4007 "No menu visible:\n"
4008 "- single tap: button activate\n"
4009 "- double tap: place/use\n"
4010 "- slide finger: look around\n"
4011 "Menu/Inventory visible:\n"
4012 "- double tap (outside):\n"
4014 "- touch stack, touch slot:\n"
4016 "- touch&drag, tap 2nd finger\n"
4017 " --> place single item to slot\n"
4020 static const std::string control_text_template = strgettext("Controls:\n"
4021 "- %s: move forwards\n"
4022 "- %s: move backwards\n"
4024 "- %s: move right\n"
4025 "- %s: jump/climb\n"
4026 "- %s: sneak/go down\n"
4029 "- Mouse: turn/look\n"
4030 "- Mouse left: dig/punch\n"
4031 "- Mouse right: place/use\n"
4032 "- Mouse wheel: select item\n"
4036 char control_text_buf[600];
4038 porting::mt_snprintf(control_text_buf, sizeof(control_text_buf), control_text_template.c_str(),
4039 GET_KEY_NAME(keymap_forward),
4040 GET_KEY_NAME(keymap_backward),
4041 GET_KEY_NAME(keymap_left),
4042 GET_KEY_NAME(keymap_right),
4043 GET_KEY_NAME(keymap_jump),
4044 GET_KEY_NAME(keymap_sneak),
4045 GET_KEY_NAME(keymap_drop),
4046 GET_KEY_NAME(keymap_inventory),
4047 GET_KEY_NAME(keymap_chat)
4050 std::string control_text = std::string(control_text_buf);
4051 str_formspec_escape(control_text);
4054 float ypos = simple_singleplayer_mode ? 0.7f : 0.1f;
4055 std::ostringstream os;
4057 os << FORMSPEC_VERSION_STRING << SIZE_TAG
4058 << "button_exit[4," << (ypos++) << ";3,0.5;btn_continue;"
4059 << strgettext("Continue") << "]";
4061 if (!simple_singleplayer_mode) {
4062 os << "button_exit[4," << (ypos++) << ";3,0.5;btn_change_password;"
4063 << strgettext("Change Password") << "]";
4065 os << "field[4.95,0;5,1.5;;" << strgettext("Game paused") << ";]";
4069 os << "button_exit[4," << (ypos++) << ";3,0.5;btn_sound;"
4070 << strgettext("Sound Volume") << "]";
4071 os << "button_exit[4," << (ypos++) << ";3,0.5;btn_key_config;"
4072 << strgettext("Change Keys") << "]";
4074 os << "button_exit[4," << (ypos++) << ";3,0.5;btn_exit_menu;"
4075 << strgettext("Exit to Menu") << "]";
4076 os << "button_exit[4," << (ypos++) << ";3,0.5;btn_exit_os;"
4077 << strgettext("Exit to OS") << "]"
4078 << "textarea[7.5,0.25;3.9,6.25;;" << control_text << ";]"
4079 << "textarea[0.4,0.25;3.9,6.25;;" << PROJECT_NAME_C " " VERSION_STRING "\n"
4081 << strgettext("Game info:") << "\n";
4082 const std::string &address = client->getAddressName();
4083 static const std::string mode = strgettext("- Mode: ");
4084 if (!simple_singleplayer_mode) {
4085 Address serverAddress = client->getServerAddress();
4086 if (!address.empty()) {
4087 os << mode << strgettext("Remote server") << "\n"
4088 << strgettext("- Address: ") << address;
4090 os << mode << strgettext("Hosting server");
4092 os << "\n" << strgettext("- Port: ") << serverAddress.getPort() << "\n";
4094 os << mode << strgettext("Singleplayer") << "\n";
4096 if (simple_singleplayer_mode || address.empty()) {
4097 static const std::string on = strgettext("On");
4098 static const std::string off = strgettext("Off");
4099 const std::string &damage = g_settings->getBool("enable_damage") ? on : off;
4100 const std::string &creative = g_settings->getBool("creative_mode") ? on : off;
4101 const std::string &announced = g_settings->getBool("server_announce") ? on : off;
4102 os << strgettext("- Damage: ") << damage << "\n"
4103 << strgettext("- Creative Mode: ") << creative << "\n";
4104 if (!simple_singleplayer_mode) {
4105 const std::string &pvp = g_settings->getBool("enable_pvp") ? on : off;
4106 os << strgettext("- PvP: ") << pvp << "\n"
4107 << strgettext("- Public: ") << announced << "\n";
4108 std::string server_name = g_settings->get("server_name");
4109 str_formspec_escape(server_name);
4110 if (announced == on && !server_name.empty())
4111 os << strgettext("- Server Name: ") << server_name;
4118 /* Note: FormspecFormSource and LocalFormspecHandler *
4119 * are deleted by guiFormSpecMenu */
4120 FormspecFormSource *fs_src = new FormspecFormSource(os.str());
4121 LocalFormspecHandler *txt_dst = new LocalFormspecHandler("MT_PAUSE_MENU");
4123 GUIFormSpecMenu::create(current_formspec, client, &input->joystick,
4124 fs_src, txt_dst, client->getFormspecPrepend());
4125 current_formspec->setFocus("btn_continue");
4126 current_formspec->doPause = true;
4129 /****************************************************************************/
4130 /****************************************************************************
4131 extern function for launching the game
4132 ****************************************************************************/
4133 /****************************************************************************/
4135 void the_game(bool *kill,
4137 InputHandler *input,
4138 const std::string &map_dir,
4139 const std::string &playername,
4140 const std::string &password,
4141 const std::string &address, // If empty local server is created
4144 std::string &error_message,
4145 ChatBackend &chat_backend,
4146 bool *reconnect_requested,
4147 const SubgameSpec &gamespec, // Used for local game
4148 bool simple_singleplayer_mode)
4152 /* Make a copy of the server address because if a local singleplayer server
4153 * is created then this is updated and we don't want to change the value
4154 * passed to us by the calling function
4156 std::string server_address = address;
4160 if (game.startup(kill, random_input, input, map_dir,
4161 playername, password, &server_address, port, error_message,
4162 reconnect_requested, &chat_backend, gamespec,
4163 simple_singleplayer_mode)) {
4168 } catch (SerializationError &e) {
4169 error_message = std::string("A serialization error occurred:\n")
4170 + e.what() + "\n\nThe server is probably "
4171 " running a different version of " PROJECT_NAME_C ".";
4172 errorstream << error_message << std::endl;
4173 } catch (ServerError &e) {
4174 error_message = e.what();
4175 errorstream << "ServerError: " << error_message << std::endl;
4176 } catch (ModError &e) {
4177 error_message = e.what() + strgettext("\nCheck debug.txt for details.");
4178 errorstream << "ModError: " << error_message << std::endl;