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/inputhandler.h"
29 #include "client/tile.h" // For TextureSource
30 #include "client/keys.h"
31 #include "client/joystick_controller.h"
32 #include "clientmap.h"
35 #include "content_cao.h"
36 #include "event_manager.h"
37 #include "fontengine.h"
42 #include "gui/guiChatConsole.h"
43 #include "gui/guiFormSpecMenu.h"
44 #include "gui/guiKeyChangeMenu.h"
45 #include "gui/guiPasswordChange.h"
46 #include "gui/guiVolumeChange.h"
47 #include "gui/mainmenumanager.h"
50 #include "nodedef.h" // Needed for determining pointing to nodes
51 #include "nodemetadata.h"
52 #include "particles.h"
54 #include "quicktune_shortcutter.h"
62 #include "translation.h"
63 #include "util/basic_macros.h"
64 #include "util/directiontables.h"
65 #include "util/pointedthing.h"
66 #include "irrlicht_changes/static_text.h"
68 #include "script/scripting_client.h"
71 #include "sound_openal.h"
79 struct TextDestNodeMetadata : public TextDest
81 TextDestNodeMetadata(v3s16 p, Client *client)
86 // This is deprecated I guess? -celeron55
87 void gotText(const std::wstring &text)
89 std::string ntext = wide_to_utf8(text);
90 infostream << "Submitting 'text' field of node at (" << m_p.X << ","
91 << m_p.Y << "," << m_p.Z << "): " << ntext << std::endl;
93 fields["text"] = ntext;
94 m_client->sendNodemetaFields(m_p, "", fields);
96 void gotText(const StringMap &fields)
98 m_client->sendNodemetaFields(m_p, "", fields);
105 struct TextDestPlayerInventory : public TextDest
107 TextDestPlayerInventory(Client *client)
112 TextDestPlayerInventory(Client *client, const std::string &formname)
115 m_formname = formname;
117 void gotText(const StringMap &fields)
119 m_client->sendInventoryFields(m_formname, fields);
125 struct LocalFormspecHandler : public TextDest
127 LocalFormspecHandler(const std::string &formname)
129 m_formname = formname;
132 LocalFormspecHandler(const std::string &formname, Client *client):
135 m_formname = formname;
138 void gotText(const StringMap &fields)
140 if (m_formname == "MT_PAUSE_MENU") {
141 if (fields.find("btn_sound") != fields.end()) {
142 g_gamecallback->changeVolume();
146 if (fields.find("btn_key_config") != fields.end()) {
147 g_gamecallback->keyConfig();
151 if (fields.find("btn_exit_menu") != fields.end()) {
152 g_gamecallback->disconnect();
156 if (fields.find("btn_exit_os") != fields.end()) {
157 g_gamecallback->exitToOS();
159 RenderingEngine::get_raw_device()->closeDevice();
164 if (fields.find("btn_change_password") != fields.end()) {
165 g_gamecallback->changePassword();
169 if (fields.find("quit") != fields.end()) {
173 if (fields.find("btn_continue") != fields.end()) {
178 // Don't disable this part when modding is disabled, it's used in builtin
179 if (m_client && m_client->getScript())
180 m_client->getScript()->on_formspec_input(m_formname, fields);
183 Client *m_client = nullptr;
186 /* Form update callback */
188 static const std::string empty_string = "";
189 class NodeMetadataFormSource: public IFormSource
192 NodeMetadataFormSource(ClientMap *map, v3s16 p):
197 const std::string &getForm() const
199 NodeMetadata *meta = m_map->getNodeMetadata(m_p);
204 return meta->getString("formspec");
207 virtual std::string resolveText(const std::string &str)
209 NodeMetadata *meta = m_map->getNodeMetadata(m_p);
214 return meta->resolveString(str);
221 class PlayerInventoryFormSource: public IFormSource
224 PlayerInventoryFormSource(Client *client):
229 const std::string &getForm() const
231 LocalPlayer *player = m_client->getEnv().getLocalPlayer();
232 return player->inventory_formspec;
238 /* Profiler display */
240 void update_profiler_gui(gui::IGUIStaticText *guitext_profiler, FontEngine *fe,
241 u32 show_profiler, u32 show_profiler_max, s32 screen_height)
243 if (show_profiler == 0) {
244 guitext_profiler->setVisible(false);
247 std::ostringstream os(std::ios_base::binary);
248 g_profiler->printPage(os, show_profiler, show_profiler_max);
249 std::wstring text = translate_string(utf8_to_wide(os.str()));
250 setStaticText(guitext_profiler, text.c_str());
251 guitext_profiler->setVisible(true);
253 s32 w = fe->getTextWidth(text);
258 unsigned text_height = fe->getTextHeight();
260 core::position2di upper_left, lower_right;
263 upper_left.Y = (text_height + 5) * 2;
264 lower_right.X = 12 + w;
265 lower_right.Y = upper_left.Y + (text_height + 1) * MAX_PROFILER_TEXT_ROWS;
267 if (lower_right.Y > screen_height * 2 / 3)
268 lower_right.Y = screen_height * 2 / 3;
270 core::rect<s32> rect(upper_left, lower_right);
272 guitext_profiler->setRelativePosition(rect);
273 guitext_profiler->setVisible(true);
281 Profiler::GraphValues values;
287 Meta(float initial = 0,
288 video::SColor color = video::SColor(255, 255, 255, 255)):
294 std::deque<Piece> m_log;
296 u32 m_log_max_size = 200;
298 ProfilerGraph() = default;
300 void put(const Profiler::GraphValues &values)
303 piece.values = values;
304 m_log.push_back(piece);
306 while (m_log.size() > m_log_max_size)
307 m_log.erase(m_log.begin());
310 void draw(s32 x_left, s32 y_bottom, video::IVideoDriver *driver,
311 gui::IGUIFont *font) const
313 // Do *not* use UNORDERED_MAP here as the order needs
314 // to be the same for each call to prevent flickering
315 std::map<std::string, Meta> m_meta;
317 for (const Piece &piece : m_log) {
318 for (const auto &i : piece.values) {
319 const std::string &id = i.first;
320 const float &value = i.second;
321 std::map<std::string, Meta>::iterator j = m_meta.find(id);
323 if (j == m_meta.end()) {
324 m_meta[id] = Meta(value);
328 if (value < j->second.min)
329 j->second.min = value;
331 if (value > j->second.max)
332 j->second.max = value;
337 static const video::SColor usable_colors[] = {
338 video::SColor(255, 255, 100, 100),
339 video::SColor(255, 90, 225, 90),
340 video::SColor(255, 100, 100, 255),
341 video::SColor(255, 255, 150, 50),
342 video::SColor(255, 220, 220, 100)
344 static const u32 usable_colors_count =
345 sizeof(usable_colors) / sizeof(*usable_colors);
346 u32 next_color_i = 0;
348 for (auto &i : m_meta) {
349 Meta &meta = i.second;
350 video::SColor color(255, 200, 200, 200);
352 if (next_color_i < usable_colors_count)
353 color = usable_colors[next_color_i++];
359 s32 textx = x_left + m_log_max_size + 15;
360 s32 textx2 = textx + 200 - 15;
363 for (std::map<std::string, Meta>::const_iterator i = m_meta.begin();
364 i != m_meta.end(); ++i) {
365 const std::string &id = i->first;
366 const Meta &meta = i->second;
368 s32 y = y_bottom - meta_i * 50;
369 float show_min = meta.min;
370 float show_max = meta.max;
372 if (show_min >= -0.0001 && show_max >= -0.0001) {
373 if (show_min <= show_max * 0.5)
379 snprintf(buf, 10, "%.3g", show_max);
380 font->draw(utf8_to_wide(buf).c_str(),
381 core::rect<s32>(textx, y - graphh,
382 textx2, y - graphh + texth),
384 snprintf(buf, 10, "%.3g", show_min);
385 font->draw(utf8_to_wide(buf).c_str(),
386 core::rect<s32>(textx, y - texth,
389 font->draw(utf8_to_wide(id).c_str(),
390 core::rect<s32>(textx, y - graphh / 2 - texth / 2,
391 textx2, y - graphh / 2 + texth / 2),
394 s32 graph1h = graphh;
395 bool relativegraph = (show_min != 0 && show_min != show_max);
396 float lastscaledvalue = 0.0;
397 bool lastscaledvalue_exists = false;
399 for (const Piece &piece : m_log) {
401 bool value_exists = false;
402 Profiler::GraphValues::const_iterator k =
403 piece.values.find(id);
405 if (k != piece.values.end()) {
412 lastscaledvalue_exists = false;
416 float scaledvalue = 1.0;
418 if (show_max != show_min)
419 scaledvalue = (value - show_min) / (show_max - show_min);
421 if (scaledvalue == 1.0 && value == 0) {
423 lastscaledvalue_exists = false;
428 if (lastscaledvalue_exists) {
429 s32 ivalue1 = lastscaledvalue * graph1h;
430 s32 ivalue2 = scaledvalue * graph1h;
431 driver->draw2DLine(v2s32(x - 1, graph1y - ivalue1),
432 v2s32(x, graph1y - ivalue2), meta.color);
435 lastscaledvalue = scaledvalue;
436 lastscaledvalue_exists = true;
438 s32 ivalue = scaledvalue * graph1h;
439 driver->draw2DLine(v2s32(x, graph1y),
440 v2s32(x, graph1y - ivalue), meta.color);
451 class NodeDugEvent: public MtEvent
457 NodeDugEvent(v3s16 p, MapNode n):
461 const char *getType() const
469 ISoundManager *m_sound;
470 INodeDefManager *m_ndef;
472 bool makes_footstep_sound;
473 float m_player_step_timer;
475 SimpleSoundSpec m_player_step_sound;
476 SimpleSoundSpec m_player_leftpunch_sound;
477 SimpleSoundSpec m_player_rightpunch_sound;
479 SoundMaker(ISoundManager *sound, INodeDefManager *ndef):
482 makes_footstep_sound(true),
483 m_player_step_timer(0)
487 void playPlayerStep()
489 if (m_player_step_timer <= 0 && m_player_step_sound.exists()) {
490 m_player_step_timer = 0.03;
491 if (makes_footstep_sound)
492 m_sound->playSound(m_player_step_sound, false);
496 static void viewBobbingStep(MtEvent *e, void *data)
498 SoundMaker *sm = (SoundMaker *)data;
499 sm->playPlayerStep();
502 static void playerRegainGround(MtEvent *e, void *data)
504 SoundMaker *sm = (SoundMaker *)data;
505 sm->playPlayerStep();
508 static void playerJump(MtEvent *e, void *data)
510 //SoundMaker *sm = (SoundMaker*)data;
513 static void cameraPunchLeft(MtEvent *e, void *data)
515 SoundMaker *sm = (SoundMaker *)data;
516 sm->m_sound->playSound(sm->m_player_leftpunch_sound, false);
519 static void cameraPunchRight(MtEvent *e, void *data)
521 SoundMaker *sm = (SoundMaker *)data;
522 sm->m_sound->playSound(sm->m_player_rightpunch_sound, false);
525 static void nodeDug(MtEvent *e, void *data)
527 SoundMaker *sm = (SoundMaker *)data;
528 NodeDugEvent *nde = (NodeDugEvent *)e;
529 sm->m_sound->playSound(sm->m_ndef->get(nde->n).sound_dug, false);
532 static void playerDamage(MtEvent *e, void *data)
534 SoundMaker *sm = (SoundMaker *)data;
535 sm->m_sound->playSound(SimpleSoundSpec("player_damage", 0.5), false);
538 static void playerFallingDamage(MtEvent *e, void *data)
540 SoundMaker *sm = (SoundMaker *)data;
541 sm->m_sound->playSound(SimpleSoundSpec("player_falling_damage", 0.5), false);
544 void registerReceiver(MtEventManager *mgr)
546 mgr->reg("ViewBobbingStep", SoundMaker::viewBobbingStep, this);
547 mgr->reg("PlayerRegainGround", SoundMaker::playerRegainGround, this);
548 mgr->reg("PlayerJump", SoundMaker::playerJump, this);
549 mgr->reg("CameraPunchLeft", SoundMaker::cameraPunchLeft, this);
550 mgr->reg("CameraPunchRight", SoundMaker::cameraPunchRight, this);
551 mgr->reg("NodeDug", SoundMaker::nodeDug, this);
552 mgr->reg("PlayerDamage", SoundMaker::playerDamage, this);
553 mgr->reg("PlayerFallingDamage", SoundMaker::playerFallingDamage, this);
556 void step(float dtime)
558 m_player_step_timer -= dtime;
562 // Locally stored sounds don't need to be preloaded because of this
563 class GameOnDemandSoundFetcher: public OnDemandSoundFetcher
565 std::set<std::string> m_fetched;
567 void paths_insert(std::set<std::string> &dst_paths,
568 const std::string &base,
569 const std::string &name)
571 dst_paths.insert(base + DIR_DELIM + "sounds" + DIR_DELIM + name + ".ogg");
572 dst_paths.insert(base + DIR_DELIM + "sounds" + DIR_DELIM + name + ".0.ogg");
573 dst_paths.insert(base + DIR_DELIM + "sounds" + DIR_DELIM + name + ".1.ogg");
574 dst_paths.insert(base + DIR_DELIM + "sounds" + DIR_DELIM + name + ".2.ogg");
575 dst_paths.insert(base + DIR_DELIM + "sounds" + DIR_DELIM + name + ".3.ogg");
576 dst_paths.insert(base + DIR_DELIM + "sounds" + DIR_DELIM + name + ".4.ogg");
577 dst_paths.insert(base + DIR_DELIM + "sounds" + DIR_DELIM + name + ".5.ogg");
578 dst_paths.insert(base + DIR_DELIM + "sounds" + DIR_DELIM + name + ".6.ogg");
579 dst_paths.insert(base + DIR_DELIM + "sounds" + DIR_DELIM + name + ".7.ogg");
580 dst_paths.insert(base + DIR_DELIM + "sounds" + DIR_DELIM + name + ".8.ogg");
581 dst_paths.insert(base + DIR_DELIM + "sounds" + DIR_DELIM + name + ".9.ogg");
584 void fetchSounds(const std::string &name,
585 std::set<std::string> &dst_paths,
586 std::set<std::string> &dst_datas)
588 if (m_fetched.count(name))
591 m_fetched.insert(name);
593 paths_insert(dst_paths, porting::path_share, name);
594 paths_insert(dst_paths, porting::path_user, name);
599 // before 1.8 there isn't a "integer interface", only float
600 #if (IRRLICHT_VERSION_MAJOR == 1 && IRRLICHT_VERSION_MINOR < 8)
601 typedef f32 SamplerLayer_t;
603 typedef s32 SamplerLayer_t;
607 class GameGlobalShaderConstantSetter : public IShaderConstantSetter
610 bool *m_force_fog_off;
613 CachedPixelShaderSetting<float, 4> m_sky_bg_color;
614 CachedPixelShaderSetting<float> m_fog_distance;
615 CachedVertexShaderSetting<float> m_animation_timer_vertex;
616 CachedPixelShaderSetting<float> m_animation_timer_pixel;
617 CachedPixelShaderSetting<float, 3> m_day_light;
618 CachedPixelShaderSetting<float, 3> m_eye_position_pixel;
619 CachedVertexShaderSetting<float, 3> m_eye_position_vertex;
620 CachedPixelShaderSetting<float, 3> m_minimap_yaw;
621 CachedPixelShaderSetting<SamplerLayer_t> m_base_texture;
622 CachedPixelShaderSetting<SamplerLayer_t> m_normal_texture;
623 CachedPixelShaderSetting<SamplerLayer_t> m_texture_flags;
627 void onSettingsChange(const std::string &name)
629 if (name == "enable_fog")
630 m_fog_enabled = g_settings->getBool("enable_fog");
633 static void settingsCallback(const std::string &name, void *userdata)
635 reinterpret_cast<GameGlobalShaderConstantSetter*>(userdata)->onSettingsChange(name);
638 void setSky(Sky *sky) { m_sky = sky; }
640 GameGlobalShaderConstantSetter(Sky *sky, bool *force_fog_off,
641 f32 *fog_range, Client *client) :
643 m_force_fog_off(force_fog_off),
644 m_fog_range(fog_range),
645 m_sky_bg_color("skyBgColor"),
646 m_fog_distance("fogDistance"),
647 m_animation_timer_vertex("animationTimer"),
648 m_animation_timer_pixel("animationTimer"),
649 m_day_light("dayLight"),
650 m_eye_position_pixel("eyePosition"),
651 m_eye_position_vertex("eyePosition"),
652 m_minimap_yaw("yawVec"),
653 m_base_texture("baseTexture"),
654 m_normal_texture("normalTexture"),
655 m_texture_flags("textureFlags"),
658 g_settings->registerChangedCallback("enable_fog", settingsCallback, this);
659 m_fog_enabled = g_settings->getBool("enable_fog");
662 ~GameGlobalShaderConstantSetter()
664 g_settings->deregisterChangedCallback("enable_fog", settingsCallback, this);
667 virtual void onSetConstants(video::IMaterialRendererServices *services,
674 video::SColor bgcolor = m_sky->getBgColor();
675 video::SColorf bgcolorf(bgcolor);
676 float bgcolorfa[4] = {
682 m_sky_bg_color.set(bgcolorfa, services);
685 float fog_distance = 10000 * BS;
687 if (m_fog_enabled && !*m_force_fog_off)
688 fog_distance = *m_fog_range;
690 m_fog_distance.set(&fog_distance, services);
692 u32 daynight_ratio = (float)m_client->getEnv().getDayNightRatio();
693 video::SColorf sunlight;
694 get_sunlight_color(&sunlight, daynight_ratio);
699 m_day_light.set(dnc, services);
701 u32 animation_timer = porting::getTimeMs() % 100000;
702 float animation_timer_f = (float)animation_timer / 100000.f;
703 m_animation_timer_vertex.set(&animation_timer_f, services);
704 m_animation_timer_pixel.set(&animation_timer_f, services);
706 float eye_position_array[3];
707 v3f epos = m_client->getEnv().getLocalPlayer()->getEyePosition();
708 #if (IRRLICHT_VERSION_MAJOR == 1 && IRRLICHT_VERSION_MINOR < 8)
709 eye_position_array[0] = epos.X;
710 eye_position_array[1] = epos.Y;
711 eye_position_array[2] = epos.Z;
713 epos.getAs3Values(eye_position_array);
715 m_eye_position_pixel.set(eye_position_array, services);
716 m_eye_position_vertex.set(eye_position_array, services);
718 if (m_client->getMinimap()) {
719 float minimap_yaw_array[3];
720 v3f minimap_yaw = m_client->getMinimap()->getYawVec();
721 #if (IRRLICHT_VERSION_MAJOR == 1 && IRRLICHT_VERSION_MINOR < 8)
722 minimap_yaw_array[0] = minimap_yaw.X;
723 minimap_yaw_array[1] = minimap_yaw.Y;
724 minimap_yaw_array[2] = minimap_yaw.Z;
726 minimap_yaw.getAs3Values(minimap_yaw_array);
728 m_minimap_yaw.set(minimap_yaw_array, services);
731 SamplerLayer_t base_tex = 0,
734 m_base_texture.set(&base_tex, services);
735 m_normal_texture.set(&normal_tex, services);
736 m_texture_flags.set(&flags_tex, services);
741 class GameGlobalShaderConstantSetterFactory : public IShaderConstantSetterFactory
744 bool *m_force_fog_off;
747 std::vector<GameGlobalShaderConstantSetter *> created_nosky;
749 GameGlobalShaderConstantSetterFactory(bool *force_fog_off,
750 f32 *fog_range, Client *client) :
752 m_force_fog_off(force_fog_off),
753 m_fog_range(fog_range),
757 void setSky(Sky *sky) {
759 for (GameGlobalShaderConstantSetter *ggscs : created_nosky) {
760 ggscs->setSky(m_sky);
762 created_nosky.clear();
765 virtual IShaderConstantSetter* create()
767 GameGlobalShaderConstantSetter *scs = new GameGlobalShaderConstantSetter(
768 m_sky, m_force_fog_off, m_fog_range, m_client);
770 created_nosky.push_back(scs);
776 bool nodePlacementPrediction(Client &client, const ItemDefinition &playeritem_def,
777 const ItemStack &playeritem, v3s16 nodepos, v3s16 neighbourpos)
779 std::string prediction = playeritem_def.node_placement_prediction;
780 INodeDefManager *nodedef = client.ndef();
781 ClientMap &map = client.getEnv().getClientMap();
783 bool is_valid_position;
785 node = map.getNodeNoEx(nodepos, &is_valid_position);
786 if (!is_valid_position)
789 if (!prediction.empty() && !nodedef->get(node).rightclickable) {
790 verbosestream << "Node placement prediction for "
791 << playeritem_def.name << " is "
792 << prediction << std::endl;
793 v3s16 p = neighbourpos;
795 // Place inside node itself if buildable_to
796 MapNode n_under = map.getNodeNoEx(nodepos, &is_valid_position);
797 if (is_valid_position)
799 if (nodedef->get(n_under).buildable_to)
802 node = map.getNodeNoEx(p, &is_valid_position);
803 if (is_valid_position &&!nodedef->get(node).buildable_to)
808 // Find id of predicted node
810 bool found = nodedef->getId(prediction, id);
813 errorstream << "Node placement prediction failed for "
814 << playeritem_def.name << " (places "
816 << ") - Name not known" << std::endl;
820 const ContentFeatures &predicted_f = nodedef->get(id);
822 // Predict param2 for facedir and wallmounted nodes
825 if (predicted_f.param_type_2 == CPT2_WALLMOUNTED ||
826 predicted_f.param_type_2 == CPT2_COLORED_WALLMOUNTED) {
827 v3s16 dir = nodepos - neighbourpos;
829 if (abs(dir.Y) > MYMAX(abs(dir.X), abs(dir.Z))) {
830 param2 = dir.Y < 0 ? 1 : 0;
831 } else if (abs(dir.X) > abs(dir.Z)) {
832 param2 = dir.X < 0 ? 3 : 2;
834 param2 = dir.Z < 0 ? 5 : 4;
838 if (predicted_f.param_type_2 == CPT2_FACEDIR ||
839 predicted_f.param_type_2 == CPT2_COLORED_FACEDIR) {
840 v3s16 dir = nodepos - floatToInt(client.getEnv().getLocalPlayer()->getPosition(), BS);
842 if (abs(dir.X) > abs(dir.Z)) {
843 param2 = dir.X < 0 ? 3 : 1;
845 param2 = dir.Z < 0 ? 2 : 0;
851 //Check attachment if node is in group attached_node
852 if (((ItemGroupList) predicted_f.groups)["attached_node"] != 0) {
853 static v3s16 wallmounted_dirs[8] = {
863 if (predicted_f.param_type_2 == CPT2_WALLMOUNTED ||
864 predicted_f.param_type_2 == CPT2_COLORED_WALLMOUNTED)
865 pp = p + wallmounted_dirs[param2];
867 pp = p + v3s16(0, -1, 0);
869 if (!nodedef->get(map.getNodeNoEx(pp)).walkable)
874 if ((predicted_f.param_type_2 == CPT2_COLOR
875 || predicted_f.param_type_2 == CPT2_COLORED_FACEDIR
876 || predicted_f.param_type_2 == CPT2_COLORED_WALLMOUNTED)) {
877 const std::string &indexstr = playeritem.metadata.getString(
879 if (!indexstr.empty()) {
880 s32 index = mystoi(indexstr);
881 if (predicted_f.param_type_2 == CPT2_COLOR) {
883 } else if (predicted_f.param_type_2
884 == CPT2_COLORED_WALLMOUNTED) {
885 // param2 = pure palette index + other
886 param2 = (index & 0xf8) | (param2 & 0x07);
887 } else if (predicted_f.param_type_2
888 == CPT2_COLORED_FACEDIR) {
889 // param2 = pure palette index + other
890 param2 = (index & 0xe0) | (param2 & 0x1f);
895 // Add node to client map
896 MapNode n(id, 0, param2);
899 LocalPlayer *player = client.getEnv().getLocalPlayer();
901 // Dont place node when player would be inside new node
902 // NOTE: This is to be eventually implemented by a mod as client-side Lua
903 if (!nodedef->get(n).walkable ||
904 g_settings->getBool("enable_build_where_you_stand") ||
905 (client.checkPrivilege("noclip") && g_settings->getBool("noclip")) ||
906 (nodedef->get(n).walkable &&
907 neighbourpos != player->getStandingNodePos() + v3s16(0, 1, 0) &&
908 neighbourpos != player->getStandingNodePos() + v3s16(0, 2, 0))) {
910 // This triggers the required mesh update too
911 client.addNode(p, n);
914 } catch (InvalidPositionException &e) {
915 errorstream << "Node placement prediction failed for "
916 << playeritem_def.name << " (places "
918 << ") - Position not loaded" << std::endl;
925 static inline void create_formspec_menu(GUIFormSpecMenu **cur_formspec,
926 Client *client, JoystickController *joystick,
927 IFormSource *fs_src, TextDest *txt_dest)
930 if (*cur_formspec == 0) {
931 *cur_formspec = new GUIFormSpecMenu(joystick, guiroot, -1, &g_menumgr,
932 client, client->getTextureSource(), fs_src, txt_dest);
933 (*cur_formspec)->doPause = false;
936 Caution: do not call (*cur_formspec)->drop() here --
937 the reference might outlive the menu, so we will
938 periodically check if *cur_formspec is the only
939 remaining reference (i.e. the menu was removed)
940 and delete it in that case.
944 (*cur_formspec)->setFormSource(fs_src);
945 (*cur_formspec)->setTextDest(txt_dest);
951 #define SIZE_TAG "size[11,5.5]"
953 #define SIZE_TAG "size[11,5.5,true]" // Fixed size on desktop
956 /******************************************************************************/
957 static void updateChat(Client &client, f32 dtime, bool show_debug,
958 const v2u32 &screensize, bool show_chat, u32 show_profiler,
959 ChatBackend &chat_backend, gui::IGUIStaticText *guitext_chat)
961 // Add chat log output for errors to be shown in chat
962 static LogOutputBuffer chat_log_error_buf(g_logger, LL_ERROR);
964 // Get new messages from error log buffer
965 while (!chat_log_error_buf.empty()) {
966 std::wstring error_message = utf8_to_wide(chat_log_error_buf.get());
967 if (!g_settings->getBool("disable_escape_sequences")) {
968 error_message = L"\x1b(c@red)" + error_message + L"\x1b(c@white)";
970 chat_backend.addMessage(L"", error_message);
973 // Get new messages from client
974 std::wstring message;
975 while (client.getChatMessage(message)) {
976 chat_backend.addUnparsedMessage(message);
979 // Remove old messages
980 chat_backend.step(dtime);
982 // Display all messages in a static text element
983 unsigned int recent_chat_count = chat_backend.getRecentBuffer().getLineCount();
984 EnrichedString recent_chat = chat_backend.getRecentChat();
985 unsigned int line_height = g_fontengine->getLineHeight();
987 setStaticText(guitext_chat, recent_chat);
989 // Update gui element size and position
993 chat_y += 2 * line_height;
995 // first pass to calculate height of text to be set
996 const v2u32 &window_size = RenderingEngine::get_instance()->getWindowSize();
997 s32 width = std::min(g_fontengine->getTextWidth(recent_chat.c_str()) + 10,
999 core::rect<s32> rect(10, chat_y, width, chat_y + window_size.Y);
1000 guitext_chat->setRelativePosition(rect);
1002 //now use real height of text and adjust rect according to this size
1003 rect = core::rect<s32>(10, chat_y, width,
1004 chat_y + guitext_chat->getTextHeight());
1007 guitext_chat->setRelativePosition(rect);
1008 // Don't show chat if disabled or empty or profiler is enabled
1009 guitext_chat->setVisible(
1010 show_chat && recent_chat_count != 0 && !show_profiler);
1014 /****************************************************************************
1015 Fast key cache for main game loop
1016 ****************************************************************************/
1018 /* This is faster than using getKeySetting with the tradeoff that functions
1019 * using it must make sure that it's initialised before using it and there is
1020 * no error handling (for example bounds checking). This is really intended for
1021 * use only in the main running loop of the client (the_game()) where the faster
1022 * (up to 10x faster) key lookup is an asset. Other parts of the codebase
1023 * (e.g. formspecs) should continue using getKeySetting().
1031 populate_nonchanging();
1036 // Keys that are not settings dependent
1037 void populate_nonchanging();
1039 KeyPress key[KeyType::INTERNAL_ENUM_COUNT];
1040 InputHandler *handler;
1043 void KeyCache::populate_nonchanging()
1045 key[KeyType::ESC] = EscapeKey;
1048 void KeyCache::populate()
1050 key[KeyType::FORWARD] = getKeySetting("keymap_forward");
1051 key[KeyType::BACKWARD] = getKeySetting("keymap_backward");
1052 key[KeyType::LEFT] = getKeySetting("keymap_left");
1053 key[KeyType::RIGHT] = getKeySetting("keymap_right");
1054 key[KeyType::JUMP] = getKeySetting("keymap_jump");
1055 key[KeyType::SPECIAL1] = getKeySetting("keymap_special1");
1056 key[KeyType::SNEAK] = getKeySetting("keymap_sneak");
1058 key[KeyType::AUTOFORWARD] = getKeySetting("keymap_autoforward");
1060 key[KeyType::DROP] = getKeySetting("keymap_drop");
1061 key[KeyType::INVENTORY] = getKeySetting("keymap_inventory");
1062 key[KeyType::CHAT] = getKeySetting("keymap_chat");
1063 key[KeyType::CMD] = getKeySetting("keymap_cmd");
1064 key[KeyType::CMD_LOCAL] = getKeySetting("keymap_cmd_local");
1065 key[KeyType::CONSOLE] = getKeySetting("keymap_console");
1066 key[KeyType::MINIMAP] = getKeySetting("keymap_minimap");
1067 key[KeyType::FREEMOVE] = getKeySetting("keymap_freemove");
1068 key[KeyType::FASTMOVE] = getKeySetting("keymap_fastmove");
1069 key[KeyType::NOCLIP] = getKeySetting("keymap_noclip");
1070 key[KeyType::HOTBAR_PREV] = getKeySetting("keymap_hotbar_previous");
1071 key[KeyType::HOTBAR_NEXT] = getKeySetting("keymap_hotbar_next");
1072 key[KeyType::MUTE] = getKeySetting("keymap_mute");
1073 key[KeyType::INC_VOLUME] = getKeySetting("keymap_increase_volume");
1074 key[KeyType::DEC_VOLUME] = getKeySetting("keymap_decrease_volume");
1075 key[KeyType::CINEMATIC] = getKeySetting("keymap_cinematic");
1076 key[KeyType::SCREENSHOT] = getKeySetting("keymap_screenshot");
1077 key[KeyType::TOGGLE_HUD] = getKeySetting("keymap_toggle_hud");
1078 key[KeyType::TOGGLE_CHAT] = getKeySetting("keymap_toggle_chat");
1079 key[KeyType::TOGGLE_FORCE_FOG_OFF]
1080 = getKeySetting("keymap_toggle_force_fog_off");
1081 key[KeyType::TOGGLE_UPDATE_CAMERA]
1082 = getKeySetting("keymap_toggle_update_camera");
1083 key[KeyType::TOGGLE_DEBUG]
1084 = getKeySetting("keymap_toggle_debug");
1085 key[KeyType::TOGGLE_PROFILER]
1086 = getKeySetting("keymap_toggle_profiler");
1087 key[KeyType::CAMERA_MODE]
1088 = getKeySetting("keymap_camera_mode");
1089 key[KeyType::INCREASE_VIEWING_RANGE]
1090 = getKeySetting("keymap_increase_viewing_range_min");
1091 key[KeyType::DECREASE_VIEWING_RANGE]
1092 = getKeySetting("keymap_decrease_viewing_range_min");
1093 key[KeyType::RANGESELECT]
1094 = getKeySetting("keymap_rangeselect");
1095 key[KeyType::ZOOM] = getKeySetting("keymap_zoom");
1097 key[KeyType::QUICKTUNE_NEXT] = getKeySetting("keymap_quicktune_next");
1098 key[KeyType::QUICKTUNE_PREV] = getKeySetting("keymap_quicktune_prev");
1099 key[KeyType::QUICKTUNE_INC] = getKeySetting("keymap_quicktune_inc");
1100 key[KeyType::QUICKTUNE_DEC] = getKeySetting("keymap_quicktune_dec");
1102 for (int i = 0; i < 23; i++) {
1103 std::string slot_key_name = "keymap_slot" + std::to_string(i + 1);
1104 key[KeyType::SLOT_1 + i] = getKeySetting(slot_key_name.c_str());
1108 // First clear all keys, then re-add the ones we listen for
1109 handler->dontListenForKeys();
1110 for (const KeyPress &k : key) {
1111 handler->listenForKey(k);
1113 handler->listenForKey(EscapeKey);
1114 handler->listenForKey(CancelKey);
1119 /****************************************************************************
1121 ****************************************************************************/
1123 const float object_hit_delay = 0.2;
1126 u32 last_time, busy_time, sleep_time;
1130 /* The reason the following structs are not anonymous structs within the
1131 * class is that they are not used by the majority of member functions and
1132 * many functions that do require objects of thse types do not modify them
1133 * (so they can be passed as a const qualified parameter)
1135 struct CameraOrientation {
1136 f32 camera_yaw; // "right/left"
1137 f32 camera_pitch; // "up/down"
1140 struct GameRunData {
1143 PointedThing pointed_old;
1147 bool digging_blocked;
1149 bool update_wielded_item_trigger;
1150 bool reset_jump_timer;
1151 float nodig_delay_timer;
1153 float dig_time_complete;
1154 float repeat_rightclick_timer;
1155 float object_hit_delay_timer;
1156 float time_from_last_punch;
1157 ClientActiveObject *selected_object;
1161 float update_draw_list_timer;
1162 float statustext_time;
1166 v3f update_draw_list_last_cam_dir;
1168 u32 profiler_current_page;
1169 u32 profiler_max_page; // Number of pages
1172 float time_of_day_smooth;
1176 f32 max, min, avg, counter, max_sample, min_sample, max_fraction;
1182 Jitter dtime_jitter, busy_time_jitter;
1187 struct ClientEventHandler
1189 void (Game::*handler)(ClientEvent *, CameraOrientation *);
1192 /****************************************************************************
1194 ****************************************************************************/
1196 /* This is not intended to be a public class. If a public class becomes
1197 * desirable then it may be better to create another 'wrapper' class that
1198 * hides most of the stuff in this class (nothing in this class is required
1199 * by any other file) but exposes the public methods/data only.
1206 bool startup(bool *kill,
1208 InputHandler *input,
1209 const std::string &map_dir,
1210 const std::string &playername,
1211 const std::string &password,
1212 // If address is "", local server is used and address is updated
1213 std::string *address,
1215 std::string &error_message,
1217 ChatBackend *chat_backend,
1218 const SubgameSpec &gamespec, // Used for local game
1219 bool simple_singleplayer_mode);
1226 void extendedResourceCleanup();
1228 // Basic initialisation
1229 bool init(const std::string &map_dir, std::string *address,
1231 const SubgameSpec &gamespec);
1233 bool createSingleplayerServer(const std::string &map_dir,
1234 const SubgameSpec &gamespec, u16 port, std::string *address);
1237 bool createClient(const std::string &playername,
1238 const std::string &password, std::string *address, u16 port);
1241 // Client connection
1242 bool connectToServer(const std::string &playername,
1243 const std::string &password, std::string *address, u16 port,
1244 bool *connect_ok, bool *aborted);
1245 bool getServerContent(bool *aborted);
1249 void updateInteractTimers(f32 dtime);
1250 bool checkConnection();
1251 bool handleCallbacks();
1252 void processQueues();
1253 void updateProfilers(const RunStats &stats, const FpsControl &draw_times, f32 dtime);
1254 void addProfilerGraphs(const RunStats &stats, const FpsControl &draw_times, f32 dtime);
1255 void updateStats(RunStats *stats, const FpsControl &draw_times, f32 dtime);
1258 void processUserInput(f32 dtime);
1259 void processKeyInput();
1260 void processItemSelection(u16 *new_playeritem);
1262 void dropSelectedItem(bool single_item = false);
1263 void openInventory();
1264 void openConsole(float scale, const wchar_t *line=NULL);
1265 void toggleFreeMove();
1266 void toggleFreeMoveAlt();
1268 void toggleNoClip();
1269 void toggleCinematic();
1270 void toggleAutoforward();
1274 void toggleMinimap(bool shift_pressed);
1277 void toggleUpdateCamera();
1278 void toggleProfiler();
1280 void increaseViewRange();
1281 void decreaseViewRange();
1282 void toggleFullViewRange();
1283 void checkZoomEnabled();
1285 void updateCameraDirection(CameraOrientation *cam, float dtime);
1286 void updateCameraOrientation(CameraOrientation *cam, float dtime);
1287 void updatePlayerControl(const CameraOrientation &cam);
1288 void step(f32 *dtime);
1289 void processClientEvents(CameraOrientation *cam);
1290 void updateCamera(u32 busy_time, f32 dtime);
1291 void updateSound(f32 dtime);
1292 void processPlayerInteraction(f32 dtime, bool show_hud, bool show_debug);
1294 * Returns the object or node the player is pointing at.
1295 * Also updates the selected thing in the Hud.
1297 * @param[in] shootline the shootline, starting from
1298 * the camera position. This also gives the maximal distance
1300 * @param[in] liquids_pointable if false, liquids are ignored
1301 * @param[in] look_for_object if false, objects are ignored
1302 * @param[in] camera_offset offset of the camera
1303 * @param[out] selected_object the selected object or
1306 PointedThing updatePointedThing(
1307 const core::line3d<f32> &shootline, bool liquids_pointable,
1308 bool look_for_object, const v3s16 &camera_offset);
1309 void handlePointingAtNothing(const ItemStack &playerItem);
1310 void handlePointingAtNode(const PointedThing &pointed,
1311 const ItemDefinition &playeritem_def, const ItemStack &playeritem,
1312 const ToolCapabilities &playeritem_toolcap, f32 dtime);
1313 void handlePointingAtObject(const PointedThing &pointed, const ItemStack &playeritem,
1314 const v3f &player_position, bool show_debug);
1315 void handleDigging(const PointedThing &pointed, const v3s16 &nodepos,
1316 const ToolCapabilities &playeritem_toolcap, f32 dtime);
1317 void updateFrame(ProfilerGraph *graph, RunStats *stats, f32 dtime,
1318 const CameraOrientation &cam);
1319 void updateGui(const RunStats &stats, f32 dtime, const CameraOrientation &cam);
1320 void updateProfilerGraphs(ProfilerGraph *graph);
1323 void limitFps(FpsControl *fps_timings, f32 *dtime);
1325 void showOverlayMessage(const char *msg, float dtime, int percent,
1326 bool draw_clouds = true);
1327 void showStatusTextSimple(const char *msg);
1329 static void settingChangedCallback(const std::string &setting_name, void *data);
1330 void readSettings();
1332 inline bool getLeftClicked()
1334 return input->getLeftClicked() ||
1335 input->joystick.getWasKeyDown(KeyType::MOUSE_L);
1337 inline bool getRightClicked()
1339 return input->getRightClicked() ||
1340 input->joystick.getWasKeyDown(KeyType::MOUSE_R);
1342 inline bool isLeftPressed()
1344 return input->getLeftState() ||
1345 input->joystick.isKeyDown(KeyType::MOUSE_L);
1347 inline bool isRightPressed()
1349 return input->getRightState() ||
1350 input->joystick.isKeyDown(KeyType::MOUSE_R);
1352 inline bool getLeftReleased()
1354 return input->getLeftReleased() ||
1355 input->joystick.wasKeyReleased(KeyType::MOUSE_L);
1358 inline bool isKeyDown(GameKeyType k)
1360 return input->isKeyDown(keycache.key[k]) || input->joystick.isKeyDown(k);
1362 inline bool wasKeyDown(GameKeyType k)
1364 return input->wasKeyDown(keycache.key[k]) || input->joystick.wasKeyDown(k);
1368 void handleAndroidChatInput();
1372 void showPauseMenu();
1374 // ClientEvent handlers
1375 void handleClientEvent_None(ClientEvent *event, CameraOrientation *cam);
1376 void handleClientEvent_PlayerDamage(ClientEvent *event, CameraOrientation *cam);
1377 void handleClientEvent_PlayerForceMove(ClientEvent *event, CameraOrientation *cam);
1378 void handleClientEvent_Deathscreen(ClientEvent *event, CameraOrientation *cam);
1379 void handleClientEvent_ShowFormSpec(ClientEvent *event, CameraOrientation *cam);
1380 void handleClientEvent_ShowLocalFormSpec(ClientEvent *event, CameraOrientation *cam);
1381 void handleClientEvent_HandleParticleEvent(ClientEvent *event,
1382 CameraOrientation *cam);
1383 void handleClientEvent_HudAdd(ClientEvent *event, CameraOrientation *cam);
1384 void handleClientEvent_HudRemove(ClientEvent *event, CameraOrientation *cam);
1385 void handleClientEvent_HudChange(ClientEvent *event, CameraOrientation *cam);
1386 void handleClientEvent_SetSky(ClientEvent *event, CameraOrientation *cam);
1387 void handleClientEvent_OverrideDayNigthRatio(ClientEvent *event,
1388 CameraOrientation *cam);
1389 void handleClientEvent_CloudParams(ClientEvent *event, CameraOrientation *cam);
1391 static const ClientEventHandler clientEventHandler[CLIENTEVENT_MAX];
1393 InputHandler *input;
1398 IWritableTextureSource *texture_src;
1399 IWritableShaderSource *shader_src;
1401 // When created, these will be filled with data received from the server
1402 IWritableItemDefManager *itemdef_manager;
1403 IWritableNodeDefManager *nodedef_manager;
1405 GameOnDemandSoundFetcher soundfetcher; // useful when testing
1406 ISoundManager *sound;
1407 bool sound_is_dummy = false;
1408 SoundMaker *soundmaker;
1410 ChatBackend *chat_backend;
1412 GUIFormSpecMenu *current_formspec;
1413 //default: "". If other than "", empty show_formspec packets will only close the formspec when the formname matches
1414 std::string cur_formname;
1416 EventManager *eventmgr;
1417 QuicktuneShortcutter *quicktune;
1419 GUIChatConsole *gui_chat_console; // Free using ->Drop()
1420 MapDrawControl *draw_control;
1422 Clouds *clouds; // Free using ->Drop()
1423 Sky *sky; // Free using ->Drop()
1424 Inventory *local_inventory;
1428 GameRunData runData;
1432 This class does take ownership/responsibily for cleaning up etc of any of
1433 these items (e.g. device)
1435 IrrlichtDevice *device;
1436 video::IVideoDriver *driver;
1437 scene::ISceneManager *smgr;
1439 std::string *error_message;
1440 bool *reconnect_requested;
1441 scene::ISceneNode *skybox;
1444 bool simple_singleplayer_mode;
1447 /* Pre-calculated values
1449 int crack_animation_length;
1453 gui::IGUIStaticText *guitext; // First line of debug text
1454 gui::IGUIStaticText *guitext2; // Second line of debug text
1455 gui::IGUIStaticText *guitext_info; // At the middle of the screen
1456 gui::IGUIStaticText *guitext_status;
1457 gui::IGUIStaticText *guitext_chat; // Chat text
1458 gui::IGUIStaticText *guitext_profiler; // Profiler text
1460 std::wstring infotext;
1461 std::wstring m_statustext;
1465 IntervalLimiter profiler_interval;
1468 * TODO: Local caching of settings is not optimal and should at some stage
1469 * be updated to use a global settings object for getting thse values
1470 * (as opposed to the this local caching). This can be addressed in
1473 bool m_cache_doubletap_jump;
1474 bool m_cache_enable_clouds;
1475 bool m_cache_enable_joysticks;
1476 bool m_cache_enable_particles;
1477 bool m_cache_enable_fog;
1478 bool m_cache_enable_noclip;
1479 bool m_cache_enable_free_move;
1480 f32 m_cache_mouse_sensitivity;
1481 f32 m_cache_joystick_frustum_sensitivity;
1482 f32 m_repeat_right_click_time;
1483 f32 m_cache_cam_smoothing;
1484 f32 m_cache_fog_start;
1486 bool m_invert_mouse = false;
1487 bool m_first_loop_after_window_activation = false;
1488 bool m_camera_offset_changed = false;
1490 bool m_does_lost_focus_pause_game = false;
1493 bool m_cache_hold_aux1;
1494 bool m_android_chat_open;
1503 itemdef_manager(NULL),
1504 nodedef_manager(NULL),
1508 current_formspec(NULL),
1512 gui_chat_console(NULL),
1517 local_inventory(NULL),
1521 g_settings->registerChangedCallback("doubletap_jump",
1522 &settingChangedCallback, this);
1523 g_settings->registerChangedCallback("enable_clouds",
1524 &settingChangedCallback, this);
1525 g_settings->registerChangedCallback("doubletap_joysticks",
1526 &settingChangedCallback, this);
1527 g_settings->registerChangedCallback("enable_particles",
1528 &settingChangedCallback, this);
1529 g_settings->registerChangedCallback("enable_fog",
1530 &settingChangedCallback, this);
1531 g_settings->registerChangedCallback("mouse_sensitivity",
1532 &settingChangedCallback, this);
1533 g_settings->registerChangedCallback("joystick_frustum_sensitivity",
1534 &settingChangedCallback, this);
1535 g_settings->registerChangedCallback("repeat_rightclick_time",
1536 &settingChangedCallback, this);
1537 g_settings->registerChangedCallback("noclip",
1538 &settingChangedCallback, this);
1539 g_settings->registerChangedCallback("free_move",
1540 &settingChangedCallback, this);
1541 g_settings->registerChangedCallback("cinematic",
1542 &settingChangedCallback, this);
1543 g_settings->registerChangedCallback("cinematic_camera_smoothing",
1544 &settingChangedCallback, this);
1545 g_settings->registerChangedCallback("camera_smoothing",
1546 &settingChangedCallback, this);
1551 m_cache_hold_aux1 = false; // This is initialised properly later
1558 /****************************************************************************
1560 ****************************************************************************/
1566 if (!sound_is_dummy)
1569 delete server; // deleted first to stop all server threads
1572 delete local_inventory;
1578 delete nodedef_manager;
1579 delete itemdef_manager;
1580 delete draw_control;
1582 extendedResourceCleanup();
1584 g_settings->deregisterChangedCallback("doubletap_jump",
1585 &settingChangedCallback, this);
1586 g_settings->deregisterChangedCallback("enable_clouds",
1587 &settingChangedCallback, this);
1588 g_settings->deregisterChangedCallback("enable_particles",
1589 &settingChangedCallback, this);
1590 g_settings->deregisterChangedCallback("enable_fog",
1591 &settingChangedCallback, this);
1592 g_settings->deregisterChangedCallback("mouse_sensitivity",
1593 &settingChangedCallback, this);
1594 g_settings->deregisterChangedCallback("repeat_rightclick_time",
1595 &settingChangedCallback, this);
1596 g_settings->deregisterChangedCallback("noclip",
1597 &settingChangedCallback, this);
1598 g_settings->deregisterChangedCallback("free_move",
1599 &settingChangedCallback, this);
1600 g_settings->deregisterChangedCallback("cinematic",
1601 &settingChangedCallback, this);
1602 g_settings->deregisterChangedCallback("cinematic_camera_smoothing",
1603 &settingChangedCallback, this);
1604 g_settings->deregisterChangedCallback("camera_smoothing",
1605 &settingChangedCallback, this);
1608 bool Game::startup(bool *kill,
1610 InputHandler *input,
1611 const std::string &map_dir,
1612 const std::string &playername,
1613 const std::string &password,
1614 std::string *address, // can change if simple_singleplayer_mode
1616 std::string &error_message,
1618 ChatBackend *chat_backend,
1619 const SubgameSpec &gamespec,
1620 bool simple_singleplayer_mode)
1623 this->device = RenderingEngine::get_raw_device();
1625 this->error_message = &error_message;
1626 this->reconnect_requested = reconnect;
1627 this->random_input = random_input;
1628 this->input = input;
1629 this->chat_backend = chat_backend;
1630 this->simple_singleplayer_mode = simple_singleplayer_mode;
1632 keycache.handler = input;
1633 keycache.populate();
1635 driver = device->getVideoDriver();
1636 smgr = RenderingEngine::get_scene_manager();
1638 RenderingEngine::get_scene_manager()->getParameters()->
1639 setAttribute(scene::OBJ_LOADER_IGNORE_MATERIAL_FILES, true);
1641 memset(&runData, 0, sizeof(runData));
1642 runData.time_from_last_punch = 10.0;
1643 runData.profiler_max_page = 3;
1644 runData.update_wielded_item_trigger = true;
1646 memset(&flags, 0, sizeof(flags));
1647 flags.show_chat = true;
1648 flags.show_hud = true;
1649 flags.show_debug = g_settings->getBool("show_debug");
1650 m_invert_mouse = g_settings->getBool("invert_mouse");
1651 m_first_loop_after_window_activation = true;
1653 g_translations->clear();
1655 if (!init(map_dir, address, port, gamespec))
1658 if (!createClient(playername, password, address, port))
1661 RenderingEngine::initialize(client, hud);
1669 ProfilerGraph graph;
1670 RunStats stats = { 0 };
1671 CameraOrientation cam_view_target = { 0 };
1672 CameraOrientation cam_view = { 0 };
1673 FpsControl draw_times = { 0 };
1674 f32 dtime; // in seconds
1676 /* Clear the profiler */
1677 Profiler::GraphValues dummyvalues;
1678 g_profiler->graphGet(dummyvalues);
1680 draw_times.last_time = RenderingEngine::get_timer_time();
1682 set_light_table(g_settings->getFloat("display_gamma"));
1685 m_cache_hold_aux1 = g_settings->getBool("fast_move")
1686 && client->checkPrivilege("fast");
1689 irr::core::dimension2d<u32> previous_screen_size(g_settings->getU16("screen_w"),
1690 g_settings->getU16("screen_h"));
1692 while (RenderingEngine::run()
1693 && !(*kill || g_gamecallback->shutdown_requested
1694 || (server && server->getShutdownRequested()))) {
1696 const irr::core::dimension2d<u32> ¤t_screen_size =
1697 RenderingEngine::get_video_driver()->getScreenSize();
1698 // Verify if window size has changed and save it if it's the case
1699 // Ensure evaluating settings->getBool after verifying screensize
1700 // First condition is cheaper
1701 if (previous_screen_size != current_screen_size &&
1702 current_screen_size != irr::core::dimension2d<u32>(0,0) &&
1703 g_settings->getBool("autosave_screensize")) {
1704 g_settings->setU16("screen_w", current_screen_size.Width);
1705 g_settings->setU16("screen_h", current_screen_size.Height);
1706 previous_screen_size = current_screen_size;
1709 /* Must be called immediately after a device->run() call because it
1710 * uses device->getTimer()->getTime()
1712 limitFps(&draw_times, &dtime);
1714 updateStats(&stats, draw_times, dtime);
1715 updateInteractTimers(dtime);
1717 if (!checkConnection())
1719 if (!handleCallbacks())
1725 hud->resizeHotbar();
1727 updateProfilers(stats, draw_times, dtime);
1728 processUserInput(dtime);
1729 // Update camera before player movement to avoid camera lag of one frame
1730 updateCameraDirection(&cam_view_target, dtime);
1731 cam_view.camera_yaw += (cam_view_target.camera_yaw -
1732 cam_view.camera_yaw) * m_cache_cam_smoothing;
1733 cam_view.camera_pitch += (cam_view_target.camera_pitch -
1734 cam_view.camera_pitch) * m_cache_cam_smoothing;
1735 updatePlayerControl(cam_view);
1737 processClientEvents(&cam_view_target);
1738 updateCamera(draw_times.busy_time, dtime);
1740 processPlayerInteraction(dtime, flags.show_hud, flags.show_debug);
1741 updateFrame(&graph, &stats, dtime, cam_view);
1742 updateProfilerGraphs(&graph);
1744 // Update if minimap has been disabled by the server
1745 flags.show_minimap &= client->shouldShowMinimap();
1747 if (m_does_lost_focus_pause_game && !device->isWindowFocused() && !isMenuActive()) {
1754 void Game::shutdown()
1756 RenderingEngine::finalize();
1757 #if IRRLICHT_VERSION_MAJOR == 1 && IRRLICHT_VERSION_MINOR <= 8
1758 if (g_settings->get("3d_mode") == "pageflip") {
1759 driver->setRenderTarget(irr::video::ERT_STEREO_BOTH_BUFFERS);
1762 if (current_formspec)
1763 current_formspec->quitMenu();
1765 showOverlayMessage("Shutting down...", 0, 0, false);
1770 if (gui_chat_console)
1771 gui_chat_console->drop();
1777 while (g_menumgr.menuCount() > 0) {
1778 g_menumgr.m_stack.front()->setVisible(false);
1779 g_menumgr.deletingMenu(g_menumgr.m_stack.front());
1782 if (current_formspec) {
1783 current_formspec->drop();
1784 current_formspec = NULL;
1787 chat_backend->addMessage(L"", L"# Disconnected.");
1788 chat_backend->addMessage(L"", L"");
1792 while (!client->isShutdown()) {
1793 assert(texture_src != NULL);
1794 assert(shader_src != NULL);
1795 texture_src->processQueue();
1796 shader_src->processQueue();
1803 /****************************************************************************/
1804 /****************************************************************************
1806 ****************************************************************************/
1807 /****************************************************************************/
1810 const std::string &map_dir,
1811 std::string *address,
1813 const SubgameSpec &gamespec)
1815 texture_src = createTextureSource();
1817 showOverlayMessage("Loading...", 0, 0);
1819 shader_src = createShaderSource();
1821 itemdef_manager = createItemDefManager();
1822 nodedef_manager = createNodeDefManager();
1824 eventmgr = new EventManager();
1825 quicktune = new QuicktuneShortcutter();
1827 if (!(texture_src && shader_src && itemdef_manager && nodedef_manager
1828 && eventmgr && quicktune))
1834 // Create a server if not connecting to an existing one
1835 if (address->empty()) {
1836 if (!createSingleplayerServer(map_dir, gamespec, port, address))
1843 bool Game::initSound()
1846 if (g_settings->getBool("enable_sound")) {
1847 infostream << "Attempting to use OpenAL audio" << std::endl;
1848 sound = createOpenALSoundManager(&soundfetcher);
1850 infostream << "Failed to initialize OpenAL audio" << std::endl;
1852 infostream << "Sound disabled." << std::endl;
1856 infostream << "Using dummy audio." << std::endl;
1857 sound = &dummySoundManager;
1858 sound_is_dummy = true;
1861 soundmaker = new SoundMaker(sound, nodedef_manager);
1865 soundmaker->registerReceiver(eventmgr);
1870 bool Game::createSingleplayerServer(const std::string &map_dir,
1871 const SubgameSpec &gamespec, u16 port, std::string *address)
1873 showOverlayMessage("Creating server...", 0, 5);
1875 std::string bind_str = g_settings->get("bind_address");
1876 Address bind_addr(0, 0, 0, 0, port);
1878 if (g_settings->getBool("ipv6_server")) {
1879 bind_addr.setAddress((IPv6AddressBytes *) NULL);
1883 bind_addr.Resolve(bind_str.c_str());
1884 } catch (ResolveError &e) {
1885 infostream << "Resolving bind address \"" << bind_str
1886 << "\" failed: " << e.what()
1887 << " -- Listening on all addresses." << std::endl;
1890 if (bind_addr.isIPv6() && !g_settings->getBool("enable_ipv6")) {
1891 *error_message = "Unable to listen on " +
1892 bind_addr.serializeString() +
1893 " because IPv6 is disabled";
1894 errorstream << *error_message << std::endl;
1898 server = new Server(map_dir, gamespec, simple_singleplayer_mode, bind_addr, false);
1904 bool Game::createClient(const std::string &playername,
1905 const std::string &password, std::string *address, u16 port)
1907 showOverlayMessage("Creating client...", 0, 10);
1909 draw_control = new MapDrawControl;
1913 bool could_connect, connect_aborted;
1915 if (!connectToServer(playername, password, address, port,
1916 &could_connect, &connect_aborted))
1919 if (!could_connect) {
1920 if (error_message->empty() && !connect_aborted) {
1921 // Should not happen if error messages are set properly
1922 *error_message = "Connection failed for unknown reason";
1923 errorstream << *error_message << std::endl;
1928 if (!getServerContent(&connect_aborted)) {
1929 if (error_message->empty() && !connect_aborted) {
1930 // Should not happen if error messages are set properly
1931 *error_message = "Connection failed for unknown reason";
1932 errorstream << *error_message << std::endl;
1937 GameGlobalShaderConstantSetterFactory *scsf = new GameGlobalShaderConstantSetterFactory(
1938 &flags.force_fog_off, &runData.fog_range, client);
1939 shader_src->addShaderConstantSetterFactory(scsf);
1941 // Update cached textures, meshes and materials
1942 client->afterContentReceived();
1946 camera = new Camera(*draw_control, client);
1947 if (!camera || !camera->successfullyCreated(*error_message))
1949 client->setCamera(camera);
1953 if (m_cache_enable_clouds) {
1954 clouds = new Clouds(smgr, -1, time(0));
1956 *error_message = "Memory allocation error (clouds)";
1957 errorstream << *error_message << std::endl;
1964 sky = new Sky(-1, texture_src);
1966 skybox = NULL; // This is used/set later on in the main run loop
1968 local_inventory = new Inventory(itemdef_manager);
1970 if (!(sky && local_inventory)) {
1971 *error_message = "Memory allocation error (sky or local inventory)";
1972 errorstream << *error_message << std::endl;
1976 /* Pre-calculated values
1978 video::ITexture *t = texture_src->getTexture("crack_anylength.png");
1980 v2u32 size = t->getOriginalSize();
1981 crack_animation_length = size.Y / size.X;
1983 crack_animation_length = 5;
1989 /* Set window caption
1991 std::wstring str = utf8_to_wide(PROJECT_NAME_C);
1993 str += utf8_to_wide(g_version_hash);
1995 str += driver->getName();
1997 device->setWindowCaption(str.c_str());
1999 LocalPlayer *player = client->getEnv().getLocalPlayer();
2000 player->hurt_tilt_timer = 0;
2001 player->hurt_tilt_strength = 0;
2003 hud = new Hud(guienv, client, player, local_inventory);
2006 *error_message = "Memory error: could not create HUD";
2007 errorstream << *error_message << std::endl;
2011 mapper = client->getMinimap();
2013 mapper->setMinimapMode(MINIMAP_MODE_OFF);
2018 bool Game::initGui()
2020 // First line of debug text
2021 guitext = addStaticText(guienv,
2022 utf8_to_wide(PROJECT_NAME_C).c_str(),
2023 core::rect<s32>(0, 0, 0, 0),
2024 false, false, guiroot);
2026 // Second line of debug text
2027 guitext2 = addStaticText(guienv,
2029 core::rect<s32>(0, 0, 0, 0),
2030 false, false, guiroot);
2032 // At the middle of the screen
2033 // Object infos are shown in this
2034 guitext_info = addStaticText(guienv,
2036 core::rect<s32>(0, 0, 400, g_fontengine->getTextHeight() * 5 + 5) + v2s32(100, 200),
2037 false, true, guiroot);
2039 // Status text (displays info when showing and hiding GUI stuff, etc.)
2040 guitext_status = addStaticText(guienv,
2042 core::rect<s32>(0, 0, 0, 0),
2043 false, false, guiroot);
2044 guitext_status->setVisible(false);
2047 guitext_chat = addStaticText(
2050 core::rect<s32>(0, 0, 0, 0),
2051 //false, false); // Disable word wrap as of now
2052 false, true, guiroot);
2054 // Remove stale "recent" chat messages from previous connections
2055 chat_backend->clearRecentChat();
2057 // Make sure the size of the recent messages buffer is right
2058 chat_backend->applySettings();
2060 // Chat backend and console
2061 gui_chat_console = new GUIChatConsole(guienv, guienv->getRootGUIElement(),
2062 -1, chat_backend, client, &g_menumgr);
2063 if (!gui_chat_console) {
2064 *error_message = "Could not allocate memory for chat console";
2065 errorstream << *error_message << std::endl;
2069 // Profiler text (size is updated when text is updated)
2070 guitext_profiler = addStaticText(guienv,
2072 core::rect<s32>(0, 0, 0, 0),
2073 false, false, guiroot);
2074 guitext_profiler->setBackgroundColor(video::SColor(120, 0, 0, 0));
2075 guitext_profiler->setVisible(false);
2076 guitext_profiler->setWordWrap(true);
2078 #ifdef HAVE_TOUCHSCREENGUI
2080 if (g_touchscreengui)
2081 g_touchscreengui->init(texture_src);
2088 bool Game::connectToServer(const std::string &playername,
2089 const std::string &password, std::string *address, u16 port,
2090 bool *connect_ok, bool *aborted)
2092 *connect_ok = false; // Let's not be overly optimistic
2094 bool local_server_mode = false;
2096 showOverlayMessage("Resolving address...", 0, 15);
2098 Address connect_address(0, 0, 0, 0, port);
2101 connect_address.Resolve(address->c_str());
2103 if (connect_address.isZero()) { // i.e. INADDR_ANY, IN6ADDR_ANY
2104 //connect_address.Resolve("localhost");
2105 if (connect_address.isIPv6()) {
2106 IPv6AddressBytes addr_bytes;
2107 addr_bytes.bytes[15] = 1;
2108 connect_address.setAddress(&addr_bytes);
2110 connect_address.setAddress(127, 0, 0, 1);
2112 local_server_mode = true;
2114 } catch (ResolveError &e) {
2115 *error_message = std::string("Couldn't resolve address: ") + e.what();
2116 errorstream << *error_message << std::endl;
2120 if (connect_address.isIPv6() && !g_settings->getBool("enable_ipv6")) {
2121 *error_message = "Unable to connect to " +
2122 connect_address.serializeString() +
2123 " because IPv6 is disabled";
2124 errorstream << *error_message << std::endl;
2128 client = new Client(playername.c_str(), password, *address,
2129 *draw_control, texture_src, shader_src,
2130 itemdef_manager, nodedef_manager, sound, eventmgr,
2131 connect_address.isIPv6(), &flags);
2136 infostream << "Connecting to server at ";
2137 connect_address.print(&infostream);
2138 infostream << std::endl;
2140 client->connect(connect_address,
2141 simple_singleplayer_mode || local_server_mode);
2144 Wait for server to accept connection
2150 FpsControl fps_control = { 0 };
2152 f32 wait_time = 0; // in seconds
2154 fps_control.last_time = RenderingEngine::get_timer_time();
2156 client->loadBuiltin();
2158 while (RenderingEngine::run()) {
2160 limitFps(&fps_control, &dtime);
2162 // Update client and server
2163 client->step(dtime);
2166 server->step(dtime);
2169 if (client->getState() == LC_Init) {
2175 if (client->accessDenied()) {
2176 *error_message = "Access denied. Reason: "
2177 + client->accessDeniedReason();
2178 *reconnect_requested = client->reconnectRequested();
2179 errorstream << *error_message << std::endl;
2183 if (wasKeyDown(KeyType::ESC) || input->wasKeyDown(CancelKey)) {
2185 infostream << "Connect aborted [Escape]" << std::endl;
2190 // Only time out if we aren't waiting for the server we started
2191 if (!address->empty() && wait_time > 10) {
2192 *error_message = "Connection timed out.";
2193 errorstream << *error_message << std::endl;
2198 showOverlayMessage("Connecting to server...", dtime, 20);
2200 } catch (con::PeerNotFoundException &e) {
2201 // TODO: Should something be done here? At least an info/error
2209 bool Game::getServerContent(bool *aborted)
2213 FpsControl fps_control = { 0 };
2214 f32 dtime; // in seconds
2216 fps_control.last_time = RenderingEngine::get_timer_time();
2218 while (RenderingEngine::run()) {
2220 limitFps(&fps_control, &dtime);
2222 // Update client and server
2223 client->step(dtime);
2226 server->step(dtime);
2229 if (client->mediaReceived() && client->itemdefReceived() &&
2230 client->nodedefReceived()) {
2235 if (!checkConnection())
2238 if (client->getState() < LC_Init) {
2239 *error_message = "Client disconnected";
2240 errorstream << *error_message << std::endl;
2244 if (wasKeyDown(KeyType::ESC) || input->wasKeyDown(CancelKey)) {
2246 infostream << "Connect aborted [Escape]" << std::endl;
2253 if (!client->itemdefReceived()) {
2254 const wchar_t *text = wgettext("Item definitions...");
2256 RenderingEngine::draw_load_screen(text, guienv, texture_src,
2259 } else if (!client->nodedefReceived()) {
2260 const wchar_t *text = wgettext("Node definitions...");
2262 RenderingEngine::draw_load_screen(text, guienv, texture_src,
2266 std::stringstream message;
2267 std::fixed(message);
2268 message.precision(0);
2269 message << gettext("Media...") << " " << (client->mediaReceiveProgress()*100) << "%";
2270 message.precision(2);
2272 if ((USE_CURL == 0) ||
2273 (!g_settings->getBool("enable_remote_media_server"))) {
2274 float cur = client->getCurRate();
2275 std::string cur_unit = gettext("KiB/s");
2279 cur_unit = gettext("MiB/s");
2282 message << " (" << cur << ' ' << cur_unit << ")";
2285 progress = 30 + client->mediaReceiveProgress() * 35 + 0.5;
2286 RenderingEngine::draw_load_screen(utf8_to_wide(message.str()), guienv,
2287 texture_src, dtime, progress);
2295 /****************************************************************************/
2296 /****************************************************************************
2298 ****************************************************************************/
2299 /****************************************************************************/
2301 inline void Game::updateInteractTimers(f32 dtime)
2303 if (runData.nodig_delay_timer >= 0)
2304 runData.nodig_delay_timer -= dtime;
2306 if (runData.object_hit_delay_timer >= 0)
2307 runData.object_hit_delay_timer -= dtime;
2309 runData.time_from_last_punch += dtime;
2313 /* returns false if game should exit, otherwise true
2315 inline bool Game::checkConnection()
2317 if (client->accessDenied()) {
2318 *error_message = "Access denied. Reason: "
2319 + client->accessDeniedReason();
2320 *reconnect_requested = client->reconnectRequested();
2321 errorstream << *error_message << std::endl;
2329 /* returns false if game should exit, otherwise true
2331 inline bool Game::handleCallbacks()
2333 if (g_gamecallback->disconnect_requested) {
2334 g_gamecallback->disconnect_requested = false;
2338 if (g_gamecallback->changepassword_requested) {
2339 (new GUIPasswordChange(guienv, guiroot, -1,
2340 &g_menumgr, client))->drop();
2341 g_gamecallback->changepassword_requested = false;
2344 if (g_gamecallback->changevolume_requested) {
2345 (new GUIVolumeChange(guienv, guiroot, -1,
2346 &g_menumgr))->drop();
2347 g_gamecallback->changevolume_requested = false;
2350 if (g_gamecallback->keyconfig_requested) {
2351 (new GUIKeyChangeMenu(guienv, guiroot, -1,
2352 &g_menumgr))->drop();
2353 g_gamecallback->keyconfig_requested = false;
2356 if (g_gamecallback->keyconfig_changed) {
2357 keycache.populate(); // update the cache with new settings
2358 g_gamecallback->keyconfig_changed = false;
2365 void Game::processQueues()
2367 texture_src->processQueue();
2368 itemdef_manager->processQueue(client);
2369 shader_src->processQueue();
2373 void Game::updateProfilers(const RunStats &stats, const FpsControl &draw_times, f32 dtime)
2375 float profiler_print_interval =
2376 g_settings->getFloat("profiler_print_interval");
2377 bool print_to_log = true;
2379 if (profiler_print_interval == 0) {
2380 print_to_log = false;
2381 profiler_print_interval = 5;
2384 if (profiler_interval.step(dtime, profiler_print_interval)) {
2386 infostream << "Profiler:" << std::endl;
2387 g_profiler->print(infostream);
2390 update_profiler_gui(guitext_profiler, g_fontengine,
2391 runData.profiler_current_page, runData.profiler_max_page,
2392 driver->getScreenSize().Height);
2394 g_profiler->clear();
2397 addProfilerGraphs(stats, draw_times, dtime);
2401 void Game::addProfilerGraphs(const RunStats &stats,
2402 const FpsControl &draw_times, f32 dtime)
2404 g_profiler->graphAdd("mainloop_other",
2405 draw_times.busy_time / 1000.0f - stats.drawtime / 1000.0f);
2407 if (draw_times.sleep_time != 0)
2408 g_profiler->graphAdd("mainloop_sleep", draw_times.sleep_time / 1000.0f);
2409 g_profiler->graphAdd("mainloop_dtime", dtime);
2411 g_profiler->add("Elapsed time", dtime);
2412 g_profiler->avg("FPS", 1. / dtime);
2416 void Game::updateStats(RunStats *stats, const FpsControl &draw_times,
2423 /* Time average and jitter calculation
2425 jp = &stats->dtime_jitter;
2426 jp->avg = jp->avg * 0.96 + dtime * 0.04;
2428 jitter = dtime - jp->avg;
2430 if (jitter > jp->max)
2433 jp->counter += dtime;
2435 if (jp->counter > 0.0) {
2437 jp->max_sample = jp->max;
2438 jp->max_fraction = jp->max_sample / (jp->avg + 0.001);
2442 /* Busytime average and jitter calculation
2444 jp = &stats->busy_time_jitter;
2445 jp->avg = jp->avg + draw_times.busy_time * 0.02;
2447 jitter = draw_times.busy_time - jp->avg;
2449 if (jitter > jp->max)
2451 if (jitter < jp->min)
2454 jp->counter += dtime;
2456 if (jp->counter > 0.0) {
2458 jp->max_sample = jp->max;
2459 jp->min_sample = jp->min;
2467 /****************************************************************************
2469 ****************************************************************************/
2471 void Game::processUserInput(f32 dtime)
2473 // Reset input if window not active or some menu is active
2474 if (!device->isWindowActive() || isMenuActive() || guienv->hasFocus(gui_chat_console)) {
2476 #ifdef HAVE_TOUCHSCREENGUI
2477 g_touchscreengui->hide();
2480 #ifdef HAVE_TOUCHSCREENGUI
2481 else if (g_touchscreengui) {
2482 /* on touchscreengui step may generate own input events which ain't
2483 * what we want in case we just did clear them */
2484 g_touchscreengui->step(dtime);
2488 if (!guienv->hasFocus(gui_chat_console) && gui_chat_console->isOpen()) {
2489 gui_chat_console->closeConsoleAtOnce();
2492 // Input handler step() (used by the random input generator)
2496 if (current_formspec != NULL)
2497 current_formspec->getAndroidUIInput();
2499 handleAndroidChatInput();
2502 // Increase timer for double tap of "keymap_jump"
2503 if (m_cache_doubletap_jump && runData.jump_timer <= 0.2f)
2504 runData.jump_timer += dtime;
2507 processItemSelection(&runData.new_playeritem);
2511 void Game::processKeyInput()
2513 if (wasKeyDown(KeyType::DROP)) {
2514 dropSelectedItem(isKeyDown(KeyType::SNEAK));
2515 } else if (wasKeyDown(KeyType::AUTOFORWARD)) {
2516 toggleAutoforward();
2517 } else if (wasKeyDown(KeyType::INVENTORY)) {
2519 } else if (wasKeyDown(KeyType::ESC) || input->wasKeyDown(CancelKey)) {
2520 if (!gui_chat_console->isOpenInhibited()) {
2523 } else if (wasKeyDown(KeyType::CHAT)) {
2524 openConsole(0.2, L"");
2525 } else if (wasKeyDown(KeyType::CMD)) {
2526 openConsole(0.2, L"/");
2527 } else if (wasKeyDown(KeyType::CMD_LOCAL)) {
2528 openConsole(0.2, L".");
2529 } else if (wasKeyDown(KeyType::CONSOLE)) {
2530 openConsole(core::clamp(g_settings->getFloat("console_height"), 0.1f, 1.0f));
2531 } else if (wasKeyDown(KeyType::FREEMOVE)) {
2533 } else if (wasKeyDown(KeyType::JUMP)) {
2534 toggleFreeMoveAlt();
2535 } else if (wasKeyDown(KeyType::FASTMOVE)) {
2537 } else if (wasKeyDown(KeyType::NOCLIP)) {
2539 } else if (wasKeyDown(KeyType::MUTE)) {
2540 bool new_mute_sound = !g_settings->getBool("mute_sound");
2541 g_settings->setBool("mute_sound", new_mute_sound);
2543 showStatusTextSimple("Sound muted");
2545 showStatusTextSimple("Sound unmuted");
2546 runData.statustext_time = 0;
2547 } else if (wasKeyDown(KeyType::INC_VOLUME)) {
2548 float new_volume = rangelim(g_settings->getFloat("sound_volume") + 0.1f, 0.0f, 1.0f);
2550 g_settings->setFloat("sound_volume", new_volume);
2551 const wchar_t *str = wgettext("Volume changed to %d%%");
2552 swprintf(buf, sizeof(buf) / sizeof(wchar_t), str, myround(new_volume * 100));
2555 runData.statustext_time = 0;
2556 } else if (wasKeyDown(KeyType::DEC_VOLUME)) {
2557 float new_volume = rangelim(g_settings->getFloat("sound_volume") - 0.1f, 0.0f, 1.0f);
2559 g_settings->setFloat("sound_volume", new_volume);
2560 const wchar_t *str = wgettext("Volume changed to %d%%");
2561 swprintf(buf, sizeof(buf) / sizeof(wchar_t), str, myround(new_volume * 100));
2564 runData.statustext_time = 0;
2565 } else if (wasKeyDown(KeyType::CINEMATIC)) {
2567 } else if (wasKeyDown(KeyType::SCREENSHOT)) {
2568 client->makeScreenshot();
2569 } else if (wasKeyDown(KeyType::TOGGLE_HUD)) {
2571 } else if (wasKeyDown(KeyType::MINIMAP)) {
2572 toggleMinimap(isKeyDown(KeyType::SNEAK));
2573 } else if (wasKeyDown(KeyType::TOGGLE_CHAT)) {
2575 } else if (wasKeyDown(KeyType::TOGGLE_FORCE_FOG_OFF)) {
2577 } else if (wasKeyDown(KeyType::TOGGLE_UPDATE_CAMERA)) {
2578 toggleUpdateCamera();
2579 } else if (wasKeyDown(KeyType::TOGGLE_DEBUG)) {
2581 } else if (wasKeyDown(KeyType::TOGGLE_PROFILER)) {
2583 } else if (wasKeyDown(KeyType::INCREASE_VIEWING_RANGE)) {
2584 increaseViewRange();
2585 } else if (wasKeyDown(KeyType::DECREASE_VIEWING_RANGE)) {
2586 decreaseViewRange();
2587 } else if (wasKeyDown(KeyType::RANGESELECT)) {
2588 toggleFullViewRange();
2589 } else if (wasKeyDown(KeyType::ZOOM)) {
2591 } else if (wasKeyDown(KeyType::QUICKTUNE_NEXT)) {
2593 } else if (wasKeyDown(KeyType::QUICKTUNE_PREV)) {
2595 } else if (wasKeyDown(KeyType::QUICKTUNE_INC)) {
2597 } else if (wasKeyDown(KeyType::QUICKTUNE_DEC)) {
2601 if (!isKeyDown(KeyType::JUMP) && runData.reset_jump_timer) {
2602 runData.reset_jump_timer = false;
2603 runData.jump_timer = 0.0f;
2606 if (quicktune->hasMessage()) {
2607 m_statustext = utf8_to_wide(quicktune->getMessage());
2608 runData.statustext_time = 0.0f;
2612 void Game::processItemSelection(u16 *new_playeritem)
2614 LocalPlayer *player = client->getEnv().getLocalPlayer();
2616 /* Item selection using mouse wheel
2618 *new_playeritem = client->getPlayerItem();
2620 s32 wheel = input->getMouseWheel();
2621 u16 max_item = MYMIN(PLAYER_INVENTORY_SIZE - 1,
2622 player->hud_hotbar_itemcount - 1);
2626 if (input->joystick.wasKeyDown(KeyType::SCROLL_DOWN) ||
2627 wasKeyDown(KeyType::HOTBAR_NEXT)) {
2631 if (input->joystick.wasKeyDown(KeyType::SCROLL_UP) ||
2632 wasKeyDown(KeyType::HOTBAR_PREV)) {
2637 *new_playeritem = *new_playeritem < max_item ? *new_playeritem + 1 : 0;
2639 *new_playeritem = *new_playeritem > 0 ? *new_playeritem - 1 : max_item;
2642 /* Item selection using hotbar slot keys
2644 for (u16 i = 0; i < 23; i++) {
2645 if (wasKeyDown((GameKeyType) (KeyType::SLOT_1 + i))) {
2646 if (i < PLAYER_INVENTORY_SIZE && i < player->hud_hotbar_itemcount) {
2647 *new_playeritem = i;
2648 infostream << "Selected item: " << new_playeritem << std::endl;
2656 void Game::dropSelectedItem(bool single_item)
2658 IDropAction *a = new IDropAction();
2659 a->count = single_item ? 1 : 0;
2660 a->from_inv.setCurrentPlayer();
2661 a->from_list = "main";
2662 a->from_i = client->getPlayerItem();
2663 client->inventoryAction(a);
2667 void Game::openInventory()
2670 * Don't permit to open inventory is CAO or player doesn't exists.
2671 * This prevent showing an empty inventory at player load
2674 LocalPlayer *player = client->getEnv().getLocalPlayer();
2675 if (!player || !player->getCAO())
2678 infostream << "the_game: " << "Launching inventory" << std::endl;
2680 PlayerInventoryFormSource *fs_src = new PlayerInventoryFormSource(client);
2682 InventoryLocation inventoryloc;
2683 inventoryloc.setCurrentPlayer();
2685 if (!client->moddingEnabled()
2686 || !client->getScript()->on_inventory_open(fs_src->m_client->getInventory(inventoryloc))) {
2687 TextDest *txt_dst = new TextDestPlayerInventory(client);
2688 create_formspec_menu(¤t_formspec, client, &input->joystick, fs_src, txt_dst);
2690 current_formspec->setFormSpec(fs_src->getForm(), inventoryloc);
2695 void Game::openConsole(float scale, const wchar_t *line)
2697 assert(scale > 0.0f && scale <= 1.0f);
2700 porting::showInputDialog(gettext("ok"), "", "", 2);
2701 m_android_chat_open = true;
2703 if (gui_chat_console->isOpenInhibited())
2705 gui_chat_console->openConsole(scale);
2707 gui_chat_console->setCloseOnEnter(true);
2708 gui_chat_console->replaceAndAddToHistory(line);
2714 void Game::handleAndroidChatInput()
2716 if (m_android_chat_open && porting::getInputDialogState() == 0) {
2717 std::string text = porting::getInputDialogValue();
2718 client->typeChatMessage(utf8_to_wide(text));
2724 void Game::toggleFreeMove()
2726 bool free_move = !g_settings->getBool("free_move");
2727 g_settings->set("free_move", bool_to_cstr(free_move));
2729 runData.statustext_time = 0;
2732 if (client->checkPrivilege("fly")) {
2733 showStatusTextSimple("Fly mode enabled");
2735 showStatusTextSimple("Fly mode enabled (note: no 'fly' privilege)");
2738 showStatusTextSimple("Fly mode disabled");
2743 void Game::toggleFreeMoveAlt()
2745 if (m_cache_doubletap_jump && runData.jump_timer < 0.2f)
2748 runData.reset_jump_timer = true;
2752 void Game::toggleFast()
2754 bool fast_move = !g_settings->getBool("fast_move");
2755 g_settings->set("fast_move", bool_to_cstr(fast_move));
2757 runData.statustext_time = 0;
2760 if (client->checkPrivilege("fast")) {
2761 showStatusTextSimple("Fast mode enabled");
2763 showStatusTextSimple("Fast mode enabled (note: no 'fast' privilege)");
2766 showStatusTextSimple("Fast mode disabled");
2770 m_cache_hold_aux1 = fast_move && has_fast_privs;
2775 void Game::toggleNoClip()
2777 bool noclip = !g_settings->getBool("noclip");
2778 g_settings->set("noclip", bool_to_cstr(noclip));
2780 runData.statustext_time = 0;
2782 if (client->checkPrivilege("noclip")) {
2783 showStatusTextSimple("Noclip mode enabled");
2785 showStatusTextSimple("Noclip mode enabled (note: no 'noclip' privilege)");
2788 showStatusTextSimple("Noclip mode disabled");
2792 void Game::toggleCinematic()
2794 bool cinematic = !g_settings->getBool("cinematic");
2795 g_settings->set("cinematic", bool_to_cstr(cinematic));
2797 runData.statustext_time = 0;
2799 showStatusTextSimple("Cinematic mode enabled");
2801 showStatusTextSimple("Cinematic mode disabled");
2804 // Autoforward by toggling continuous forward.
2805 void Game::toggleAutoforward()
2807 bool autorun_enabled = !g_settings->getBool("continuous_forward");
2808 g_settings->set("continuous_forward", bool_to_cstr(autorun_enabled));
2810 runData.statustext_time = 0;
2811 if (autorun_enabled)
2812 showStatusTextSimple("Automatic forwards enabled");
2814 showStatusTextSimple("Automatic forwards disabled");
2817 void Game::toggleChat()
2819 flags.show_chat = !flags.show_chat;
2820 runData.statustext_time = 0;
2821 if (flags.show_chat)
2822 showStatusTextSimple("Chat shown");
2824 showStatusTextSimple("Chat hidden");
2828 void Game::toggleHud()
2830 flags.show_hud = !flags.show_hud;
2831 runData.statustext_time = 0;
2833 showStatusTextSimple("HUD shown");
2835 showStatusTextSimple("HUD hidden");
2838 void Game::toggleMinimap(bool shift_pressed)
2840 if (!mapper || !flags.show_hud || !g_settings->getBool("enable_minimap"))
2843 if (shift_pressed) {
2844 mapper->toggleMinimapShape();
2848 u32 hud_flags = client->getEnv().getLocalPlayer()->hud_flags;
2850 MinimapMode mode = MINIMAP_MODE_OFF;
2851 if (hud_flags & HUD_FLAG_MINIMAP_VISIBLE) {
2852 mode = mapper->getMinimapMode();
2853 mode = (MinimapMode)((int)mode + 1);
2854 // If radar is disabled and in, or switching to, radar mode
2855 if (!(hud_flags & HUD_FLAG_MINIMAP_RADAR_VISIBLE) && mode > 3)
2856 mode = MINIMAP_MODE_OFF;
2859 flags.show_minimap = true;
2861 case MINIMAP_MODE_SURFACEx1:
2862 showStatusTextSimple("Minimap in surface mode, Zoom x1");
2864 case MINIMAP_MODE_SURFACEx2:
2865 showStatusTextSimple("Minimap in surface mode, Zoom x2");
2867 case MINIMAP_MODE_SURFACEx4:
2868 showStatusTextSimple("Minimap in surface mode, Zoom x4");
2870 case MINIMAP_MODE_RADARx1:
2871 showStatusTextSimple("Minimap in radar mode, Zoom x1");
2873 case MINIMAP_MODE_RADARx2:
2874 showStatusTextSimple("Minimap in radar mode, Zoom x2");
2876 case MINIMAP_MODE_RADARx4:
2877 showStatusTextSimple("Minimap in radar mode, Zoom x4");
2880 mode = MINIMAP_MODE_OFF;
2881 flags.show_minimap = false;
2882 if (hud_flags & HUD_FLAG_MINIMAP_VISIBLE)
2883 showStatusTextSimple("Minimap hidden");
2885 showStatusTextSimple("Minimap currently disabled by game or mod");
2888 runData.statustext_time = 0;
2889 mapper->setMinimapMode(mode);
2892 void Game::toggleFog()
2894 flags.force_fog_off = !flags.force_fog_off;
2895 runData.statustext_time = 0;
2896 if (flags.force_fog_off)
2897 showStatusTextSimple("Fog disabled");
2899 showStatusTextSimple("Fog enabled");
2903 void Game::toggleDebug()
2905 // Initial / 4x toggle: Chat only
2906 // 1x toggle: Debug text with chat
2907 // 2x toggle: Debug text with profiler graph
2908 // 3x toggle: Debug text and wireframe
2909 if (!flags.show_debug) {
2910 flags.show_debug = true;
2911 flags.show_profiler_graph = false;
2912 draw_control->show_wireframe = false;
2913 showStatusTextSimple("Debug info shown");
2914 } else if (!flags.show_profiler_graph && !draw_control->show_wireframe) {
2915 flags.show_profiler_graph = true;
2916 showStatusTextSimple("Profiler graph shown");
2917 } else if (!draw_control->show_wireframe && client->checkPrivilege("debug")) {
2918 flags.show_profiler_graph = false;
2919 draw_control->show_wireframe = true;
2920 showStatusTextSimple("Wireframe shown");
2922 flags.show_debug = false;
2923 flags.show_profiler_graph = false;
2924 draw_control->show_wireframe = false;
2925 if (client->checkPrivilege("debug")) {
2926 showStatusTextSimple("Debug info, profiler graph, and wireframe hidden");
2928 showStatusTextSimple("Debug info and profiler graph hidden");
2931 runData.statustext_time = 0;
2935 void Game::toggleUpdateCamera()
2937 flags.disable_camera_update = !flags.disable_camera_update;
2938 runData.statustext_time = 0;
2939 if (flags.disable_camera_update)
2940 showStatusTextSimple("Camera update disabled");
2942 showStatusTextSimple("Camera update enabled");
2946 void Game::toggleProfiler()
2948 runData.profiler_current_page =
2949 (runData.profiler_current_page + 1) % (runData.profiler_max_page + 1);
2951 // FIXME: This updates the profiler with incomplete values
2952 update_profiler_gui(guitext_profiler, g_fontengine, runData.profiler_current_page,
2953 runData.profiler_max_page, driver->getScreenSize().Height);
2955 if (runData.profiler_current_page != 0) {
2957 const wchar_t* str = wgettext("Profiler shown (page %d of %d)");
2958 swprintf(buf, sizeof(buf) / sizeof(wchar_t), str,
2959 runData.profiler_current_page,
2960 runData.profiler_max_page);
2964 showStatusTextSimple("Profiler hidden");
2966 runData.statustext_time = 0;
2970 void Game::increaseViewRange()
2972 s16 range = g_settings->getS16("viewing_range");
2973 s16 range_new = range + 10;
2977 if (range_new > 4000) {
2979 str = wgettext("Viewing range is at maximum: %d");
2980 swprintf(buf, sizeof(buf) / sizeof(wchar_t), str, range_new);
2985 str = wgettext("Viewing range changed to %d");
2986 swprintf(buf, sizeof(buf) / sizeof(wchar_t), str, range_new);
2990 g_settings->set("viewing_range", itos(range_new));
2991 runData.statustext_time = 0;
2995 void Game::decreaseViewRange()
2997 s16 range = g_settings->getS16("viewing_range");
2998 s16 range_new = range - 10;
3002 if (range_new < 20) {
3004 str = wgettext("Viewing range is at minimum: %d");
3005 swprintf(buf, sizeof(buf) / sizeof(wchar_t), str, range_new);
3009 str = wgettext("Viewing range changed to %d");
3010 swprintf(buf, sizeof(buf) / sizeof(wchar_t), str, range_new);
3014 g_settings->set("viewing_range", itos(range_new));
3015 runData.statustext_time = 0;
3019 void Game::toggleFullViewRange()
3021 draw_control->range_all = !draw_control->range_all;
3022 runData.statustext_time = 0;
3023 if (draw_control->range_all)
3024 showStatusTextSimple("Enabled unlimited viewing range");
3026 showStatusTextSimple("Disabled unlimited viewing range");
3030 void Game::checkZoomEnabled()
3032 LocalPlayer *player = client->getEnv().getLocalPlayer();
3033 if (player->getZoomFOV() < 0.001f)
3034 showStatusTextSimple("Zoom currently disabled by game or mod");
3038 void Game::updateCameraDirection(CameraOrientation *cam, float dtime)
3040 if ((device->isWindowActive() && device->isWindowFocused()
3041 && !isMenuActive()) || random_input) {
3044 if (!random_input) {
3045 // Mac OSX gets upset if this is set every frame
3046 if (device->getCursorControl()->isVisible())
3047 device->getCursorControl()->setVisible(false);
3051 if (m_first_loop_after_window_activation)
3052 m_first_loop_after_window_activation = false;
3054 updateCameraOrientation(cam, dtime);
3056 input->setMousePos((driver->getScreenSize().Width / 2),
3057 (driver->getScreenSize().Height / 2));
3061 // Mac OSX gets upset if this is set every frame
3062 if (!device->getCursorControl()->isVisible())
3063 device->getCursorControl()->setVisible(true);
3066 m_first_loop_after_window_activation = true;
3071 void Game::updateCameraOrientation(CameraOrientation *cam, float dtime)
3073 #ifdef HAVE_TOUCHSCREENGUI
3074 if (g_touchscreengui) {
3075 cam->camera_yaw += g_touchscreengui->getYawChange();
3076 cam->camera_pitch = g_touchscreengui->getPitch();
3080 s32 dx = input->getMousePos().X - (driver->getScreenSize().Width / 2);
3081 s32 dy = input->getMousePos().Y - (driver->getScreenSize().Height / 2);
3083 if (m_invert_mouse || camera->getCameraMode() == CAMERA_MODE_THIRD_FRONT) {
3087 cam->camera_yaw -= dx * m_cache_mouse_sensitivity;
3088 cam->camera_pitch += dy * m_cache_mouse_sensitivity;
3090 #ifdef HAVE_TOUCHSCREENGUI
3094 if (m_cache_enable_joysticks) {
3095 f32 c = m_cache_joystick_frustum_sensitivity * (1.f / 32767.f) * dtime;
3096 cam->camera_yaw -= input->joystick.getAxisWithoutDead(JA_FRUSTUM_HORIZONTAL) * c;
3097 cam->camera_pitch += input->joystick.getAxisWithoutDead(JA_FRUSTUM_VERTICAL) * c;
3100 cam->camera_pitch = rangelim(cam->camera_pitch, -89.5, 89.5);
3104 void Game::updatePlayerControl(const CameraOrientation &cam)
3106 //TimeTaker tt("update player control", NULL, PRECISION_NANO);
3108 // DO NOT use the isKeyDown method for the forward, backward, left, right
3109 // buttons, as the code that uses the controls needs to be able to
3110 // distinguish between the two in order to know when to use joysticks.
3112 PlayerControl control(
3113 input->isKeyDown(keycache.key[KeyType::FORWARD]),
3114 input->isKeyDown(keycache.key[KeyType::BACKWARD]),
3115 input->isKeyDown(keycache.key[KeyType::LEFT]),
3116 input->isKeyDown(keycache.key[KeyType::RIGHT]),
3117 isKeyDown(KeyType::JUMP),
3118 isKeyDown(KeyType::SPECIAL1),
3119 isKeyDown(KeyType::SNEAK),
3120 isKeyDown(KeyType::ZOOM),
3125 input->joystick.getAxisWithoutDead(JA_SIDEWARD_MOVE),
3126 input->joystick.getAxisWithoutDead(JA_FORWARD_MOVE)
3130 ( (u32)(isKeyDown(KeyType::FORWARD) & 0x1) << 0) |
3131 ( (u32)(isKeyDown(KeyType::BACKWARD) & 0x1) << 1) |
3132 ( (u32)(isKeyDown(KeyType::LEFT) & 0x1) << 2) |
3133 ( (u32)(isKeyDown(KeyType::RIGHT) & 0x1) << 3) |
3134 ( (u32)(isKeyDown(KeyType::JUMP) & 0x1) << 4) |
3135 ( (u32)(isKeyDown(KeyType::SPECIAL1) & 0x1) << 5) |
3136 ( (u32)(isKeyDown(KeyType::SNEAK) & 0x1) << 6) |
3137 ( (u32)(isLeftPressed() & 0x1) << 7) |
3138 ( (u32)(isRightPressed() & 0x1) << 8
3142 /* For Android, simulate holding down AUX1 (fast move) if the user has
3143 * the fast_move setting toggled on. If there is an aux1 key defined for
3144 * Android then its meaning is inverted (i.e. holding aux1 means walk and
3147 if (m_cache_hold_aux1) {
3148 control.aux1 = control.aux1 ^ true;
3149 keypress_bits ^= ((u32)(1U << 5));
3153 client->setPlayerControl(control);
3154 LocalPlayer *player = client->getEnv().getLocalPlayer();
3155 player->keyPressed = keypress_bits;
3161 inline void Game::step(f32 *dtime)
3163 bool can_be_and_is_paused =
3164 (simple_singleplayer_mode && g_menumgr.pausesGame());
3166 if (can_be_and_is_paused) { // This is for a singleplayer server
3167 *dtime = 0; // No time passes
3169 if (server != NULL) {
3170 //TimeTaker timer("server->step(dtime)");
3171 server->step(*dtime);
3174 //TimeTaker timer("client.step(dtime)");
3175 client->step(*dtime);
3179 const ClientEventHandler Game::clientEventHandler[CLIENTEVENT_MAX] = {
3180 {&Game::handleClientEvent_None},
3181 {&Game::handleClientEvent_PlayerDamage},
3182 {&Game::handleClientEvent_PlayerForceMove},
3183 {&Game::handleClientEvent_Deathscreen},
3184 {&Game::handleClientEvent_ShowFormSpec},
3185 {&Game::handleClientEvent_ShowLocalFormSpec},
3186 {&Game::handleClientEvent_HandleParticleEvent},
3187 {&Game::handleClientEvent_HandleParticleEvent},
3188 {&Game::handleClientEvent_HandleParticleEvent},
3189 {&Game::handleClientEvent_HudAdd},
3190 {&Game::handleClientEvent_HudRemove},
3191 {&Game::handleClientEvent_HudChange},
3192 {&Game::handleClientEvent_SetSky},
3193 {&Game::handleClientEvent_OverrideDayNigthRatio},
3194 {&Game::handleClientEvent_CloudParams},
3197 void Game::handleClientEvent_None(ClientEvent *event, CameraOrientation *cam)
3199 FATAL_ERROR("ClientEvent type None received");
3202 void Game::handleClientEvent_PlayerDamage(ClientEvent *event, CameraOrientation *cam)
3204 if (client->getHP() == 0)
3207 if (client->moddingEnabled()) {
3208 client->getScript()->on_damage_taken(event->player_damage.amount);
3211 runData.damage_flash += 95.0 + 3.2 * event->player_damage.amount;
3212 runData.damage_flash = MYMIN(runData.damage_flash, 127.0);
3214 LocalPlayer *player = client->getEnv().getLocalPlayer();
3216 player->hurt_tilt_timer = 1.5;
3217 player->hurt_tilt_strength =
3218 rangelim(event->player_damage.amount / 4, 1.0, 4.0);
3220 client->event()->put(new SimpleTriggerEvent("PlayerDamage"));
3223 void Game::handleClientEvent_PlayerForceMove(ClientEvent *event, CameraOrientation *cam)
3225 cam->camera_yaw = event->player_force_move.yaw;
3226 cam->camera_pitch = event->player_force_move.pitch;
3229 void Game::handleClientEvent_Deathscreen(ClientEvent *event, CameraOrientation *cam)
3231 // This should be enabled for death formspec in builtin
3232 client->getScript()->on_death();
3234 LocalPlayer *player = client->getEnv().getLocalPlayer();
3236 /* Handle visualization */
3237 runData.damage_flash = 0;
3238 player->hurt_tilt_timer = 0;
3239 player->hurt_tilt_strength = 0;
3242 void Game::handleClientEvent_ShowFormSpec(ClientEvent *event, CameraOrientation *cam)
3244 if (event->show_formspec.formspec->empty()) {
3245 if (current_formspec && (event->show_formspec.formname->empty()
3246 || *(event->show_formspec.formname) == cur_formname)) {
3247 current_formspec->quitMenu();
3250 FormspecFormSource *fs_src =
3251 new FormspecFormSource(*(event->show_formspec.formspec));
3252 TextDestPlayerInventory *txt_dst =
3253 new TextDestPlayerInventory(client, *(event->show_formspec.formname));
3255 create_formspec_menu(¤t_formspec, client, &input->joystick,
3257 cur_formname = *(event->show_formspec.formname);
3260 delete event->show_formspec.formspec;
3261 delete event->show_formspec.formname;
3264 void Game::handleClientEvent_ShowLocalFormSpec(ClientEvent *event, CameraOrientation *cam)
3266 FormspecFormSource *fs_src = new FormspecFormSource(*event->show_formspec.formspec);
3267 LocalFormspecHandler *txt_dst =
3268 new LocalFormspecHandler(*event->show_formspec.formname, client);
3269 create_formspec_menu(¤t_formspec, client, &input->joystick, fs_src, txt_dst);
3271 delete event->show_formspec.formspec;
3272 delete event->show_formspec.formname;
3275 void Game::handleClientEvent_HandleParticleEvent(ClientEvent *event,
3276 CameraOrientation *cam)
3278 LocalPlayer *player = client->getEnv().getLocalPlayer();
3279 client->getParticleManager()->handleParticleEvent(event, client, player);
3282 void Game::handleClientEvent_HudAdd(ClientEvent *event, CameraOrientation *cam)
3284 LocalPlayer *player = client->getEnv().getLocalPlayer();
3286 u32 id = event->hudadd.id;
3288 HudElement *e = player->getHud(id);
3291 delete event->hudadd.pos;
3292 delete event->hudadd.name;
3293 delete event->hudadd.scale;
3294 delete event->hudadd.text;
3295 delete event->hudadd.align;
3296 delete event->hudadd.offset;
3297 delete event->hudadd.world_pos;
3298 delete event->hudadd.size;
3303 e->type = (HudElementType)event->hudadd.type;
3304 e->pos = *event->hudadd.pos;
3305 e->name = *event->hudadd.name;
3306 e->scale = *event->hudadd.scale;
3307 e->text = *event->hudadd.text;
3308 e->number = event->hudadd.number;
3309 e->item = event->hudadd.item;
3310 e->dir = event->hudadd.dir;
3311 e->align = *event->hudadd.align;
3312 e->offset = *event->hudadd.offset;
3313 e->world_pos = *event->hudadd.world_pos;
3314 e->size = *event->hudadd.size;
3316 u32 new_id = player->addHud(e);
3317 //if this isn't true our huds aren't consistent
3318 sanity_check(new_id == id);
3320 delete event->hudadd.pos;
3321 delete event->hudadd.name;
3322 delete event->hudadd.scale;
3323 delete event->hudadd.text;
3324 delete event->hudadd.align;
3325 delete event->hudadd.offset;
3326 delete event->hudadd.world_pos;
3327 delete event->hudadd.size;
3330 void Game::handleClientEvent_HudRemove(ClientEvent *event, CameraOrientation *cam)
3332 LocalPlayer *player = client->getEnv().getLocalPlayer();
3333 HudElement *e = player->removeHud(event->hudrm.id);
3337 void Game::handleClientEvent_HudChange(ClientEvent *event, CameraOrientation *cam)
3339 LocalPlayer *player = client->getEnv().getLocalPlayer();
3341 u32 id = event->hudchange.id;
3342 HudElement *e = player->getHud(id);
3345 delete event->hudchange.v3fdata;
3346 delete event->hudchange.v2fdata;
3347 delete event->hudchange.sdata;
3348 delete event->hudchange.v2s32data;
3352 switch (event->hudchange.stat) {
3354 e->pos = *event->hudchange.v2fdata;
3358 e->name = *event->hudchange.sdata;
3361 case HUD_STAT_SCALE:
3362 e->scale = *event->hudchange.v2fdata;
3366 e->text = *event->hudchange.sdata;
3369 case HUD_STAT_NUMBER:
3370 e->number = event->hudchange.data;
3374 e->item = event->hudchange.data;
3378 e->dir = event->hudchange.data;
3381 case HUD_STAT_ALIGN:
3382 e->align = *event->hudchange.v2fdata;
3385 case HUD_STAT_OFFSET:
3386 e->offset = *event->hudchange.v2fdata;
3389 case HUD_STAT_WORLD_POS:
3390 e->world_pos = *event->hudchange.v3fdata;
3394 e->size = *event->hudchange.v2s32data;
3398 delete event->hudchange.v3fdata;
3399 delete event->hudchange.v2fdata;
3400 delete event->hudchange.sdata;
3401 delete event->hudchange.v2s32data;
3404 void Game::handleClientEvent_SetSky(ClientEvent *event, CameraOrientation *cam)
3406 sky->setVisible(false);
3407 // Whether clouds are visible in front of a custom skybox
3408 sky->setCloudsEnabled(event->set_sky.clouds);
3415 // Handle according to type
3416 if (*event->set_sky.type == "regular") {
3417 sky->setVisible(true);
3418 sky->setCloudsEnabled(true);
3419 } else if (*event->set_sky.type == "skybox" &&
3420 event->set_sky.params->size() == 6) {
3421 sky->setFallbackBgColor(*event->set_sky.bgcolor);
3422 skybox = RenderingEngine::get_scene_manager()->addSkyBoxSceneNode(
3423 texture_src->getTextureForMesh((*event->set_sky.params)[0]),
3424 texture_src->getTextureForMesh((*event->set_sky.params)[1]),
3425 texture_src->getTextureForMesh((*event->set_sky.params)[2]),
3426 texture_src->getTextureForMesh((*event->set_sky.params)[3]),
3427 texture_src->getTextureForMesh((*event->set_sky.params)[4]),
3428 texture_src->getTextureForMesh((*event->set_sky.params)[5]));
3430 // Handle everything else as plain color
3432 if (*event->set_sky.type != "plain")
3433 infostream << "Unknown sky type: "
3434 << (*event->set_sky.type) << std::endl;
3436 sky->setFallbackBgColor(*event->set_sky.bgcolor);
3439 delete event->set_sky.bgcolor;
3440 delete event->set_sky.type;
3441 delete event->set_sky.params;
3444 void Game::handleClientEvent_OverrideDayNigthRatio(ClientEvent *event,
3445 CameraOrientation *cam)
3447 client->getEnv().setDayNightRatioOverride(
3448 event->override_day_night_ratio.do_override,
3449 event->override_day_night_ratio.ratio_f * 1000.0f);
3452 void Game::handleClientEvent_CloudParams(ClientEvent *event, CameraOrientation *cam)
3457 clouds->setDensity(event->cloud_params.density);
3458 clouds->setColorBright(video::SColor(event->cloud_params.color_bright));
3459 clouds->setColorAmbient(video::SColor(event->cloud_params.color_ambient));
3460 clouds->setHeight(event->cloud_params.height);
3461 clouds->setThickness(event->cloud_params.thickness);
3462 clouds->setSpeed(v2f(event->cloud_params.speed_x, event->cloud_params.speed_y));
3465 void Game::processClientEvents(CameraOrientation *cam)
3467 while (client->hasClientEvents()) {
3468 std::unique_ptr<ClientEvent> event(client->getClientEvent());
3469 FATAL_ERROR_IF(event->type >= CLIENTEVENT_MAX, "Invalid clientevent type");
3470 const ClientEventHandler& evHandler = clientEventHandler[event->type];
3471 (this->*evHandler.handler)(event.get(), cam);
3475 void Game::updateCamera(u32 busy_time, f32 dtime)
3477 LocalPlayer *player = client->getEnv().getLocalPlayer();
3480 For interaction purposes, get info about the held item
3482 - Is it a usable item?
3483 - Can it point to liquids?
3485 ItemStack playeritem;
3487 InventoryList *mlist = local_inventory->getList("main");
3489 if (mlist && client->getPlayerItem() < mlist->getSize())
3490 playeritem = mlist->getItem(client->getPlayerItem());
3493 if (playeritem.getDefinition(itemdef_manager).name.empty()) { // override the hand
3494 InventoryList *hlist = local_inventory->getList("hand");
3496 playeritem = hlist->getItem(0);
3500 ToolCapabilities playeritem_toolcap =
3501 playeritem.getToolCapabilities(itemdef_manager);
3503 v3s16 old_camera_offset = camera->getOffset();
3505 if (wasKeyDown(KeyType::CAMERA_MODE)) {
3506 GenericCAO *playercao = player->getCAO();
3508 // If playercao not loaded, don't change camera
3512 camera->toggleCameraMode();
3514 playercao->setVisible(camera->getCameraMode() > CAMERA_MODE_FIRST);
3515 playercao->setChildrenVisible(camera->getCameraMode() > CAMERA_MODE_FIRST);
3518 float full_punch_interval = playeritem_toolcap.full_punch_interval;
3519 float tool_reload_ratio = runData.time_from_last_punch / full_punch_interval;
3521 tool_reload_ratio = MYMIN(tool_reload_ratio, 1.0);
3522 camera->update(player, dtime, busy_time / 1000.0f, tool_reload_ratio);
3523 camera->step(dtime);
3525 v3f camera_position = camera->getPosition();
3526 v3f camera_direction = camera->getDirection();
3527 f32 camera_fov = camera->getFovMax();
3528 v3s16 camera_offset = camera->getOffset();
3530 m_camera_offset_changed = (camera_offset != old_camera_offset);
3532 if (!flags.disable_camera_update) {
3533 client->getEnv().getClientMap().updateCamera(camera_position,
3534 camera_direction, camera_fov, camera_offset);
3536 if (m_camera_offset_changed) {
3537 client->updateCameraOffset(camera_offset);
3538 client->getEnv().updateCameraOffset(camera_offset);
3541 clouds->updateCameraOffset(camera_offset);
3547 void Game::updateSound(f32 dtime)
3549 // Update sound listener
3550 v3s16 camera_offset = camera->getOffset();
3551 sound->updateListener(camera->getCameraNode()->getPosition() + intToFloat(camera_offset, BS),
3552 v3f(0, 0, 0), // velocity
3553 camera->getDirection(),
3554 camera->getCameraNode()->getUpVector());
3556 bool mute_sound = g_settings->getBool("mute_sound");
3558 sound->setListenerGain(0.0f);
3560 // Check if volume is in the proper range, else fix it.
3561 float old_volume = g_settings->getFloat("sound_volume");
3562 float new_volume = rangelim(old_volume, 0.0f, 1.0f);
3563 sound->setListenerGain(new_volume);
3565 if (old_volume != new_volume) {
3566 g_settings->setFloat("sound_volume", new_volume);
3570 LocalPlayer *player = client->getEnv().getLocalPlayer();
3572 // Tell the sound maker whether to make footstep sounds
3573 soundmaker->makes_footstep_sound = player->makes_footstep_sound;
3575 // Update sound maker
3576 if (player->makes_footstep_sound)
3577 soundmaker->step(dtime);
3579 ClientMap &map = client->getEnv().getClientMap();
3580 MapNode n = map.getNodeNoEx(player->getFootstepNodePos());
3581 soundmaker->m_player_step_sound = nodedef_manager->get(n).sound_footstep;
3585 void Game::processPlayerInteraction(f32 dtime, bool show_hud, bool show_debug)
3587 LocalPlayer *player = client->getEnv().getLocalPlayer();
3589 ItemStack playeritem;
3591 InventoryList *mlist = local_inventory->getList("main");
3593 if (mlist && client->getPlayerItem() < mlist->getSize())
3594 playeritem = mlist->getItem(client->getPlayerItem());
3597 const ItemDefinition &playeritem_def =
3598 playeritem.getDefinition(itemdef_manager);
3599 InventoryList *hlist = local_inventory->getList("hand");
3600 const ItemDefinition &hand_def =
3601 hlist ? hlist->getItem(0).getDefinition(itemdef_manager) : itemdef_manager->get("");
3603 v3f player_position = player->getPosition();
3604 v3f camera_position = camera->getPosition();
3605 v3f camera_direction = camera->getDirection();
3606 v3s16 camera_offset = camera->getOffset();
3610 Calculate what block is the crosshair pointing to
3613 f32 d = playeritem_def.range; // max. distance
3614 f32 d_hand = hand_def.range;
3616 if (d < 0 && d_hand >= 0)
3621 core::line3d<f32> shootline;
3623 if (camera->getCameraMode() != CAMERA_MODE_THIRD_FRONT) {
3624 shootline = core::line3d<f32>(camera_position,
3625 camera_position + camera_direction * BS * d);
3627 // prevent player pointing anything in front-view
3628 shootline = core::line3d<f32>(camera_position,camera_position);
3631 #ifdef HAVE_TOUCHSCREENGUI
3633 if ((g_settings->getBool("touchtarget")) && (g_touchscreengui)) {
3634 shootline = g_touchscreengui->getShootline();
3635 // Scale shootline to the acual distance the player can reach
3636 shootline.end = shootline.start
3637 + shootline.getVector().normalize() * BS * d;
3638 shootline.start += intToFloat(camera_offset, BS);
3639 shootline.end += intToFloat(camera_offset, BS);
3644 PointedThing pointed = updatePointedThing(shootline,
3645 playeritem_def.liquids_pointable,
3646 !runData.ldown_for_dig,
3649 if (pointed != runData.pointed_old) {
3650 infostream << "Pointing at " << pointed.dump() << std::endl;
3651 hud->updateSelectionMesh(camera_offset);
3654 if (runData.digging_blocked && !isLeftPressed()) {
3655 // allow digging again if button is not pressed
3656 runData.digging_blocked = false;
3661 - releasing left mouse button
3662 - pointing away from node
3664 if (runData.digging) {
3665 if (getLeftReleased()) {
3666 infostream << "Left button released"
3667 << " (stopped digging)" << std::endl;
3668 runData.digging = false;
3669 } else if (pointed != runData.pointed_old) {
3670 if (pointed.type == POINTEDTHING_NODE
3671 && runData.pointed_old.type == POINTEDTHING_NODE
3672 && pointed.node_undersurface
3673 == runData.pointed_old.node_undersurface) {
3674 // Still pointing to the same node, but a different face.
3677 infostream << "Pointing away from node"
3678 << " (stopped digging)" << std::endl;
3679 runData.digging = false;
3680 hud->updateSelectionMesh(camera_offset);
3684 if (!runData.digging) {
3685 client->interact(1, runData.pointed_old);
3686 client->setCrack(-1, v3s16(0, 0, 0));
3687 runData.dig_time = 0.0;
3689 } else if (runData.dig_instantly && getLeftReleased()) {
3690 // Remove e.g. torches faster when clicking instead of holding LMB
3691 runData.nodig_delay_timer = 0;
3692 runData.dig_instantly = false;
3695 if (!runData.digging && runData.ldown_for_dig && !isLeftPressed()) {
3696 runData.ldown_for_dig = false;
3699 runData.left_punch = false;
3701 soundmaker->m_player_leftpunch_sound.name = "";
3703 // Prepare for repeating, unless we're not supposed to
3704 if (isRightPressed() && !g_settings->getBool("safe_dig_and_place"))
3705 runData.repeat_rightclick_timer += dtime;
3707 runData.repeat_rightclick_timer = 0;
3709 if (playeritem_def.usable && isLeftPressed()) {
3710 if (getLeftClicked() && (!client->moddingEnabled()
3711 || !client->getScript()->on_item_use(playeritem, pointed)))
3712 client->interact(4, pointed);
3713 } else if (pointed.type == POINTEDTHING_NODE) {
3714 ToolCapabilities playeritem_toolcap =
3715 playeritem.getToolCapabilities(itemdef_manager);
3716 if (playeritem.name.empty()) {
3717 const ToolCapabilities *handToolcap = hlist
3718 ? &hlist->getItem(0).getToolCapabilities(itemdef_manager)
3719 : itemdef_manager->get("").tool_capabilities;
3721 if (handToolcap != nullptr)
3722 playeritem_toolcap = *handToolcap;
3724 handlePointingAtNode(pointed, playeritem_def, playeritem,
3725 playeritem_toolcap, dtime);
3726 } else if (pointed.type == POINTEDTHING_OBJECT) {
3727 handlePointingAtObject(pointed, playeritem, player_position, show_debug);
3728 } else if (isLeftPressed()) {
3729 // When button is held down in air, show continuous animation
3730 runData.left_punch = true;
3731 } else if (getRightClicked()) {
3732 handlePointingAtNothing(playeritem);
3735 runData.pointed_old = pointed;
3737 if (runData.left_punch || getLeftClicked())
3738 camera->setDigging(0); // left click animation
3740 input->resetLeftClicked();
3741 input->resetRightClicked();
3743 input->joystick.clearWasKeyDown(KeyType::MOUSE_L);
3744 input->joystick.clearWasKeyDown(KeyType::MOUSE_R);
3746 input->resetLeftReleased();
3747 input->resetRightReleased();
3749 input->joystick.clearWasKeyReleased(KeyType::MOUSE_L);
3750 input->joystick.clearWasKeyReleased(KeyType::MOUSE_R);
3754 PointedThing Game::updatePointedThing(
3755 const core::line3d<f32> &shootline,
3756 bool liquids_pointable,
3757 bool look_for_object,
3758 const v3s16 &camera_offset)
3760 std::vector<aabb3f> *selectionboxes = hud->getSelectionBoxes();
3761 selectionboxes->clear();
3762 hud->setSelectedFaceNormal(v3f(0.0, 0.0, 0.0));
3763 static thread_local const bool show_entity_selectionbox = g_settings->getBool(
3764 "show_entity_selectionbox");
3766 ClientEnvironment &env = client->getEnv();
3767 ClientMap &map = env.getClientMap();
3768 INodeDefManager *nodedef = map.getNodeDefManager();
3770 runData.selected_object = NULL;
3772 RaycastState s(shootline, look_for_object, liquids_pointable);
3773 PointedThing result;
3774 env.continueRaycast(&s, &result);
3775 if (result.type == POINTEDTHING_OBJECT) {
3776 runData.selected_object = client->getEnv().getActiveObject(result.object_id);
3777 aabb3f selection_box;
3778 if (show_entity_selectionbox && runData.selected_object->doShowSelectionBox() &&
3779 runData.selected_object->getSelectionBox(&selection_box)) {
3780 v3f pos = runData.selected_object->getPosition();
3781 selectionboxes->push_back(aabb3f(selection_box));
3782 hud->setSelectionPos(pos, camera_offset);
3784 } else if (result.type == POINTEDTHING_NODE) {
3785 // Update selection boxes
3786 MapNode n = map.getNodeNoEx(result.node_undersurface);
3787 std::vector<aabb3f> boxes;
3788 n.getSelectionBoxes(nodedef, &boxes,
3789 n.getNeighbors(result.node_undersurface, &map));
3792 for (std::vector<aabb3f>::const_iterator i = boxes.begin();
3793 i != boxes.end(); ++i) {
3795 box.MinEdge -= v3f(d, d, d);
3796 box.MaxEdge += v3f(d, d, d);
3797 selectionboxes->push_back(box);
3799 hud->setSelectionPos(intToFloat(result.node_undersurface, BS),
3801 hud->setSelectedFaceNormal(v3f(
3802 result.intersection_normal.X,
3803 result.intersection_normal.Y,
3804 result.intersection_normal.Z));
3807 // Update selection mesh light level and vertex colors
3808 if (!selectionboxes->empty()) {
3809 v3f pf = hud->getSelectionPos();
3810 v3s16 p = floatToInt(pf, BS);
3812 // Get selection mesh light level
3813 MapNode n = map.getNodeNoEx(p);
3814 u16 node_light = getInteriorLight(n, -1, nodedef);
3815 u16 light_level = node_light;
3817 for (const v3s16 &dir : g_6dirs) {
3818 n = map.getNodeNoEx(p + dir);
3819 node_light = getInteriorLight(n, -1, nodedef);
3820 if (node_light > light_level)
3821 light_level = node_light;
3824 u32 daynight_ratio = client->getEnv().getDayNightRatio();
3826 final_color_blend(&c, light_level, daynight_ratio);
3828 // Modify final color a bit with time
3829 u32 timer = porting::getTimeMs() % 5000;
3830 float timerf = (float) (irr::core::PI * ((timer / 2500.0) - 0.5));
3831 float sin_r = 0.08 * sin(timerf);
3832 float sin_g = 0.08 * sin(timerf + irr::core::PI * 0.5);
3833 float sin_b = 0.08 * sin(timerf + irr::core::PI);
3834 c.setRed(core::clamp(core::round32(c.getRed() * (0.8 + sin_r)), 0, 255));
3835 c.setGreen(core::clamp(core::round32(c.getGreen() * (0.8 + sin_g)), 0, 255));
3836 c.setBlue(core::clamp(core::round32(c.getBlue() * (0.8 + sin_b)), 0, 255));
3838 // Set mesh final color
3839 hud->setSelectionMeshColor(c);
3845 void Game::handlePointingAtNothing(const ItemStack &playerItem)
3847 infostream << "Right Clicked in Air" << std::endl;
3848 PointedThing fauxPointed;
3849 fauxPointed.type = POINTEDTHING_NOTHING;
3850 client->interact(5, fauxPointed);
3854 void Game::handlePointingAtNode(const PointedThing &pointed,
3855 const ItemDefinition &playeritem_def, const ItemStack &playeritem,
3856 const ToolCapabilities &playeritem_toolcap, f32 dtime)
3858 v3s16 nodepos = pointed.node_undersurface;
3859 v3s16 neighbourpos = pointed.node_abovesurface;
3862 Check information text of node
3865 ClientMap &map = client->getEnv().getClientMap();
3867 if (runData.nodig_delay_timer <= 0.0 && isLeftPressed()
3868 && !runData.digging_blocked
3869 && client->checkPrivilege("interact")) {
3870 handleDigging(pointed, nodepos, playeritem_toolcap, dtime);
3873 // This should be done after digging handling
3874 NodeMetadata *meta = map.getNodeMetadata(nodepos);
3877 infotext = unescape_translate(utf8_to_wide(meta->getString("infotext")));
3879 MapNode n = map.getNodeNoEx(nodepos);
3881 if (nodedef_manager->get(n).tiledef[0].name == "unknown_node.png") {
3882 infotext = L"Unknown node: ";
3883 infotext += utf8_to_wide(nodedef_manager->get(n).name);
3887 if ((getRightClicked() ||
3888 runData.repeat_rightclick_timer >= m_repeat_right_click_time) &&
3889 client->checkPrivilege("interact")) {
3890 runData.repeat_rightclick_timer = 0;
3891 infostream << "Ground right-clicked" << std::endl;
3893 if (meta && !meta->getString("formspec").empty() && !random_input
3894 && !isKeyDown(KeyType::SNEAK)) {
3895 // Report right click to server
3896 if (nodedef_manager->get(map.getNodeNoEx(nodepos)).rightclickable) {
3897 client->interact(3, pointed);
3900 infostream << "Launching custom inventory view" << std::endl;
3902 InventoryLocation inventoryloc;
3903 inventoryloc.setNodeMeta(nodepos);
3905 NodeMetadataFormSource *fs_src = new NodeMetadataFormSource(
3906 &client->getEnv().getClientMap(), nodepos);
3907 TextDest *txt_dst = new TextDestNodeMetadata(nodepos, client);
3909 create_formspec_menu(¤t_formspec, client,
3910 &input->joystick, fs_src, txt_dst);
3913 current_formspec->setFormSpec(meta->getString("formspec"), inventoryloc);
3915 // Report right click to server
3917 camera->setDigging(1); // right click animation (always shown for feedback)
3919 // If the wielded item has node placement prediction,
3921 bool placed = nodePlacementPrediction(*client,
3922 playeritem_def, playeritem,
3923 nodepos, neighbourpos);
3927 client->interact(3, pointed);
3929 soundmaker->m_player_rightpunch_sound =
3930 playeritem_def.sound_place;
3932 if (client->moddingEnabled())
3933 client->getScript()->on_placenode(pointed, playeritem_def);
3935 soundmaker->m_player_rightpunch_sound =
3938 if (playeritem_def.node_placement_prediction.empty() ||
3939 nodedef_manager->get(map.getNodeNoEx(nodepos)).rightclickable) {
3940 client->interact(3, pointed); // Report to server
3942 soundmaker->m_player_rightpunch_sound =
3943 playeritem_def.sound_place_failed;
3951 void Game::handlePointingAtObject(const PointedThing &pointed, const ItemStack &playeritem,
3952 const v3f &player_position, bool show_debug)
3954 infotext = unescape_translate(
3955 utf8_to_wide(runData.selected_object->infoText()));
3958 if (!infotext.empty()) {
3961 infotext += utf8_to_wide(runData.selected_object->debugInfoText());
3964 if (isLeftPressed()) {
3965 bool do_punch = false;
3966 bool do_punch_damage = false;
3968 if (runData.object_hit_delay_timer <= 0.0) {
3970 do_punch_damage = true;
3971 runData.object_hit_delay_timer = object_hit_delay;
3974 if (getLeftClicked())
3978 infostream << "Left-clicked object" << std::endl;
3979 runData.left_punch = true;
3982 if (do_punch_damage) {
3983 // Report direct punch
3984 v3f objpos = runData.selected_object->getPosition();
3985 v3f dir = (objpos - player_position).normalize();
3986 ItemStack item = playeritem;
3987 if (playeritem.name.empty()) {
3988 InventoryList *hlist = local_inventory->getList("hand");
3990 item = hlist->getItem(0);
3994 bool disable_send = runData.selected_object->directReportPunch(
3995 dir, &item, runData.time_from_last_punch);
3996 runData.time_from_last_punch = 0;
3999 client->interact(0, pointed);
4001 } else if (getRightClicked()) {
4002 infostream << "Right-clicked object" << std::endl;
4003 client->interact(3, pointed); // place
4008 void Game::handleDigging(const PointedThing &pointed, const v3s16 &nodepos,
4009 const ToolCapabilities &playeritem_toolcap, f32 dtime)
4011 LocalPlayer *player = client->getEnv().getLocalPlayer();
4012 ClientMap &map = client->getEnv().getClientMap();
4013 MapNode n = client->getEnv().getClientMap().getNodeNoEx(nodepos);
4015 // NOTE: Similar piece of code exists on the server side for
4017 // Get digging parameters
4018 DigParams params = getDigParams(nodedef_manager->get(n).groups,
4019 &playeritem_toolcap);
4021 // If can't dig, try hand
4022 if (!params.diggable) {
4023 InventoryList *hlist = local_inventory->getList("hand");
4024 const ToolCapabilities *tp = hlist
4025 ? &hlist->getItem(0).getToolCapabilities(itemdef_manager)
4026 : itemdef_manager->get("").tool_capabilities;
4029 params = getDigParams(nodedef_manager->get(n).groups, tp);
4032 if (!params.diggable) {
4033 // I guess nobody will wait for this long
4034 runData.dig_time_complete = 10000000.0;
4036 runData.dig_time_complete = params.time;
4038 if (m_cache_enable_particles) {
4039 const ContentFeatures &features = client->getNodeDefManager()->get(n);
4040 client->getParticleManager()->addNodeParticle(client,
4041 player, nodepos, n, features);
4045 if (!runData.digging) {
4046 infostream << "Started digging" << std::endl;
4047 runData.dig_instantly = runData.dig_time_complete == 0;
4048 if (client->moddingEnabled() && client->getScript()->on_punchnode(nodepos, n))
4050 client->interact(0, pointed);
4051 runData.digging = true;
4052 runData.ldown_for_dig = true;
4055 if (!runData.dig_instantly) {
4056 runData.dig_index = (float)crack_animation_length
4058 / runData.dig_time_complete;
4060 // This is for e.g. torches
4061 runData.dig_index = crack_animation_length;
4064 SimpleSoundSpec sound_dig = nodedef_manager->get(n).sound_dig;
4066 if (sound_dig.exists() && params.diggable) {
4067 if (sound_dig.name == "__group") {
4068 if (!params.main_group.empty()) {
4069 soundmaker->m_player_leftpunch_sound.gain = 0.5;
4070 soundmaker->m_player_leftpunch_sound.name =
4071 std::string("default_dig_") +
4075 soundmaker->m_player_leftpunch_sound = sound_dig;
4079 // Don't show cracks if not diggable
4080 if (runData.dig_time_complete >= 100000.0) {
4081 } else if (runData.dig_index < crack_animation_length) {
4082 //TimeTaker timer("client.setTempMod");
4083 //infostream<<"dig_index="<<dig_index<<std::endl;
4084 client->setCrack(runData.dig_index, nodepos);
4086 infostream << "Digging completed" << std::endl;
4087 client->setCrack(-1, v3s16(0, 0, 0));
4089 runData.dig_time = 0;
4090 runData.digging = false;
4091 // we successfully dug, now block it from repeating if we want to be safe
4092 if (g_settings->getBool("safe_dig_and_place"))
4093 runData.digging_blocked = true;
4095 runData.nodig_delay_timer =
4096 runData.dig_time_complete / (float)crack_animation_length;
4098 // We don't want a corresponding delay to very time consuming nodes
4099 // and nodes without digging time (e.g. torches) get a fixed delay.
4100 if (runData.nodig_delay_timer > 0.3)
4101 runData.nodig_delay_timer = 0.3;
4102 else if (runData.dig_instantly)
4103 runData.nodig_delay_timer = 0.15;
4105 bool is_valid_position;
4106 MapNode wasnode = map.getNodeNoEx(nodepos, &is_valid_position);
4107 if (is_valid_position) {
4108 if (client->moddingEnabled() &&
4109 client->getScript()->on_dignode(nodepos, wasnode)) {
4113 const ContentFeatures &f = client->ndef()->get(wasnode);
4114 if (f.node_dig_prediction == "air") {
4115 client->removeNode(nodepos);
4116 } else if (!f.node_dig_prediction.empty()) {
4118 bool found = client->ndef()->getId(f.node_dig_prediction, id);
4120 client->addNode(nodepos, id, true);
4122 // implicit else: no prediction
4125 client->interact(2, pointed);
4127 if (m_cache_enable_particles) {
4128 const ContentFeatures &features =
4129 client->getNodeDefManager()->get(wasnode);
4130 client->getParticleManager()->addDiggingParticles(client,
4131 player, nodepos, wasnode, features);
4135 // Send event to trigger sound
4136 MtEvent *e = new NodeDugEvent(nodepos, wasnode);
4137 client->event()->put(e);
4140 if (runData.dig_time_complete < 100000.0) {
4141 runData.dig_time += dtime;
4143 runData.dig_time = 0;
4144 client->setCrack(-1, nodepos);
4147 camera->setDigging(0); // left click animation
4151 void Game::updateFrame(ProfilerGraph *graph, RunStats *stats, f32 dtime,
4152 const CameraOrientation &cam)
4154 LocalPlayer *player = client->getEnv().getLocalPlayer();
4160 if (draw_control->range_all) {
4161 runData.fog_range = 100000 * BS;
4163 runData.fog_range = draw_control->wanted_range * BS;
4167 Calculate general brightness
4169 u32 daynight_ratio = client->getEnv().getDayNightRatio();
4170 float time_brightness = decode_light_f((float)daynight_ratio / 1000.0);
4171 float direct_brightness;
4174 if (m_cache_enable_noclip && m_cache_enable_free_move) {
4175 direct_brightness = time_brightness;
4176 sunlight_seen = true;
4178 ScopeProfiler sp(g_profiler, "Detecting background light", SPT_AVG);
4179 float old_brightness = sky->getBrightness();
4180 direct_brightness = client->getEnv().getClientMap()
4181 .getBackgroundBrightness(MYMIN(runData.fog_range * 1.2, 60 * BS),
4182 daynight_ratio, (int)(old_brightness * 255.5), &sunlight_seen)
4186 float time_of_day_smooth = runData.time_of_day_smooth;
4187 float time_of_day = client->getEnv().getTimeOfDayF();
4189 static const float maxsm = 0.05;
4190 static const float todsm = 0.05;
4192 if (fabs(time_of_day - time_of_day_smooth) > maxsm &&
4193 fabs(time_of_day - time_of_day_smooth + 1.0) > maxsm &&
4194 fabs(time_of_day - time_of_day_smooth - 1.0) > maxsm)
4195 time_of_day_smooth = time_of_day;
4197 if (time_of_day_smooth > 0.8 && time_of_day < 0.2)
4198 time_of_day_smooth = time_of_day_smooth * (1.0 - todsm)
4199 + (time_of_day + 1.0) * todsm;
4201 time_of_day_smooth = time_of_day_smooth * (1.0 - todsm)
4202 + time_of_day * todsm;
4204 runData.time_of_day = time_of_day;
4205 runData.time_of_day_smooth = time_of_day_smooth;
4207 sky->update(time_of_day_smooth, time_brightness, direct_brightness,
4208 sunlight_seen, camera->getCameraMode(), player->getYaw(),
4209 player->getPitch());
4215 if (sky->getCloudsVisible()) {
4216 clouds->setVisible(true);
4217 clouds->step(dtime);
4218 // camera->getPosition is not enough for 3rd person views
4219 v3f camera_node_position = camera->getCameraNode()->getPosition();
4220 v3s16 camera_offset = camera->getOffset();
4221 camera_node_position.X = camera_node_position.X + camera_offset.X * BS;
4222 camera_node_position.Y = camera_node_position.Y + camera_offset.Y * BS;
4223 camera_node_position.Z = camera_node_position.Z + camera_offset.Z * BS;
4224 clouds->update(camera_node_position,
4225 sky->getCloudColor());
4226 if (clouds->isCameraInsideCloud() && m_cache_enable_fog &&
4227 !flags.force_fog_off) {
4228 // if inside clouds, and fog enabled, use that as sky
4230 video::SColor clouds_dark = clouds->getColor()
4231 .getInterpolated(video::SColor(255, 0, 0, 0), 0.9);
4232 sky->overrideColors(clouds_dark, clouds->getColor());
4233 sky->setBodiesVisible(false);
4234 runData.fog_range = std::fmin(runData.fog_range * 0.5f, 32.0f * BS);
4235 // do not draw clouds after all
4236 clouds->setVisible(false);
4239 clouds->setVisible(false);
4246 client->getParticleManager()->step(dtime);
4252 if (m_cache_enable_fog && !flags.force_fog_off) {
4255 video::EFT_FOG_LINEAR,
4256 runData.fog_range * m_cache_fog_start,
4257 runData.fog_range * 1.0,
4265 video::EFT_FOG_LINEAR,
4275 Get chat messages from client
4278 v2u32 screensize = driver->getScreenSize();
4280 updateChat(*client, dtime, flags.show_debug, screensize,
4281 flags.show_chat, runData.profiler_current_page,
4282 *chat_backend, guitext_chat);
4288 if (client->getPlayerItem() != runData.new_playeritem)
4289 client->selectPlayerItem(runData.new_playeritem);
4291 // Update local inventory if it has changed
4292 if (client->getLocalInventoryUpdated()) {
4293 //infostream<<"Updating local inventory"<<std::endl;
4294 client->getLocalInventory(*local_inventory);
4295 runData.update_wielded_item_trigger = true;
4298 if (runData.update_wielded_item_trigger) {
4299 // Update wielded tool
4300 InventoryList *mlist = local_inventory->getList("main");
4302 if (mlist && (client->getPlayerItem() < mlist->getSize())) {
4303 ItemStack item = mlist->getItem(client->getPlayerItem());
4304 if (item.getDefinition(itemdef_manager).name.empty()) { // override the hand
4305 InventoryList *hlist = local_inventory->getList("hand");
4307 item = hlist->getItem(0);
4309 camera->wield(item);
4312 runData.update_wielded_item_trigger = false;
4316 Update block draw list every 200ms or when camera direction has
4319 runData.update_draw_list_timer += dtime;
4321 v3f camera_direction = camera->getDirection();
4322 if (runData.update_draw_list_timer >= 0.2
4323 || runData.update_draw_list_last_cam_dir.getDistanceFrom(camera_direction) > 0.2
4324 || m_camera_offset_changed) {
4325 runData.update_draw_list_timer = 0;
4326 client->getEnv().getClientMap().updateDrawList();
4327 runData.update_draw_list_last_cam_dir = camera_direction;
4330 updateGui(*stats, dtime, cam);
4333 make sure menu is on top
4334 1. Delete formspec menu reference if menu was removed
4335 2. Else, make sure formspec menu is on top
4337 if (current_formspec) {
4338 if (current_formspec->getReferenceCount() == 1) {
4339 current_formspec->drop();
4340 current_formspec = NULL;
4341 } else if (isMenuActive()) {
4342 guiroot->bringToFront(current_formspec);
4349 const video::SColor &skycolor = sky->getSkyColor();
4351 TimeTaker tt_draw("mainloop: draw");
4352 driver->beginScene(true, true, skycolor);
4354 bool draw_wield_tool = (flags.show_hud &&
4355 (player->hud_flags & HUD_FLAG_WIELDITEM_VISIBLE) &&
4356 (camera->getCameraMode() == CAMERA_MODE_FIRST));
4357 bool draw_crosshair = (
4358 (player->hud_flags & HUD_FLAG_CROSSHAIR_VISIBLE) &&
4359 (camera->getCameraMode() != CAMERA_MODE_THIRD_FRONT));
4360 #ifdef HAVE_TOUCHSCREENGUI
4362 draw_crosshair = !g_settings->getBool("touchtarget");
4363 } catch (SettingNotFoundException) {
4366 RenderingEngine::draw_scene(skycolor, flags.show_hud, flags.show_minimap,
4367 draw_wield_tool, draw_crosshair);
4372 if (flags.show_profiler_graph)
4373 graph->draw(10, screensize.Y - 10, driver, g_fontengine->getFont());
4378 if (runData.damage_flash > 0.0) {
4379 video::SColor color(runData.damage_flash, 180, 0, 0);
4380 driver->draw2DRectangle(color,
4381 core::rect<s32>(0, 0, screensize.X, screensize.Y),
4384 runData.damage_flash -= 100.0 * dtime;
4390 if (player->hurt_tilt_timer > 0.0) {
4391 player->hurt_tilt_timer -= dtime * 5;
4393 if (player->hurt_tilt_timer < 0)
4394 player->hurt_tilt_strength = 0;
4398 Update minimap pos and rotation
4400 if (mapper && flags.show_minimap && flags.show_hud) {
4401 mapper->setPos(floatToInt(player->getPosition(), BS));
4402 mapper->setAngle(player->getYaw());
4410 stats->drawtime = tt_draw.stop(true);
4411 g_profiler->graphAdd("mainloop_draw", stats->drawtime / 1000.0f);
4415 inline static const char *yawToDirectionString(int yaw)
4417 static const char *direction[4] = {"N +Z", "W -X", "S -Z", "E +X"};
4419 yaw = wrapDegrees_0_360(yaw);
4420 yaw = (yaw + 45) % 360 / 90;
4422 return direction[yaw];
4426 void Game::updateGui(const RunStats &stats, f32 dtime, const CameraOrientation &cam)
4428 v2u32 screensize = RenderingEngine::get_instance()->getWindowSize();
4429 LocalPlayer *player = client->getEnv().getLocalPlayer();
4430 v3f player_position = player->getPosition();
4432 if (flags.show_debug) {
4433 static float drawtime_avg = 0;
4434 drawtime_avg = drawtime_avg * 0.95 + stats.drawtime * 0.05;
4435 u16 fps = 1.0 / stats.dtime_jitter.avg;
4437 std::ostringstream os(std::ios_base::binary);
4439 << PROJECT_NAME_C " " << g_version_hash
4441 << std::setprecision(0)
4442 << ", drawtime: " << drawtime_avg << "ms"
4443 << std::setprecision(1)
4444 << ", dtime jitter: "
4445 << (stats.dtime_jitter.max_fraction * 100.0) << "%"
4446 << std::setprecision(1)
4448 << (draw_control->range_all ? "All" : itos(draw_control->wanted_range))
4449 << std::setprecision(3)
4450 << ", RTT: " << client->getRTT() << "s";
4451 setStaticText(guitext, utf8_to_wide(os.str()).c_str());
4452 guitext->setVisible(true);
4454 guitext->setVisible(false);
4457 if (guitext->isVisible()) {
4458 core::rect<s32> rect(
4460 screensize.X, 5 + g_fontengine->getTextHeight()
4462 guitext->setRelativePosition(rect);
4465 if (flags.show_debug) {
4466 std::ostringstream os(std::ios_base::binary);
4467 os << std::setprecision(1) << std::fixed
4468 << "pos: (" << (player_position.X / BS)
4469 << ", " << (player_position.Y / BS)
4470 << ", " << (player_position.Z / BS)
4471 << "), yaw: " << (wrapDegrees_0_360(cam.camera_yaw)) << "° "
4472 << yawToDirectionString(cam.camera_yaw)
4473 << ", seed: " << ((u64)client->getMapSeed());
4475 if (runData.pointed_old.type == POINTEDTHING_NODE) {
4476 ClientMap &map = client->getEnv().getClientMap();
4477 const INodeDefManager *nodedef = client->getNodeDefManager();
4478 MapNode n = map.getNodeNoEx(runData.pointed_old.node_undersurface);
4480 if (n.getContent() != CONTENT_IGNORE && nodedef->get(n).name != "unknown") {
4481 os << ", pointed: " << nodedef->get(n).name
4482 << ", param2: " << (u64) n.getParam2();
4486 setStaticText(guitext2, utf8_to_wide(os.str()).c_str());
4487 guitext2->setVisible(true);
4489 guitext2->setVisible(false);
4492 if (guitext2->isVisible()) {
4493 core::rect<s32> rect(
4494 5, 5 + g_fontengine->getTextHeight(),
4495 screensize.X, 5 + g_fontengine->getTextHeight() * 2
4497 guitext2->setRelativePosition(rect);
4500 setStaticText(guitext_info, translate_string(infotext).c_str());
4501 guitext_info->setVisible(flags.show_hud && g_menumgr.menuCount() == 0);
4503 float statustext_time_max = 1.5;
4505 if (!m_statustext.empty()) {
4506 runData.statustext_time += dtime;
4508 if (runData.statustext_time >= statustext_time_max) {
4510 runData.statustext_time = 0;
4514 setStaticText(guitext_status, translate_string(m_statustext).c_str());
4515 guitext_status->setVisible(!m_statustext.empty());
4517 if (!m_statustext.empty()) {
4518 s32 status_width = guitext_status->getTextWidth();
4519 s32 status_height = guitext_status->getTextHeight();
4520 s32 status_y = screensize.Y - 150;
4521 s32 status_x = (screensize.X - status_width) / 2;
4522 core::rect<s32> rect(
4523 status_x , status_y - status_height,
4524 status_x + status_width, status_y
4526 guitext_status->setRelativePosition(rect);
4529 video::SColor initial_color(255, 0, 0, 0);
4531 if (guienv->getSkin())
4532 initial_color = guienv->getSkin()->getColor(gui::EGDC_BUTTON_TEXT);
4534 video::SColor final_color = initial_color;
4535 final_color.setAlpha(0);
4536 video::SColor fade_color = initial_color.getInterpolated_quadratic(
4537 initial_color, final_color,
4538 pow(runData.statustext_time / statustext_time_max, 2.0f));
4539 guitext_status->setOverrideColor(fade_color);
4540 guitext_status->enableOverrideColor(true);
4545 /* Log times and stuff for visualization */
4546 inline void Game::updateProfilerGraphs(ProfilerGraph *graph)
4548 Profiler::GraphValues values;
4549 g_profiler->graphGet(values);
4555 /****************************************************************************
4557 ****************************************************************************/
4559 /* On some computers framerate doesn't seem to be automatically limited
4561 inline void Game::limitFps(FpsControl *fps_timings, f32 *dtime)
4563 // not using getRealTime is necessary for wine
4564 device->getTimer()->tick(); // Maker sure device time is up-to-date
4565 u32 time = device->getTimer()->getTime();
4566 u32 last_time = fps_timings->last_time;
4568 if (time > last_time) // Make sure time hasn't overflowed
4569 fps_timings->busy_time = time - last_time;
4571 fps_timings->busy_time = 0;
4573 u32 frametime_min = 1000 / (g_menumgr.pausesGame()
4574 ? g_settings->getFloat("pause_fps_max")
4575 : g_settings->getFloat("fps_max"));
4577 if (fps_timings->busy_time < frametime_min) {
4578 fps_timings->sleep_time = frametime_min - fps_timings->busy_time;
4579 device->sleep(fps_timings->sleep_time);
4581 fps_timings->sleep_time = 0;
4584 /* Get the new value of the device timer. Note that device->sleep() may
4585 * not sleep for the entire requested time as sleep may be interrupted and
4586 * therefore it is arguably more accurate to get the new time from the
4587 * device rather than calculating it by adding sleep_time to time.
4590 device->getTimer()->tick(); // Update device timer
4591 time = device->getTimer()->getTime();
4593 if (time > last_time) // Make sure last_time hasn't overflowed
4594 *dtime = (time - last_time) / 1000.0;
4598 fps_timings->last_time = time;
4601 void Game::showOverlayMessage(const char *msg, float dtime, int percent, bool draw_clouds)
4603 const wchar_t *wmsg = wgettext(msg);
4604 RenderingEngine::draw_load_screen(wmsg, guienv, texture_src, dtime, percent,
4609 void Game::showStatusTextSimple(const char *msg)
4611 const wchar_t *wmsg = wgettext(msg);
4612 m_statustext = wmsg;
4616 void Game::settingChangedCallback(const std::string &setting_name, void *data)
4618 ((Game *)data)->readSettings();
4621 void Game::readSettings()
4623 m_cache_doubletap_jump = g_settings->getBool("doubletap_jump");
4624 m_cache_enable_clouds = g_settings->getBool("enable_clouds");
4625 m_cache_enable_joysticks = g_settings->getBool("enable_joysticks");
4626 m_cache_enable_particles = g_settings->getBool("enable_particles");
4627 m_cache_enable_fog = g_settings->getBool("enable_fog");
4628 m_cache_mouse_sensitivity = g_settings->getFloat("mouse_sensitivity");
4629 m_cache_joystick_frustum_sensitivity = g_settings->getFloat("joystick_frustum_sensitivity");
4630 m_repeat_right_click_time = g_settings->getFloat("repeat_rightclick_time");
4632 m_cache_enable_noclip = g_settings->getBool("noclip");
4633 m_cache_enable_free_move = g_settings->getBool("free_move");
4635 m_cache_fog_start = g_settings->getFloat("fog_start");
4637 m_cache_cam_smoothing = 0;
4638 if (g_settings->getBool("cinematic"))
4639 m_cache_cam_smoothing = 1 - g_settings->getFloat("cinematic_camera_smoothing");
4641 m_cache_cam_smoothing = 1 - g_settings->getFloat("camera_smoothing");
4643 m_cache_fog_start = rangelim(m_cache_fog_start, 0.0f, 0.99f);
4644 m_cache_cam_smoothing = rangelim(m_cache_cam_smoothing, 0.01f, 1.0f);
4645 m_cache_mouse_sensitivity = rangelim(m_cache_mouse_sensitivity, 0.001, 100.0);
4647 m_does_lost_focus_pause_game = g_settings->getBool("pause_on_lost_focus");
4650 /****************************************************************************/
4651 /****************************************************************************
4653 ****************************************************************************/
4654 /****************************************************************************/
4656 void Game::extendedResourceCleanup()
4658 // Extended resource accounting
4659 infostream << "Irrlicht resources after cleanup:" << std::endl;
4660 infostream << "\tRemaining meshes : "
4661 << RenderingEngine::get_mesh_cache()->getMeshCount() << std::endl;
4662 infostream << "\tRemaining textures : "
4663 << driver->getTextureCount() << std::endl;
4665 for (unsigned int i = 0; i < driver->getTextureCount(); i++) {
4666 irr::video::ITexture *texture = driver->getTextureByIndex(i);
4667 infostream << "\t\t" << i << ":" << texture->getName().getPath().c_str()
4671 clearTextureNameCache();
4672 infostream << "\tRemaining materials: "
4673 << driver-> getMaterialRendererCount()
4674 << " (note: irrlicht doesn't support removing renderers)" << std::endl;
4677 #define GET_KEY_NAME(KEY) gettext(getKeySetting(#KEY).name())
4678 void Game::showPauseMenu()
4681 static const std::string control_text = strgettext("Default Controls:\n"
4682 "No menu visible:\n"
4683 "- single tap: button activate\n"
4684 "- double tap: place/use\n"
4685 "- slide finger: look around\n"
4686 "Menu/Inventory visible:\n"
4687 "- double tap (outside):\n"
4689 "- touch stack, touch slot:\n"
4691 "- touch&drag, tap 2nd finger\n"
4692 " --> place single item to slot\n"
4695 static const std::string control_text_template = strgettext("Controls:\n"
4696 "- %s: move forwards\n"
4697 "- %s: move backwards\n"
4699 "- %s: move right\n"
4700 "- %s: jump/climb\n"
4701 "- %s: sneak/go down\n"
4704 "- Mouse: turn/look\n"
4705 "- Mouse left: dig/punch\n"
4706 "- Mouse right: place/use\n"
4707 "- Mouse wheel: select item\n"
4711 char control_text_buf[600];
4713 snprintf(control_text_buf, ARRLEN(control_text_buf), control_text_template.c_str(),
4714 GET_KEY_NAME(keymap_forward),
4715 GET_KEY_NAME(keymap_backward),
4716 GET_KEY_NAME(keymap_left),
4717 GET_KEY_NAME(keymap_right),
4718 GET_KEY_NAME(keymap_jump),
4719 GET_KEY_NAME(keymap_sneak),
4720 GET_KEY_NAME(keymap_drop),
4721 GET_KEY_NAME(keymap_inventory),
4722 GET_KEY_NAME(keymap_chat)
4725 std::string control_text = std::string(control_text_buf);
4726 str_formspec_escape(control_text);
4729 float ypos = simple_singleplayer_mode ? 0.7f : 0.1f;
4730 std::ostringstream os;
4732 os << FORMSPEC_VERSION_STRING << SIZE_TAG
4733 << "button_exit[4," << (ypos++) << ";3,0.5;btn_continue;"
4734 << strgettext("Continue") << "]";
4736 if (!simple_singleplayer_mode) {
4737 os << "button_exit[4," << (ypos++) << ";3,0.5;btn_change_password;"
4738 << strgettext("Change Password") << "]";
4740 os << "field[4.95,0;5,1.5;;" << strgettext("Game paused") << ";]";
4744 os << "button_exit[4," << (ypos++) << ";3,0.5;btn_sound;"
4745 << strgettext("Sound Volume") << "]";
4746 os << "button_exit[4," << (ypos++) << ";3,0.5;btn_key_config;"
4747 << strgettext("Change Keys") << "]";
4749 os << "button_exit[4," << (ypos++) << ";3,0.5;btn_exit_menu;"
4750 << strgettext("Exit to Menu") << "]";
4751 os << "button_exit[4," << (ypos++) << ";3,0.5;btn_exit_os;"
4752 << strgettext("Exit to OS") << "]"
4753 << "textarea[7.5,0.25;3.9,6.25;;" << control_text << ";]"
4754 << "textarea[0.4,0.25;3.9,6.25;;" << PROJECT_NAME_C " " VERSION_STRING "\n"
4756 << strgettext("Game info:") << "\n";
4757 const std::string &address = client->getAddressName();
4758 static const std::string mode = strgettext("- Mode: ");
4759 if (!simple_singleplayer_mode) {
4760 Address serverAddress = client->getServerAddress();
4761 if (!address.empty()) {
4762 os << mode << strgettext("Remote server") << "\n"
4763 << strgettext("- Address: ") << address;
4765 os << mode << strgettext("Hosting server");
4767 os << "\n" << strgettext("- Port: ") << serverAddress.getPort() << "\n";
4769 os << mode << strgettext("Singleplayer") << "\n";
4771 if (simple_singleplayer_mode || address.empty()) {
4772 static const std::string on = strgettext("On");
4773 static const std::string off = strgettext("Off");
4774 const std::string &damage = g_settings->getBool("enable_damage") ? on : off;
4775 const std::string &creative = g_settings->getBool("creative_mode") ? on : off;
4776 const std::string &announced = g_settings->getBool("server_announce") ? on : off;
4777 os << strgettext("- Damage: ") << damage << "\n"
4778 << strgettext("- Creative Mode: ") << creative << "\n";
4779 if (!simple_singleplayer_mode) {
4780 const std::string &pvp = g_settings->getBool("enable_pvp") ? on : off;
4781 os << strgettext("- PvP: ") << pvp << "\n"
4782 << strgettext("- Public: ") << announced << "\n";
4783 std::string server_name = g_settings->get("server_name");
4784 str_formspec_escape(server_name);
4785 if (announced == on && !server_name.empty())
4786 os << strgettext("- Server Name: ") << server_name;
4793 /* Note: FormspecFormSource and LocalFormspecHandler *
4794 * are deleted by guiFormSpecMenu */
4795 FormspecFormSource *fs_src = new FormspecFormSource(os.str());
4796 LocalFormspecHandler *txt_dst = new LocalFormspecHandler("MT_PAUSE_MENU");
4798 create_formspec_menu(¤t_formspec, client, &input->joystick, fs_src, txt_dst);
4799 current_formspec->setFocus("btn_continue");
4800 current_formspec->doPause = true;
4803 /****************************************************************************/
4804 /****************************************************************************
4805 extern function for launching the game
4806 ****************************************************************************/
4807 /****************************************************************************/
4809 void the_game(bool *kill,
4811 InputHandler *input,
4812 const std::string &map_dir,
4813 const std::string &playername,
4814 const std::string &password,
4815 const std::string &address, // If empty local server is created
4818 std::string &error_message,
4819 ChatBackend &chat_backend,
4820 bool *reconnect_requested,
4821 const SubgameSpec &gamespec, // Used for local game
4822 bool simple_singleplayer_mode)
4826 /* Make a copy of the server address because if a local singleplayer server
4827 * is created then this is updated and we don't want to change the value
4828 * passed to us by the calling function
4830 std::string server_address = address;
4834 if (game.startup(kill, random_input, input, map_dir,
4835 playername, password, &server_address, port, error_message,
4836 reconnect_requested, &chat_backend, gamespec,
4837 simple_singleplayer_mode)) {
4842 } catch (SerializationError &e) {
4843 error_message = std::string("A serialization error occurred:\n")
4844 + e.what() + "\n\nThe server is probably "
4845 " running a different version of " PROJECT_NAME_C ".";
4846 errorstream << error_message << std::endl;
4847 } catch (ServerError &e) {
4848 error_message = e.what();
4849 errorstream << "ServerError: " << error_message << std::endl;
4850 } catch (ModError &e) {
4851 error_message = e.what() + strgettext("\nCheck debug.txt for details.");
4852 errorstream << "ModError: " << error_message << std::endl;