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/inputhandler.h"
28 #include "client/tile.h" // For TextureSource
29 #include "client/keys.h"
30 #include "client/joystick_controller.h"
31 #include "clientmap.h"
34 #include "content_cao.h"
35 #include "event_manager.h"
36 #include "fontengine.h"
41 #include "guiChatConsole.h"
42 #include "guiFormSpecMenu.h"
43 #include "guiKeyChangeMenu.h"
44 #include "guiPasswordChange.h"
45 #include "guiVolumeChange.h"
46 #include "mainmenumanager.h"
49 #include "nodedef.h" // Needed for determining pointing to nodes
50 #include "nodemetadata.h"
51 #include "particles.h"
53 #include "quicktune_shortcutter.h"
61 #include "util/basic_macros.h"
62 #include "util/directiontables.h"
63 #include "util/pointedthing.h"
64 #include "irrlicht_changes/static_text.h"
66 #include "script/scripting_client.h"
69 #include "sound_openal.h"
77 struct TextDestNodeMetadata : public TextDest
79 TextDestNodeMetadata(v3s16 p, Client *client)
84 // This is deprecated I guess? -celeron55
85 void gotText(const std::wstring &text)
87 std::string ntext = wide_to_utf8(text);
88 infostream << "Submitting 'text' field of node at (" << m_p.X << ","
89 << m_p.Y << "," << m_p.Z << "): " << ntext << std::endl;
91 fields["text"] = ntext;
92 m_client->sendNodemetaFields(m_p, "", fields);
94 void gotText(const StringMap &fields)
96 m_client->sendNodemetaFields(m_p, "", fields);
103 struct TextDestPlayerInventory : public TextDest
105 TextDestPlayerInventory(Client *client)
110 TextDestPlayerInventory(Client *client, const std::string &formname)
113 m_formname = formname;
115 void gotText(const StringMap &fields)
117 m_client->sendInventoryFields(m_formname, fields);
123 struct LocalFormspecHandler : public TextDest
125 LocalFormspecHandler(const std::string &formname)
127 m_formname = formname;
130 LocalFormspecHandler(const std::string &formname, Client *client):
133 m_formname = formname;
136 void gotText(const StringMap &fields)
138 if (m_formname == "MT_PAUSE_MENU") {
139 if (fields.find("btn_sound") != fields.end()) {
140 g_gamecallback->changeVolume();
144 if (fields.find("btn_key_config") != fields.end()) {
145 g_gamecallback->keyConfig();
149 if (fields.find("btn_exit_menu") != fields.end()) {
150 g_gamecallback->disconnect();
154 if (fields.find("btn_exit_os") != fields.end()) {
155 g_gamecallback->exitToOS();
157 RenderingEngine::get_raw_device()->closeDevice();
162 if (fields.find("btn_change_password") != fields.end()) {
163 g_gamecallback->changePassword();
167 if (fields.find("quit") != fields.end()) {
171 if (fields.find("btn_continue") != fields.end()) {
176 // Don't disable this part when modding is disabled, it's used in builtin
177 if (m_client && m_client->getScript())
178 m_client->getScript()->on_formspec_input(m_formname, fields);
181 Client *m_client = nullptr;
184 /* Form update callback */
186 class NodeMetadataFormSource: public IFormSource
189 NodeMetadataFormSource(ClientMap *map, v3s16 p):
194 std::string getForm()
196 NodeMetadata *meta = m_map->getNodeMetadata(m_p);
201 return meta->getString("formspec");
204 virtual std::string resolveText(const std::string &str)
206 NodeMetadata *meta = m_map->getNodeMetadata(m_p);
211 return meta->resolveString(str);
218 class PlayerInventoryFormSource: public IFormSource
221 PlayerInventoryFormSource(Client *client):
225 std::string getForm()
227 LocalPlayer *player = m_client->getEnv().getLocalPlayer();
228 return player->inventory_formspec;
234 /* Profiler display */
236 void update_profiler_gui(gui::IGUIStaticText *guitext_profiler, FontEngine *fe,
237 u32 show_profiler, u32 show_profiler_max, s32 screen_height)
239 if (show_profiler == 0) {
240 guitext_profiler->setVisible(false);
243 std::ostringstream os(std::ios_base::binary);
244 g_profiler->printPage(os, show_profiler, show_profiler_max);
245 std::wstring text = utf8_to_wide(os.str());
246 setStaticText(guitext_profiler, text.c_str());
247 guitext_profiler->setVisible(true);
249 s32 w = fe->getTextWidth(text);
254 unsigned text_height = fe->getTextHeight();
256 core::position2di upper_left, lower_right;
259 upper_left.Y = (text_height + 5) * 2;
260 lower_right.X = 12 + w;
261 lower_right.Y = upper_left.Y + (text_height + 1) * MAX_PROFILER_TEXT_ROWS;
263 if (lower_right.Y > screen_height * 2 / 3)
264 lower_right.Y = screen_height * 2 / 3;
266 core::rect<s32> rect(upper_left, lower_right);
268 guitext_profiler->setRelativePosition(rect);
269 guitext_profiler->setVisible(true);
277 Profiler::GraphValues values;
283 Meta(float initial = 0,
284 video::SColor color = video::SColor(255, 255, 255, 255)):
290 std::deque<Piece> m_log;
292 u32 m_log_max_size = 200;
294 ProfilerGraph() = default;
296 void put(const Profiler::GraphValues &values)
299 piece.values = values;
300 m_log.push_back(piece);
302 while (m_log.size() > m_log_max_size)
303 m_log.erase(m_log.begin());
306 void draw(s32 x_left, s32 y_bottom, video::IVideoDriver *driver,
307 gui::IGUIFont *font) const
309 // Do *not* use UNORDERED_MAP here as the order needs
310 // to be the same for each call to prevent flickering
311 std::map<std::string, Meta> m_meta;
313 for (const Piece &piece : m_log) {
314 for (const auto &i : piece.values) {
315 const std::string &id = i.first;
316 const float &value = i.second;
317 std::map<std::string, Meta>::iterator j = m_meta.find(id);
319 if (j == m_meta.end()) {
320 m_meta[id] = Meta(value);
324 if (value < j->second.min)
325 j->second.min = value;
327 if (value > j->second.max)
328 j->second.max = value;
333 static const video::SColor usable_colors[] = {
334 video::SColor(255, 255, 100, 100),
335 video::SColor(255, 90, 225, 90),
336 video::SColor(255, 100, 100, 255),
337 video::SColor(255, 255, 150, 50),
338 video::SColor(255, 220, 220, 100)
340 static const u32 usable_colors_count =
341 sizeof(usable_colors) / sizeof(*usable_colors);
342 u32 next_color_i = 0;
344 for (auto &i : m_meta) {
345 Meta &meta = i.second;
346 video::SColor color(255, 200, 200, 200);
348 if (next_color_i < usable_colors_count)
349 color = usable_colors[next_color_i++];
355 s32 textx = x_left + m_log_max_size + 15;
356 s32 textx2 = textx + 200 - 15;
359 for (std::map<std::string, Meta>::const_iterator i = m_meta.begin();
360 i != m_meta.end(); ++i) {
361 const std::string &id = i->first;
362 const Meta &meta = i->second;
364 s32 y = y_bottom - meta_i * 50;
365 float show_min = meta.min;
366 float show_max = meta.max;
368 if (show_min >= -0.0001 && show_max >= -0.0001) {
369 if (show_min <= show_max * 0.5)
375 snprintf(buf, 10, "%.3g", show_max);
376 font->draw(utf8_to_wide(buf).c_str(),
377 core::rect<s32>(textx, y - graphh,
378 textx2, y - graphh + texth),
380 snprintf(buf, 10, "%.3g", show_min);
381 font->draw(utf8_to_wide(buf).c_str(),
382 core::rect<s32>(textx, y - texth,
385 font->draw(utf8_to_wide(id).c_str(),
386 core::rect<s32>(textx, y - graphh / 2 - texth / 2,
387 textx2, y - graphh / 2 + texth / 2),
390 s32 graph1h = graphh;
391 bool relativegraph = (show_min != 0 && show_min != show_max);
392 float lastscaledvalue = 0.0;
393 bool lastscaledvalue_exists = false;
395 for (const Piece &piece : m_log) {
397 bool value_exists = false;
398 Profiler::GraphValues::const_iterator k =
399 piece.values.find(id);
401 if (k != piece.values.end()) {
408 lastscaledvalue_exists = false;
412 float scaledvalue = 1.0;
414 if (show_max != show_min)
415 scaledvalue = (value - show_min) / (show_max - show_min);
417 if (scaledvalue == 1.0 && value == 0) {
419 lastscaledvalue_exists = false;
424 if (lastscaledvalue_exists) {
425 s32 ivalue1 = lastscaledvalue * graph1h;
426 s32 ivalue2 = scaledvalue * graph1h;
427 driver->draw2DLine(v2s32(x - 1, graph1y - ivalue1),
428 v2s32(x, graph1y - ivalue2), meta.color);
431 lastscaledvalue = scaledvalue;
432 lastscaledvalue_exists = true;
434 s32 ivalue = scaledvalue * graph1h;
435 driver->draw2DLine(v2s32(x, graph1y),
436 v2s32(x, graph1y - ivalue), meta.color);
447 class NodeDugEvent: public MtEvent
453 NodeDugEvent(v3s16 p, MapNode n):
457 const char *getType() const
465 ISoundManager *m_sound;
466 INodeDefManager *m_ndef;
468 bool makes_footstep_sound;
469 float m_player_step_timer;
471 SimpleSoundSpec m_player_step_sound;
472 SimpleSoundSpec m_player_leftpunch_sound;
473 SimpleSoundSpec m_player_rightpunch_sound;
475 SoundMaker(ISoundManager *sound, INodeDefManager *ndef):
478 makes_footstep_sound(true),
479 m_player_step_timer(0)
483 void playPlayerStep()
485 if (m_player_step_timer <= 0 && m_player_step_sound.exists()) {
486 m_player_step_timer = 0.03;
487 if (makes_footstep_sound)
488 m_sound->playSound(m_player_step_sound, false);
492 static void viewBobbingStep(MtEvent *e, void *data)
494 SoundMaker *sm = (SoundMaker *)data;
495 sm->playPlayerStep();
498 static void playerRegainGround(MtEvent *e, void *data)
500 SoundMaker *sm = (SoundMaker *)data;
501 sm->playPlayerStep();
504 static void playerJump(MtEvent *e, void *data)
506 //SoundMaker *sm = (SoundMaker*)data;
509 static void cameraPunchLeft(MtEvent *e, void *data)
511 SoundMaker *sm = (SoundMaker *)data;
512 sm->m_sound->playSound(sm->m_player_leftpunch_sound, false);
515 static void cameraPunchRight(MtEvent *e, void *data)
517 SoundMaker *sm = (SoundMaker *)data;
518 sm->m_sound->playSound(sm->m_player_rightpunch_sound, false);
521 static void nodeDug(MtEvent *e, void *data)
523 SoundMaker *sm = (SoundMaker *)data;
524 NodeDugEvent *nde = (NodeDugEvent *)e;
525 sm->m_sound->playSound(sm->m_ndef->get(nde->n).sound_dug, false);
528 static void playerDamage(MtEvent *e, void *data)
530 SoundMaker *sm = (SoundMaker *)data;
531 sm->m_sound->playSound(SimpleSoundSpec("player_damage", 0.5), false);
534 static void playerFallingDamage(MtEvent *e, void *data)
536 SoundMaker *sm = (SoundMaker *)data;
537 sm->m_sound->playSound(SimpleSoundSpec("player_falling_damage", 0.5), false);
540 void registerReceiver(MtEventManager *mgr)
542 mgr->reg("ViewBobbingStep", SoundMaker::viewBobbingStep, this);
543 mgr->reg("PlayerRegainGround", SoundMaker::playerRegainGround, this);
544 mgr->reg("PlayerJump", SoundMaker::playerJump, this);
545 mgr->reg("CameraPunchLeft", SoundMaker::cameraPunchLeft, this);
546 mgr->reg("CameraPunchRight", SoundMaker::cameraPunchRight, this);
547 mgr->reg("NodeDug", SoundMaker::nodeDug, this);
548 mgr->reg("PlayerDamage", SoundMaker::playerDamage, this);
549 mgr->reg("PlayerFallingDamage", SoundMaker::playerFallingDamage, this);
552 void step(float dtime)
554 m_player_step_timer -= dtime;
558 // Locally stored sounds don't need to be preloaded because of this
559 class GameOnDemandSoundFetcher: public OnDemandSoundFetcher
561 std::set<std::string> m_fetched;
563 void paths_insert(std::set<std::string> &dst_paths,
564 const std::string &base,
565 const std::string &name)
567 dst_paths.insert(base + DIR_DELIM + "sounds" + DIR_DELIM + name + ".ogg");
568 dst_paths.insert(base + DIR_DELIM + "sounds" + DIR_DELIM + name + ".0.ogg");
569 dst_paths.insert(base + DIR_DELIM + "sounds" + DIR_DELIM + name + ".1.ogg");
570 dst_paths.insert(base + DIR_DELIM + "sounds" + DIR_DELIM + name + ".2.ogg");
571 dst_paths.insert(base + DIR_DELIM + "sounds" + DIR_DELIM + name + ".3.ogg");
572 dst_paths.insert(base + DIR_DELIM + "sounds" + DIR_DELIM + name + ".4.ogg");
573 dst_paths.insert(base + DIR_DELIM + "sounds" + DIR_DELIM + name + ".5.ogg");
574 dst_paths.insert(base + DIR_DELIM + "sounds" + DIR_DELIM + name + ".6.ogg");
575 dst_paths.insert(base + DIR_DELIM + "sounds" + DIR_DELIM + name + ".7.ogg");
576 dst_paths.insert(base + DIR_DELIM + "sounds" + DIR_DELIM + name + ".8.ogg");
577 dst_paths.insert(base + DIR_DELIM + "sounds" + DIR_DELIM + name + ".9.ogg");
580 void fetchSounds(const std::string &name,
581 std::set<std::string> &dst_paths,
582 std::set<std::string> &dst_datas)
584 if (m_fetched.count(name))
587 m_fetched.insert(name);
589 paths_insert(dst_paths, porting::path_share, name);
590 paths_insert(dst_paths, porting::path_user, name);
595 // before 1.8 there isn't a "integer interface", only float
596 #if (IRRLICHT_VERSION_MAJOR == 1 && IRRLICHT_VERSION_MINOR < 8)
597 typedef f32 SamplerLayer_t;
599 typedef s32 SamplerLayer_t;
603 class GameGlobalShaderConstantSetter : public IShaderConstantSetter
606 bool *m_force_fog_off;
609 CachedPixelShaderSetting<float, 4> m_sky_bg_color;
610 CachedPixelShaderSetting<float> m_fog_distance;
611 CachedVertexShaderSetting<float> m_animation_timer_vertex;
612 CachedPixelShaderSetting<float> m_animation_timer_pixel;
613 CachedPixelShaderSetting<float, 3> m_day_light;
614 CachedPixelShaderSetting<float, 3> m_eye_position_pixel;
615 CachedVertexShaderSetting<float, 3> m_eye_position_vertex;
616 CachedPixelShaderSetting<float, 3> m_minimap_yaw;
617 CachedPixelShaderSetting<SamplerLayer_t> m_base_texture;
618 CachedPixelShaderSetting<SamplerLayer_t> m_normal_texture;
619 CachedPixelShaderSetting<SamplerLayer_t> m_texture_flags;
623 void onSettingsChange(const std::string &name)
625 if (name == "enable_fog")
626 m_fog_enabled = g_settings->getBool("enable_fog");
629 static void settingsCallback(const std::string &name, void *userdata)
631 reinterpret_cast<GameGlobalShaderConstantSetter*>(userdata)->onSettingsChange(name);
634 void setSky(Sky *sky) { m_sky = sky; }
636 GameGlobalShaderConstantSetter(Sky *sky, bool *force_fog_off,
637 f32 *fog_range, Client *client) :
639 m_force_fog_off(force_fog_off),
640 m_fog_range(fog_range),
641 m_sky_bg_color("skyBgColor"),
642 m_fog_distance("fogDistance"),
643 m_animation_timer_vertex("animationTimer"),
644 m_animation_timer_pixel("animationTimer"),
645 m_day_light("dayLight"),
646 m_eye_position_pixel("eyePosition"),
647 m_eye_position_vertex("eyePosition"),
648 m_minimap_yaw("yawVec"),
649 m_base_texture("baseTexture"),
650 m_normal_texture("normalTexture"),
651 m_texture_flags("textureFlags"),
654 g_settings->registerChangedCallback("enable_fog", settingsCallback, this);
655 m_fog_enabled = g_settings->getBool("enable_fog");
658 ~GameGlobalShaderConstantSetter()
660 g_settings->deregisterChangedCallback("enable_fog", settingsCallback, this);
663 virtual void onSetConstants(video::IMaterialRendererServices *services,
670 video::SColor bgcolor = m_sky->getBgColor();
671 video::SColorf bgcolorf(bgcolor);
672 float bgcolorfa[4] = {
678 m_sky_bg_color.set(bgcolorfa, services);
681 float fog_distance = 10000 * BS;
683 if (m_fog_enabled && !*m_force_fog_off)
684 fog_distance = *m_fog_range;
686 m_fog_distance.set(&fog_distance, services);
688 u32 daynight_ratio = (float)m_client->getEnv().getDayNightRatio();
689 video::SColorf sunlight;
690 get_sunlight_color(&sunlight, daynight_ratio);
695 m_day_light.set(dnc, services);
697 u32 animation_timer = porting::getTimeMs() % 100000;
698 float animation_timer_f = (float)animation_timer / 100000.f;
699 m_animation_timer_vertex.set(&animation_timer_f, services);
700 m_animation_timer_pixel.set(&animation_timer_f, services);
702 float eye_position_array[3];
703 v3f epos = m_client->getEnv().getLocalPlayer()->getEyePosition();
704 #if (IRRLICHT_VERSION_MAJOR == 1 && IRRLICHT_VERSION_MINOR < 8)
705 eye_position_array[0] = epos.X;
706 eye_position_array[1] = epos.Y;
707 eye_position_array[2] = epos.Z;
709 epos.getAs3Values(eye_position_array);
711 m_eye_position_pixel.set(eye_position_array, services);
712 m_eye_position_vertex.set(eye_position_array, services);
714 if (m_client->getMinimap()) {
715 float minimap_yaw_array[3];
716 v3f minimap_yaw = m_client->getMinimap()->getYawVec();
717 #if (IRRLICHT_VERSION_MAJOR == 1 && IRRLICHT_VERSION_MINOR < 8)
718 minimap_yaw_array[0] = minimap_yaw.X;
719 minimap_yaw_array[1] = minimap_yaw.Y;
720 minimap_yaw_array[2] = minimap_yaw.Z;
722 minimap_yaw.getAs3Values(minimap_yaw_array);
724 m_minimap_yaw.set(minimap_yaw_array, services);
727 SamplerLayer_t base_tex = 0,
730 m_base_texture.set(&base_tex, services);
731 m_normal_texture.set(&normal_tex, services);
732 m_texture_flags.set(&flags_tex, services);
737 class GameGlobalShaderConstantSetterFactory : public IShaderConstantSetterFactory
740 bool *m_force_fog_off;
743 std::vector<GameGlobalShaderConstantSetter *> created_nosky;
745 GameGlobalShaderConstantSetterFactory(bool *force_fog_off,
746 f32 *fog_range, Client *client) :
748 m_force_fog_off(force_fog_off),
749 m_fog_range(fog_range),
753 void setSky(Sky *sky) {
755 for (GameGlobalShaderConstantSetter *ggscs : created_nosky) {
756 ggscs->setSky(m_sky);
758 created_nosky.clear();
761 virtual IShaderConstantSetter* create()
763 GameGlobalShaderConstantSetter *scs = new GameGlobalShaderConstantSetter(
764 m_sky, m_force_fog_off, m_fog_range, m_client);
766 created_nosky.push_back(scs);
772 bool nodePlacementPrediction(Client &client, const ItemDefinition &playeritem_def,
773 const ItemStack &playeritem, v3s16 nodepos, v3s16 neighbourpos)
775 std::string prediction = playeritem_def.node_placement_prediction;
776 INodeDefManager *nodedef = client.ndef();
777 ClientMap &map = client.getEnv().getClientMap();
779 bool is_valid_position;
781 node = map.getNodeNoEx(nodepos, &is_valid_position);
782 if (!is_valid_position)
785 if (!prediction.empty() && !nodedef->get(node).rightclickable) {
786 verbosestream << "Node placement prediction for "
787 << playeritem_def.name << " is "
788 << prediction << std::endl;
789 v3s16 p = neighbourpos;
791 // Place inside node itself if buildable_to
792 MapNode n_under = map.getNodeNoEx(nodepos, &is_valid_position);
793 if (is_valid_position)
795 if (nodedef->get(n_under).buildable_to)
798 node = map.getNodeNoEx(p, &is_valid_position);
799 if (is_valid_position &&!nodedef->get(node).buildable_to)
804 // Find id of predicted node
806 bool found = nodedef->getId(prediction, id);
809 errorstream << "Node placement prediction failed for "
810 << playeritem_def.name << " (places "
812 << ") - Name not known" << std::endl;
816 const ContentFeatures &predicted_f = nodedef->get(id);
818 // Predict param2 for facedir and wallmounted nodes
821 if (predicted_f.param_type_2 == CPT2_WALLMOUNTED ||
822 predicted_f.param_type_2 == CPT2_COLORED_WALLMOUNTED) {
823 v3s16 dir = nodepos - neighbourpos;
825 if (abs(dir.Y) > MYMAX(abs(dir.X), abs(dir.Z))) {
826 param2 = dir.Y < 0 ? 1 : 0;
827 } else if (abs(dir.X) > abs(dir.Z)) {
828 param2 = dir.X < 0 ? 3 : 2;
830 param2 = dir.Z < 0 ? 5 : 4;
834 if (predicted_f.param_type_2 == CPT2_FACEDIR ||
835 predicted_f.param_type_2 == CPT2_COLORED_FACEDIR) {
836 v3s16 dir = nodepos - floatToInt(client.getEnv().getLocalPlayer()->getPosition(), BS);
838 if (abs(dir.X) > abs(dir.Z)) {
839 param2 = dir.X < 0 ? 3 : 1;
841 param2 = dir.Z < 0 ? 2 : 0;
847 //Check attachment if node is in group attached_node
848 if (((ItemGroupList) predicted_f.groups)["attached_node"] != 0) {
849 static v3s16 wallmounted_dirs[8] = {
859 if (predicted_f.param_type_2 == CPT2_WALLMOUNTED ||
860 predicted_f.param_type_2 == CPT2_COLORED_WALLMOUNTED)
861 pp = p + wallmounted_dirs[param2];
863 pp = p + v3s16(0, -1, 0);
865 if (!nodedef->get(map.getNodeNoEx(pp)).walkable)
870 if ((predicted_f.param_type_2 == CPT2_COLOR
871 || predicted_f.param_type_2 == CPT2_COLORED_FACEDIR
872 || predicted_f.param_type_2 == CPT2_COLORED_WALLMOUNTED)) {
873 const std::string &indexstr = playeritem.metadata.getString(
875 if (!indexstr.empty()) {
876 s32 index = mystoi(indexstr);
877 if (predicted_f.param_type_2 == CPT2_COLOR) {
879 } else if (predicted_f.param_type_2
880 == CPT2_COLORED_WALLMOUNTED) {
881 // param2 = pure palette index + other
882 param2 = (index & 0xf8) | (param2 & 0x07);
883 } else if (predicted_f.param_type_2
884 == CPT2_COLORED_FACEDIR) {
885 // param2 = pure palette index + other
886 param2 = (index & 0xe0) | (param2 & 0x1f);
891 // Add node to client map
892 MapNode n(id, 0, param2);
895 LocalPlayer *player = client.getEnv().getLocalPlayer();
897 // Dont place node when player would be inside new node
898 // NOTE: This is to be eventually implemented by a mod as client-side Lua
899 if (!nodedef->get(n).walkable ||
900 g_settings->getBool("enable_build_where_you_stand") ||
901 (client.checkPrivilege("noclip") && g_settings->getBool("noclip")) ||
902 (nodedef->get(n).walkable &&
903 neighbourpos != player->getStandingNodePos() + v3s16(0, 1, 0) &&
904 neighbourpos != player->getStandingNodePos() + v3s16(0, 2, 0))) {
906 // This triggers the required mesh update too
907 client.addNode(p, n);
910 } catch (InvalidPositionException &e) {
911 errorstream << "Node placement prediction failed for "
912 << playeritem_def.name << " (places "
914 << ") - Position not loaded" << std::endl;
921 static inline void create_formspec_menu(GUIFormSpecMenu **cur_formspec,
922 Client *client, JoystickController *joystick,
923 IFormSource *fs_src, TextDest *txt_dest)
926 if (*cur_formspec == 0) {
927 *cur_formspec = new GUIFormSpecMenu(joystick, guiroot, -1, &g_menumgr,
928 client, client->getTextureSource(), fs_src, txt_dest);
929 (*cur_formspec)->doPause = false;
932 Caution: do not call (*cur_formspec)->drop() here --
933 the reference might outlive the menu, so we will
934 periodically check if *cur_formspec is the only
935 remaining reference (i.e. the menu was removed)
936 and delete it in that case.
940 (*cur_formspec)->setFormSource(fs_src);
941 (*cur_formspec)->setTextDest(txt_dest);
947 #define SIZE_TAG "size[11,5.5]"
949 #define SIZE_TAG "size[11,5.5,true]" // Fixed size on desktop
952 /******************************************************************************/
953 static void updateChat(Client &client, f32 dtime, bool show_debug,
954 const v2u32 &screensize, bool show_chat, u32 show_profiler,
955 ChatBackend &chat_backend, gui::IGUIStaticText *guitext_chat)
957 // Add chat log output for errors to be shown in chat
958 static LogOutputBuffer chat_log_error_buf(g_logger, LL_ERROR);
960 // Get new messages from error log buffer
961 while (!chat_log_error_buf.empty()) {
962 std::wstring error_message = utf8_to_wide(chat_log_error_buf.get());
963 if (!g_settings->getBool("disable_escape_sequences")) {
964 error_message = L"\x1b(c@red)" + error_message + L"\x1b(c@white)";
966 chat_backend.addMessage(L"", error_message);
969 // Get new messages from client
970 std::wstring message;
971 while (client.getChatMessage(message)) {
972 chat_backend.addUnparsedMessage(message);
975 // Remove old messages
976 chat_backend.step(dtime);
978 // Display all messages in a static text element
979 unsigned int recent_chat_count = chat_backend.getRecentBuffer().getLineCount();
980 EnrichedString recent_chat = chat_backend.getRecentChat();
981 unsigned int line_height = g_fontengine->getLineHeight();
983 setStaticText(guitext_chat, recent_chat);
985 // Update gui element size and position
989 chat_y += 3 * line_height;
991 // first pass to calculate height of text to be set
992 const v2u32 &window_size = RenderingEngine::get_instance()->getWindowSize();
993 s32 width = std::min(g_fontengine->getTextWidth(recent_chat.c_str()) + 10,
995 core::rect<s32> rect(10, chat_y, width, chat_y + window_size.Y);
996 guitext_chat->setRelativePosition(rect);
998 //now use real height of text and adjust rect according to this size
999 rect = core::rect<s32>(10, chat_y, width,
1000 chat_y + guitext_chat->getTextHeight());
1003 guitext_chat->setRelativePosition(rect);
1004 // Don't show chat if disabled or empty or profiler is enabled
1005 guitext_chat->setVisible(
1006 show_chat && recent_chat_count != 0 && !show_profiler);
1010 /****************************************************************************
1011 Fast key cache for main game loop
1012 ****************************************************************************/
1014 /* This is faster than using getKeySetting with the tradeoff that functions
1015 * using it must make sure that it's initialised before using it and there is
1016 * no error handling (for example bounds checking). This is really intended for
1017 * use only in the main running loop of the client (the_game()) where the faster
1018 * (up to 10x faster) key lookup is an asset. Other parts of the codebase
1019 * (e.g. formspecs) should continue using getKeySetting().
1027 populate_nonchanging();
1032 // Keys that are not settings dependent
1033 void populate_nonchanging();
1035 KeyPress key[KeyType::INTERNAL_ENUM_COUNT];
1036 InputHandler *handler;
1039 void KeyCache::populate_nonchanging()
1041 key[KeyType::ESC] = EscapeKey;
1044 void KeyCache::populate()
1046 key[KeyType::FORWARD] = getKeySetting("keymap_forward");
1047 key[KeyType::BACKWARD] = getKeySetting("keymap_backward");
1048 key[KeyType::LEFT] = getKeySetting("keymap_left");
1049 key[KeyType::RIGHT] = getKeySetting("keymap_right");
1050 key[KeyType::JUMP] = getKeySetting("keymap_jump");
1051 key[KeyType::SPECIAL1] = getKeySetting("keymap_special1");
1052 key[KeyType::SNEAK] = getKeySetting("keymap_sneak");
1054 key[KeyType::AUTOFORWARD] = getKeySetting("keymap_autoforward");
1056 key[KeyType::DROP] = getKeySetting("keymap_drop");
1057 key[KeyType::INVENTORY] = getKeySetting("keymap_inventory");
1058 key[KeyType::CHAT] = getKeySetting("keymap_chat");
1059 key[KeyType::CMD] = getKeySetting("keymap_cmd");
1060 key[KeyType::CMD_LOCAL] = getKeySetting("keymap_cmd_local");
1061 key[KeyType::CONSOLE] = getKeySetting("keymap_console");
1062 key[KeyType::MINIMAP] = getKeySetting("keymap_minimap");
1063 key[KeyType::FREEMOVE] = getKeySetting("keymap_freemove");
1064 key[KeyType::FASTMOVE] = getKeySetting("keymap_fastmove");
1065 key[KeyType::NOCLIP] = getKeySetting("keymap_noclip");
1066 key[KeyType::HOTBAR_PREV] = getKeySetting("keymap_hotbar_previous");
1067 key[KeyType::HOTBAR_NEXT] = getKeySetting("keymap_hotbar_next");
1068 key[KeyType::MUTE] = getKeySetting("keymap_mute");
1069 key[KeyType::INC_VOLUME] = getKeySetting("keymap_increase_volume");
1070 key[KeyType::DEC_VOLUME] = getKeySetting("keymap_decrease_volume");
1071 key[KeyType::CINEMATIC] = getKeySetting("keymap_cinematic");
1072 key[KeyType::SCREENSHOT] = getKeySetting("keymap_screenshot");
1073 key[KeyType::TOGGLE_HUD] = getKeySetting("keymap_toggle_hud");
1074 key[KeyType::TOGGLE_CHAT] = getKeySetting("keymap_toggle_chat");
1075 key[KeyType::TOGGLE_FORCE_FOG_OFF]
1076 = getKeySetting("keymap_toggle_force_fog_off");
1077 key[KeyType::TOGGLE_UPDATE_CAMERA]
1078 = getKeySetting("keymap_toggle_update_camera");
1079 key[KeyType::TOGGLE_DEBUG]
1080 = getKeySetting("keymap_toggle_debug");
1081 key[KeyType::TOGGLE_PROFILER]
1082 = getKeySetting("keymap_toggle_profiler");
1083 key[KeyType::CAMERA_MODE]
1084 = getKeySetting("keymap_camera_mode");
1085 key[KeyType::INCREASE_VIEWING_RANGE]
1086 = getKeySetting("keymap_increase_viewing_range_min");
1087 key[KeyType::DECREASE_VIEWING_RANGE]
1088 = getKeySetting("keymap_decrease_viewing_range_min");
1089 key[KeyType::RANGESELECT]
1090 = getKeySetting("keymap_rangeselect");
1091 key[KeyType::ZOOM] = getKeySetting("keymap_zoom");
1093 key[KeyType::QUICKTUNE_NEXT] = getKeySetting("keymap_quicktune_next");
1094 key[KeyType::QUICKTUNE_PREV] = getKeySetting("keymap_quicktune_prev");
1095 key[KeyType::QUICKTUNE_INC] = getKeySetting("keymap_quicktune_inc");
1096 key[KeyType::QUICKTUNE_DEC] = getKeySetting("keymap_quicktune_dec");
1098 key[KeyType::DEBUG_STACKS] = getKeySetting("keymap_print_debug_stacks");
1100 for (int i = 0; i < 23; i++) {
1101 std::string slot_key_name = "keymap_slot" + std::to_string(i + 1);
1102 key[KeyType::SLOT_1 + i] = getKeySetting(slot_key_name.c_str());
1106 // First clear all keys, then re-add the ones we listen for
1107 handler->dontListenForKeys();
1108 for (const KeyPress &k : key) {
1109 handler->listenForKey(k);
1111 handler->listenForKey(EscapeKey);
1112 handler->listenForKey(CancelKey);
1117 /****************************************************************************
1119 ****************************************************************************/
1121 const float object_hit_delay = 0.2;
1124 u32 last_time, busy_time, sleep_time;
1128 /* The reason the following structs are not anonymous structs within the
1129 * class is that they are not used by the majority of member functions and
1130 * many functions that do require objects of thse types do not modify them
1131 * (so they can be passed as a const qualified parameter)
1133 struct CameraOrientation {
1134 f32 camera_yaw; // "right/left"
1135 f32 camera_pitch; // "up/down"
1138 struct GameRunData {
1141 PointedThing pointed_old;
1146 bool update_wielded_item_trigger;
1147 bool reset_jump_timer;
1148 float nodig_delay_timer;
1150 float dig_time_complete;
1151 float repeat_rightclick_timer;
1152 float object_hit_delay_timer;
1153 float time_from_last_punch;
1154 ClientActiveObject *selected_object;
1158 float update_draw_list_timer;
1159 float statustext_time;
1163 v3f update_draw_list_last_cam_dir;
1165 u32 profiler_current_page;
1166 u32 profiler_max_page; // Number of pages
1169 float time_of_day_smooth;
1173 f32 max, min, avg, counter, max_sample, min_sample, max_fraction;
1179 Jitter dtime_jitter, busy_time_jitter;
1182 /****************************************************************************
1184 ****************************************************************************/
1186 /* This is not intended to be a public class. If a public class becomes
1187 * desirable then it may be better to create another 'wrapper' class that
1188 * hides most of the stuff in this class (nothing in this class is required
1189 * by any other file) but exposes the public methods/data only.
1196 bool startup(bool *kill,
1198 InputHandler *input,
1199 const std::string &map_dir,
1200 const std::string &playername,
1201 const std::string &password,
1202 // If address is "", local server is used and address is updated
1203 std::string *address,
1205 std::string &error_message,
1207 ChatBackend *chat_backend,
1208 const SubgameSpec &gamespec, // Used for local game
1209 bool simple_singleplayer_mode);
1216 void extendedResourceCleanup();
1218 // Basic initialisation
1219 bool init(const std::string &map_dir, std::string *address,
1221 const SubgameSpec &gamespec);
1223 bool createSingleplayerServer(const std::string &map_dir,
1224 const SubgameSpec &gamespec, u16 port, std::string *address);
1227 bool createClient(const std::string &playername,
1228 const std::string &password, std::string *address, u16 port);
1231 // Client connection
1232 bool connectToServer(const std::string &playername,
1233 const std::string &password, std::string *address, u16 port,
1234 bool *connect_ok, bool *aborted);
1235 bool getServerContent(bool *aborted);
1239 void updateInteractTimers(f32 dtime);
1240 bool checkConnection();
1241 bool handleCallbacks();
1242 void processQueues();
1243 void updateProfilers(const RunStats &stats, const FpsControl &draw_times, f32 dtime);
1244 void addProfilerGraphs(const RunStats &stats, const FpsControl &draw_times, f32 dtime);
1245 void updateStats(RunStats *stats, const FpsControl &draw_times, f32 dtime);
1248 void processUserInput(f32 dtime);
1249 void processKeyInput();
1250 void processItemSelection(u16 *new_playeritem);
1252 void dropSelectedItem();
1253 void openInventory();
1254 void openConsole(float scale, const wchar_t *line=NULL);
1255 void toggleFreeMove();
1256 void toggleFreeMoveAlt();
1258 void toggleNoClip();
1259 void toggleCinematic();
1260 void toggleAutoforward();
1264 void toggleMinimap(bool shift_pressed);
1267 void toggleUpdateCamera();
1268 void toggleProfiler();
1270 void increaseViewRange();
1271 void decreaseViewRange();
1272 void toggleFullViewRange();
1274 void updateCameraDirection(CameraOrientation *cam, float dtime);
1275 void updateCameraOrientation(CameraOrientation *cam, float dtime);
1276 void updatePlayerControl(const CameraOrientation &cam);
1277 void step(f32 *dtime);
1278 void processClientEvents(CameraOrientation *cam);
1279 void updateCamera(u32 busy_time, f32 dtime);
1280 void updateSound(f32 dtime);
1281 void processPlayerInteraction(f32 dtime, bool show_hud, bool show_debug);
1283 * Returns the object or node the player is pointing at.
1284 * Also updates the selected thing in the Hud.
1286 * @param[in] shootline the shootline, starting from
1287 * the camera position. This also gives the maximal distance
1289 * @param[in] liquids_pointable if false, liquids are ignored
1290 * @param[in] look_for_object if false, objects are ignored
1291 * @param[in] camera_offset offset of the camera
1292 * @param[out] selected_object the selected object or
1295 PointedThing updatePointedThing(
1296 const core::line3d<f32> &shootline, bool liquids_pointable,
1297 bool look_for_object, const v3s16 &camera_offset);
1298 void handlePointingAtNothing(const ItemStack &playerItem);
1299 void handlePointingAtNode(const PointedThing &pointed,
1300 const ItemDefinition &playeritem_def, const ItemStack &playeritem,
1301 const ToolCapabilities &playeritem_toolcap, f32 dtime);
1302 void handlePointingAtObject(const PointedThing &pointed, const ItemStack &playeritem,
1303 const v3f &player_position, bool show_debug);
1304 void handleDigging(const PointedThing &pointed, const v3s16 &nodepos,
1305 const ToolCapabilities &playeritem_toolcap, f32 dtime);
1306 void updateFrame(ProfilerGraph *graph, RunStats *stats, f32 dtime,
1307 const CameraOrientation &cam);
1308 void updateGui(const RunStats &stats, f32 dtime, const CameraOrientation &cam);
1309 void updateProfilerGraphs(ProfilerGraph *graph);
1312 void limitFps(FpsControl *fps_timings, f32 *dtime);
1314 void showOverlayMessage(const char *msg, float dtime, int percent,
1315 bool draw_clouds = true);
1317 static void settingChangedCallback(const std::string &setting_name, void *data);
1318 void readSettings();
1320 inline bool getLeftClicked()
1322 return input->getLeftClicked() ||
1323 input->joystick.getWasKeyDown(KeyType::MOUSE_L);
1325 inline bool getRightClicked()
1327 return input->getRightClicked() ||
1328 input->joystick.getWasKeyDown(KeyType::MOUSE_R);
1330 inline bool isLeftPressed()
1332 return input->getLeftState() ||
1333 input->joystick.isKeyDown(KeyType::MOUSE_L);
1335 inline bool isRightPressed()
1337 return input->getRightState() ||
1338 input->joystick.isKeyDown(KeyType::MOUSE_R);
1340 inline bool getLeftReleased()
1342 return input->getLeftReleased() ||
1343 input->joystick.wasKeyReleased(KeyType::MOUSE_L);
1346 inline bool isKeyDown(GameKeyType k)
1348 return input->isKeyDown(keycache.key[k]) || input->joystick.isKeyDown(k);
1350 inline bool wasKeyDown(GameKeyType k)
1352 return input->wasKeyDown(keycache.key[k]) || input->joystick.wasKeyDown(k);
1356 void handleAndroidChatInput();
1360 void showPauseMenu();
1362 InputHandler *input;
1367 IWritableTextureSource *texture_src;
1368 IWritableShaderSource *shader_src;
1370 // When created, these will be filled with data received from the server
1371 IWritableItemDefManager *itemdef_manager;
1372 IWritableNodeDefManager *nodedef_manager;
1374 GameOnDemandSoundFetcher soundfetcher; // useful when testing
1375 ISoundManager *sound;
1376 bool sound_is_dummy = false;
1377 SoundMaker *soundmaker;
1379 ChatBackend *chat_backend;
1381 GUIFormSpecMenu *current_formspec;
1382 //default: "". If other than "", empty show_formspec packets will only close the formspec when the formname matches
1383 std::string cur_formname;
1385 EventManager *eventmgr;
1386 QuicktuneShortcutter *quicktune;
1388 GUIChatConsole *gui_chat_console; // Free using ->Drop()
1389 MapDrawControl *draw_control;
1391 Clouds *clouds; // Free using ->Drop()
1392 Sky *sky; // Free using ->Drop()
1393 Inventory *local_inventory;
1397 GameRunData runData;
1401 This class does take ownership/responsibily for cleaning up etc of any of
1402 these items (e.g. device)
1404 IrrlichtDevice *device;
1405 video::IVideoDriver *driver;
1406 scene::ISceneManager *smgr;
1408 std::string *error_message;
1409 bool *reconnect_requested;
1410 scene::ISceneNode *skybox;
1413 bool simple_singleplayer_mode;
1416 /* Pre-calculated values
1418 int crack_animation_length;
1422 gui::IGUIStaticText *guitext; // First line of debug text
1423 gui::IGUIStaticText *guitext2; // Second line of debug text
1424 gui::IGUIStaticText *guitext3; // Third line of debug text
1425 gui::IGUIStaticText *guitext_info; // At the middle of the screen
1426 gui::IGUIStaticText *guitext_status;
1427 gui::IGUIStaticText *guitext_chat; // Chat text
1428 gui::IGUIStaticText *guitext_profiler; // Profiler text
1430 std::wstring infotext;
1431 std::wstring m_statustext;
1435 IntervalLimiter profiler_interval;
1438 * TODO: Local caching of settings is not optimal and should at some stage
1439 * be updated to use a global settings object for getting thse values
1440 * (as opposed to the this local caching). This can be addressed in
1443 bool m_cache_doubletap_jump;
1444 bool m_cache_enable_clouds;
1445 bool m_cache_enable_joysticks;
1446 bool m_cache_enable_particles;
1447 bool m_cache_enable_fog;
1448 bool m_cache_enable_noclip;
1449 bool m_cache_enable_free_move;
1450 f32 m_cache_mouse_sensitivity;
1451 f32 m_cache_joystick_frustum_sensitivity;
1452 f32 m_repeat_right_click_time;
1453 f32 m_cache_cam_smoothing;
1454 f32 m_cache_fog_start;
1456 bool m_invert_mouse = false;
1457 bool m_first_loop_after_window_activation = false;
1458 bool m_camera_offset_changed = false;
1461 bool m_cache_hold_aux1;
1462 bool m_android_chat_open;
1471 itemdef_manager(NULL),
1472 nodedef_manager(NULL),
1476 current_formspec(NULL),
1480 gui_chat_console(NULL),
1485 local_inventory(NULL),
1489 g_settings->registerChangedCallback("doubletap_jump",
1490 &settingChangedCallback, this);
1491 g_settings->registerChangedCallback("enable_clouds",
1492 &settingChangedCallback, this);
1493 g_settings->registerChangedCallback("doubletap_joysticks",
1494 &settingChangedCallback, this);
1495 g_settings->registerChangedCallback("enable_particles",
1496 &settingChangedCallback, this);
1497 g_settings->registerChangedCallback("enable_fog",
1498 &settingChangedCallback, this);
1499 g_settings->registerChangedCallback("mouse_sensitivity",
1500 &settingChangedCallback, this);
1501 g_settings->registerChangedCallback("joystick_frustum_sensitivity",
1502 &settingChangedCallback, this);
1503 g_settings->registerChangedCallback("repeat_rightclick_time",
1504 &settingChangedCallback, this);
1505 g_settings->registerChangedCallback("noclip",
1506 &settingChangedCallback, this);
1507 g_settings->registerChangedCallback("free_move",
1508 &settingChangedCallback, this);
1509 g_settings->registerChangedCallback("cinematic",
1510 &settingChangedCallback, this);
1511 g_settings->registerChangedCallback("cinematic_camera_smoothing",
1512 &settingChangedCallback, this);
1513 g_settings->registerChangedCallback("camera_smoothing",
1514 &settingChangedCallback, this);
1519 m_cache_hold_aux1 = false; // This is initialised properly later
1526 /****************************************************************************
1528 ****************************************************************************/
1534 if (!sound_is_dummy)
1537 delete server; // deleted first to stop all server threads
1540 delete local_inventory;
1546 delete nodedef_manager;
1547 delete itemdef_manager;
1548 delete draw_control;
1550 extendedResourceCleanup();
1552 g_settings->deregisterChangedCallback("doubletap_jump",
1553 &settingChangedCallback, this);
1554 g_settings->deregisterChangedCallback("enable_clouds",
1555 &settingChangedCallback, this);
1556 g_settings->deregisterChangedCallback("enable_particles",
1557 &settingChangedCallback, this);
1558 g_settings->deregisterChangedCallback("enable_fog",
1559 &settingChangedCallback, this);
1560 g_settings->deregisterChangedCallback("mouse_sensitivity",
1561 &settingChangedCallback, this);
1562 g_settings->deregisterChangedCallback("repeat_rightclick_time",
1563 &settingChangedCallback, this);
1564 g_settings->deregisterChangedCallback("noclip",
1565 &settingChangedCallback, this);
1566 g_settings->deregisterChangedCallback("free_move",
1567 &settingChangedCallback, this);
1568 g_settings->deregisterChangedCallback("cinematic",
1569 &settingChangedCallback, this);
1570 g_settings->deregisterChangedCallback("cinematic_camera_smoothing",
1571 &settingChangedCallback, this);
1572 g_settings->deregisterChangedCallback("camera_smoothing",
1573 &settingChangedCallback, this);
1576 bool Game::startup(bool *kill,
1578 InputHandler *input,
1579 const std::string &map_dir,
1580 const std::string &playername,
1581 const std::string &password,
1582 std::string *address, // can change if simple_singleplayer_mode
1584 std::string &error_message,
1586 ChatBackend *chat_backend,
1587 const SubgameSpec &gamespec,
1588 bool simple_singleplayer_mode)
1591 this->device = RenderingEngine::get_raw_device();
1593 this->error_message = &error_message;
1594 this->reconnect_requested = reconnect;
1595 this->random_input = random_input;
1596 this->input = input;
1597 this->chat_backend = chat_backend;
1598 this->simple_singleplayer_mode = simple_singleplayer_mode;
1600 keycache.handler = input;
1601 keycache.populate();
1603 driver = device->getVideoDriver();
1604 smgr = RenderingEngine::get_scene_manager();
1606 RenderingEngine::get_scene_manager()->getParameters()->
1607 setAttribute(scene::OBJ_LOADER_IGNORE_MATERIAL_FILES, true);
1609 memset(&runData, 0, sizeof(runData));
1610 runData.time_from_last_punch = 10.0;
1611 runData.profiler_max_page = 3;
1612 runData.update_wielded_item_trigger = true;
1614 memset(&flags, 0, sizeof(flags));
1615 flags.show_chat = true;
1616 flags.show_hud = true;
1617 flags.show_debug = g_settings->getBool("show_debug");
1618 m_invert_mouse = g_settings->getBool("invert_mouse");
1619 m_first_loop_after_window_activation = true;
1621 if (!init(map_dir, address, port, gamespec))
1624 if (!createClient(playername, password, address, port))
1633 ProfilerGraph graph;
1634 RunStats stats = { 0 };
1635 CameraOrientation cam_view_target = { 0 };
1636 CameraOrientation cam_view = { 0 };
1637 FpsControl draw_times = { 0 };
1638 f32 dtime; // in seconds
1640 /* Clear the profiler */
1641 Profiler::GraphValues dummyvalues;
1642 g_profiler->graphGet(dummyvalues);
1644 draw_times.last_time = RenderingEngine::get_timer_time();
1646 set_light_table(g_settings->getFloat("display_gamma"));
1649 m_cache_hold_aux1 = g_settings->getBool("fast_move")
1650 && client->checkPrivilege("fast");
1653 irr::core::dimension2d<u32> previous_screen_size(g_settings->getU16("screen_w"),
1654 g_settings->getU16("screen_h"));
1656 while (RenderingEngine::run()
1657 && !(*kill || g_gamecallback->shutdown_requested
1658 || (server && server->getShutdownRequested()))) {
1660 const irr::core::dimension2d<u32> ¤t_screen_size =
1661 RenderingEngine::get_video_driver()->getScreenSize();
1662 // Verify if window size has changed and save it if it's the case
1663 // Ensure evaluating settings->getBool after verifying screensize
1664 // First condition is cheaper
1665 if (previous_screen_size != current_screen_size &&
1666 current_screen_size != irr::core::dimension2d<u32>(0,0) &&
1667 g_settings->getBool("autosave_screensize")) {
1668 g_settings->setU16("screen_w", current_screen_size.Width);
1669 g_settings->setU16("screen_h", current_screen_size.Height);
1670 previous_screen_size = current_screen_size;
1673 /* Must be called immediately after a device->run() call because it
1674 * uses device->getTimer()->getTime()
1676 limitFps(&draw_times, &dtime);
1678 updateStats(&stats, draw_times, dtime);
1679 updateInteractTimers(dtime);
1681 if (!checkConnection())
1683 if (!handleCallbacks())
1689 hud->resizeHotbar();
1691 updateProfilers(stats, draw_times, dtime);
1692 processUserInput(dtime);
1693 // Update camera before player movement to avoid camera lag of one frame
1694 updateCameraDirection(&cam_view_target, dtime);
1695 cam_view.camera_yaw += (cam_view_target.camera_yaw -
1696 cam_view.camera_yaw) * m_cache_cam_smoothing;
1697 cam_view.camera_pitch += (cam_view_target.camera_pitch -
1698 cam_view.camera_pitch) * m_cache_cam_smoothing;
1699 updatePlayerControl(cam_view);
1701 processClientEvents(&cam_view_target);
1702 updateCamera(draw_times.busy_time, dtime);
1704 processPlayerInteraction(dtime, flags.show_hud, flags.show_debug);
1705 updateFrame(&graph, &stats, dtime, cam_view);
1706 updateProfilerGraphs(&graph);
1708 // Update if minimap has been disabled by the server
1709 flags.show_minimap &= client->shouldShowMinimap();
1714 void Game::shutdown()
1716 #if IRRLICHT_VERSION_MAJOR == 1 && IRRLICHT_VERSION_MINOR <= 8
1717 if (g_settings->get("3d_mode") == "pageflip") {
1718 driver->setRenderTarget(irr::video::ERT_STEREO_BOTH_BUFFERS);
1721 if (current_formspec)
1722 current_formspec->quitMenu();
1724 showOverlayMessage("Shutting down...", 0, 0, false);
1729 if (gui_chat_console)
1730 gui_chat_console->drop();
1736 while (g_menumgr.menuCount() > 0) {
1737 g_menumgr.m_stack.front()->setVisible(false);
1738 g_menumgr.deletingMenu(g_menumgr.m_stack.front());
1741 if (current_formspec) {
1742 current_formspec->drop();
1743 current_formspec = NULL;
1746 chat_backend->addMessage(L"", L"# Disconnected.");
1747 chat_backend->addMessage(L"", L"");
1751 while (!client->isShutdown()) {
1752 assert(texture_src != NULL);
1753 assert(shader_src != NULL);
1754 texture_src->processQueue();
1755 shader_src->processQueue();
1762 /****************************************************************************/
1763 /****************************************************************************
1765 ****************************************************************************/
1766 /****************************************************************************/
1769 const std::string &map_dir,
1770 std::string *address,
1772 const SubgameSpec &gamespec)
1774 texture_src = createTextureSource();
1776 showOverlayMessage("Loading...", 0, 0);
1778 shader_src = createShaderSource();
1780 itemdef_manager = createItemDefManager();
1781 nodedef_manager = createNodeDefManager();
1783 eventmgr = new EventManager();
1784 quicktune = new QuicktuneShortcutter();
1786 if (!(texture_src && shader_src && itemdef_manager && nodedef_manager
1787 && eventmgr && quicktune))
1793 // Create a server if not connecting to an existing one
1794 if (address->empty()) {
1795 if (!createSingleplayerServer(map_dir, gamespec, port, address))
1802 bool Game::initSound()
1805 if (g_settings->getBool("enable_sound")) {
1806 infostream << "Attempting to use OpenAL audio" << std::endl;
1807 sound = createOpenALSoundManager(&soundfetcher);
1809 infostream << "Failed to initialize OpenAL audio" << std::endl;
1811 infostream << "Sound disabled." << std::endl;
1815 infostream << "Using dummy audio." << std::endl;
1816 sound = &dummySoundManager;
1817 sound_is_dummy = true;
1820 soundmaker = new SoundMaker(sound, nodedef_manager);
1824 soundmaker->registerReceiver(eventmgr);
1829 bool Game::createSingleplayerServer(const std::string &map_dir,
1830 const SubgameSpec &gamespec, u16 port, std::string *address)
1832 showOverlayMessage("Creating server...", 0, 5);
1834 std::string bind_str = g_settings->get("bind_address");
1835 Address bind_addr(0, 0, 0, 0, port);
1837 if (g_settings->getBool("ipv6_server")) {
1838 bind_addr.setAddress((IPv6AddressBytes *) NULL);
1842 bind_addr.Resolve(bind_str.c_str());
1843 } catch (ResolveError &e) {
1844 infostream << "Resolving bind address \"" << bind_str
1845 << "\" failed: " << e.what()
1846 << " -- Listening on all addresses." << std::endl;
1849 if (bind_addr.isIPv6() && !g_settings->getBool("enable_ipv6")) {
1850 *error_message = "Unable to listen on " +
1851 bind_addr.serializeString() +
1852 " because IPv6 is disabled";
1853 errorstream << *error_message << std::endl;
1857 server = new Server(map_dir, gamespec, simple_singleplayer_mode,
1858 bind_addr.isIPv6(), false);
1860 server->start(bind_addr);
1865 bool Game::createClient(const std::string &playername,
1866 const std::string &password, std::string *address, u16 port)
1868 showOverlayMessage("Creating client...", 0, 10);
1870 draw_control = new MapDrawControl;
1874 bool could_connect, connect_aborted;
1876 if (!connectToServer(playername, password, address, port,
1877 &could_connect, &connect_aborted))
1880 if (!could_connect) {
1881 if (error_message->empty() && !connect_aborted) {
1882 // Should not happen if error messages are set properly
1883 *error_message = "Connection failed for unknown reason";
1884 errorstream << *error_message << std::endl;
1889 if (!getServerContent(&connect_aborted)) {
1890 if (error_message->empty() && !connect_aborted) {
1891 // Should not happen if error messages are set properly
1892 *error_message = "Connection failed for unknown reason";
1893 errorstream << *error_message << std::endl;
1898 GameGlobalShaderConstantSetterFactory *scsf = new GameGlobalShaderConstantSetterFactory(
1899 &flags.force_fog_off, &runData.fog_range, client);
1900 shader_src->addShaderConstantSetterFactory(scsf);
1902 // Update cached textures, meshes and materials
1903 client->afterContentReceived();
1907 camera = new Camera(*draw_control, client);
1908 if (!camera || !camera->successfullyCreated(*error_message))
1910 client->setCamera(camera);
1914 if (m_cache_enable_clouds) {
1915 clouds = new Clouds(smgr, -1, time(0));
1917 *error_message = "Memory allocation error (clouds)";
1918 errorstream << *error_message << std::endl;
1925 sky = new Sky(-1, texture_src);
1927 skybox = NULL; // This is used/set later on in the main run loop
1929 local_inventory = new Inventory(itemdef_manager);
1931 if (!(sky && local_inventory)) {
1932 *error_message = "Memory allocation error (sky or local inventory)";
1933 errorstream << *error_message << std::endl;
1937 /* Pre-calculated values
1939 video::ITexture *t = texture_src->getTexture("crack_anylength.png");
1941 v2u32 size = t->getOriginalSize();
1942 crack_animation_length = size.Y / size.X;
1944 crack_animation_length = 5;
1950 /* Set window caption
1952 std::wstring str = utf8_to_wide(PROJECT_NAME_C);
1954 str += utf8_to_wide(g_version_hash);
1956 str += driver->getName();
1958 device->setWindowCaption(str.c_str());
1960 LocalPlayer *player = client->getEnv().getLocalPlayer();
1961 player->hurt_tilt_timer = 0;
1962 player->hurt_tilt_strength = 0;
1964 hud = new Hud(guienv, client, player, local_inventory);
1967 *error_message = "Memory error: could not create HUD";
1968 errorstream << *error_message << std::endl;
1972 mapper = client->getMinimap();
1974 mapper->setMinimapMode(MINIMAP_MODE_OFF);
1979 bool Game::initGui()
1981 // First line of debug text
1982 guitext = addStaticText(guienv,
1983 utf8_to_wide(PROJECT_NAME_C).c_str(),
1984 core::rect<s32>(0, 0, 0, 0),
1985 false, false, guiroot);
1987 // Second line of debug text
1988 guitext2 = addStaticText(guienv,
1990 core::rect<s32>(0, 0, 0, 0),
1991 false, false, guiroot);
1993 // Third line of debug text
1994 guitext3 = addStaticText(guienv,
1996 core::rect<s32>(0, 0, 0, 0),
1997 false, false, guiroot);
1999 // At the middle of the screen
2000 // Object infos are shown in this
2001 guitext_info = addStaticText(guienv,
2003 core::rect<s32>(0, 0, 400, g_fontengine->getTextHeight() * 5 + 5) + v2s32(100, 200),
2004 false, true, guiroot);
2006 // Status text (displays info when showing and hiding GUI stuff, etc.)
2007 guitext_status = addStaticText(guienv,
2009 core::rect<s32>(0, 0, 0, 0),
2010 false, false, guiroot);
2011 guitext_status->setVisible(false);
2014 guitext_chat = addStaticText(
2017 core::rect<s32>(0, 0, 0, 0),
2018 //false, false); // Disable word wrap as of now
2019 false, true, guiroot);
2021 // Remove stale "recent" chat messages from previous connections
2022 chat_backend->clearRecentChat();
2024 // Chat backend and console
2025 gui_chat_console = new GUIChatConsole(guienv, guienv->getRootGUIElement(),
2026 -1, chat_backend, client, &g_menumgr);
2027 if (!gui_chat_console) {
2028 *error_message = "Could not allocate memory for chat console";
2029 errorstream << *error_message << std::endl;
2033 // Profiler text (size is updated when text is updated)
2034 guitext_profiler = addStaticText(guienv,
2036 core::rect<s32>(0, 0, 0, 0),
2037 false, false, guiroot);
2038 guitext_profiler->setBackgroundColor(video::SColor(120, 0, 0, 0));
2039 guitext_profiler->setVisible(false);
2040 guitext_profiler->setWordWrap(true);
2042 #ifdef HAVE_TOUCHSCREENGUI
2044 if (g_touchscreengui)
2045 g_touchscreengui->init(texture_src);
2052 bool Game::connectToServer(const std::string &playername,
2053 const std::string &password, std::string *address, u16 port,
2054 bool *connect_ok, bool *aborted)
2056 *connect_ok = false; // Let's not be overly optimistic
2058 bool local_server_mode = false;
2060 showOverlayMessage("Resolving address...", 0, 15);
2062 Address connect_address(0, 0, 0, 0, port);
2065 connect_address.Resolve(address->c_str());
2067 if (connect_address.isZero()) { // i.e. INADDR_ANY, IN6ADDR_ANY
2068 //connect_address.Resolve("localhost");
2069 if (connect_address.isIPv6()) {
2070 IPv6AddressBytes addr_bytes;
2071 addr_bytes.bytes[15] = 1;
2072 connect_address.setAddress(&addr_bytes);
2074 connect_address.setAddress(127, 0, 0, 1);
2076 local_server_mode = true;
2078 } catch (ResolveError &e) {
2079 *error_message = std::string("Couldn't resolve address: ") + e.what();
2080 errorstream << *error_message << std::endl;
2084 if (connect_address.isIPv6() && !g_settings->getBool("enable_ipv6")) {
2085 *error_message = "Unable to connect to " +
2086 connect_address.serializeString() +
2087 " because IPv6 is disabled";
2088 errorstream << *error_message << std::endl;
2092 client = new Client(playername.c_str(), password, *address,
2093 *draw_control, texture_src, shader_src,
2094 itemdef_manager, nodedef_manager, sound, eventmgr,
2095 connect_address.isIPv6(), &flags);
2100 infostream << "Connecting to server at ";
2101 connect_address.print(&infostream);
2102 infostream << std::endl;
2104 client->connect(connect_address,
2105 simple_singleplayer_mode || local_server_mode);
2108 Wait for server to accept connection
2114 FpsControl fps_control = { 0 };
2116 f32 wait_time = 0; // in seconds
2118 fps_control.last_time = RenderingEngine::get_timer_time();
2123 while (RenderingEngine::run()) {
2125 limitFps(&fps_control, &dtime);
2127 // Update client and server
2128 client->step(dtime);
2131 server->step(dtime);
2134 if (client->getState() == LC_Init) {
2140 if (client->accessDenied()) {
2141 *error_message = "Access denied. Reason: "
2142 + client->accessDeniedReason();
2143 *reconnect_requested = client->reconnectRequested();
2144 errorstream << *error_message << std::endl;
2148 if (wasKeyDown(KeyType::ESC) || input->wasKeyDown(CancelKey)) {
2150 infostream << "Connect aborted [Escape]" << std::endl;
2155 // Only time out if we aren't waiting for the server we started
2156 if ((!address->empty()) && (wait_time > 10)) {
2157 bool sent_old_init = g_settings->getFlag("send_pre_v25_init");
2158 // If no pre v25 init was sent, and no answer was received,
2159 // but the low level connection could be established
2160 // (meaning that we have a peer id), then we probably wanted
2161 // to connect to a legacy server. In this case, tell the user
2162 // to enable the option to be able to connect.
2163 if (!sent_old_init &&
2164 (client->getProtoVersion() == 0) &&
2165 client->connectedToServer()) {
2166 *error_message = "Connection failure: init packet not "
2167 "recognized by server.\n"
2168 "Most likely the server uses an old protocol version (<v25).\n"
2169 "Please ask the server owner to update to 0.4.13 or later.\n"
2170 "To still connect to the server in the meantime,\n"
2171 "you can enable the 'send_pre_v25_init' setting by editing minetest.conf,\n"
2172 "or by enabling the 'Client -> Network -> Support older Servers'\n"
2173 "entry in the advanced settings menu.";
2175 *error_message = "Connection timed out.";
2177 errorstream << *error_message << std::endl;
2182 showOverlayMessage("Connecting to server...", dtime, 20);
2184 } catch (con::PeerNotFoundException &e) {
2185 // TODO: Should something be done here? At least an info/error
2193 bool Game::getServerContent(bool *aborted)
2197 FpsControl fps_control = { 0 };
2198 f32 dtime; // in seconds
2200 fps_control.last_time = RenderingEngine::get_timer_time();
2202 while (RenderingEngine::run()) {
2204 limitFps(&fps_control, &dtime);
2206 // Update client and server
2207 client->step(dtime);
2210 server->step(dtime);
2213 if (client->mediaReceived() && client->itemdefReceived() &&
2214 client->nodedefReceived()) {
2219 if (!checkConnection())
2222 if (client->getState() < LC_Init) {
2223 *error_message = "Client disconnected";
2224 errorstream << *error_message << std::endl;
2228 if (wasKeyDown(KeyType::ESC) || input->wasKeyDown(CancelKey)) {
2230 infostream << "Connect aborted [Escape]" << std::endl;
2237 if (!client->itemdefReceived()) {
2238 const wchar_t *text = wgettext("Item definitions...");
2240 RenderingEngine::draw_load_screen(text, guienv, texture_src,
2243 } else if (!client->nodedefReceived()) {
2244 const wchar_t *text = wgettext("Node definitions...");
2246 RenderingEngine::draw_load_screen(text, guienv, texture_src,
2250 std::stringstream message;
2251 std::fixed(message);
2252 message.precision(0);
2253 message << gettext("Media...") << " " << (client->mediaReceiveProgress()*100) << "%";
2254 message.precision(2);
2256 if ((USE_CURL == 0) ||
2257 (!g_settings->getBool("enable_remote_media_server"))) {
2258 float cur = client->getCurRate();
2259 std::string cur_unit = gettext("KiB/s");
2263 cur_unit = gettext("MiB/s");
2266 message << " (" << cur << ' ' << cur_unit << ")";
2269 progress = 30 + client->mediaReceiveProgress() * 35 + 0.5;
2270 RenderingEngine::draw_load_screen(utf8_to_wide(message.str()), guienv,
2271 texture_src, dtime, progress);
2279 /****************************************************************************/
2280 /****************************************************************************
2282 ****************************************************************************/
2283 /****************************************************************************/
2285 inline void Game::updateInteractTimers(f32 dtime)
2287 if (runData.nodig_delay_timer >= 0)
2288 runData.nodig_delay_timer -= dtime;
2290 if (runData.object_hit_delay_timer >= 0)
2291 runData.object_hit_delay_timer -= dtime;
2293 runData.time_from_last_punch += dtime;
2297 /* returns false if game should exit, otherwise true
2299 inline bool Game::checkConnection()
2301 if (client->accessDenied()) {
2302 *error_message = "Access denied. Reason: "
2303 + client->accessDeniedReason();
2304 *reconnect_requested = client->reconnectRequested();
2305 errorstream << *error_message << std::endl;
2313 /* returns false if game should exit, otherwise true
2315 inline bool Game::handleCallbacks()
2317 if (g_gamecallback->disconnect_requested) {
2318 g_gamecallback->disconnect_requested = false;
2322 if (g_gamecallback->changepassword_requested) {
2323 (new GUIPasswordChange(guienv, guiroot, -1,
2324 &g_menumgr, client))->drop();
2325 g_gamecallback->changepassword_requested = false;
2328 if (g_gamecallback->changevolume_requested) {
2329 (new GUIVolumeChange(guienv, guiroot, -1,
2330 &g_menumgr))->drop();
2331 g_gamecallback->changevolume_requested = false;
2334 if (g_gamecallback->keyconfig_requested) {
2335 (new GUIKeyChangeMenu(guienv, guiroot, -1,
2336 &g_menumgr))->drop();
2337 g_gamecallback->keyconfig_requested = false;
2340 if (g_gamecallback->keyconfig_changed) {
2341 keycache.populate(); // update the cache with new settings
2342 g_gamecallback->keyconfig_changed = false;
2349 void Game::processQueues()
2351 texture_src->processQueue();
2352 itemdef_manager->processQueue(client);
2353 shader_src->processQueue();
2357 void Game::updateProfilers(const RunStats &stats, const FpsControl &draw_times, f32 dtime)
2359 float profiler_print_interval =
2360 g_settings->getFloat("profiler_print_interval");
2361 bool print_to_log = true;
2363 if (profiler_print_interval == 0) {
2364 print_to_log = false;
2365 profiler_print_interval = 5;
2368 if (profiler_interval.step(dtime, profiler_print_interval)) {
2370 infostream << "Profiler:" << std::endl;
2371 g_profiler->print(infostream);
2374 update_profiler_gui(guitext_profiler, g_fontengine,
2375 runData.profiler_current_page, runData.profiler_max_page,
2376 driver->getScreenSize().Height);
2378 g_profiler->clear();
2381 addProfilerGraphs(stats, draw_times, dtime);
2385 void Game::addProfilerGraphs(const RunStats &stats,
2386 const FpsControl &draw_times, f32 dtime)
2388 g_profiler->graphAdd("mainloop_other",
2389 draw_times.busy_time / 1000.0f - stats.drawtime / 1000.0f);
2391 if (draw_times.sleep_time != 0)
2392 g_profiler->graphAdd("mainloop_sleep", draw_times.sleep_time / 1000.0f);
2393 g_profiler->graphAdd("mainloop_dtime", dtime);
2395 g_profiler->add("Elapsed time", dtime);
2396 g_profiler->avg("FPS", 1. / dtime);
2400 void Game::updateStats(RunStats *stats, const FpsControl &draw_times,
2407 /* Time average and jitter calculation
2409 jp = &stats->dtime_jitter;
2410 jp->avg = jp->avg * 0.96 + dtime * 0.04;
2412 jitter = dtime - jp->avg;
2414 if (jitter > jp->max)
2417 jp->counter += dtime;
2419 if (jp->counter > 0.0) {
2421 jp->max_sample = jp->max;
2422 jp->max_fraction = jp->max_sample / (jp->avg + 0.001);
2426 /* Busytime average and jitter calculation
2428 jp = &stats->busy_time_jitter;
2429 jp->avg = jp->avg + draw_times.busy_time * 0.02;
2431 jitter = draw_times.busy_time - jp->avg;
2433 if (jitter > jp->max)
2435 if (jitter < jp->min)
2438 jp->counter += dtime;
2440 if (jp->counter > 0.0) {
2442 jp->max_sample = jp->max;
2443 jp->min_sample = jp->min;
2451 /****************************************************************************
2453 ****************************************************************************/
2455 void Game::processUserInput(f32 dtime)
2457 // Reset input if window not active or some menu is active
2458 if (!device->isWindowActive() || isMenuActive() || guienv->hasFocus(gui_chat_console)) {
2460 #ifdef HAVE_TOUCHSCREENGUI
2461 g_touchscreengui->hide();
2464 #ifdef HAVE_TOUCHSCREENGUI
2465 else if (g_touchscreengui) {
2466 /* on touchscreengui step may generate own input events which ain't
2467 * what we want in case we just did clear them */
2468 g_touchscreengui->step(dtime);
2472 if (!guienv->hasFocus(gui_chat_console) && gui_chat_console->isOpen()) {
2473 gui_chat_console->closeConsoleAtOnce();
2476 // Input handler step() (used by the random input generator)
2480 if (current_formspec != NULL)
2481 current_formspec->getAndroidUIInput();
2483 handleAndroidChatInput();
2486 // Increase timer for double tap of "keymap_jump"
2487 if (m_cache_doubletap_jump && runData.jump_timer <= 0.2f)
2488 runData.jump_timer += dtime;
2491 processItemSelection(&runData.new_playeritem);
2495 void Game::processKeyInput()
2497 if (wasKeyDown(KeyType::DROP)) {
2499 } else if (wasKeyDown(KeyType::AUTOFORWARD)) {
2500 toggleAutoforward();
2501 } else if (wasKeyDown(KeyType::INVENTORY)) {
2503 } else if (wasKeyDown(KeyType::ESC) || input->wasKeyDown(CancelKey)) {
2504 if (!gui_chat_console->isOpenInhibited()) {
2507 } else if (wasKeyDown(KeyType::CHAT)) {
2508 openConsole(0.2, L"");
2509 } else if (wasKeyDown(KeyType::CMD)) {
2510 openConsole(0.2, L"/");
2511 } else if (wasKeyDown(KeyType::CMD_LOCAL)) {
2512 openConsole(0.2, L".");
2513 } else if (wasKeyDown(KeyType::CONSOLE)) {
2514 openConsole(core::clamp(g_settings->getFloat("console_height"), 0.1f, 1.0f));
2515 } else if (wasKeyDown(KeyType::FREEMOVE)) {
2517 } else if (wasKeyDown(KeyType::JUMP)) {
2518 toggleFreeMoveAlt();
2519 } else if (wasKeyDown(KeyType::FASTMOVE)) {
2521 } else if (wasKeyDown(KeyType::NOCLIP)) {
2523 } else if (wasKeyDown(KeyType::MUTE)) {
2524 float volume = g_settings->getFloat("sound_volume");
2525 if (volume < 0.001f) {
2526 g_settings->setFloat("sound_volume", 1.0f);
2527 m_statustext = narrow_to_wide(gettext("Volume changed to 100%"));
2529 g_settings->setFloat("sound_volume", 0.0f);
2530 m_statustext = narrow_to_wide(gettext("Volume changed to 0%"));
2532 runData.statustext_time = 0;
2533 } else if (wasKeyDown(KeyType::INC_VOLUME)) {
2534 float new_volume = rangelim(g_settings->getFloat("sound_volume") + 0.1f, 0.0f, 1.0f);
2536 g_settings->setFloat("sound_volume", new_volume);
2537 snprintf(buf, sizeof(buf), gettext("Volume changed to %d%%"), myround(new_volume * 100));
2538 m_statustext = narrow_to_wide(buf);
2539 runData.statustext_time = 0;
2540 } else if (wasKeyDown(KeyType::DEC_VOLUME)) {
2541 float new_volume = rangelim(g_settings->getFloat("sound_volume") - 0.1f, 0.0f, 1.0f);
2543 g_settings->setFloat("sound_volume", new_volume);
2544 snprintf(buf, sizeof(buf), gettext("Volume changed to %d%%"), myround(new_volume * 100));
2545 m_statustext = narrow_to_wide(buf);
2546 runData.statustext_time = 0;
2547 } else if (wasKeyDown(KeyType::CINEMATIC)) {
2549 } else if (wasKeyDown(KeyType::SCREENSHOT)) {
2550 client->makeScreenshot();
2551 } else if (wasKeyDown(KeyType::TOGGLE_HUD)) {
2553 } else if (wasKeyDown(KeyType::MINIMAP)) {
2554 toggleMinimap(isKeyDown(KeyType::SNEAK));
2555 } else if (wasKeyDown(KeyType::TOGGLE_CHAT)) {
2557 } else if (wasKeyDown(KeyType::TOGGLE_FORCE_FOG_OFF)) {
2559 } else if (wasKeyDown(KeyType::TOGGLE_UPDATE_CAMERA)) {
2560 toggleUpdateCamera();
2561 } else if (wasKeyDown(KeyType::TOGGLE_DEBUG)) {
2563 } else if (wasKeyDown(KeyType::TOGGLE_PROFILER)) {
2565 } else if (wasKeyDown(KeyType::INCREASE_VIEWING_RANGE)) {
2566 increaseViewRange();
2567 } else if (wasKeyDown(KeyType::DECREASE_VIEWING_RANGE)) {
2568 decreaseViewRange();
2569 } else if (wasKeyDown(KeyType::RANGESELECT)) {
2570 toggleFullViewRange();
2571 } else if (wasKeyDown(KeyType::QUICKTUNE_NEXT)) {
2573 } else if (wasKeyDown(KeyType::QUICKTUNE_PREV)) {
2575 } else if (wasKeyDown(KeyType::QUICKTUNE_INC)) {
2577 } else if (wasKeyDown(KeyType::QUICKTUNE_DEC)) {
2579 } else if (wasKeyDown(KeyType::DEBUG_STACKS)) {
2580 // Print debug stacks
2581 dstream << "-----------------------------------------"
2583 dstream << "Printing debug stacks:" << std::endl;
2584 dstream << "-----------------------------------------"
2586 debug_stacks_print();
2589 if (!isKeyDown(KeyType::JUMP) && runData.reset_jump_timer) {
2590 runData.reset_jump_timer = false;
2591 runData.jump_timer = 0.0f;
2594 if (quicktune->hasMessage()) {
2595 m_statustext = utf8_to_wide(quicktune->getMessage());
2596 runData.statustext_time = 0.0f;
2600 void Game::processItemSelection(u16 *new_playeritem)
2602 LocalPlayer *player = client->getEnv().getLocalPlayer();
2604 /* Item selection using mouse wheel
2606 *new_playeritem = client->getPlayerItem();
2608 s32 wheel = input->getMouseWheel();
2609 u16 max_item = MYMIN(PLAYER_INVENTORY_SIZE - 1,
2610 player->hud_hotbar_itemcount - 1);
2614 if (input->joystick.wasKeyDown(KeyType::SCROLL_DOWN) ||
2615 wasKeyDown(KeyType::HOTBAR_NEXT)) {
2619 if (input->joystick.wasKeyDown(KeyType::SCROLL_UP) ||
2620 wasKeyDown(KeyType::HOTBAR_PREV)) {
2625 *new_playeritem = *new_playeritem < max_item ? *new_playeritem + 1 : 0;
2627 *new_playeritem = *new_playeritem > 0 ? *new_playeritem - 1 : max_item;
2630 /* Item selection using hotbar slot keys
2632 for (u16 i = 0; i < 23; i++) {
2633 if (wasKeyDown((GameKeyType) (KeyType::SLOT_1 + i))) {
2634 if (i < PLAYER_INVENTORY_SIZE && i < player->hud_hotbar_itemcount) {
2635 *new_playeritem = i;
2636 infostream << "Selected item: " << new_playeritem << std::endl;
2644 void Game::dropSelectedItem()
2646 IDropAction *a = new IDropAction();
2648 a->from_inv.setCurrentPlayer();
2649 a->from_list = "main";
2650 a->from_i = client->getPlayerItem();
2651 client->inventoryAction(a);
2655 void Game::openInventory()
2658 * Don't permit to open inventory is CAO or player doesn't exists.
2659 * This prevent showing an empty inventory at player load
2662 LocalPlayer *player = client->getEnv().getLocalPlayer();
2663 if (!player || !player->getCAO())
2666 infostream << "the_game: " << "Launching inventory" << std::endl;
2668 PlayerInventoryFormSource *fs_src = new PlayerInventoryFormSource(client);
2669 TextDest *txt_dst = new TextDestPlayerInventory(client);
2671 create_formspec_menu(¤t_formspec, client, &input->joystick, fs_src, txt_dst);
2674 InventoryLocation inventoryloc;
2675 inventoryloc.setCurrentPlayer();
2676 current_formspec->setFormSpec(fs_src->getForm(), inventoryloc);
2680 void Game::openConsole(float scale, const wchar_t *line)
2682 assert(scale > 0.0f && scale <= 1.0f);
2685 porting::showInputDialog(gettext("ok"), "", "", 2);
2686 m_android_chat_open = true;
2688 if (gui_chat_console->isOpenInhibited())
2690 gui_chat_console->openConsole(scale);
2692 gui_chat_console->setCloseOnEnter(true);
2693 gui_chat_console->replaceAndAddToHistory(line);
2699 void Game::handleAndroidChatInput()
2701 if (m_android_chat_open && porting::getInputDialogState() == 0) {
2702 std::string text = porting::getInputDialogValue();
2703 client->typeChatMessage(utf8_to_wide(text));
2709 void Game::toggleFreeMove()
2711 static const wchar_t *msg[] = { L"free_move disabled", L"free_move enabled" };
2713 bool free_move = !g_settings->getBool("free_move");
2714 g_settings->set("free_move", bool_to_cstr(free_move));
2716 runData.statustext_time = 0;
2717 m_statustext = msg[free_move];
2718 if (free_move && !client->checkPrivilege("fly"))
2719 m_statustext += L" (note: no 'fly' privilege)";
2723 void Game::toggleFreeMoveAlt()
2725 if (m_cache_doubletap_jump && runData.jump_timer < 0.2f)
2728 runData.reset_jump_timer = true;
2732 void Game::toggleFast()
2734 static const wchar_t *msg[] = { L"fast_move disabled", L"fast_move enabled" };
2735 bool fast_move = !g_settings->getBool("fast_move");
2736 g_settings->set("fast_move", bool_to_cstr(fast_move));
2738 runData.statustext_time = 0;
2739 m_statustext = msg[fast_move];
2741 bool has_fast_privs = client->checkPrivilege("fast");
2743 if (fast_move && !has_fast_privs)
2744 m_statustext += L" (note: no 'fast' privilege)";
2747 m_cache_hold_aux1 = fast_move && has_fast_privs;
2752 void Game::toggleNoClip()
2754 static const wchar_t *msg[] = { L"noclip disabled", L"noclip enabled" };
2755 bool noclip = !g_settings->getBool("noclip");
2756 g_settings->set("noclip", bool_to_cstr(noclip));
2758 runData.statustext_time = 0;
2759 m_statustext = msg[noclip];
2761 if (noclip && !client->checkPrivilege("noclip"))
2762 m_statustext += L" (note: no 'noclip' privilege)";
2765 void Game::toggleCinematic()
2767 static const wchar_t *msg[] = { L"cinematic disabled", L"cinematic enabled" };
2768 bool cinematic = !g_settings->getBool("cinematic");
2769 g_settings->set("cinematic", bool_to_cstr(cinematic));
2771 runData.statustext_time = 0;
2772 m_statustext = msg[cinematic];
2775 // Autoforward by toggling continuous forward.
2776 void Game::toggleAutoforward()
2778 static const wchar_t *msg[] = { L"autoforward disabled", L"autoforward enabled" };
2779 bool autoforward_enabled = !g_settings->getBool("continuous_forward");
2780 g_settings->set("continuous_forward", bool_to_cstr(autoforward_enabled));
2782 runData.statustext_time = 0;
2783 m_statustext = msg[autoforward_enabled ? 1 : 0];
2786 void Game::toggleChat()
2788 static const wchar_t *msg[] = { L"Chat hidden", L"Chat shown" };
2790 flags.show_chat = !flags.show_chat;
2791 runData.statustext_time = 0;
2792 m_statustext = msg[flags.show_chat];
2796 void Game::toggleHud()
2798 static const wchar_t *msg[] = { L"HUD hidden", L"HUD shown" };
2800 flags.show_hud = !flags.show_hud;
2801 runData.statustext_time = 0;
2802 m_statustext = msg[flags.show_hud];
2805 void Game::toggleMinimap(bool shift_pressed)
2807 if (!mapper || !flags.show_hud || !g_settings->getBool("enable_minimap"))
2810 if (shift_pressed) {
2811 mapper->toggleMinimapShape();
2815 u32 hud_flags = client->getEnv().getLocalPlayer()->hud_flags;
2817 MinimapMode mode = MINIMAP_MODE_OFF;
2818 if (hud_flags & HUD_FLAG_MINIMAP_VISIBLE) {
2819 mode = mapper->getMinimapMode();
2820 mode = (MinimapMode)((int)mode + 1);
2823 flags.show_minimap = true;
2825 case MINIMAP_MODE_SURFACEx1:
2826 m_statustext = L"Minimap in surface mode, Zoom x1";
2828 case MINIMAP_MODE_SURFACEx2:
2829 m_statustext = L"Minimap in surface mode, Zoom x2";
2831 case MINIMAP_MODE_SURFACEx4:
2832 m_statustext = L"Minimap in surface mode, Zoom x4";
2834 case MINIMAP_MODE_RADARx1:
2835 m_statustext = L"Minimap in radar mode, Zoom x1";
2837 case MINIMAP_MODE_RADARx2:
2838 m_statustext = L"Minimap in radar mode, Zoom x2";
2840 case MINIMAP_MODE_RADARx4:
2841 m_statustext = L"Minimap in radar mode, Zoom x4";
2844 mode = MINIMAP_MODE_OFF;
2845 flags.show_minimap = false;
2846 m_statustext = (hud_flags & HUD_FLAG_MINIMAP_VISIBLE) ?
2847 L"Minimap hidden" : L"Minimap disabled by server";
2850 runData.statustext_time = 0;
2851 mapper->setMinimapMode(mode);
2854 void Game::toggleFog()
2856 static const wchar_t *msg[] = { L"Fog enabled", L"Fog disabled" };
2858 flags.force_fog_off = !flags.force_fog_off;
2859 runData.statustext_time = 0;
2860 m_statustext = msg[flags.force_fog_off];
2864 void Game::toggleDebug()
2866 // Initial / 4x toggle: Chat only
2867 // 1x toggle: Debug text with chat
2868 // 2x toggle: Debug text with profiler graph
2869 // 3x toggle: Debug text and wireframe
2870 if (!flags.show_debug) {
2871 flags.show_debug = true;
2872 flags.show_profiler_graph = false;
2873 draw_control->show_wireframe = false;
2874 m_statustext = L"Debug info shown";
2875 } else if (!flags.show_profiler_graph && !draw_control->show_wireframe) {
2876 flags.show_profiler_graph = true;
2877 m_statustext = L"Profiler graph shown";
2878 } else if (!draw_control->show_wireframe && client->checkPrivilege("debug")) {
2879 flags.show_profiler_graph = false;
2880 draw_control->show_wireframe = true;
2881 m_statustext = L"Wireframe shown";
2883 flags.show_debug = false;
2884 flags.show_profiler_graph = false;
2885 draw_control->show_wireframe = false;
2886 if (client->checkPrivilege("debug")) {
2887 m_statustext = L"Debug info, profiler graph, and wireframe hidden";
2889 m_statustext = L"Debug info and profiler graph hidden";
2892 runData.statustext_time = 0;
2896 void Game::toggleUpdateCamera()
2898 static const wchar_t *msg[] = {
2899 L"Camera update enabled",
2900 L"Camera update disabled"
2903 flags.disable_camera_update = !flags.disable_camera_update;
2904 runData.statustext_time = 0;
2905 m_statustext = msg[flags.disable_camera_update];
2909 void Game::toggleProfiler()
2911 runData.profiler_current_page =
2912 (runData.profiler_current_page + 1) % (runData.profiler_max_page + 1);
2914 // FIXME: This updates the profiler with incomplete values
2915 update_profiler_gui(guitext_profiler, g_fontengine, runData.profiler_current_page,
2916 runData.profiler_max_page, driver->getScreenSize().Height);
2918 if (runData.profiler_current_page != 0) {
2919 std::wstringstream sstr;
2920 sstr << "Profiler shown (page " << runData.profiler_current_page
2921 << " of " << runData.profiler_max_page << ")";
2922 m_statustext = sstr.str();
2924 m_statustext = L"Profiler hidden";
2926 runData.statustext_time = 0;
2930 void Game::increaseViewRange()
2932 s16 range = g_settings->getS16("viewing_range");
2933 s16 range_new = range + 10;
2935 if (range_new > 4000) {
2937 m_statustext = utf8_to_wide("Viewing range is at maximum: "
2940 m_statustext = utf8_to_wide("Viewing range changed to "
2943 g_settings->set("viewing_range", itos(range_new));
2944 runData.statustext_time = 0;
2948 void Game::decreaseViewRange()
2950 s16 range = g_settings->getS16("viewing_range");
2951 s16 range_new = range - 10;
2953 if (range_new < 20) {
2955 m_statustext = utf8_to_wide("Viewing range is at minimum: "
2958 m_statustext = utf8_to_wide("Viewing range changed to "
2961 g_settings->set("viewing_range", itos(range_new));
2962 runData.statustext_time = 0;
2966 void Game::toggleFullViewRange()
2968 static const wchar_t *msg[] = {
2969 L"Normal view range",
2970 L"Infinite view range"
2973 draw_control->range_all = !draw_control->range_all;
2974 infostream << msg[draw_control->range_all] << std::endl;
2975 m_statustext = msg[draw_control->range_all];
2976 runData.statustext_time = 0;
2980 void Game::updateCameraDirection(CameraOrientation *cam, float dtime)
2982 if ((device->isWindowActive() && device->isWindowFocused()
2983 && !isMenuActive()) || random_input) {
2986 if (!random_input) {
2987 // Mac OSX gets upset if this is set every frame
2988 if (device->getCursorControl()->isVisible())
2989 device->getCursorControl()->setVisible(false);
2993 if (m_first_loop_after_window_activation)
2994 m_first_loop_after_window_activation = false;
2996 updateCameraOrientation(cam, dtime);
2998 input->setMousePos((driver->getScreenSize().Width / 2),
2999 (driver->getScreenSize().Height / 2));
3003 // Mac OSX gets upset if this is set every frame
3004 if (!device->getCursorControl()->isVisible())
3005 device->getCursorControl()->setVisible(true);
3008 m_first_loop_after_window_activation = true;
3013 void Game::updateCameraOrientation(CameraOrientation *cam, float dtime)
3015 #ifdef HAVE_TOUCHSCREENGUI
3016 if (g_touchscreengui) {
3017 cam->camera_yaw += g_touchscreengui->getYawChange();
3018 cam->camera_pitch = g_touchscreengui->getPitch();
3022 s32 dx = input->getMousePos().X - (driver->getScreenSize().Width / 2);
3023 s32 dy = input->getMousePos().Y - (driver->getScreenSize().Height / 2);
3025 if (m_invert_mouse || camera->getCameraMode() == CAMERA_MODE_THIRD_FRONT) {
3029 cam->camera_yaw -= dx * m_cache_mouse_sensitivity;
3030 cam->camera_pitch += dy * m_cache_mouse_sensitivity;
3032 #ifdef HAVE_TOUCHSCREENGUI
3036 if (m_cache_enable_joysticks) {
3037 f32 c = m_cache_joystick_frustum_sensitivity * (1.f / 32767.f) * dtime;
3038 cam->camera_yaw -= input->joystick.getAxisWithoutDead(JA_FRUSTUM_HORIZONTAL) * c;
3039 cam->camera_pitch += input->joystick.getAxisWithoutDead(JA_FRUSTUM_VERTICAL) * c;
3042 cam->camera_pitch = rangelim(cam->camera_pitch, -89.5, 89.5);
3046 void Game::updatePlayerControl(const CameraOrientation &cam)
3048 //TimeTaker tt("update player control", NULL, PRECISION_NANO);
3050 // DO NOT use the isKeyDown method for the forward, backward, left, right
3051 // buttons, as the code that uses the controls needs to be able to
3052 // distinguish between the two in order to know when to use joysticks.
3054 PlayerControl control(
3055 input->isKeyDown(keycache.key[KeyType::FORWARD]),
3056 input->isKeyDown(keycache.key[KeyType::BACKWARD]),
3057 input->isKeyDown(keycache.key[KeyType::LEFT]),
3058 input->isKeyDown(keycache.key[KeyType::RIGHT]),
3059 isKeyDown(KeyType::JUMP),
3060 isKeyDown(KeyType::SPECIAL1),
3061 isKeyDown(KeyType::SNEAK),
3062 isKeyDown(KeyType::ZOOM),
3067 input->joystick.getAxisWithoutDead(JA_SIDEWARD_MOVE),
3068 input->joystick.getAxisWithoutDead(JA_FORWARD_MOVE)
3072 ( (u32)(isKeyDown(KeyType::FORWARD) & 0x1) << 0) |
3073 ( (u32)(isKeyDown(KeyType::BACKWARD) & 0x1) << 1) |
3074 ( (u32)(isKeyDown(KeyType::LEFT) & 0x1) << 2) |
3075 ( (u32)(isKeyDown(KeyType::RIGHT) & 0x1) << 3) |
3076 ( (u32)(isKeyDown(KeyType::JUMP) & 0x1) << 4) |
3077 ( (u32)(isKeyDown(KeyType::SPECIAL1) & 0x1) << 5) |
3078 ( (u32)(isKeyDown(KeyType::SNEAK) & 0x1) << 6) |
3079 ( (u32)(isLeftPressed() & 0x1) << 7) |
3080 ( (u32)(isRightPressed() & 0x1) << 8
3084 /* For Android, simulate holding down AUX1 (fast move) if the user has
3085 * the fast_move setting toggled on. If there is an aux1 key defined for
3086 * Android then its meaning is inverted (i.e. holding aux1 means walk and
3089 if (m_cache_hold_aux1) {
3090 control.aux1 = control.aux1 ^ true;
3091 keypress_bits ^= ((u32)(1U << 5));
3095 client->setPlayerControl(control);
3096 LocalPlayer *player = client->getEnv().getLocalPlayer();
3097 player->keyPressed = keypress_bits;
3103 inline void Game::step(f32 *dtime)
3105 bool can_be_and_is_paused =
3106 (simple_singleplayer_mode && g_menumgr.pausesGame());
3108 if (can_be_and_is_paused) { // This is for a singleplayer server
3109 *dtime = 0; // No time passes
3111 if (server != NULL) {
3112 //TimeTaker timer("server->step(dtime)");
3113 server->step(*dtime);
3116 //TimeTaker timer("client.step(dtime)");
3117 client->step(*dtime);
3122 void Game::processClientEvents(CameraOrientation *cam)
3124 LocalPlayer *player = client->getEnv().getLocalPlayer();
3126 while (client->hasClientEvents()) {
3127 ClientEvent event = client->getClientEvent();
3129 switch (event.type) {
3130 case CE_PLAYER_DAMAGE:
3131 if (client->getHP() == 0)
3133 if (client->moddingEnabled()) {
3134 client->getScript()->on_damage_taken(event.player_damage.amount);
3137 runData.damage_flash += 95.0 + 3.2 * event.player_damage.amount;
3138 runData.damage_flash = MYMIN(runData.damage_flash, 127.0);
3140 player->hurt_tilt_timer = 1.5;
3141 player->hurt_tilt_strength =
3142 rangelim(event.player_damage.amount / 4, 1.0, 4.0);
3144 client->event()->put(new SimpleTriggerEvent("PlayerDamage"));
3147 case CE_PLAYER_FORCE_MOVE:
3148 cam->camera_yaw = event.player_force_move.yaw;
3149 cam->camera_pitch = event.player_force_move.pitch;
3152 case CE_DEATHSCREEN:
3153 // This should be enabled for death formspec in builtin
3154 client->getScript()->on_death();
3156 /* Handle visualization */
3157 runData.damage_flash = 0;
3158 player->hurt_tilt_timer = 0;
3159 player->hurt_tilt_strength = 0;
3162 case CE_SHOW_FORMSPEC:
3163 if (event.show_formspec.formspec->empty()) {
3164 if (current_formspec && (event.show_formspec.formname->empty()
3165 || *(event.show_formspec.formname) == cur_formname)) {
3166 current_formspec->quitMenu();
3169 FormspecFormSource *fs_src =
3170 new FormspecFormSource(*(event.show_formspec.formspec));
3171 TextDestPlayerInventory *txt_dst =
3172 new TextDestPlayerInventory(client, *(event.show_formspec.formname));
3174 create_formspec_menu(¤t_formspec, client, &input->joystick,
3176 cur_formname = *(event.show_formspec.formname);
3179 delete event.show_formspec.formspec;
3180 delete event.show_formspec.formname;
3183 case CE_SHOW_LOCAL_FORMSPEC:
3185 FormspecFormSource *fs_src = new FormspecFormSource(*event.show_formspec.formspec);
3186 LocalFormspecHandler *txt_dst = new LocalFormspecHandler(*event.show_formspec.formname, client);
3187 create_formspec_menu(¤t_formspec, client, &input->joystick,
3190 delete event.show_formspec.formspec;
3191 delete event.show_formspec.formname;
3194 case CE_SPAWN_PARTICLE:
3195 case CE_ADD_PARTICLESPAWNER:
3196 case CE_DELETE_PARTICLESPAWNER:
3197 client->getParticleManager()->handleParticleEvent(&event, client, player);
3202 u32 id = event.hudadd.id;
3204 HudElement *e = player->getHud(id);
3207 delete event.hudadd.pos;
3208 delete event.hudadd.name;
3209 delete event.hudadd.scale;
3210 delete event.hudadd.text;
3211 delete event.hudadd.align;
3212 delete event.hudadd.offset;
3213 delete event.hudadd.world_pos;
3214 delete event.hudadd.size;
3219 e->type = (HudElementType)event.hudadd.type;
3220 e->pos = *event.hudadd.pos;
3221 e->name = *event.hudadd.name;
3222 e->scale = *event.hudadd.scale;
3223 e->text = *event.hudadd.text;
3224 e->number = event.hudadd.number;
3225 e->item = event.hudadd.item;
3226 e->dir = event.hudadd.dir;
3227 e->align = *event.hudadd.align;
3228 e->offset = *event.hudadd.offset;
3229 e->world_pos = *event.hudadd.world_pos;
3230 e->size = *event.hudadd.size;
3232 u32 new_id = player->addHud(e);
3233 //if this isn't true our huds aren't consistent
3234 sanity_check(new_id == id);
3237 delete event.hudadd.pos;
3238 delete event.hudadd.name;
3239 delete event.hudadd.scale;
3240 delete event.hudadd.text;
3241 delete event.hudadd.align;
3242 delete event.hudadd.offset;
3243 delete event.hudadd.world_pos;
3244 delete event.hudadd.size;
3249 HudElement *e = player->removeHud(event.hudrm.id);
3257 u32 id = event.hudchange.id;
3258 HudElement *e = player->getHud(id);
3261 delete event.hudchange.v3fdata;
3262 delete event.hudchange.v2fdata;
3263 delete event.hudchange.sdata;
3264 delete event.hudchange.v2s32data;
3268 switch (event.hudchange.stat) {
3270 e->pos = *event.hudchange.v2fdata;
3274 e->name = *event.hudchange.sdata;
3277 case HUD_STAT_SCALE:
3278 e->scale = *event.hudchange.v2fdata;
3282 e->text = *event.hudchange.sdata;
3285 case HUD_STAT_NUMBER:
3286 e->number = event.hudchange.data;
3290 e->item = event.hudchange.data;
3294 e->dir = event.hudchange.data;
3297 case HUD_STAT_ALIGN:
3298 e->align = *event.hudchange.v2fdata;
3301 case HUD_STAT_OFFSET:
3302 e->offset = *event.hudchange.v2fdata;
3305 case HUD_STAT_WORLD_POS:
3306 e->world_pos = *event.hudchange.v3fdata;
3310 e->size = *event.hudchange.v2s32data;
3315 delete event.hudchange.v3fdata;
3316 delete event.hudchange.v2fdata;
3317 delete event.hudchange.sdata;
3318 delete event.hudchange.v2s32data;
3322 sky->setVisible(false);
3323 // Whether clouds are visible in front of a custom skybox
3324 sky->setCloudsEnabled(event.set_sky.clouds);
3331 // Handle according to type
3332 if (*event.set_sky.type == "regular") {
3333 sky->setVisible(true);
3334 sky->setCloudsEnabled(true);
3335 } else if (*event.set_sky.type == "skybox" &&
3336 event.set_sky.params->size() == 6) {
3337 sky->setFallbackBgColor(*event.set_sky.bgcolor);
3338 skybox = RenderingEngine::get_scene_manager()->addSkyBoxSceneNode(
3339 texture_src->getTextureForMesh((*event.set_sky.params)[0]),
3340 texture_src->getTextureForMesh((*event.set_sky.params)[1]),
3341 texture_src->getTextureForMesh((*event.set_sky.params)[2]),
3342 texture_src->getTextureForMesh((*event.set_sky.params)[3]),
3343 texture_src->getTextureForMesh((*event.set_sky.params)[4]),
3344 texture_src->getTextureForMesh((*event.set_sky.params)[5]));
3346 // Handle everything else as plain color
3348 if (*event.set_sky.type != "plain")
3349 infostream << "Unknown sky type: "
3350 << (*event.set_sky.type) << std::endl;
3352 sky->setFallbackBgColor(*event.set_sky.bgcolor);
3355 delete event.set_sky.bgcolor;
3356 delete event.set_sky.type;
3357 delete event.set_sky.params;
3360 case CE_OVERRIDE_DAY_NIGHT_RATIO:
3361 client->getEnv().setDayNightRatioOverride(
3362 event.override_day_night_ratio.do_override,
3363 event.override_day_night_ratio.ratio_f * 1000);
3366 case CE_CLOUD_PARAMS:
3368 clouds->setDensity(event.cloud_params.density);
3369 clouds->setColorBright(video::SColor(event.cloud_params.color_bright));
3370 clouds->setColorAmbient(video::SColor(event.cloud_params.color_ambient));
3371 clouds->setHeight(event.cloud_params.height);
3372 clouds->setThickness(event.cloud_params.thickness);
3373 clouds->setSpeed(v2f(
3374 event.cloud_params.speed_x,
3375 event.cloud_params.speed_y));
3380 // unknown or unhandled type
3388 void Game::updateCamera(u32 busy_time, f32 dtime)
3390 LocalPlayer *player = client->getEnv().getLocalPlayer();
3393 For interaction purposes, get info about the held item
3395 - Is it a usable item?
3396 - Can it point to liquids?
3398 ItemStack playeritem;
3400 InventoryList *mlist = local_inventory->getList("main");
3402 if (mlist && client->getPlayerItem() < mlist->getSize())
3403 playeritem = mlist->getItem(client->getPlayerItem());
3406 if (playeritem.getDefinition(itemdef_manager).name.empty()) { // override the hand
3407 InventoryList *hlist = local_inventory->getList("hand");
3409 playeritem = hlist->getItem(0);
3413 ToolCapabilities playeritem_toolcap =
3414 playeritem.getToolCapabilities(itemdef_manager);
3416 v3s16 old_camera_offset = camera->getOffset();
3418 if (wasKeyDown(KeyType::CAMERA_MODE)) {
3419 GenericCAO *playercao = player->getCAO();
3421 // If playercao not loaded, don't change camera
3425 camera->toggleCameraMode();
3427 playercao->setVisible(camera->getCameraMode() > CAMERA_MODE_FIRST);
3428 playercao->setChildrenVisible(camera->getCameraMode() > CAMERA_MODE_FIRST);
3431 float full_punch_interval = playeritem_toolcap.full_punch_interval;
3432 float tool_reload_ratio = runData.time_from_last_punch / full_punch_interval;
3434 tool_reload_ratio = MYMIN(tool_reload_ratio, 1.0);
3435 camera->update(player, dtime, busy_time / 1000.0f, tool_reload_ratio);
3436 camera->step(dtime);
3438 v3f camera_position = camera->getPosition();
3439 v3f camera_direction = camera->getDirection();
3440 f32 camera_fov = camera->getFovMax();
3441 v3s16 camera_offset = camera->getOffset();
3443 m_camera_offset_changed = (camera_offset != old_camera_offset);
3445 if (!flags.disable_camera_update) {
3446 client->getEnv().getClientMap().updateCamera(camera_position,
3447 camera_direction, camera_fov, camera_offset);
3449 if (m_camera_offset_changed) {
3450 client->updateCameraOffset(camera_offset);
3451 client->getEnv().updateCameraOffset(camera_offset);
3454 clouds->updateCameraOffset(camera_offset);
3460 void Game::updateSound(f32 dtime)
3462 // Update sound listener
3463 v3s16 camera_offset = camera->getOffset();
3464 sound->updateListener(camera->getCameraNode()->getPosition() + intToFloat(camera_offset, BS),
3465 v3f(0, 0, 0), // velocity
3466 camera->getDirection(),
3467 camera->getCameraNode()->getUpVector());
3469 // Check if volume is in the proper range, else fix it.
3470 float old_volume = g_settings->getFloat("sound_volume");
3471 float new_volume = rangelim(old_volume, 0.0f, 1.0f);
3472 sound->setListenerGain(new_volume);
3474 if (old_volume != new_volume) {
3475 g_settings->setFloat("sound_volume", new_volume);
3478 LocalPlayer *player = client->getEnv().getLocalPlayer();
3480 // Tell the sound maker whether to make footstep sounds
3481 soundmaker->makes_footstep_sound = player->makes_footstep_sound;
3483 // Update sound maker
3484 if (player->makes_footstep_sound)
3485 soundmaker->step(dtime);
3487 ClientMap &map = client->getEnv().getClientMap();
3488 MapNode n = map.getNodeNoEx(player->getFootstepNodePos());
3489 soundmaker->m_player_step_sound = nodedef_manager->get(n).sound_footstep;
3493 void Game::processPlayerInteraction(f32 dtime, bool show_hud, bool show_debug)
3495 LocalPlayer *player = client->getEnv().getLocalPlayer();
3497 ItemStack playeritem;
3499 InventoryList *mlist = local_inventory->getList("main");
3501 if (mlist && client->getPlayerItem() < mlist->getSize())
3502 playeritem = mlist->getItem(client->getPlayerItem());
3505 const ItemDefinition &playeritem_def =
3506 playeritem.getDefinition(itemdef_manager);
3507 InventoryList *hlist = local_inventory->getList("hand");
3508 const ItemDefinition &hand_def =
3509 hlist ? hlist->getItem(0).getDefinition(itemdef_manager) : itemdef_manager->get("");
3511 v3f player_position = player->getPosition();
3512 v3f camera_position = camera->getPosition();
3513 v3f camera_direction = camera->getDirection();
3514 v3s16 camera_offset = camera->getOffset();
3518 Calculate what block is the crosshair pointing to
3521 f32 d = playeritem_def.range; // max. distance
3522 f32 d_hand = hand_def.range;
3524 if (d < 0 && d_hand >= 0)
3529 core::line3d<f32> shootline;
3531 if (camera->getCameraMode() != CAMERA_MODE_THIRD_FRONT) {
3532 shootline = core::line3d<f32>(camera_position,
3533 camera_position + camera_direction * BS * d);
3535 // prevent player pointing anything in front-view
3536 shootline = core::line3d<f32>(camera_position,camera_position);
3539 #ifdef HAVE_TOUCHSCREENGUI
3541 if ((g_settings->getBool("touchtarget")) && (g_touchscreengui)) {
3542 shootline = g_touchscreengui->getShootline();
3543 shootline.start += intToFloat(camera_offset, BS);
3544 shootline.end += intToFloat(camera_offset, BS);
3549 PointedThing pointed = updatePointedThing(shootline,
3550 playeritem_def.liquids_pointable,
3551 !runData.ldown_for_dig,
3554 if (pointed != runData.pointed_old) {
3555 infostream << "Pointing at " << pointed.dump() << std::endl;
3556 hud->updateSelectionMesh(camera_offset);
3561 - releasing left mouse button
3562 - pointing away from node
3564 if (runData.digging) {
3565 if (getLeftReleased()) {
3566 infostream << "Left button released"
3567 << " (stopped digging)" << std::endl;
3568 runData.digging = false;
3569 } else if (pointed != runData.pointed_old) {
3570 if (pointed.type == POINTEDTHING_NODE
3571 && runData.pointed_old.type == POINTEDTHING_NODE
3572 && pointed.node_undersurface
3573 == runData.pointed_old.node_undersurface) {
3574 // Still pointing to the same node, but a different face.
3577 infostream << "Pointing away from node"
3578 << " (stopped digging)" << std::endl;
3579 runData.digging = false;
3580 hud->updateSelectionMesh(camera_offset);
3584 if (!runData.digging) {
3585 client->interact(1, runData.pointed_old);
3586 client->setCrack(-1, v3s16(0, 0, 0));
3587 runData.dig_time = 0.0;
3589 } else if (runData.dig_instantly && getLeftReleased()) {
3590 // Remove e.g. torches faster when clicking instead of holding LMB
3591 runData.nodig_delay_timer = 0;
3592 runData.dig_instantly = false;
3595 if (!runData.digging && runData.ldown_for_dig && !isLeftPressed()) {
3596 runData.ldown_for_dig = false;
3599 runData.left_punch = false;
3601 soundmaker->m_player_leftpunch_sound.name = "";
3603 if (isRightPressed())
3604 runData.repeat_rightclick_timer += dtime;
3606 runData.repeat_rightclick_timer = 0;
3608 if (playeritem_def.usable && isLeftPressed()) {
3609 if (getLeftClicked() && (!client->moddingEnabled()
3610 || !client->getScript()->on_item_use(playeritem, pointed)))
3611 client->interact(4, pointed);
3612 } else if (pointed.type == POINTEDTHING_NODE) {
3613 ToolCapabilities playeritem_toolcap =
3614 playeritem.getToolCapabilities(itemdef_manager);
3615 if (playeritem.name.empty() && hand_def.tool_capabilities != NULL) {
3616 playeritem_toolcap = *hand_def.tool_capabilities;
3618 handlePointingAtNode(pointed, playeritem_def, playeritem,
3619 playeritem_toolcap, dtime);
3620 } else if (pointed.type == POINTEDTHING_OBJECT) {
3621 handlePointingAtObject(pointed, playeritem, player_position, show_debug);
3622 } else if (isLeftPressed()) {
3623 // When button is held down in air, show continuous animation
3624 runData.left_punch = true;
3625 } else if (getRightClicked()) {
3626 handlePointingAtNothing(playeritem);
3629 runData.pointed_old = pointed;
3631 if (runData.left_punch || getLeftClicked())
3632 camera->setDigging(0); // left click animation
3634 input->resetLeftClicked();
3635 input->resetRightClicked();
3637 input->joystick.clearWasKeyDown(KeyType::MOUSE_L);
3638 input->joystick.clearWasKeyDown(KeyType::MOUSE_R);
3640 input->resetLeftReleased();
3641 input->resetRightReleased();
3643 input->joystick.clearWasKeyReleased(KeyType::MOUSE_L);
3644 input->joystick.clearWasKeyReleased(KeyType::MOUSE_R);
3648 PointedThing Game::updatePointedThing(
3649 const core::line3d<f32> &shootline,
3650 bool liquids_pointable,
3651 bool look_for_object,
3652 const v3s16 &camera_offset)
3654 std::vector<aabb3f> *selectionboxes = hud->getSelectionBoxes();
3655 selectionboxes->clear();
3656 hud->setSelectedFaceNormal(v3f(0.0, 0.0, 0.0));
3657 static thread_local const bool show_entity_selectionbox = g_settings->getBool(
3658 "show_entity_selectionbox");
3660 ClientEnvironment &env = client->getEnv();
3661 ClientMap &map = env.getClientMap();
3662 INodeDefManager *nodedef = map.getNodeDefManager();
3664 runData.selected_object = NULL;
3666 RaycastState s(shootline, look_for_object, liquids_pointable);
3667 PointedThing result;
3668 env.continueRaycast(&s, &result);
3669 if (result.type == POINTEDTHING_OBJECT) {
3670 runData.selected_object = client->getEnv().getActiveObject(result.object_id);
3671 aabb3f selection_box;
3672 if (show_entity_selectionbox && runData.selected_object->doShowSelectionBox() &&
3673 runData.selected_object->getSelectionBox(&selection_box)) {
3674 v3f pos = runData.selected_object->getPosition();
3675 selectionboxes->push_back(aabb3f(selection_box));
3676 hud->setSelectionPos(pos, camera_offset);
3678 } else if (result.type == POINTEDTHING_NODE) {
3679 // Update selection boxes
3680 MapNode n = map.getNodeNoEx(result.node_undersurface);
3681 std::vector<aabb3f> boxes;
3682 n.getSelectionBoxes(nodedef, &boxes,
3683 n.getNeighbors(result.node_undersurface, &map));
3686 for (std::vector<aabb3f>::const_iterator i = boxes.begin();
3687 i != boxes.end(); ++i) {
3689 box.MinEdge -= v3f(d, d, d);
3690 box.MaxEdge += v3f(d, d, d);
3691 selectionboxes->push_back(box);
3693 hud->setSelectionPos(intToFloat(result.node_undersurface, BS),
3695 hud->setSelectedFaceNormal(v3f(
3696 result.intersection_normal.X,
3697 result.intersection_normal.Y,
3698 result.intersection_normal.Z));
3701 // Update selection mesh light level and vertex colors
3702 if (!selectionboxes->empty()) {
3703 v3f pf = hud->getSelectionPos();
3704 v3s16 p = floatToInt(pf, BS);
3706 // Get selection mesh light level
3707 MapNode n = map.getNodeNoEx(p);
3708 u16 node_light = getInteriorLight(n, -1, nodedef);
3709 u16 light_level = node_light;
3711 for (const v3s16 &dir : g_6dirs) {
3712 n = map.getNodeNoEx(p + dir);
3713 node_light = getInteriorLight(n, -1, nodedef);
3714 if (node_light > light_level)
3715 light_level = node_light;
3718 u32 daynight_ratio = client->getEnv().getDayNightRatio();
3720 final_color_blend(&c, light_level, daynight_ratio);
3722 // Modify final color a bit with time
3723 u32 timer = porting::getTimeMs() % 5000;
3724 float timerf = (float) (irr::core::PI * ((timer / 2500.0) - 0.5));
3725 float sin_r = 0.08 * sin(timerf);
3726 float sin_g = 0.08 * sin(timerf + irr::core::PI * 0.5);
3727 float sin_b = 0.08 * sin(timerf + irr::core::PI);
3728 c.setRed(core::clamp(core::round32(c.getRed() * (0.8 + sin_r)), 0, 255));
3729 c.setGreen(core::clamp(core::round32(c.getGreen() * (0.8 + sin_g)), 0, 255));
3730 c.setBlue(core::clamp(core::round32(c.getBlue() * (0.8 + sin_b)), 0, 255));
3732 // Set mesh final color
3733 hud->setSelectionMeshColor(c);
3739 void Game::handlePointingAtNothing(const ItemStack &playerItem)
3741 infostream << "Right Clicked in Air" << std::endl;
3742 PointedThing fauxPointed;
3743 fauxPointed.type = POINTEDTHING_NOTHING;
3744 client->interact(5, fauxPointed);
3748 void Game::handlePointingAtNode(const PointedThing &pointed,
3749 const ItemDefinition &playeritem_def, const ItemStack &playeritem,
3750 const ToolCapabilities &playeritem_toolcap, f32 dtime)
3752 v3s16 nodepos = pointed.node_undersurface;
3753 v3s16 neighbourpos = pointed.node_abovesurface;
3756 Check information text of node
3759 ClientMap &map = client->getEnv().getClientMap();
3761 if (runData.nodig_delay_timer <= 0.0 && isLeftPressed()
3762 && client->checkPrivilege("interact")) {
3763 handleDigging(pointed, nodepos, playeritem_toolcap, dtime);
3766 // This should be done after digging handling
3767 NodeMetadata *meta = map.getNodeMetadata(nodepos);
3770 infotext = unescape_enriched(utf8_to_wide(meta->getString("infotext")));
3772 MapNode n = map.getNodeNoEx(nodepos);
3774 if (nodedef_manager->get(n).tiledef[0].name == "unknown_node.png") {
3775 infotext = L"Unknown node: ";
3776 infotext += utf8_to_wide(nodedef_manager->get(n).name);
3780 if ((getRightClicked() ||
3781 runData.repeat_rightclick_timer >= m_repeat_right_click_time) &&
3782 client->checkPrivilege("interact")) {
3783 runData.repeat_rightclick_timer = 0;
3784 infostream << "Ground right-clicked" << std::endl;
3786 if (meta && !meta->getString("formspec").empty() && !random_input
3787 && !isKeyDown(KeyType::SNEAK)) {
3788 // Report right click to server
3789 if (nodedef_manager->get(map.getNodeNoEx(nodepos)).rightclickable) {
3790 client->interact(3, pointed);
3793 infostream << "Launching custom inventory view" << std::endl;
3795 InventoryLocation inventoryloc;
3796 inventoryloc.setNodeMeta(nodepos);
3798 NodeMetadataFormSource *fs_src = new NodeMetadataFormSource(
3799 &client->getEnv().getClientMap(), nodepos);
3800 TextDest *txt_dst = new TextDestNodeMetadata(nodepos, client);
3802 create_formspec_menu(¤t_formspec, client,
3803 &input->joystick, fs_src, txt_dst);
3806 current_formspec->setFormSpec(meta->getString("formspec"), inventoryloc);
3808 // Report right click to server
3810 camera->setDigging(1); // right click animation (always shown for feedback)
3812 // If the wielded item has node placement prediction,
3814 bool placed = nodePlacementPrediction(*client,
3815 playeritem_def, playeritem,
3816 nodepos, neighbourpos);
3820 client->interact(3, pointed);
3822 soundmaker->m_player_rightpunch_sound =
3823 playeritem_def.sound_place;
3825 if (client->moddingEnabled())
3826 client->getScript()->on_placenode(pointed, playeritem_def);
3828 soundmaker->m_player_rightpunch_sound =
3831 if (playeritem_def.node_placement_prediction.empty() ||
3832 nodedef_manager->get(map.getNodeNoEx(nodepos)).rightclickable) {
3833 client->interact(3, pointed); // Report to server
3835 soundmaker->m_player_rightpunch_sound =
3836 playeritem_def.sound_place_failed;
3844 void Game::handlePointingAtObject(const PointedThing &pointed, const ItemStack &playeritem,
3845 const v3f &player_position, bool show_debug)
3847 infotext = unescape_enriched(
3848 utf8_to_wide(runData.selected_object->infoText()));
3851 if (!infotext.empty()) {
3854 infotext += unescape_enriched(utf8_to_wide(
3855 runData.selected_object->debugInfoText()));
3858 if (isLeftPressed()) {
3859 bool do_punch = false;
3860 bool do_punch_damage = false;
3862 if (runData.object_hit_delay_timer <= 0.0) {
3864 do_punch_damage = true;
3865 runData.object_hit_delay_timer = object_hit_delay;
3868 if (getLeftClicked())
3872 infostream << "Left-clicked object" << std::endl;
3873 runData.left_punch = true;
3876 if (do_punch_damage) {
3877 // Report direct punch
3878 v3f objpos = runData.selected_object->getPosition();
3879 v3f dir = (objpos - player_position).normalize();
3880 ItemStack item = playeritem;
3881 if (playeritem.name.empty()) {
3882 InventoryList *hlist = local_inventory->getList("hand");
3884 item = hlist->getItem(0);
3888 bool disable_send = runData.selected_object->directReportPunch(
3889 dir, &item, runData.time_from_last_punch);
3890 runData.time_from_last_punch = 0;
3893 client->interact(0, pointed);
3895 } else if (getRightClicked()) {
3896 infostream << "Right-clicked object" << std::endl;
3897 client->interact(3, pointed); // place
3902 void Game::handleDigging(const PointedThing &pointed, const v3s16 &nodepos,
3903 const ToolCapabilities &playeritem_toolcap, f32 dtime)
3905 LocalPlayer *player = client->getEnv().getLocalPlayer();
3906 ClientMap &map = client->getEnv().getClientMap();
3907 MapNode n = client->getEnv().getClientMap().getNodeNoEx(nodepos);
3909 // NOTE: Similar piece of code exists on the server side for
3911 // Get digging parameters
3912 DigParams params = getDigParams(nodedef_manager->get(n).groups,
3913 &playeritem_toolcap);
3915 // If can't dig, try hand
3916 if (!params.diggable) {
3917 InventoryList *hlist = local_inventory->getList("hand");
3918 const ItemDefinition &hand =
3919 hlist ? hlist->getItem(0).getDefinition(itemdef_manager) : itemdef_manager->get("");
3920 const ToolCapabilities *tp = hand.tool_capabilities;
3923 params = getDigParams(nodedef_manager->get(n).groups, tp);
3926 if (!params.diggable) {
3927 // I guess nobody will wait for this long
3928 runData.dig_time_complete = 10000000.0;
3930 runData.dig_time_complete = params.time;
3932 if (m_cache_enable_particles) {
3933 const ContentFeatures &features = client->getNodeDefManager()->get(n);
3934 client->getParticleManager()->addPunchingParticles(client,
3935 player, nodepos, n, features);
3939 if (!runData.digging) {
3940 infostream << "Started digging" << std::endl;
3941 runData.dig_instantly = runData.dig_time_complete == 0;
3942 if (client->moddingEnabled() && client->getScript()->on_punchnode(nodepos, n))
3944 client->interact(0, pointed);
3945 runData.digging = true;
3946 runData.ldown_for_dig = true;
3949 if (!runData.dig_instantly) {
3950 runData.dig_index = (float)crack_animation_length
3952 / runData.dig_time_complete;
3954 // This is for e.g. torches
3955 runData.dig_index = crack_animation_length;
3958 SimpleSoundSpec sound_dig = nodedef_manager->get(n).sound_dig;
3960 if (sound_dig.exists() && params.diggable) {
3961 if (sound_dig.name == "__group") {
3962 if (!params.main_group.empty()) {
3963 soundmaker->m_player_leftpunch_sound.gain = 0.5;
3964 soundmaker->m_player_leftpunch_sound.name =
3965 std::string("default_dig_") +
3969 soundmaker->m_player_leftpunch_sound = sound_dig;
3973 // Don't show cracks if not diggable
3974 if (runData.dig_time_complete >= 100000.0) {
3975 } else if (runData.dig_index < crack_animation_length) {
3976 //TimeTaker timer("client.setTempMod");
3977 //infostream<<"dig_index="<<dig_index<<std::endl;
3978 client->setCrack(runData.dig_index, nodepos);
3980 infostream << "Digging completed" << std::endl;
3981 client->setCrack(-1, v3s16(0, 0, 0));
3983 runData.dig_time = 0;
3984 runData.digging = false;
3986 runData.nodig_delay_timer =
3987 runData.dig_time_complete / (float)crack_animation_length;
3989 // We don't want a corresponding delay to very time consuming nodes
3990 // and nodes without digging time (e.g. torches) get a fixed delay.
3991 if (runData.nodig_delay_timer > 0.3)
3992 runData.nodig_delay_timer = 0.3;
3993 else if (runData.dig_instantly)
3994 runData.nodig_delay_timer = 0.15;
3996 bool is_valid_position;
3997 MapNode wasnode = map.getNodeNoEx(nodepos, &is_valid_position);
3998 if (is_valid_position) {
3999 if (client->moddingEnabled() &&
4000 client->getScript()->on_dignode(nodepos, wasnode)) {
4003 client->removeNode(nodepos);
4006 client->interact(2, pointed);
4008 if (m_cache_enable_particles) {
4009 const ContentFeatures &features =
4010 client->getNodeDefManager()->get(wasnode);
4011 client->getParticleManager()->addDiggingParticles(client,
4012 player, nodepos, wasnode, features);
4016 // Send event to trigger sound
4017 MtEvent *e = new NodeDugEvent(nodepos, wasnode);
4018 client->event()->put(e);
4021 if (runData.dig_time_complete < 100000.0) {
4022 runData.dig_time += dtime;
4024 runData.dig_time = 0;
4025 client->setCrack(-1, nodepos);
4028 camera->setDigging(0); // left click animation
4032 void Game::updateFrame(ProfilerGraph *graph, RunStats *stats, f32 dtime,
4033 const CameraOrientation &cam)
4035 LocalPlayer *player = client->getEnv().getLocalPlayer();
4041 if (draw_control->range_all) {
4042 runData.fog_range = 100000 * BS;
4044 runData.fog_range = draw_control->wanted_range * BS;
4048 Calculate general brightness
4050 u32 daynight_ratio = client->getEnv().getDayNightRatio();
4051 float time_brightness = decode_light_f((float)daynight_ratio / 1000.0);
4052 float direct_brightness;
4055 if (m_cache_enable_noclip && m_cache_enable_free_move) {
4056 direct_brightness = time_brightness;
4057 sunlight_seen = true;
4059 ScopeProfiler sp(g_profiler, "Detecting background light", SPT_AVG);
4060 float old_brightness = sky->getBrightness();
4061 direct_brightness = client->getEnv().getClientMap()
4062 .getBackgroundBrightness(MYMIN(runData.fog_range * 1.2, 60 * BS),
4063 daynight_ratio, (int)(old_brightness * 255.5), &sunlight_seen)
4067 float time_of_day_smooth = runData.time_of_day_smooth;
4068 float time_of_day = client->getEnv().getTimeOfDayF();
4070 static const float maxsm = 0.05;
4071 static const float todsm = 0.05;
4073 if (fabs(time_of_day - time_of_day_smooth) > maxsm &&
4074 fabs(time_of_day - time_of_day_smooth + 1.0) > maxsm &&
4075 fabs(time_of_day - time_of_day_smooth - 1.0) > maxsm)
4076 time_of_day_smooth = time_of_day;
4078 if (time_of_day_smooth > 0.8 && time_of_day < 0.2)
4079 time_of_day_smooth = time_of_day_smooth * (1.0 - todsm)
4080 + (time_of_day + 1.0) * todsm;
4082 time_of_day_smooth = time_of_day_smooth * (1.0 - todsm)
4083 + time_of_day * todsm;
4085 runData.time_of_day = time_of_day;
4086 runData.time_of_day_smooth = time_of_day_smooth;
4088 sky->update(time_of_day_smooth, time_brightness, direct_brightness,
4089 sunlight_seen, camera->getCameraMode(), player->getYaw(),
4090 player->getPitch());
4096 if (sky->getCloudsVisible()) {
4097 clouds->setVisible(true);
4098 clouds->step(dtime);
4099 // camera->getPosition is not enough for 3rd person views
4100 v3f camera_node_position = camera->getCameraNode()->getPosition();
4101 v3s16 camera_offset = camera->getOffset();
4102 camera_node_position.X = camera_node_position.X + camera_offset.X * BS;
4103 camera_node_position.Y = camera_node_position.Y + camera_offset.Y * BS;
4104 camera_node_position.Z = camera_node_position.Z + camera_offset.Z * BS;
4105 clouds->update(camera_node_position,
4106 sky->getCloudColor());
4107 if (clouds->isCameraInsideCloud() && m_cache_enable_fog &&
4108 !flags.force_fog_off) {
4109 // if inside clouds, and fog enabled, use that as sky
4111 video::SColor clouds_dark = clouds->getColor()
4112 .getInterpolated(video::SColor(255, 0, 0, 0), 0.9);
4113 sky->overrideColors(clouds_dark, clouds->getColor());
4114 sky->setBodiesVisible(false);
4115 runData.fog_range = std::fmin(runData.fog_range * 0.5f, 32.0f * BS);
4116 // do not draw clouds after all
4117 clouds->setVisible(false);
4120 clouds->setVisible(false);
4127 client->getParticleManager()->step(dtime);
4133 if (m_cache_enable_fog && !flags.force_fog_off) {
4136 video::EFT_FOG_LINEAR,
4137 runData.fog_range * m_cache_fog_start,
4138 runData.fog_range * 1.0,
4146 video::EFT_FOG_LINEAR,
4156 Get chat messages from client
4159 v2u32 screensize = driver->getScreenSize();
4161 updateChat(*client, dtime, flags.show_debug, screensize,
4162 flags.show_chat, runData.profiler_current_page,
4163 *chat_backend, guitext_chat);
4169 if (client->getPlayerItem() != runData.new_playeritem)
4170 client->selectPlayerItem(runData.new_playeritem);
4172 // Update local inventory if it has changed
4173 if (client->getLocalInventoryUpdated()) {
4174 //infostream<<"Updating local inventory"<<std::endl;
4175 client->getLocalInventory(*local_inventory);
4176 runData.update_wielded_item_trigger = true;
4179 if (runData.update_wielded_item_trigger) {
4180 // Update wielded tool
4181 InventoryList *mlist = local_inventory->getList("main");
4183 if (mlist && (client->getPlayerItem() < mlist->getSize())) {
4184 ItemStack item = mlist->getItem(client->getPlayerItem());
4185 if (item.getDefinition(itemdef_manager).name.empty()) { // override the hand
4186 InventoryList *hlist = local_inventory->getList("hand");
4188 item = hlist->getItem(0);
4190 camera->wield(item);
4193 runData.update_wielded_item_trigger = false;
4197 Update block draw list every 200ms or when camera direction has
4200 runData.update_draw_list_timer += dtime;
4202 v3f camera_direction = camera->getDirection();
4203 if (runData.update_draw_list_timer >= 0.2
4204 || runData.update_draw_list_last_cam_dir.getDistanceFrom(camera_direction) > 0.2
4205 || m_camera_offset_changed) {
4206 runData.update_draw_list_timer = 0;
4207 client->getEnv().getClientMap().updateDrawList();
4208 runData.update_draw_list_last_cam_dir = camera_direction;
4211 updateGui(*stats, dtime, cam);
4214 make sure menu is on top
4215 1. Delete formspec menu reference if menu was removed
4216 2. Else, make sure formspec menu is on top
4218 if (current_formspec) {
4219 if (current_formspec->getReferenceCount() == 1) {
4220 current_formspec->drop();
4221 current_formspec = NULL;
4222 } else if (isMenuActive()) {
4223 guiroot->bringToFront(current_formspec);
4230 const video::SColor &skycolor = sky->getSkyColor();
4232 TimeTaker tt_draw("mainloop: draw");
4233 driver->beginScene(true, true, skycolor);
4235 RenderingEngine::draw_scene(camera, client, player, hud, mapper,
4236 guienv, screensize, skycolor, flags.show_hud,
4237 flags.show_minimap);
4242 if (flags.show_profiler_graph)
4243 graph->draw(10, screensize.Y - 10, driver, g_fontengine->getFont());
4248 if (runData.damage_flash > 0.0) {
4249 video::SColor color(runData.damage_flash, 180, 0, 0);
4250 driver->draw2DRectangle(color,
4251 core::rect<s32>(0, 0, screensize.X, screensize.Y),
4254 runData.damage_flash -= 100.0 * dtime;
4260 if (player->hurt_tilt_timer > 0.0) {
4261 player->hurt_tilt_timer -= dtime * 5;
4263 if (player->hurt_tilt_timer < 0)
4264 player->hurt_tilt_strength = 0;
4268 Update minimap pos and rotation
4270 if (mapper && flags.show_minimap && flags.show_hud) {
4271 mapper->setPos(floatToInt(player->getPosition(), BS));
4272 mapper->setAngle(player->getYaw());
4280 stats->drawtime = tt_draw.stop(true);
4281 g_profiler->graphAdd("mainloop_draw", stats->drawtime / 1000.0f);
4285 inline static const char *yawToDirectionString(int yaw)
4287 static const char *direction[4] = {"North [+Z]", "West [-X]", "South [-Z]", "East [+X]"};
4289 yaw = wrapDegrees_0_360(yaw);
4290 yaw = (yaw + 45) % 360 / 90;
4292 return direction[yaw];
4296 void Game::updateGui(const RunStats &stats, f32 dtime, const CameraOrientation &cam)
4298 v2u32 screensize = driver->getScreenSize();
4299 LocalPlayer *player = client->getEnv().getLocalPlayer();
4300 v3f player_position = player->getPosition();
4302 if (flags.show_debug) {
4303 static float drawtime_avg = 0;
4304 drawtime_avg = drawtime_avg * 0.95 + stats.drawtime * 0.05;
4305 u16 fps = 1.0 / stats.dtime_jitter.avg;
4307 std::ostringstream os(std::ios_base::binary);
4309 << PROJECT_NAME_C " " << g_version_hash
4310 << ", FPS = " << fps
4311 << ", range_all = " << draw_control->range_all
4312 << std::setprecision(0)
4313 << ", drawtime = " << drawtime_avg << " ms"
4314 << std::setprecision(1)
4315 << ", dtime_jitter = "
4316 << (stats.dtime_jitter.max_fraction * 100.0) << " %"
4317 << std::setprecision(1)
4318 << ", view_range = " << draw_control->wanted_range
4319 << std::setprecision(3)
4320 << ", RTT = " << client->getRTT() << " s";
4321 setStaticText(guitext, utf8_to_wide(os.str()).c_str());
4322 guitext->setVisible(true);
4324 guitext->setVisible(false);
4327 if (guitext->isVisible()) {
4328 core::rect<s32> rect(
4330 screensize.X, 5 + g_fontengine->getTextHeight()
4332 guitext->setRelativePosition(rect);
4335 if (flags.show_debug) {
4336 std::ostringstream os(std::ios_base::binary);
4337 os << std::setprecision(1) << std::fixed
4338 << "pos = (" << (player_position.X / BS)
4339 << ", " << (player_position.Y / BS)
4340 << ", " << (player_position.Z / BS)
4341 << "), yaw = " << (wrapDegrees_0_360(cam.camera_yaw)) << "°"
4342 << " " << yawToDirectionString(cam.camera_yaw)
4343 << ", seed = " << ((u64)client->getMapSeed());
4344 setStaticText(guitext2, utf8_to_wide(os.str()).c_str());
4345 guitext2->setVisible(true);
4347 guitext2->setVisible(false);
4350 if (guitext2->isVisible()) {
4351 core::rect<s32> rect(
4352 5, 5 + g_fontengine->getTextHeight(),
4353 screensize.X, 5 + g_fontengine->getTextHeight() * 2
4355 guitext2->setRelativePosition(rect);
4358 if (flags.show_debug && runData.pointed_old.type == POINTEDTHING_NODE) {
4359 ClientMap &map = client->getEnv().getClientMap();
4360 const INodeDefManager *nodedef = client->getNodeDefManager();
4361 MapNode n = map.getNodeNoEx(runData.pointed_old.node_undersurface);
4363 if (n.getContent() != CONTENT_IGNORE && nodedef->get(n).name != "unknown") {
4364 std::ostringstream os(std::ios_base::binary);
4365 os << "pointing_at = (" << nodedef->get(n).name
4366 << ", param2 = " << (u64) n.getParam2()
4368 setStaticText(guitext3, utf8_to_wide(os.str()).c_str());
4369 guitext3->setVisible(true);
4371 guitext3->setVisible(false);
4374 guitext3->setVisible(false);
4377 if (guitext3->isVisible()) {
4378 core::rect<s32> rect(
4379 5, 5 + g_fontengine->getTextHeight() * 2,
4380 screensize.X, 5 + g_fontengine->getTextHeight() * 3
4382 guitext3->setRelativePosition(rect);
4385 setStaticText(guitext_info, infotext.c_str());
4386 guitext_info->setVisible(flags.show_hud && g_menumgr.menuCount() == 0);
4388 float statustext_time_max = 1.5;
4390 if (!m_statustext.empty()) {
4391 runData.statustext_time += dtime;
4393 if (runData.statustext_time >= statustext_time_max) {
4395 runData.statustext_time = 0;
4399 setStaticText(guitext_status, m_statustext.c_str());
4400 guitext_status->setVisible(!m_statustext.empty());
4402 if (!m_statustext.empty()) {
4403 s32 status_width = guitext_status->getTextWidth();
4404 s32 status_height = guitext_status->getTextHeight();
4405 s32 status_y = screensize.Y - 150;
4406 s32 status_x = (screensize.X - status_width) / 2;
4407 core::rect<s32> rect(
4408 status_x , status_y - status_height,
4409 status_x + status_width, status_y
4411 guitext_status->setRelativePosition(rect);
4414 video::SColor initial_color(255, 0, 0, 0);
4416 if (guienv->getSkin())
4417 initial_color = guienv->getSkin()->getColor(gui::EGDC_BUTTON_TEXT);
4419 video::SColor final_color = initial_color;
4420 final_color.setAlpha(0);
4421 video::SColor fade_color = initial_color.getInterpolated_quadratic(
4422 initial_color, final_color,
4423 pow(runData.statustext_time / statustext_time_max, 2.0f));
4424 guitext_status->setOverrideColor(fade_color);
4425 guitext_status->enableOverrideColor(true);
4430 /* Log times and stuff for visualization */
4431 inline void Game::updateProfilerGraphs(ProfilerGraph *graph)
4433 Profiler::GraphValues values;
4434 g_profiler->graphGet(values);
4440 /****************************************************************************
4442 ****************************************************************************/
4444 /* On some computers framerate doesn't seem to be automatically limited
4446 inline void Game::limitFps(FpsControl *fps_timings, f32 *dtime)
4448 // not using getRealTime is necessary for wine
4449 device->getTimer()->tick(); // Maker sure device time is up-to-date
4450 u32 time = device->getTimer()->getTime();
4451 u32 last_time = fps_timings->last_time;
4453 if (time > last_time) // Make sure time hasn't overflowed
4454 fps_timings->busy_time = time - last_time;
4456 fps_timings->busy_time = 0;
4458 u32 frametime_min = 1000 / (g_menumgr.pausesGame()
4459 ? g_settings->getFloat("pause_fps_max")
4460 : g_settings->getFloat("fps_max"));
4462 if (fps_timings->busy_time < frametime_min) {
4463 fps_timings->sleep_time = frametime_min - fps_timings->busy_time;
4464 device->sleep(fps_timings->sleep_time);
4466 fps_timings->sleep_time = 0;
4469 /* Get the new value of the device timer. Note that device->sleep() may
4470 * not sleep for the entire requested time as sleep may be interrupted and
4471 * therefore it is arguably more accurate to get the new time from the
4472 * device rather than calculating it by adding sleep_time to time.
4475 device->getTimer()->tick(); // Update device timer
4476 time = device->getTimer()->getTime();
4478 if (time > last_time) // Make sure last_time hasn't overflowed
4479 *dtime = (time - last_time) / 1000.0;
4483 fps_timings->last_time = time;
4486 void Game::showOverlayMessage(const char *msg, float dtime, int percent, bool draw_clouds)
4488 const wchar_t *wmsg = wgettext(msg);
4489 RenderingEngine::draw_load_screen(wmsg, guienv, texture_src, dtime, percent,
4494 void Game::settingChangedCallback(const std::string &setting_name, void *data)
4496 ((Game *)data)->readSettings();
4499 void Game::readSettings()
4501 m_cache_doubletap_jump = g_settings->getBool("doubletap_jump");
4502 m_cache_enable_clouds = g_settings->getBool("enable_clouds");
4503 m_cache_enable_joysticks = g_settings->getBool("enable_joysticks");
4504 m_cache_enable_particles = g_settings->getBool("enable_particles");
4505 m_cache_enable_fog = g_settings->getBool("enable_fog");
4506 m_cache_mouse_sensitivity = g_settings->getFloat("mouse_sensitivity");
4507 m_cache_joystick_frustum_sensitivity = g_settings->getFloat("joystick_frustum_sensitivity");
4508 m_repeat_right_click_time = g_settings->getFloat("repeat_rightclick_time");
4510 m_cache_enable_noclip = g_settings->getBool("noclip");
4511 m_cache_enable_free_move = g_settings->getBool("free_move");
4513 m_cache_fog_start = g_settings->getFloat("fog_start");
4515 m_cache_cam_smoothing = 0;
4516 if (g_settings->getBool("cinematic"))
4517 m_cache_cam_smoothing = 1 - g_settings->getFloat("cinematic_camera_smoothing");
4519 m_cache_cam_smoothing = 1 - g_settings->getFloat("camera_smoothing");
4521 m_cache_fog_start = rangelim(m_cache_fog_start, 0.0f, 0.99f);
4522 m_cache_cam_smoothing = rangelim(m_cache_cam_smoothing, 0.01f, 1.0f);
4523 m_cache_mouse_sensitivity = rangelim(m_cache_mouse_sensitivity, 0.001, 100.0);
4527 /****************************************************************************/
4528 /****************************************************************************
4530 ****************************************************************************/
4531 /****************************************************************************/
4533 void Game::extendedResourceCleanup()
4535 // Extended resource accounting
4536 infostream << "Irrlicht resources after cleanup:" << std::endl;
4537 infostream << "\tRemaining meshes : "
4538 << RenderingEngine::get_mesh_cache()->getMeshCount() << std::endl;
4539 infostream << "\tRemaining textures : "
4540 << driver->getTextureCount() << std::endl;
4542 for (unsigned int i = 0; i < driver->getTextureCount(); i++) {
4543 irr::video::ITexture *texture = driver->getTextureByIndex(i);
4544 infostream << "\t\t" << i << ":" << texture->getName().getPath().c_str()
4548 clearTextureNameCache();
4549 infostream << "\tRemaining materials: "
4550 << driver-> getMaterialRendererCount()
4551 << " (note: irrlicht doesn't support removing renderers)" << std::endl;
4554 #define GET_KEY_NAME(KEY) gettext(getKeySetting(#KEY).name())
4555 void Game::showPauseMenu()
4558 static const std::string control_text = strgettext("Default Controls:\n"
4559 "No menu visible:\n"
4560 "- single tap: button activate\n"
4561 "- double tap: place/use\n"
4562 "- slide finger: look around\n"
4563 "Menu/Inventory visible:\n"
4564 "- double tap (outside):\n"
4566 "- touch stack, touch slot:\n"
4568 "- touch&drag, tap 2nd finger\n"
4569 " --> place single item to slot\n"
4572 static const std::string control_text_template = strgettext("Controls:\n"
4573 "- %s: move forwards\n"
4574 "- %s: move backwards\n"
4576 "- %s: move right\n"
4577 "- %s: jump/climb\n"
4578 "- %s: sneak/go down\n"
4581 "- Mouse: turn/look\n"
4582 "- Mouse left: dig/punch\n"
4583 "- Mouse right: place/use\n"
4584 "- Mouse wheel: select item\n"
4588 char control_text_buf[600];
4590 snprintf(control_text_buf, ARRLEN(control_text_buf), control_text_template.c_str(),
4591 GET_KEY_NAME(keymap_forward),
4592 GET_KEY_NAME(keymap_backward),
4593 GET_KEY_NAME(keymap_left),
4594 GET_KEY_NAME(keymap_right),
4595 GET_KEY_NAME(keymap_jump),
4596 GET_KEY_NAME(keymap_sneak),
4597 GET_KEY_NAME(keymap_drop),
4598 GET_KEY_NAME(keymap_inventory),
4599 GET_KEY_NAME(keymap_chat)
4602 std::string control_text = std::string(control_text_buf);
4603 str_formspec_escape(control_text);
4606 float ypos = simple_singleplayer_mode ? 0.7f : 0.1f;
4607 std::ostringstream os;
4609 os << FORMSPEC_VERSION_STRING << SIZE_TAG
4610 << "button_exit[4," << (ypos++) << ";3,0.5;btn_continue;"
4611 << strgettext("Continue") << "]";
4613 if (!simple_singleplayer_mode) {
4614 os << "button_exit[4," << (ypos++) << ";3,0.5;btn_change_password;"
4615 << strgettext("Change Password") << "]";
4617 os << "field[4.95,0;5,1.5;;" << strgettext("Game paused") << ";]";
4621 os << "button_exit[4," << (ypos++) << ";3,0.5;btn_sound;"
4622 << strgettext("Sound Volume") << "]";
4623 os << "button_exit[4," << (ypos++) << ";3,0.5;btn_key_config;"
4624 << strgettext("Change Keys") << "]";
4626 os << "button_exit[4," << (ypos++) << ";3,0.5;btn_exit_menu;"
4627 << strgettext("Exit to Menu") << "]";
4628 os << "button_exit[4," << (ypos++) << ";3,0.5;btn_exit_os;"
4629 << strgettext("Exit to OS") << "]"
4630 << "textarea[7.5,0.25;3.9,6.25;;" << control_text << ";]"
4631 << "textarea[0.4,0.25;3.9,6.25;;" << PROJECT_NAME_C " " VERSION_STRING "\n"
4633 << strgettext("Game info:") << "\n";
4634 const std::string &address = client->getAddressName();
4635 static const std::string mode = strgettext("- Mode: ");
4636 if (!simple_singleplayer_mode) {
4637 Address serverAddress = client->getServerAddress();
4638 if (!address.empty()) {
4639 os << mode << strgettext("Remote server") << "\n"
4640 << strgettext("- Address: ") << address;
4642 os << mode << strgettext("Hosting server");
4644 os << "\n" << strgettext("- Port: ") << serverAddress.getPort() << "\n";
4646 os << mode << strgettext("Singleplayer") << "\n";
4648 if (simple_singleplayer_mode || address.empty()) {
4649 static const std::string on = strgettext("On");
4650 static const std::string off = strgettext("Off");
4651 const std::string &damage = g_settings->getBool("enable_damage") ? on : off;
4652 const std::string &creative = g_settings->getBool("creative_mode") ? on : off;
4653 const std::string &announced = g_settings->getBool("server_announce") ? on : off;
4654 os << strgettext("- Damage: ") << damage << "\n"
4655 << strgettext("- Creative Mode: ") << creative << "\n";
4656 if (!simple_singleplayer_mode) {
4657 const std::string &pvp = g_settings->getBool("enable_pvp") ? on : off;
4658 os << strgettext("- PvP: ") << pvp << "\n"
4659 << strgettext("- Public: ") << announced << "\n";
4660 std::string server_name = g_settings->get("server_name");
4661 str_formspec_escape(server_name);
4662 if (announced == on && !server_name.empty())
4663 os << strgettext("- Server Name: ") << server_name;
4670 /* Note: FormspecFormSource and LocalFormspecHandler *
4671 * are deleted by guiFormSpecMenu */
4672 FormspecFormSource *fs_src = new FormspecFormSource(os.str());
4673 LocalFormspecHandler *txt_dst = new LocalFormspecHandler("MT_PAUSE_MENU");
4675 create_formspec_menu(¤t_formspec, client, &input->joystick, fs_src, txt_dst);
4676 current_formspec->setFocus("btn_continue");
4677 current_formspec->doPause = true;
4680 /****************************************************************************/
4681 /****************************************************************************
4682 extern function for launching the game
4683 ****************************************************************************/
4684 /****************************************************************************/
4686 void the_game(bool *kill,
4688 InputHandler *input,
4689 const std::string &map_dir,
4690 const std::string &playername,
4691 const std::string &password,
4692 const std::string &address, // If empty local server is created
4695 std::string &error_message,
4696 ChatBackend &chat_backend,
4697 bool *reconnect_requested,
4698 const SubgameSpec &gamespec, // Used for local game
4699 bool simple_singleplayer_mode)
4703 /* Make a copy of the server address because if a local singleplayer server
4704 * is created then this is updated and we don't want to change the value
4705 * passed to us by the calling function
4707 std::string server_address = address;
4711 if (game.startup(kill, random_input, input, map_dir,
4712 playername, password, &server_address, port, error_message,
4713 reconnect_requested, &chat_backend, gamespec,
4714 simple_singleplayer_mode)) {
4719 } catch (SerializationError &e) {
4720 error_message = std::string("A serialization error occurred:\n")
4721 + e.what() + "\n\nThe server is probably "
4722 " running a different version of " PROJECT_NAME_C ".";
4723 errorstream << error_message << std::endl;
4724 } catch (ServerError &e) {
4725 error_message = e.what();
4726 errorstream << "ServerError: " << error_message << std::endl;
4727 } catch (ModError &e) {
4728 error_message = e.what() + strgettext("\nCheck debug.txt for details.");
4729 errorstream << "ModError: " << error_message << std::endl;