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.
25 #include "client/inputhandler.h"
26 #include "client/tile.h" // For TextureSource
27 #include "client/keys.h"
28 #include "client/joystick_controller.h"
29 #include "clientmap.h"
32 #include "content_cao.h"
33 #include "drawscene.h"
34 #include "event_manager.h"
35 #include "fontengine.h"
40 #include "guiChatConsole.h"
41 #include "guiFormSpecMenu.h"
42 #include "guiKeyChangeMenu.h"
43 #include "guiPasswordChange.h"
44 #include "guiVolumeChange.h"
45 #include "mainmenumanager.h"
47 #include "nodedef.h" // Needed for determining pointing to nodes
48 #include "nodemetadata.h"
49 #include "particles.h"
51 #include "quicktune_shortcutter.h"
57 #include "util/basic_macros.h"
58 #include "util/directiontables.h"
59 #include "util/pointedthing.h"
60 #include "irrlicht_changes/static_text.h"
62 #include "script/scripting_client.h"
65 #include "sound_openal.h"
68 extern Settings *g_settings;
69 extern Profiler *g_profiler;
75 struct TextDestNodeMetadata : public TextDest
77 TextDestNodeMetadata(v3s16 p, Client *client)
82 // This is deprecated I guess? -celeron55
83 void gotText(const std::wstring &text)
85 std::string ntext = wide_to_utf8(text);
86 infostream << "Submitting 'text' field of node at (" << m_p.X << ","
87 << m_p.Y << "," << m_p.Z << "): " << ntext << std::endl;
89 fields["text"] = ntext;
90 m_client->sendNodemetaFields(m_p, "", fields);
92 void gotText(const StringMap &fields)
94 m_client->sendNodemetaFields(m_p, "", fields);
101 struct TextDestPlayerInventory : public TextDest
103 TextDestPlayerInventory(Client *client)
108 TextDestPlayerInventory(Client *client, const std::string &formname)
111 m_formname = formname;
113 void gotText(const StringMap &fields)
115 m_client->sendInventoryFields(m_formname, fields);
121 struct LocalFormspecHandler : public TextDest
123 LocalFormspecHandler(const std::string &formname):
126 m_formname = formname;
129 LocalFormspecHandler(const std::string &formname, Client *client):
132 m_formname = formname;
135 void gotText(const StringMap &fields)
137 if (m_formname == "MT_PAUSE_MENU") {
138 if (fields.find("btn_sound") != fields.end()) {
139 g_gamecallback->changeVolume();
143 if (fields.find("btn_key_config") != fields.end()) {
144 g_gamecallback->keyConfig();
148 if (fields.find("btn_exit_menu") != fields.end()) {
149 g_gamecallback->disconnect();
153 if (fields.find("btn_exit_os") != fields.end()) {
154 g_gamecallback->exitToOS();
158 if (fields.find("btn_change_password") != fields.end()) {
159 g_gamecallback->changePassword();
163 if (fields.find("quit") != fields.end()) {
167 if (fields.find("btn_continue") != fields.end()) {
172 // Don't disable this part when modding is disabled, it's used in builtin
173 m_client->getScript()->on_formspec_input(m_formname, fields);
179 /* Form update callback */
181 class NodeMetadataFormSource: public IFormSource
184 NodeMetadataFormSource(ClientMap *map, v3s16 p):
189 std::string getForm()
191 NodeMetadata *meta = m_map->getNodeMetadata(m_p);
196 return meta->getString("formspec");
199 virtual std::string resolveText(const std::string &str)
201 NodeMetadata *meta = m_map->getNodeMetadata(m_p);
206 return meta->resolveString(str);
213 class PlayerInventoryFormSource: public IFormSource
216 PlayerInventoryFormSource(Client *client):
220 std::string getForm()
222 LocalPlayer *player = m_client->getEnv().getLocalPlayer();
223 return player->inventory_formspec;
229 /* Profiler display */
231 void update_profiler_gui(gui::IGUIStaticText *guitext_profiler, FontEngine *fe,
232 u32 show_profiler, u32 show_profiler_max, s32 screen_height)
234 if (show_profiler == 0) {
235 guitext_profiler->setVisible(false);
238 std::ostringstream os(std::ios_base::binary);
239 g_profiler->printPage(os, show_profiler, show_profiler_max);
240 std::wstring text = utf8_to_wide(os.str());
241 setStaticText(guitext_profiler, text.c_str());
242 guitext_profiler->setVisible(true);
244 s32 w = fe->getTextWidth(text.c_str());
249 unsigned text_height = fe->getTextHeight();
251 core::position2di upper_left, lower_right;
254 upper_left.Y = (text_height + 5) * 2;
255 lower_right.X = 12 + w;
256 lower_right.Y = upper_left.Y + (text_height + 1) * MAX_PROFILER_TEXT_ROWS;
258 if (lower_right.Y > screen_height * 2 / 3)
259 lower_right.Y = screen_height * 2 / 3;
261 core::rect<s32> rect(upper_left, lower_right);
263 guitext_profiler->setRelativePosition(rect);
264 guitext_profiler->setVisible(true);
272 Profiler::GraphValues values;
278 Meta(float initial = 0,
279 video::SColor color = video::SColor(255, 255, 255, 255)):
285 std::deque<Piece> m_log;
293 void put(const Profiler::GraphValues &values)
296 piece.values = values;
297 m_log.push_back(piece);
299 while (m_log.size() > m_log_max_size)
300 m_log.erase(m_log.begin());
303 void draw(s32 x_left, s32 y_bottom, video::IVideoDriver *driver,
304 gui::IGUIFont *font) const
306 // Do *not* use UNORDERED_MAP here as the order needs
307 // to be the same for each call to prevent flickering
308 std::map<std::string, Meta> m_meta;
310 for (std::deque<Piece>::const_iterator k = m_log.begin();
311 k != m_log.end(); ++k) {
312 const Piece &piece = *k;
314 for (Profiler::GraphValues::const_iterator i = piece.values.begin();
315 i != piece.values.end(); ++i) {
316 const std::string &id = i->first;
317 const float &value = i->second;
318 std::map<std::string, Meta>::iterator j = m_meta.find(id);
320 if (j == m_meta.end()) {
321 m_meta[id] = Meta(value);
325 if (value < j->second.min)
326 j->second.min = value;
328 if (value > j->second.max)
329 j->second.max = value;
334 static const video::SColor usable_colors[] = {
335 video::SColor(255, 255, 100, 100),
336 video::SColor(255, 90, 225, 90),
337 video::SColor(255, 100, 100, 255),
338 video::SColor(255, 255, 150, 50),
339 video::SColor(255, 220, 220, 100)
341 static const u32 usable_colors_count =
342 sizeof(usable_colors) / sizeof(*usable_colors);
343 u32 next_color_i = 0;
345 for (std::map<std::string, Meta>::iterator i = m_meta.begin();
346 i != m_meta.end(); ++i) {
347 Meta &meta = i->second;
348 video::SColor color(255, 200, 200, 200);
350 if (next_color_i < usable_colors_count)
351 color = usable_colors[next_color_i++];
357 s32 textx = x_left + m_log_max_size + 15;
358 s32 textx2 = textx + 200 - 15;
361 for (std::map<std::string, Meta>::const_iterator i = m_meta.begin();
362 i != m_meta.end(); ++i) {
363 const std::string &id = i->first;
364 const Meta &meta = i->second;
366 s32 y = y_bottom - meta_i * 50;
367 float show_min = meta.min;
368 float show_max = meta.max;
370 if (show_min >= -0.0001 && show_max >= -0.0001) {
371 if (show_min <= show_max * 0.5)
377 snprintf(buf, 10, "%.3g", show_max);
378 font->draw(utf8_to_wide(buf).c_str(),
379 core::rect<s32>(textx, y - graphh,
380 textx2, y - graphh + texth),
382 snprintf(buf, 10, "%.3g", show_min);
383 font->draw(utf8_to_wide(buf).c_str(),
384 core::rect<s32>(textx, y - texth,
387 font->draw(utf8_to_wide(id).c_str(),
388 core::rect<s32>(textx, y - graphh / 2 - texth / 2,
389 textx2, y - graphh / 2 + texth / 2),
392 s32 graph1h = graphh;
393 bool relativegraph = (show_min != 0 && show_min != show_max);
394 float lastscaledvalue = 0.0;
395 bool lastscaledvalue_exists = false;
397 for (std::deque<Piece>::const_iterator j = m_log.begin();
398 j != m_log.end(); ++j) {
399 const Piece &piece = *j;
401 bool value_exists = false;
402 Profiler::GraphValues::const_iterator k =
403 piece.values.find(id);
405 if (k != piece.values.end()) {
412 lastscaledvalue_exists = false;
416 float scaledvalue = 1.0;
418 if (show_max != show_min)
419 scaledvalue = (value - show_min) / (show_max - show_min);
421 if (scaledvalue == 1.0 && value == 0) {
423 lastscaledvalue_exists = false;
428 if (lastscaledvalue_exists) {
429 s32 ivalue1 = lastscaledvalue * graph1h;
430 s32 ivalue2 = scaledvalue * graph1h;
431 driver->draw2DLine(v2s32(x - 1, graph1y - ivalue1),
432 v2s32(x, graph1y - ivalue2), meta.color);
435 lastscaledvalue = scaledvalue;
436 lastscaledvalue_exists = true;
438 s32 ivalue = scaledvalue * graph1h;
439 driver->draw2DLine(v2s32(x, graph1y),
440 v2s32(x, graph1y - ivalue), meta.color);
451 class NodeDugEvent: public MtEvent
457 NodeDugEvent(v3s16 p, MapNode n):
461 const char *getType() const
469 ISoundManager *m_sound;
470 INodeDefManager *m_ndef;
472 bool makes_footstep_sound;
473 float m_player_step_timer;
475 SimpleSoundSpec m_player_step_sound;
476 SimpleSoundSpec m_player_leftpunch_sound;
477 SimpleSoundSpec m_player_rightpunch_sound;
479 SoundMaker(ISoundManager *sound, INodeDefManager *ndef):
482 makes_footstep_sound(true),
483 m_player_step_timer(0)
487 void playPlayerStep()
489 if (m_player_step_timer <= 0 && m_player_step_sound.exists()) {
490 m_player_step_timer = 0.03;
491 if (makes_footstep_sound)
492 m_sound->playSound(m_player_step_sound, false);
496 static void viewBobbingStep(MtEvent *e, void *data)
498 SoundMaker *sm = (SoundMaker *)data;
499 sm->playPlayerStep();
502 static void playerRegainGround(MtEvent *e, void *data)
504 SoundMaker *sm = (SoundMaker *)data;
505 sm->playPlayerStep();
508 static void playerJump(MtEvent *e, void *data)
510 //SoundMaker *sm = (SoundMaker*)data;
513 static void cameraPunchLeft(MtEvent *e, void *data)
515 SoundMaker *sm = (SoundMaker *)data;
516 sm->m_sound->playSound(sm->m_player_leftpunch_sound, false);
519 static void cameraPunchRight(MtEvent *e, void *data)
521 SoundMaker *sm = (SoundMaker *)data;
522 sm->m_sound->playSound(sm->m_player_rightpunch_sound, false);
525 static void nodeDug(MtEvent *e, void *data)
527 SoundMaker *sm = (SoundMaker *)data;
528 NodeDugEvent *nde = (NodeDugEvent *)e;
529 sm->m_sound->playSound(sm->m_ndef->get(nde->n).sound_dug, false);
532 static void playerDamage(MtEvent *e, void *data)
534 SoundMaker *sm = (SoundMaker *)data;
535 sm->m_sound->playSound(SimpleSoundSpec("player_damage", 0.5), false);
538 static void playerFallingDamage(MtEvent *e, void *data)
540 SoundMaker *sm = (SoundMaker *)data;
541 sm->m_sound->playSound(SimpleSoundSpec("player_falling_damage", 0.5), false);
544 void registerReceiver(MtEventManager *mgr)
546 mgr->reg("ViewBobbingStep", SoundMaker::viewBobbingStep, this);
547 mgr->reg("PlayerRegainGround", SoundMaker::playerRegainGround, this);
548 mgr->reg("PlayerJump", SoundMaker::playerJump, this);
549 mgr->reg("CameraPunchLeft", SoundMaker::cameraPunchLeft, this);
550 mgr->reg("CameraPunchRight", SoundMaker::cameraPunchRight, this);
551 mgr->reg("NodeDug", SoundMaker::nodeDug, this);
552 mgr->reg("PlayerDamage", SoundMaker::playerDamage, this);
553 mgr->reg("PlayerFallingDamage", SoundMaker::playerFallingDamage, this);
556 void step(float dtime)
558 m_player_step_timer -= dtime;
562 // Locally stored sounds don't need to be preloaded because of this
563 class GameOnDemandSoundFetcher: public OnDemandSoundFetcher
565 std::set<std::string> m_fetched;
567 void paths_insert(std::set<std::string> &dst_paths,
568 const std::string &base,
569 const std::string &name)
571 dst_paths.insert(base + DIR_DELIM + "sounds" + DIR_DELIM + name + ".ogg");
572 dst_paths.insert(base + DIR_DELIM + "sounds" + DIR_DELIM + name + ".0.ogg");
573 dst_paths.insert(base + DIR_DELIM + "sounds" + DIR_DELIM + name + ".1.ogg");
574 dst_paths.insert(base + DIR_DELIM + "sounds" + DIR_DELIM + name + ".2.ogg");
575 dst_paths.insert(base + DIR_DELIM + "sounds" + DIR_DELIM + name + ".3.ogg");
576 dst_paths.insert(base + DIR_DELIM + "sounds" + DIR_DELIM + name + ".4.ogg");
577 dst_paths.insert(base + DIR_DELIM + "sounds" + DIR_DELIM + name + ".5.ogg");
578 dst_paths.insert(base + DIR_DELIM + "sounds" + DIR_DELIM + name + ".6.ogg");
579 dst_paths.insert(base + DIR_DELIM + "sounds" + DIR_DELIM + name + ".7.ogg");
580 dst_paths.insert(base + DIR_DELIM + "sounds" + DIR_DELIM + name + ".8.ogg");
581 dst_paths.insert(base + DIR_DELIM + "sounds" + DIR_DELIM + name + ".9.ogg");
584 void fetchSounds(const std::string &name,
585 std::set<std::string> &dst_paths,
586 std::set<std::string> &dst_datas)
588 if (m_fetched.count(name))
591 m_fetched.insert(name);
593 paths_insert(dst_paths, porting::path_share, name);
594 paths_insert(dst_paths, porting::path_user, name);
599 // before 1.8 there isn't a "integer interface", only float
600 #if (IRRLICHT_VERSION_MAJOR == 1 && IRRLICHT_VERSION_MINOR < 8)
601 typedef f32 SamplerLayer_t;
603 typedef s32 SamplerLayer_t;
607 class GameGlobalShaderConstantSetter : public IShaderConstantSetter
610 bool *m_force_fog_off;
613 CachedPixelShaderSetting<float, 4> m_sky_bg_color;
614 CachedPixelShaderSetting<float> m_fog_distance;
615 CachedVertexShaderSetting<float> m_animation_timer_vertex;
616 CachedPixelShaderSetting<float> m_animation_timer_pixel;
617 CachedPixelShaderSetting<float, 3> m_day_light;
618 CachedPixelShaderSetting<float, 3> m_eye_position_pixel;
619 CachedVertexShaderSetting<float, 3> m_eye_position_vertex;
620 CachedPixelShaderSetting<float, 3> m_minimap_yaw;
621 CachedPixelShaderSetting<SamplerLayer_t> m_base_texture;
622 CachedPixelShaderSetting<SamplerLayer_t> m_normal_texture;
623 CachedPixelShaderSetting<SamplerLayer_t> m_texture_flags;
627 void onSettingsChange(const std::string &name)
629 if (name == "enable_fog")
630 m_fog_enabled = g_settings->getBool("enable_fog");
633 static void settingsCallback(const std::string &name, void *userdata)
635 reinterpret_cast<GameGlobalShaderConstantSetter*>(userdata)->onSettingsChange(name);
638 void setSky(Sky *sky) { m_sky = sky; }
640 GameGlobalShaderConstantSetter(Sky *sky, bool *force_fog_off,
641 f32 *fog_range, Client *client) :
643 m_force_fog_off(force_fog_off),
644 m_fog_range(fog_range),
645 m_sky_bg_color("skyBgColor"),
646 m_fog_distance("fogDistance"),
647 m_animation_timer_vertex("animationTimer"),
648 m_animation_timer_pixel("animationTimer"),
649 m_day_light("dayLight"),
650 m_eye_position_pixel("eyePosition"),
651 m_eye_position_vertex("eyePosition"),
652 m_minimap_yaw("yawVec"),
653 m_base_texture("baseTexture"),
654 m_normal_texture("normalTexture"),
655 m_texture_flags("textureFlags"),
658 g_settings->registerChangedCallback("enable_fog", settingsCallback, this);
659 m_fog_enabled = g_settings->getBool("enable_fog");
662 ~GameGlobalShaderConstantSetter()
664 g_settings->deregisterChangedCallback("enable_fog", settingsCallback, this);
667 virtual void onSetConstants(video::IMaterialRendererServices *services,
674 video::SColor bgcolor = m_sky->getBgColor();
675 video::SColorf bgcolorf(bgcolor);
676 float bgcolorfa[4] = {
682 m_sky_bg_color.set(bgcolorfa, services);
685 float fog_distance = 10000 * BS;
687 if (m_fog_enabled && !*m_force_fog_off)
688 fog_distance = *m_fog_range;
690 m_fog_distance.set(&fog_distance, services);
692 u32 daynight_ratio = (float)m_client->getEnv().getDayNightRatio();
693 video::SColorf sunlight;
694 get_sunlight_color(&sunlight, daynight_ratio);
699 m_day_light.set(dnc, services);
701 u32 animation_timer = porting::getTimeMs() % 100000;
702 float animation_timer_f = (float)animation_timer / 100000.f;
703 m_animation_timer_vertex.set(&animation_timer_f, services);
704 m_animation_timer_pixel.set(&animation_timer_f, services);
706 float eye_position_array[3];
707 v3f epos = m_client->getEnv().getLocalPlayer()->getEyePosition();
708 #if (IRRLICHT_VERSION_MAJOR == 1 && IRRLICHT_VERSION_MINOR < 8)
709 eye_position_array[0] = epos.X;
710 eye_position_array[1] = epos.Y;
711 eye_position_array[2] = epos.Z;
713 epos.getAs3Values(eye_position_array);
715 m_eye_position_pixel.set(eye_position_array, services);
716 m_eye_position_vertex.set(eye_position_array, services);
718 if (m_client->getMinimap()) {
719 float minimap_yaw_array[3];
720 v3f minimap_yaw = m_client->getMinimap()->getYawVec();
721 #if (IRRLICHT_VERSION_MAJOR == 1 && IRRLICHT_VERSION_MINOR < 8)
722 minimap_yaw_array[0] = minimap_yaw.X;
723 minimap_yaw_array[1] = minimap_yaw.Y;
724 minimap_yaw_array[2] = minimap_yaw.Z;
726 minimap_yaw.getAs3Values(minimap_yaw_array);
728 m_minimap_yaw.set(minimap_yaw_array, services);
732 SamplerLayer_t base_tex = 0,
735 m_base_texture.set(&base_tex, services);
736 m_normal_texture.set(&normal_tex, services);
737 m_texture_flags.set(&flags_tex, services);
742 class GameGlobalShaderConstantSetterFactory : public IShaderConstantSetterFactory
745 bool *m_force_fog_off;
748 std::vector<GameGlobalShaderConstantSetter *> created_nosky;
750 GameGlobalShaderConstantSetterFactory(bool *force_fog_off,
751 f32 *fog_range, Client *client) :
753 m_force_fog_off(force_fog_off),
754 m_fog_range(fog_range),
758 void setSky(Sky *sky) {
760 for (size_t i = 0; i < created_nosky.size(); ++i) {
761 created_nosky[i]->setSky(m_sky);
763 created_nosky.clear();
766 virtual IShaderConstantSetter* create()
768 GameGlobalShaderConstantSetter *scs = new GameGlobalShaderConstantSetter(
769 m_sky, m_force_fog_off, m_fog_range, m_client);
771 created_nosky.push_back(scs);
777 bool nodePlacementPrediction(Client &client, const ItemDefinition &playeritem_def,
778 const ItemStack &playeritem, v3s16 nodepos, v3s16 neighbourpos)
780 std::string prediction = playeritem_def.node_placement_prediction;
781 INodeDefManager *nodedef = client.ndef();
782 ClientMap &map = client.getEnv().getClientMap();
784 bool is_valid_position;
786 node = map.getNodeNoEx(nodepos, &is_valid_position);
787 if (!is_valid_position)
790 if (prediction != "" && !nodedef->get(node).rightclickable) {
791 verbosestream << "Node placement prediction for "
792 << playeritem_def.name << " is "
793 << prediction << std::endl;
794 v3s16 p = neighbourpos;
796 // Place inside node itself if buildable_to
797 MapNode n_under = map.getNodeNoEx(nodepos, &is_valid_position);
798 if (is_valid_position)
800 if (nodedef->get(n_under).buildable_to)
803 node = map.getNodeNoEx(p, &is_valid_position);
804 if (is_valid_position &&!nodedef->get(node).buildable_to)
809 // Find id of predicted node
811 bool found = nodedef->getId(prediction, id);
814 errorstream << "Node placement prediction failed for "
815 << playeritem_def.name << " (places "
817 << ") - Name not known" << std::endl;
821 const ContentFeatures &predicted_f = nodedef->get(id);
823 // Predict param2 for facedir and wallmounted nodes
826 if (predicted_f.param_type_2 == CPT2_WALLMOUNTED ||
827 predicted_f.param_type_2 == CPT2_COLORED_WALLMOUNTED) {
828 v3s16 dir = nodepos - neighbourpos;
830 if (abs(dir.Y) > MYMAX(abs(dir.X), abs(dir.Z))) {
831 param2 = dir.Y < 0 ? 1 : 0;
832 } else if (abs(dir.X) > abs(dir.Z)) {
833 param2 = dir.X < 0 ? 3 : 2;
835 param2 = dir.Z < 0 ? 5 : 4;
839 if (predicted_f.param_type_2 == CPT2_FACEDIR ||
840 predicted_f.param_type_2 == CPT2_COLORED_FACEDIR) {
841 v3s16 dir = nodepos - floatToInt(client.getEnv().getLocalPlayer()->getPosition(), BS);
843 if (abs(dir.X) > abs(dir.Z)) {
844 param2 = dir.X < 0 ? 3 : 1;
846 param2 = dir.Z < 0 ? 2 : 0;
852 //Check attachment if node is in group attached_node
853 if (((ItemGroupList) predicted_f.groups)["attached_node"] != 0) {
854 static v3s16 wallmounted_dirs[8] = {
864 if (predicted_f.param_type_2 == CPT2_WALLMOUNTED ||
865 predicted_f.param_type_2 == CPT2_COLORED_WALLMOUNTED)
866 pp = p + wallmounted_dirs[param2];
868 pp = p + v3s16(0, -1, 0);
870 if (!nodedef->get(map.getNodeNoEx(pp)).walkable)
875 if ((predicted_f.param_type_2 == CPT2_COLOR
876 || predicted_f.param_type_2 == CPT2_COLORED_FACEDIR
877 || predicted_f.param_type_2 == CPT2_COLORED_WALLMOUNTED)) {
878 const std::string &indexstr = playeritem.metadata.getString(
880 if (!indexstr.empty()) {
881 s32 index = mystoi(indexstr);
882 if (predicted_f.param_type_2 == CPT2_COLOR) {
884 } else if (predicted_f.param_type_2
885 == CPT2_COLORED_WALLMOUNTED) {
886 // param2 = pure palette index + other
887 param2 = (index & 0xf8) | (param2 & 0x07);
888 } else if (predicted_f.param_type_2
889 == CPT2_COLORED_FACEDIR) {
890 // param2 = pure palette index + other
891 param2 = (index & 0xe0) | (param2 & 0x1f);
896 // Add node to client map
897 MapNode n(id, 0, param2);
900 LocalPlayer *player = client.getEnv().getLocalPlayer();
902 // Dont place node when player would be inside new node
903 // NOTE: This is to be eventually implemented by a mod as client-side Lua
904 if (!nodedef->get(n).walkable ||
905 g_settings->getBool("enable_build_where_you_stand") ||
906 (client.checkPrivilege("noclip") && g_settings->getBool("noclip")) ||
907 (nodedef->get(n).walkable &&
908 neighbourpos != player->getStandingNodePos() + v3s16(0, 1, 0) &&
909 neighbourpos != player->getStandingNodePos() + v3s16(0, 2, 0))) {
911 // This triggers the required mesh update too
912 client.addNode(p, n);
915 } catch (InvalidPositionException &e) {
916 errorstream << "Node placement prediction failed for "
917 << playeritem_def.name << " (places "
919 << ") - Position not loaded" << std::endl;
926 static inline void create_formspec_menu(GUIFormSpecMenu **cur_formspec,
927 Client *client, IrrlichtDevice *device, JoystickController *joystick,
928 IFormSource *fs_src, TextDest *txt_dest)
931 if (*cur_formspec == 0) {
932 *cur_formspec = new GUIFormSpecMenu(device, joystick,
933 guiroot, -1, &g_menumgr, client, client->getTextureSource(),
935 (*cur_formspec)->doPause = false;
938 Caution: do not call (*cur_formspec)->drop() here --
939 the reference might outlive the menu, so we will
940 periodically check if *cur_formspec is the only
941 remaining reference (i.e. the menu was removed)
942 and delete it in that case.
946 (*cur_formspec)->setFormSource(fs_src);
947 (*cur_formspec)->setTextDest(txt_dest);
953 #define SIZE_TAG "size[11,5.5]"
955 #define SIZE_TAG "size[11,5.5,true]" // Fixed size on desktop
958 /******************************************************************************/
959 static void updateChat(Client &client, f32 dtime, bool show_debug,
960 const v2u32 &screensize, bool show_chat, u32 show_profiler,
961 ChatBackend &chat_backend, gui::IGUIStaticText *guitext_chat)
963 // Add chat log output for errors to be shown in chat
964 static LogOutputBuffer chat_log_error_buf(g_logger, LL_ERROR);
966 // Get new messages from error log buffer
967 while (!chat_log_error_buf.empty()) {
968 std::wstring error_message = utf8_to_wide(chat_log_error_buf.get());
969 if (!g_settings->getBool("disable_escape_sequences")) {
970 error_message = L"\x1b(c@red)" + error_message + L"\x1b(c@white)";
972 chat_backend.addMessage(L"", error_message);
975 // Get new messages from client
976 std::wstring message;
978 while (client.getChatMessage(message)) {
979 chat_backend.addUnparsedMessage(message);
982 // Remove old messages
983 chat_backend.step(dtime);
985 // Display all messages in a static text element
986 unsigned int recent_chat_count = chat_backend.getRecentBuffer().getLineCount();
987 EnrichedString recent_chat = chat_backend.getRecentChat();
988 unsigned int line_height = g_fontengine->getLineHeight();
990 setStaticText(guitext_chat, recent_chat);
992 // Update gui element size and position
996 chat_y += 2 * line_height;
998 // first pass to calculate height of text to be set
999 s32 width = std::min(g_fontengine->getTextWidth(recent_chat.c_str()) + 10,
1000 porting::getWindowSize().X - 20);
1001 core::rect<s32> rect(10, chat_y, width, chat_y + porting::getWindowSize().Y);
1002 guitext_chat->setRelativePosition(rect);
1004 //now use real height of text and adjust rect according to this size
1005 rect = core::rect<s32>(10, chat_y, width,
1006 chat_y + guitext_chat->getTextHeight());
1009 guitext_chat->setRelativePosition(rect);
1010 // Don't show chat if disabled or empty or profiler is enabled
1011 guitext_chat->setVisible(
1012 show_chat && recent_chat_count != 0 && !show_profiler);
1016 /****************************************************************************
1017 Fast key cache for main game loop
1018 ****************************************************************************/
1020 /* This is faster than using getKeySetting with the tradeoff that functions
1021 * using it must make sure that it's initialised before using it and there is
1022 * no error handling (for example bounds checking). This is really intended for
1023 * use only in the main running loop of the client (the_game()) where the faster
1024 * (up to 10x faster) key lookup is an asset. Other parts of the codebase
1025 * (e.g. formspecs) should continue using getKeySetting().
1033 populate_nonchanging();
1038 // Keys that are not settings dependent
1039 void populate_nonchanging();
1041 KeyPress key[KeyType::INTERNAL_ENUM_COUNT];
1042 InputHandler *handler;
1045 void KeyCache::populate_nonchanging()
1047 key[KeyType::ESC] = EscapeKey;
1050 void KeyCache::populate()
1052 key[KeyType::FORWARD] = getKeySetting("keymap_forward");
1053 key[KeyType::BACKWARD] = getKeySetting("keymap_backward");
1054 key[KeyType::LEFT] = getKeySetting("keymap_left");
1055 key[KeyType::RIGHT] = getKeySetting("keymap_right");
1056 key[KeyType::JUMP] = getKeySetting("keymap_jump");
1057 key[KeyType::SPECIAL1] = getKeySetting("keymap_special1");
1058 key[KeyType::SNEAK] = getKeySetting("keymap_sneak");
1060 key[KeyType::AUTOFORWARD] = getKeySetting("keymap_autoforward");
1062 key[KeyType::DROP] = getKeySetting("keymap_drop");
1063 key[KeyType::INVENTORY] = getKeySetting("keymap_inventory");
1064 key[KeyType::CHAT] = getKeySetting("keymap_chat");
1065 key[KeyType::CMD] = getKeySetting("keymap_cmd");
1066 key[KeyType::CMD_LOCAL] = getKeySetting("keymap_cmd_local");
1067 key[KeyType::CONSOLE] = getKeySetting("keymap_console");
1068 key[KeyType::MINIMAP] = getKeySetting("keymap_minimap");
1069 key[KeyType::FREEMOVE] = getKeySetting("keymap_freemove");
1070 key[KeyType::FASTMOVE] = getKeySetting("keymap_fastmove");
1071 key[KeyType::NOCLIP] = getKeySetting("keymap_noclip");
1072 key[KeyType::HOTBAR_PREV] = getKeySetting("keymap_hotbar_previous");
1073 key[KeyType::HOTBAR_NEXT] = getKeySetting("keymap_hotbar_next");
1074 key[KeyType::MUTE] = getKeySetting("keymap_mute");
1075 key[KeyType::INC_VOLUME] = getKeySetting("keymap_increase_volume");
1076 key[KeyType::DEC_VOLUME] = getKeySetting("keymap_decrease_volume");
1077 key[KeyType::CINEMATIC] = getKeySetting("keymap_cinematic");
1078 key[KeyType::SCREENSHOT] = getKeySetting("keymap_screenshot");
1079 key[KeyType::TOGGLE_HUD] = getKeySetting("keymap_toggle_hud");
1080 key[KeyType::TOGGLE_CHAT] = getKeySetting("keymap_toggle_chat");
1081 key[KeyType::TOGGLE_FORCE_FOG_OFF]
1082 = getKeySetting("keymap_toggle_force_fog_off");
1083 key[KeyType::TOGGLE_UPDATE_CAMERA]
1084 = getKeySetting("keymap_toggle_update_camera");
1085 key[KeyType::TOGGLE_DEBUG]
1086 = getKeySetting("keymap_toggle_debug");
1087 key[KeyType::TOGGLE_PROFILER]
1088 = getKeySetting("keymap_toggle_profiler");
1089 key[KeyType::CAMERA_MODE]
1090 = getKeySetting("keymap_camera_mode");
1091 key[KeyType::INCREASE_VIEWING_RANGE]
1092 = getKeySetting("keymap_increase_viewing_range_min");
1093 key[KeyType::DECREASE_VIEWING_RANGE]
1094 = getKeySetting("keymap_decrease_viewing_range_min");
1095 key[KeyType::RANGESELECT]
1096 = getKeySetting("keymap_rangeselect");
1097 key[KeyType::ZOOM] = getKeySetting("keymap_zoom");
1099 key[KeyType::QUICKTUNE_NEXT] = getKeySetting("keymap_quicktune_next");
1100 key[KeyType::QUICKTUNE_PREV] = getKeySetting("keymap_quicktune_prev");
1101 key[KeyType::QUICKTUNE_INC] = getKeySetting("keymap_quicktune_inc");
1102 key[KeyType::QUICKTUNE_DEC] = getKeySetting("keymap_quicktune_dec");
1104 key[KeyType::DEBUG_STACKS] = getKeySetting("keymap_print_debug_stacks");
1107 // First clear all keys, then re-add the ones we listen for
1108 handler->dontListenForKeys();
1109 for (size_t i = 0; i < KeyType::INTERNAL_ENUM_COUNT; i++) {
1110 handler->listenForKey(key[i]);
1112 handler->listenForKey(EscapeKey);
1113 handler->listenForKey(CancelKey);
1114 for (size_t i = 0; i < 10; i++) {
1115 handler->listenForKey(NumberKey[i]);
1121 /****************************************************************************
1123 ****************************************************************************/
1125 const float object_hit_delay = 0.2;
1128 u32 last_time, busy_time, sleep_time;
1132 /* The reason the following structs are not anonymous structs within the
1133 * class is that they are not used by the majority of member functions and
1134 * many functions that do require objects of thse types do not modify them
1135 * (so they can be passed as a const qualified parameter)
1137 struct CameraOrientation {
1138 f32 camera_yaw; // "right/left"
1139 f32 camera_pitch; // "up/down"
1142 struct GameRunData {
1145 PointedThing pointed_old;
1150 bool update_wielded_item_trigger;
1151 bool reset_jump_timer;
1152 float nodig_delay_timer;
1154 float dig_time_complete;
1155 float repeat_rightclick_timer;
1156 float object_hit_delay_timer;
1157 float time_from_last_punch;
1158 ClientActiveObject *selected_object;
1162 float update_draw_list_timer;
1163 float statustext_time;
1167 v3f update_draw_list_last_cam_dir;
1169 u32 profiler_current_page;
1170 u32 profiler_max_page; // Number of pages
1173 float time_of_day_smooth;
1177 f32 max, min, avg, counter, max_sample, min_sample, max_fraction;
1183 Jitter dtime_jitter, busy_time_jitter;
1186 /****************************************************************************
1188 ****************************************************************************/
1190 /* This is not intended to be a public class. If a public class becomes
1191 * desirable then it may be better to create another 'wrapper' class that
1192 * hides most of the stuff in this class (nothing in this class is required
1193 * by any other file) but exposes the public methods/data only.
1200 bool startup(bool *kill,
1202 InputHandler *input,
1203 IrrlichtDevice *device,
1204 const std::string &map_dir,
1205 const std::string &playername,
1206 const std::string &password,
1207 // If address is "", local server is used and address is updated
1208 std::string *address,
1210 std::string &error_message,
1212 ChatBackend *chat_backend,
1213 const SubgameSpec &gamespec, // Used for local game
1214 bool simple_singleplayer_mode);
1221 void extendedResourceCleanup();
1223 // Basic initialisation
1224 bool init(const std::string &map_dir, std::string *address,
1226 const SubgameSpec &gamespec);
1228 bool createSingleplayerServer(const std::string &map_dir,
1229 const SubgameSpec &gamespec, u16 port, std::string *address);
1232 bool createClient(const std::string &playername,
1233 const std::string &password, std::string *address, u16 port);
1236 // Client connection
1237 bool connectToServer(const std::string &playername,
1238 const std::string &password, std::string *address, u16 port,
1239 bool *connect_ok, bool *aborted);
1240 bool getServerContent(bool *aborted);
1244 void updateInteractTimers(f32 dtime);
1245 bool checkConnection();
1246 bool handleCallbacks();
1247 void processQueues();
1248 void updateProfilers(const RunStats &stats, const FpsControl &draw_times, f32 dtime);
1249 void addProfilerGraphs(const RunStats &stats, const FpsControl &draw_times, f32 dtime);
1250 void updateStats(RunStats *stats, const FpsControl &draw_times, f32 dtime);
1253 void processUserInput(f32 dtime);
1254 void processKeyInput();
1255 void processItemSelection(u16 *new_playeritem);
1257 void dropSelectedItem();
1258 void openInventory();
1259 void openConsole(float scale, const wchar_t *line=NULL);
1260 void toggleFreeMove();
1261 void toggleFreeMoveAlt();
1263 void toggleNoClip();
1264 void toggleCinematic();
1265 void toggleAutoforward();
1269 void toggleMinimap(bool shift_pressed);
1272 void toggleUpdateCamera();
1273 void toggleProfiler();
1275 void increaseViewRange();
1276 void decreaseViewRange();
1277 void toggleFullViewRange();
1279 void updateCameraDirection(CameraOrientation *cam, float dtime);
1280 void updateCameraOrientation(CameraOrientation *cam, float dtime);
1281 void updatePlayerControl(const CameraOrientation &cam);
1282 void step(f32 *dtime);
1283 void processClientEvents(CameraOrientation *cam);
1284 void updateCamera(u32 busy_time, f32 dtime);
1285 void updateSound(f32 dtime);
1286 void processPlayerInteraction(f32 dtime, bool show_hud, bool show_debug);
1288 * Returns the object or node the player is pointing at.
1289 * Also updates the selected thing in the Hud.
1291 * @param[in] shootline the shootline, starting from
1292 * the camera position. This also gives the maximal distance
1294 * @param[in] liquids_pointable if false, liquids are ignored
1295 * @param[in] look_for_object if false, objects are ignored
1296 * @param[in] camera_offset offset of the camera
1297 * @param[out] selected_object the selected object or
1300 PointedThing updatePointedThing(
1301 const core::line3d<f32> &shootline, bool liquids_pointable,
1302 bool look_for_object, const v3s16 &camera_offset);
1303 void handlePointingAtNothing(const ItemStack &playerItem);
1304 void handlePointingAtNode(const PointedThing &pointed,
1305 const ItemDefinition &playeritem_def, const ItemStack &playeritem,
1306 const ToolCapabilities &playeritem_toolcap, f32 dtime);
1307 void handlePointingAtObject(const PointedThing &pointed, const ItemStack &playeritem,
1308 const v3f &player_position, bool show_debug);
1309 void handleDigging(const PointedThing &pointed, const v3s16 &nodepos,
1310 const ToolCapabilities &playeritem_toolcap, f32 dtime);
1311 void updateFrame(ProfilerGraph *graph, RunStats *stats, f32 dtime,
1312 const CameraOrientation &cam);
1313 void updateGui(const RunStats &stats, f32 dtime, const CameraOrientation &cam);
1314 void updateProfilerGraphs(ProfilerGraph *graph);
1317 void limitFps(FpsControl *fps_timings, f32 *dtime);
1319 void showOverlayMessage(const wchar_t *msg, float dtime, int percent,
1320 bool draw_clouds = true);
1322 static void settingChangedCallback(const std::string &setting_name, void *data);
1323 void readSettings();
1325 inline bool getLeftClicked()
1327 return input->getLeftClicked() ||
1328 input->joystick.getWasKeyDown(KeyType::MOUSE_L);
1330 inline bool getRightClicked()
1332 return input->getRightClicked() ||
1333 input->joystick.getWasKeyDown(KeyType::MOUSE_R);
1335 inline bool isLeftPressed()
1337 return input->getLeftState() ||
1338 input->joystick.isKeyDown(KeyType::MOUSE_L);
1340 inline bool isRightPressed()
1342 return input->getRightState() ||
1343 input->joystick.isKeyDown(KeyType::MOUSE_R);
1345 inline bool getLeftReleased()
1347 return input->getLeftReleased() ||
1348 input->joystick.wasKeyReleased(KeyType::MOUSE_L);
1351 inline bool isKeyDown(GameKeyType k)
1353 return input->isKeyDown(keycache.key[k]) || input->joystick.isKeyDown(k);
1355 inline bool wasKeyDown(GameKeyType k)
1357 return input->wasKeyDown(keycache.key[k]) || input->joystick.wasKeyDown(k);
1361 void handleAndroidChatInput();
1365 void showPauseMenu();
1367 InputHandler *input;
1372 IWritableTextureSource *texture_src;
1373 IWritableShaderSource *shader_src;
1375 // When created, these will be filled with data received from the server
1376 IWritableItemDefManager *itemdef_manager;
1377 IWritableNodeDefManager *nodedef_manager;
1379 GameOnDemandSoundFetcher soundfetcher; // useful when testing
1380 ISoundManager *sound;
1381 bool sound_is_dummy;
1382 SoundMaker *soundmaker;
1384 ChatBackend *chat_backend;
1386 GUIFormSpecMenu *current_formspec;
1387 //default: "". If other than "", empty show_formspec packets will only close the formspec when the formname matches
1388 std::string cur_formname;
1390 EventManager *eventmgr;
1391 QuicktuneShortcutter *quicktune;
1393 GUIChatConsole *gui_chat_console; // Free using ->Drop()
1394 MapDrawControl *draw_control;
1396 Clouds *clouds; // Free using ->Drop()
1397 Sky *sky; // Free using ->Drop()
1398 Inventory *local_inventory;
1402 GameRunData runData;
1406 This class does take ownership/responsibily for cleaning up etc of any of
1407 these items (e.g. device)
1409 IrrlichtDevice *device;
1410 video::IVideoDriver *driver;
1411 scene::ISceneManager *smgr;
1413 std::string *error_message;
1414 bool *reconnect_requested;
1415 scene::ISceneNode *skybox;
1418 bool simple_singleplayer_mode;
1421 /* Pre-calculated values
1423 int crack_animation_length;
1427 gui::IGUIStaticText *guitext; // First line of debug text
1428 gui::IGUIStaticText *guitext2; // Second line of debug text
1429 gui::IGUIStaticText *guitext_info; // At the middle of the screen
1430 gui::IGUIStaticText *guitext_status;
1431 gui::IGUIStaticText *guitext_chat; // Chat text
1432 gui::IGUIStaticText *guitext_profiler; // Profiler text
1434 std::wstring infotext;
1435 std::wstring m_statustext;
1439 IntervalLimiter profiler_interval;
1442 * TODO: Local caching of settings is not optimal and should at some stage
1443 * be updated to use a global settings object for getting thse values
1444 * (as opposed to the this local caching). This can be addressed in
1447 bool m_cache_doubletap_jump;
1448 bool m_cache_enable_clouds;
1449 bool m_cache_enable_joysticks;
1450 bool m_cache_enable_particles;
1451 bool m_cache_enable_fog;
1452 bool m_cache_enable_noclip;
1453 bool m_cache_enable_free_move;
1454 f32 m_cache_mouse_sensitivity;
1455 f32 m_cache_joystick_frustum_sensitivity;
1456 f32 m_repeat_right_click_time;
1457 f32 m_cache_cam_smoothing;
1458 f32 m_cache_fog_start;
1460 bool m_invert_mouse;
1461 bool m_first_loop_after_window_activation;
1462 bool m_camera_offset_changed;
1465 bool m_cache_hold_aux1;
1466 bool m_android_chat_open;
1475 itemdef_manager(NULL),
1476 nodedef_manager(NULL),
1478 sound_is_dummy(false),
1481 current_formspec(NULL),
1485 gui_chat_console(NULL),
1490 local_inventory(NULL),
1493 m_invert_mouse(false),
1494 m_first_loop_after_window_activation(false),
1495 m_camera_offset_changed(false)
1497 g_settings->registerChangedCallback("doubletap_jump",
1498 &settingChangedCallback, this);
1499 g_settings->registerChangedCallback("enable_clouds",
1500 &settingChangedCallback, this);
1501 g_settings->registerChangedCallback("doubletap_joysticks",
1502 &settingChangedCallback, this);
1503 g_settings->registerChangedCallback("enable_particles",
1504 &settingChangedCallback, this);
1505 g_settings->registerChangedCallback("enable_fog",
1506 &settingChangedCallback, this);
1507 g_settings->registerChangedCallback("mouse_sensitivity",
1508 &settingChangedCallback, this);
1509 g_settings->registerChangedCallback("joystick_frustum_sensitivity",
1510 &settingChangedCallback, this);
1511 g_settings->registerChangedCallback("repeat_rightclick_time",
1512 &settingChangedCallback, this);
1513 g_settings->registerChangedCallback("noclip",
1514 &settingChangedCallback, this);
1515 g_settings->registerChangedCallback("free_move",
1516 &settingChangedCallback, this);
1517 g_settings->registerChangedCallback("cinematic",
1518 &settingChangedCallback, this);
1519 g_settings->registerChangedCallback("cinematic_camera_smoothing",
1520 &settingChangedCallback, this);
1521 g_settings->registerChangedCallback("camera_smoothing",
1522 &settingChangedCallback, this);
1527 m_cache_hold_aux1 = false; // This is initialised properly later
1534 /****************************************************************************
1536 ****************************************************************************/
1542 if (!sound_is_dummy)
1545 delete server; // deleted first to stop all server threads
1548 delete local_inventory;
1554 delete nodedef_manager;
1555 delete itemdef_manager;
1556 delete draw_control;
1558 extendedResourceCleanup();
1560 g_settings->deregisterChangedCallback("doubletap_jump",
1561 &settingChangedCallback, this);
1562 g_settings->deregisterChangedCallback("enable_clouds",
1563 &settingChangedCallback, this);
1564 g_settings->deregisterChangedCallback("enable_particles",
1565 &settingChangedCallback, this);
1566 g_settings->deregisterChangedCallback("enable_fog",
1567 &settingChangedCallback, this);
1568 g_settings->deregisterChangedCallback("mouse_sensitivity",
1569 &settingChangedCallback, this);
1570 g_settings->deregisterChangedCallback("repeat_rightclick_time",
1571 &settingChangedCallback, this);
1572 g_settings->deregisterChangedCallback("noclip",
1573 &settingChangedCallback, this);
1574 g_settings->deregisterChangedCallback("free_move",
1575 &settingChangedCallback, this);
1576 g_settings->deregisterChangedCallback("cinematic",
1577 &settingChangedCallback, this);
1578 g_settings->deregisterChangedCallback("cinematic_camera_smoothing",
1579 &settingChangedCallback, this);
1580 g_settings->deregisterChangedCallback("camera_smoothing",
1581 &settingChangedCallback, this);
1584 bool Game::startup(bool *kill,
1586 InputHandler *input,
1587 IrrlichtDevice *device,
1588 const std::string &map_dir,
1589 const std::string &playername,
1590 const std::string &password,
1591 std::string *address, // can change if simple_singleplayer_mode
1593 std::string &error_message,
1595 ChatBackend *chat_backend,
1596 const SubgameSpec &gamespec,
1597 bool simple_singleplayer_mode)
1600 this->device = device;
1602 this->error_message = &error_message;
1603 this->reconnect_requested = reconnect;
1604 this->random_input = random_input;
1605 this->input = input;
1606 this->chat_backend = chat_backend;
1607 this->simple_singleplayer_mode = simple_singleplayer_mode;
1609 keycache.handler = input;
1610 keycache.populate();
1612 driver = device->getVideoDriver();
1613 smgr = device->getSceneManager();
1615 smgr->getParameters()->setAttribute(scene::OBJ_LOADER_IGNORE_MATERIAL_FILES, true);
1617 memset(&runData, 0, sizeof(runData));
1618 runData.time_from_last_punch = 10.0;
1619 runData.profiler_max_page = 3;
1620 runData.update_wielded_item_trigger = true;
1622 memset(&flags, 0, sizeof(flags));
1623 flags.show_chat = true;
1624 flags.show_hud = true;
1625 flags.show_debug = g_settings->getBool("show_debug");
1626 m_invert_mouse = g_settings->getBool("invert_mouse");
1627 m_first_loop_after_window_activation = true;
1629 if (!init(map_dir, address, port, gamespec))
1632 if (!createClient(playername, password, address, port))
1641 ProfilerGraph graph;
1642 RunStats stats = { 0 };
1643 CameraOrientation cam_view_target = { 0 };
1644 CameraOrientation cam_view = { 0 };
1645 FpsControl draw_times = { 0 };
1646 f32 dtime; // in seconds
1648 /* Clear the profiler */
1649 Profiler::GraphValues dummyvalues;
1650 g_profiler->graphGet(dummyvalues);
1652 draw_times.last_time = device->getTimer()->getTime();
1654 set_light_table(g_settings->getFloat("display_gamma"));
1657 m_cache_hold_aux1 = g_settings->getBool("fast_move")
1658 && client->checkPrivilege("fast");
1661 irr::core::dimension2d<u32> previous_screen_size(g_settings->getU16("screen_w"),
1662 g_settings->getU16("screen_h"));
1664 while (device->run()
1665 && !(*kill || g_gamecallback->shutdown_requested
1666 || (server && server->getShutdownRequested()))) {
1668 const irr::core::dimension2d<u32> ¤t_screen_size =
1669 device->getVideoDriver()->getScreenSize();
1670 // Verify if window size has changed and save it if it's the case
1671 // Ensure evaluating settings->getBool after verifying screensize
1672 // First condition is cheaper
1673 if (previous_screen_size != current_screen_size &&
1674 current_screen_size != irr::core::dimension2d<u32>(0,0) &&
1675 g_settings->getBool("autosave_screensize")) {
1676 g_settings->setU16("screen_w", current_screen_size.Width);
1677 g_settings->setU16("screen_h", current_screen_size.Height);
1678 previous_screen_size = current_screen_size;
1681 /* Must be called immediately after a device->run() call because it
1682 * uses device->getTimer()->getTime()
1684 limitFps(&draw_times, &dtime);
1686 updateStats(&stats, draw_times, dtime);
1687 updateInteractTimers(dtime);
1689 if (!checkConnection())
1691 if (!handleCallbacks())
1697 hud->resizeHotbar();
1699 updateProfilers(stats, draw_times, dtime);
1700 processUserInput(dtime);
1701 // Update camera before player movement to avoid camera lag of one frame
1702 updateCameraDirection(&cam_view_target, dtime);
1703 cam_view.camera_yaw += (cam_view_target.camera_yaw -
1704 cam_view.camera_yaw) * m_cache_cam_smoothing;
1705 cam_view.camera_pitch += (cam_view_target.camera_pitch -
1706 cam_view.camera_pitch) * m_cache_cam_smoothing;
1707 updatePlayerControl(cam_view);
1709 processClientEvents(&cam_view_target);
1710 updateCamera(draw_times.busy_time, dtime);
1712 processPlayerInteraction(dtime, flags.show_hud, flags.show_debug);
1713 updateFrame(&graph, &stats, dtime, cam_view);
1714 updateProfilerGraphs(&graph);
1716 // Update if minimap has been disabled by the server
1717 flags.show_minimap &= client->shouldShowMinimap();
1722 void Game::shutdown()
1724 #if IRRLICHT_VERSION_MAJOR == 1 && IRRLICHT_VERSION_MINOR <= 8
1725 if (g_settings->get("3d_mode") == "pageflip") {
1726 driver->setRenderTarget(irr::video::ERT_STEREO_BOTH_BUFFERS);
1729 if (current_formspec)
1730 current_formspec->quitMenu();
1732 showOverlayMessage(wgettext("Shutting down..."), 0, 0, false);
1737 if (gui_chat_console)
1738 gui_chat_console->drop();
1744 while (g_menumgr.menuCount() > 0) {
1745 g_menumgr.m_stack.front()->setVisible(false);
1746 g_menumgr.deletingMenu(g_menumgr.m_stack.front());
1749 if (current_formspec) {
1750 current_formspec->drop();
1751 current_formspec = NULL;
1754 chat_backend->addMessage(L"", L"# Disconnected.");
1755 chat_backend->addMessage(L"", L"");
1759 while (!client->isShutdown()) {
1760 assert(texture_src != NULL);
1761 assert(shader_src != NULL);
1762 texture_src->processQueue();
1763 shader_src->processQueue();
1770 /****************************************************************************/
1771 /****************************************************************************
1773 ****************************************************************************/
1774 /****************************************************************************/
1777 const std::string &map_dir,
1778 std::string *address,
1780 const SubgameSpec &gamespec)
1782 texture_src = createTextureSource(device);
1784 showOverlayMessage(wgettext("Loading..."), 0, 0);
1786 shader_src = createShaderSource(device);
1788 itemdef_manager = createItemDefManager();
1789 nodedef_manager = createNodeDefManager();
1791 eventmgr = new EventManager();
1792 quicktune = new QuicktuneShortcutter();
1794 if (!(texture_src && shader_src && itemdef_manager && nodedef_manager
1795 && eventmgr && quicktune))
1801 // Create a server if not connecting to an existing one
1802 if (*address == "") {
1803 if (!createSingleplayerServer(map_dir, gamespec, port, address))
1810 bool Game::initSound()
1813 if (g_settings->getBool("enable_sound")) {
1814 infostream << "Attempting to use OpenAL audio" << std::endl;
1815 sound = createOpenALSoundManager(&soundfetcher);
1817 infostream << "Failed to initialize OpenAL audio" << std::endl;
1819 infostream << "Sound disabled." << std::endl;
1823 infostream << "Using dummy audio." << std::endl;
1824 sound = &dummySoundManager;
1825 sound_is_dummy = true;
1828 soundmaker = new SoundMaker(sound, nodedef_manager);
1832 soundmaker->registerReceiver(eventmgr);
1837 bool Game::createSingleplayerServer(const std::string &map_dir,
1838 const SubgameSpec &gamespec, u16 port, std::string *address)
1840 showOverlayMessage(wgettext("Creating server..."), 0, 5);
1842 std::string bind_str = g_settings->get("bind_address");
1843 Address bind_addr(0, 0, 0, 0, port);
1845 if (g_settings->getBool("ipv6_server")) {
1846 bind_addr.setAddress((IPv6AddressBytes *) NULL);
1850 bind_addr.Resolve(bind_str.c_str());
1851 } catch (ResolveError &e) {
1852 infostream << "Resolving bind address \"" << bind_str
1853 << "\" failed: " << e.what()
1854 << " -- Listening on all addresses." << std::endl;
1857 if (bind_addr.isIPv6() && !g_settings->getBool("enable_ipv6")) {
1858 *error_message = "Unable to listen on " +
1859 bind_addr.serializeString() +
1860 " because IPv6 is disabled";
1861 errorstream << *error_message << std::endl;
1865 server = new Server(map_dir, gamespec, simple_singleplayer_mode,
1866 bind_addr.isIPv6(), false);
1868 server->start(bind_addr);
1873 bool Game::createClient(const std::string &playername,
1874 const std::string &password, std::string *address, u16 port)
1876 showOverlayMessage(wgettext("Creating client..."), 0, 10);
1878 draw_control = new MapDrawControl;
1882 bool could_connect, connect_aborted;
1884 if (!connectToServer(playername, password, address, port,
1885 &could_connect, &connect_aborted))
1888 if (!could_connect) {
1889 if (error_message->empty() && !connect_aborted) {
1890 // Should not happen if error messages are set properly
1891 *error_message = "Connection failed for unknown reason";
1892 errorstream << *error_message << std::endl;
1897 if (!getServerContent(&connect_aborted)) {
1898 if (error_message->empty() && !connect_aborted) {
1899 // Should not happen if error messages are set properly
1900 *error_message = "Connection failed for unknown reason";
1901 errorstream << *error_message << std::endl;
1906 GameGlobalShaderConstantSetterFactory *scsf = new GameGlobalShaderConstantSetterFactory(
1907 &flags.force_fog_off, &runData.fog_range, client);
1908 shader_src->addShaderConstantSetterFactory(scsf);
1910 // Update cached textures, meshes and materials
1911 client->afterContentReceived(device);
1915 camera = new Camera(smgr, *draw_control, client);
1916 if (!camera || !camera->successfullyCreated(*error_message))
1918 client->setCamera(camera);
1922 if (m_cache_enable_clouds) {
1923 clouds = new Clouds(smgr->getRootSceneNode(), smgr, -1, time(0));
1925 *error_message = "Memory allocation error (clouds)";
1926 errorstream << *error_message << std::endl;
1933 sky = new Sky(smgr->getRootSceneNode(), smgr, -1, texture_src);
1935 skybox = NULL; // This is used/set later on in the main run loop
1937 local_inventory = new Inventory(itemdef_manager);
1939 if (!(sky && local_inventory)) {
1940 *error_message = "Memory allocation error (sky or local inventory)";
1941 errorstream << *error_message << std::endl;
1945 /* Pre-calculated values
1947 video::ITexture *t = texture_src->getTexture("crack_anylength.png");
1949 v2u32 size = t->getOriginalSize();
1950 crack_animation_length = size.Y / size.X;
1952 crack_animation_length = 5;
1958 /* Set window caption
1960 std::wstring str = utf8_to_wide(PROJECT_NAME_C);
1962 str += utf8_to_wide(g_version_hash);
1964 str += driver->getName();
1966 device->setWindowCaption(str.c_str());
1968 LocalPlayer *player = client->getEnv().getLocalPlayer();
1969 player->hurt_tilt_timer = 0;
1970 player->hurt_tilt_strength = 0;
1972 hud = new Hud(driver, smgr, guienv, client, player, local_inventory);
1975 *error_message = "Memory error: could not create HUD";
1976 errorstream << *error_message << std::endl;
1980 mapper = client->getMinimap();
1982 mapper->setMinimapMode(MINIMAP_MODE_OFF);
1987 bool Game::initGui()
1989 // First line of debug text
1990 guitext = addStaticText(guienv,
1991 utf8_to_wide(PROJECT_NAME_C).c_str(),
1992 core::rect<s32>(0, 0, 0, 0),
1993 false, false, guiroot);
1995 // Second line of debug text
1996 guitext2 = addStaticText(guienv,
1998 core::rect<s32>(0, 0, 0, 0),
1999 false, false, guiroot);
2001 // At the middle of the screen
2002 // Object infos are shown in this
2003 guitext_info = addStaticText(guienv,
2005 core::rect<s32>(0, 0, 400, g_fontengine->getTextHeight() * 5 + 5) + v2s32(100, 200),
2006 false, true, guiroot);
2008 // Status text (displays info when showing and hiding GUI stuff, etc.)
2009 guitext_status = addStaticText(guienv,
2011 core::rect<s32>(0, 0, 0, 0),
2012 false, false, guiroot);
2013 guitext_status->setVisible(false);
2016 guitext_chat = addStaticText(
2019 core::rect<s32>(0, 0, 0, 0),
2020 //false, false); // Disable word wrap as of now
2021 false, true, guiroot);
2023 // Remove stale "recent" chat messages from previous connections
2024 chat_backend->clearRecentChat();
2026 // Chat backend and console
2027 gui_chat_console = new GUIChatConsole(guienv, guienv->getRootGUIElement(),
2028 -1, chat_backend, client, &g_menumgr);
2029 if (!gui_chat_console) {
2030 *error_message = "Could not allocate memory for chat console";
2031 errorstream << *error_message << std::endl;
2035 // Profiler text (size is updated when text is updated)
2036 guitext_profiler = addStaticText(guienv,
2038 core::rect<s32>(0, 0, 0, 0),
2039 false, false, guiroot);
2040 guitext_profiler->setBackgroundColor(video::SColor(120, 0, 0, 0));
2041 guitext_profiler->setVisible(false);
2042 guitext_profiler->setWordWrap(true);
2044 #ifdef HAVE_TOUCHSCREENGUI
2046 if (g_touchscreengui)
2047 g_touchscreengui->init(texture_src);
2054 bool Game::connectToServer(const std::string &playername,
2055 const std::string &password, std::string *address, u16 port,
2056 bool *connect_ok, bool *aborted)
2058 *connect_ok = false; // Let's not be overly optimistic
2060 bool local_server_mode = false;
2062 showOverlayMessage(wgettext("Resolving address..."), 0, 15);
2064 Address connect_address(0, 0, 0, 0, port);
2067 connect_address.Resolve(address->c_str());
2069 if (connect_address.isZero()) { // i.e. INADDR_ANY, IN6ADDR_ANY
2070 //connect_address.Resolve("localhost");
2071 if (connect_address.isIPv6()) {
2072 IPv6AddressBytes addr_bytes;
2073 addr_bytes.bytes[15] = 1;
2074 connect_address.setAddress(&addr_bytes);
2076 connect_address.setAddress(127, 0, 0, 1);
2078 local_server_mode = true;
2080 } catch (ResolveError &e) {
2081 *error_message = std::string("Couldn't resolve address: ") + e.what();
2082 errorstream << *error_message << std::endl;
2086 if (connect_address.isIPv6() && !g_settings->getBool("enable_ipv6")) {
2087 *error_message = "Unable to connect to " +
2088 connect_address.serializeString() +
2089 " because IPv6 is disabled";
2090 errorstream << *error_message << std::endl;
2094 client = new Client(device,
2095 playername.c_str(), password, *address,
2096 *draw_control, texture_src, shader_src,
2097 itemdef_manager, nodedef_manager, sound, eventmgr,
2098 connect_address.isIPv6(), &flags);
2103 infostream << "Connecting to server at ";
2104 connect_address.print(&infostream);
2105 infostream << std::endl;
2107 client->connect(connect_address,
2108 simple_singleplayer_mode || local_server_mode);
2111 Wait for server to accept connection
2117 FpsControl fps_control = { 0 };
2119 f32 wait_time = 0; // in seconds
2121 fps_control.last_time = device->getTimer()->getTime();
2125 while (device->run()) {
2127 limitFps(&fps_control, &dtime);
2129 // Update client and server
2130 client->step(dtime);
2133 server->step(dtime);
2136 if (client->getState() == LC_Init) {
2142 if (client->accessDenied()) {
2143 *error_message = "Access denied. Reason: "
2144 + client->accessDeniedReason();
2145 *reconnect_requested = client->reconnectRequested();
2146 errorstream << *error_message << std::endl;
2150 if (wasKeyDown(KeyType::ESC) || input->wasKeyDown(CancelKey)) {
2152 infostream << "Connect aborted [Escape]" << std::endl;
2157 // Only time out if we aren't waiting for the server we started
2158 if ((*address != "") && (wait_time > 10)) {
2159 bool sent_old_init = g_settings->getFlag("send_pre_v25_init");
2160 // If no pre v25 init was sent, and no answer was received,
2161 // but the low level connection could be established
2162 // (meaning that we have a peer id), then we probably wanted
2163 // to connect to a legacy server. In this case, tell the user
2164 // to enable the option to be able to connect.
2165 if (!sent_old_init &&
2166 (client->getProtoVersion() == 0) &&
2167 client->connectedToServer()) {
2168 *error_message = "Connection failure: init packet not "
2169 "recognized by server.\n"
2170 "Most likely the server uses an old protocol version (<v25).\n"
2171 "Please ask the server owner to update to 0.4.13 or later.\n"
2172 "To still connect to the server in the meantime,\n"
2173 "you can enable the 'send_pre_v25_init' setting by editing minetest.conf,\n"
2174 "or by enabling the 'Client -> Network -> Support older Servers'\n"
2175 "entry in the advanced settings menu.";
2177 *error_message = "Connection timed out.";
2179 errorstream << *error_message << std::endl;
2184 showOverlayMessage(wgettext("Connecting to server..."), dtime, 20);
2186 } catch (con::PeerNotFoundException &e) {
2187 // TODO: Should something be done here? At least an info/error
2195 bool Game::getServerContent(bool *aborted)
2199 FpsControl fps_control = { 0 };
2200 f32 dtime; // in seconds
2202 fps_control.last_time = device->getTimer()->getTime();
2204 while (device->run()) {
2206 limitFps(&fps_control, &dtime);
2208 // Update client and server
2209 client->step(dtime);
2212 server->step(dtime);
2215 if (client->mediaReceived() && client->itemdefReceived() &&
2216 client->nodedefReceived()) {
2221 if (!checkConnection())
2224 if (client->getState() < LC_Init) {
2225 *error_message = "Client disconnected";
2226 errorstream << *error_message << std::endl;
2230 if (wasKeyDown(KeyType::ESC) || input->wasKeyDown(CancelKey)) {
2232 infostream << "Connect aborted [Escape]" << std::endl;
2239 if (!client->itemdefReceived()) {
2240 const wchar_t *text = wgettext("Item definitions...");
2242 draw_load_screen(text, device, guienv, texture_src,
2245 } else if (!client->nodedefReceived()) {
2246 const wchar_t *text = wgettext("Node definitions...");
2248 draw_load_screen(text, device, guienv, texture_src,
2252 std::stringstream message;
2253 std::fixed(message);
2254 message.precision(0);
2255 message << gettext("Media...") << " " << (client->mediaReceiveProgress()*100) << "%";
2256 message.precision(2);
2258 if ((USE_CURL == 0) ||
2259 (!g_settings->getBool("enable_remote_media_server"))) {
2260 float cur = client->getCurRate();
2261 std::string cur_unit = gettext("KiB/s");
2265 cur_unit = gettext("MiB/s");
2268 message << " (" << cur << ' ' << cur_unit << ")";
2271 progress = 30 + client->mediaReceiveProgress() * 35 + 0.5;
2272 draw_load_screen(utf8_to_wide(message.str()), device,
2273 guienv, texture_src, dtime, progress);
2281 /****************************************************************************/
2282 /****************************************************************************
2284 ****************************************************************************/
2285 /****************************************************************************/
2287 inline void Game::updateInteractTimers(f32 dtime)
2289 if (runData.nodig_delay_timer >= 0)
2290 runData.nodig_delay_timer -= dtime;
2292 if (runData.object_hit_delay_timer >= 0)
2293 runData.object_hit_delay_timer -= dtime;
2295 runData.time_from_last_punch += dtime;
2299 /* returns false if game should exit, otherwise true
2301 inline bool Game::checkConnection()
2303 if (client->accessDenied()) {
2304 *error_message = "Access denied. Reason: "
2305 + client->accessDeniedReason();
2306 *reconnect_requested = client->reconnectRequested();
2307 errorstream << *error_message << std::endl;
2315 /* returns false if game should exit, otherwise true
2317 inline bool Game::handleCallbacks()
2319 if (g_gamecallback->disconnect_requested) {
2320 g_gamecallback->disconnect_requested = false;
2324 if (g_gamecallback->changepassword_requested) {
2325 (new GUIPasswordChange(guienv, guiroot, -1,
2326 &g_menumgr, client))->drop();
2327 g_gamecallback->changepassword_requested = false;
2330 if (g_gamecallback->changevolume_requested) {
2331 (new GUIVolumeChange(guienv, guiroot, -1,
2332 &g_menumgr))->drop();
2333 g_gamecallback->changevolume_requested = false;
2336 if (g_gamecallback->keyconfig_requested) {
2337 (new GUIKeyChangeMenu(guienv, guiroot, -1,
2338 &g_menumgr))->drop();
2339 g_gamecallback->keyconfig_requested = false;
2342 if (g_gamecallback->keyconfig_changed) {
2343 keycache.populate(); // update the cache with new settings
2344 g_gamecallback->keyconfig_changed = false;
2351 void Game::processQueues()
2353 texture_src->processQueue();
2354 itemdef_manager->processQueue(client);
2355 shader_src->processQueue();
2359 void Game::updateProfilers(const RunStats &stats, const FpsControl &draw_times, f32 dtime)
2361 float profiler_print_interval =
2362 g_settings->getFloat("profiler_print_interval");
2363 bool print_to_log = true;
2365 if (profiler_print_interval == 0) {
2366 print_to_log = false;
2367 profiler_print_interval = 5;
2370 if (profiler_interval.step(dtime, profiler_print_interval)) {
2372 infostream << "Profiler:" << std::endl;
2373 g_profiler->print(infostream);
2376 update_profiler_gui(guitext_profiler, g_fontengine,
2377 runData.profiler_current_page, runData.profiler_max_page,
2378 driver->getScreenSize().Height);
2380 g_profiler->clear();
2383 addProfilerGraphs(stats, draw_times, dtime);
2387 void Game::addProfilerGraphs(const RunStats &stats,
2388 const FpsControl &draw_times, f32 dtime)
2390 g_profiler->graphAdd("mainloop_other",
2391 draw_times.busy_time / 1000.0f - stats.drawtime / 1000.0f);
2393 if (draw_times.sleep_time != 0)
2394 g_profiler->graphAdd("mainloop_sleep", draw_times.sleep_time / 1000.0f);
2395 g_profiler->graphAdd("mainloop_dtime", dtime);
2397 g_profiler->add("Elapsed time", dtime);
2398 g_profiler->avg("FPS", 1. / dtime);
2402 void Game::updateStats(RunStats *stats, const FpsControl &draw_times,
2409 /* Time average and jitter calculation
2411 jp = &stats->dtime_jitter;
2412 jp->avg = jp->avg * 0.96 + dtime * 0.04;
2414 jitter = dtime - jp->avg;
2416 if (jitter > jp->max)
2419 jp->counter += dtime;
2421 if (jp->counter > 0.0) {
2423 jp->max_sample = jp->max;
2424 jp->max_fraction = jp->max_sample / (jp->avg + 0.001);
2428 /* Busytime average and jitter calculation
2430 jp = &stats->busy_time_jitter;
2431 jp->avg = jp->avg + draw_times.busy_time * 0.02;
2433 jitter = draw_times.busy_time - jp->avg;
2435 if (jitter > jp->max)
2437 if (jitter < jp->min)
2440 jp->counter += dtime;
2442 if (jp->counter > 0.0) {
2444 jp->max_sample = jp->max;
2445 jp->min_sample = jp->min;
2453 /****************************************************************************
2455 ****************************************************************************/
2457 void Game::processUserInput(f32 dtime)
2459 // Reset input if window not active or some menu is active
2460 if (!device->isWindowActive() || isMenuActive() || guienv->hasFocus(gui_chat_console)) {
2462 #ifdef HAVE_TOUCHSCREENGUI
2463 g_touchscreengui->hide();
2466 #ifdef HAVE_TOUCHSCREENGUI
2467 else if (g_touchscreengui) {
2468 /* on touchscreengui step may generate own input events which ain't
2469 * what we want in case we just did clear them */
2470 g_touchscreengui->step(dtime);
2474 if (!guienv->hasFocus(gui_chat_console) && gui_chat_console->isOpen()) {
2475 gui_chat_console->closeConsoleAtOnce();
2478 // Input handler step() (used by the random input generator)
2482 if (current_formspec != NULL)
2483 current_formspec->getAndroidUIInput();
2485 handleAndroidChatInput();
2488 // Increase timer for double tap of "keymap_jump"
2489 if (m_cache_doubletap_jump && runData.jump_timer <= 0.2f)
2490 runData.jump_timer += dtime;
2493 processItemSelection(&runData.new_playeritem);
2497 void Game::processKeyInput()
2499 if (wasKeyDown(KeyType::DROP)) {
2501 } else if (wasKeyDown(KeyType::AUTOFORWARD)) {
2502 toggleAutoforward();
2503 } else if (wasKeyDown(KeyType::INVENTORY)) {
2505 } else if (wasKeyDown(KeyType::ESC) || input->wasKeyDown(CancelKey)) {
2506 if (!gui_chat_console->isOpenInhibited()) {
2509 } else if (wasKeyDown(KeyType::CHAT)) {
2510 openConsole(0.2, L"");
2511 } else if (wasKeyDown(KeyType::CMD)) {
2512 openConsole(0.2, L"/");
2513 } else if (wasKeyDown(KeyType::CMD_LOCAL)) {
2514 openConsole(0.2, L".");
2515 } else if (wasKeyDown(KeyType::CONSOLE)) {
2516 openConsole(core::clamp(g_settings->getFloat("console_height"), 0.1f, 1.0f));
2517 } else if (wasKeyDown(KeyType::FREEMOVE)) {
2519 } else if (wasKeyDown(KeyType::JUMP)) {
2520 toggleFreeMoveAlt();
2521 } else if (wasKeyDown(KeyType::FASTMOVE)) {
2523 } else if (wasKeyDown(KeyType::NOCLIP)) {
2525 } else if (wasKeyDown(KeyType::MUTE)) {
2526 float volume = g_settings->getFloat("sound_volume");
2527 if (volume < 0.001f) {
2528 g_settings->setFloat("sound_volume", 1.0f);
2529 m_statustext = narrow_to_wide(gettext("Volume changed to 100%"));
2531 g_settings->setFloat("sound_volume", 0.0f);
2532 m_statustext = narrow_to_wide(gettext("Volume changed to 0%"));
2534 runData.statustext_time = 0;
2535 } else if (wasKeyDown(KeyType::INC_VOLUME)) {
2536 float new_volume = rangelim(g_settings->getFloat("sound_volume") + 0.1f, 0.0f, 1.0f);
2538 g_settings->setFloat("sound_volume", new_volume);
2539 snprintf(buf, sizeof(buf), gettext("Volume changed to %d%%"), myround(new_volume * 100));
2540 m_statustext = narrow_to_wide(buf);
2541 runData.statustext_time = 0;
2542 } else if (wasKeyDown(KeyType::DEC_VOLUME)) {
2543 float new_volume = rangelim(g_settings->getFloat("sound_volume") - 0.1f, 0.0f, 1.0f);
2545 g_settings->setFloat("sound_volume", new_volume);
2546 snprintf(buf, sizeof(buf), gettext("Volume changed to %d%%"), myround(new_volume * 100));
2547 m_statustext = narrow_to_wide(buf);
2548 runData.statustext_time = 0;
2549 } else if (wasKeyDown(KeyType::CINEMATIC)) {
2551 } else if (wasKeyDown(KeyType::SCREENSHOT)) {
2552 client->makeScreenshot();
2553 } else if (wasKeyDown(KeyType::TOGGLE_HUD)) {
2555 } else if (wasKeyDown(KeyType::MINIMAP)) {
2556 toggleMinimap(isKeyDown(KeyType::SNEAK));
2557 } else if (wasKeyDown(KeyType::TOGGLE_CHAT)) {
2559 } else if (wasKeyDown(KeyType::TOGGLE_FORCE_FOG_OFF)) {
2561 } else if (wasKeyDown(KeyType::TOGGLE_UPDATE_CAMERA)) {
2562 toggleUpdateCamera();
2563 } else if (wasKeyDown(KeyType::TOGGLE_DEBUG)) {
2565 } else if (wasKeyDown(KeyType::TOGGLE_PROFILER)) {
2567 } else if (wasKeyDown(KeyType::INCREASE_VIEWING_RANGE)) {
2568 increaseViewRange();
2569 } else if (wasKeyDown(KeyType::DECREASE_VIEWING_RANGE)) {
2570 decreaseViewRange();
2571 } else if (wasKeyDown(KeyType::RANGESELECT)) {
2572 toggleFullViewRange();
2573 } else if (wasKeyDown(KeyType::QUICKTUNE_NEXT)) {
2575 } else if (wasKeyDown(KeyType::QUICKTUNE_PREV)) {
2577 } else if (wasKeyDown(KeyType::QUICKTUNE_INC)) {
2579 } else if (wasKeyDown(KeyType::QUICKTUNE_DEC)) {
2581 } else if (wasKeyDown(KeyType::DEBUG_STACKS)) {
2582 // Print debug stacks
2583 dstream << "-----------------------------------------"
2585 dstream << "Printing debug stacks:" << std::endl;
2586 dstream << "-----------------------------------------"
2588 debug_stacks_print();
2591 if (!isKeyDown(KeyType::JUMP) && runData.reset_jump_timer) {
2592 runData.reset_jump_timer = false;
2593 runData.jump_timer = 0.0f;
2596 if (quicktune->hasMessage()) {
2597 m_statustext = utf8_to_wide(quicktune->getMessage());
2598 runData.statustext_time = 0.0f;
2602 void Game::processItemSelection(u16 *new_playeritem)
2604 LocalPlayer *player = client->getEnv().getLocalPlayer();
2606 /* Item selection using mouse wheel
2608 *new_playeritem = client->getPlayerItem();
2610 s32 wheel = input->getMouseWheel();
2611 u16 max_item = MYMIN(PLAYER_INVENTORY_SIZE - 1,
2612 player->hud_hotbar_itemcount - 1);
2616 if (input->joystick.wasKeyDown(KeyType::SCROLL_DOWN) ||
2617 wasKeyDown(KeyType::HOTBAR_NEXT)) {
2621 if (input->joystick.wasKeyDown(KeyType::SCROLL_UP) ||
2622 wasKeyDown(KeyType::HOTBAR_PREV)) {
2627 *new_playeritem = *new_playeritem < max_item ? *new_playeritem + 1 : 0;
2629 *new_playeritem = *new_playeritem > 0 ? *new_playeritem - 1 : max_item;
2632 /* Item selection using keyboard
2634 for (u16 i = 0; i < 10; i++) {
2635 static const KeyPress *item_keys[10] = {
2636 NumberKey + 1, NumberKey + 2, NumberKey + 3, NumberKey + 4,
2637 NumberKey + 5, NumberKey + 6, NumberKey + 7, NumberKey + 8,
2638 NumberKey + 9, NumberKey + 0,
2641 if (input->wasKeyDown(*item_keys[i])) {
2642 if (i < PLAYER_INVENTORY_SIZE && i < player->hud_hotbar_itemcount) {
2643 *new_playeritem = i;
2644 infostream << "Selected item: " << new_playeritem << std::endl;
2652 void Game::dropSelectedItem()
2654 IDropAction *a = new IDropAction();
2656 a->from_inv.setCurrentPlayer();
2657 a->from_list = "main";
2658 a->from_i = client->getPlayerItem();
2659 client->inventoryAction(a);
2663 void Game::openInventory()
2666 * Don't permit to open inventory is CAO or player doesn't exists.
2667 * This prevent showing an empty inventory at player load
2670 LocalPlayer *player = client->getEnv().getLocalPlayer();
2671 if (!player || !player->getCAO())
2674 infostream << "the_game: " << "Launching inventory" << std::endl;
2676 PlayerInventoryFormSource *fs_src = new PlayerInventoryFormSource(client);
2677 TextDest *txt_dst = new TextDestPlayerInventory(client);
2679 create_formspec_menu(¤t_formspec, client, device, &input->joystick, fs_src, txt_dst);
2682 InventoryLocation inventoryloc;
2683 inventoryloc.setCurrentPlayer();
2684 current_formspec->setFormSpec(fs_src->getForm(), inventoryloc);
2688 void Game::openConsole(float scale, const wchar_t *line)
2690 assert(scale > 0.0f && scale <= 1.0f);
2693 porting::showInputDialog(gettext("ok"), "", "", 2);
2694 m_android_chat_open = true;
2696 if (gui_chat_console->isOpenInhibited())
2698 gui_chat_console->openConsole(scale);
2700 gui_chat_console->setCloseOnEnter(true);
2701 gui_chat_console->replaceAndAddToHistory(line);
2707 void Game::handleAndroidChatInput()
2709 if (m_android_chat_open && porting::getInputDialogState() == 0) {
2710 std::string text = porting::getInputDialogValue();
2711 client->typeChatMessage(utf8_to_wide(text));
2717 void Game::toggleFreeMove()
2719 static const wchar_t *msg[] = { L"free_move disabled", L"free_move enabled" };
2721 bool free_move = !g_settings->getBool("free_move");
2722 g_settings->set("free_move", bool_to_cstr(free_move));
2724 runData.statustext_time = 0;
2725 m_statustext = msg[free_move];
2726 if (free_move && !client->checkPrivilege("fly"))
2727 m_statustext += L" (note: no 'fly' privilege)";
2731 void Game::toggleFreeMoveAlt()
2733 if (m_cache_doubletap_jump && runData.jump_timer < 0.2f)
2736 runData.reset_jump_timer = true;
2740 void Game::toggleFast()
2742 static const wchar_t *msg[] = { L"fast_move disabled", L"fast_move enabled" };
2743 bool fast_move = !g_settings->getBool("fast_move");
2744 g_settings->set("fast_move", bool_to_cstr(fast_move));
2746 runData.statustext_time = 0;
2747 m_statustext = msg[fast_move];
2749 bool has_fast_privs = client->checkPrivilege("fast");
2751 if (fast_move && !has_fast_privs)
2752 m_statustext += L" (note: no 'fast' privilege)";
2755 m_cache_hold_aux1 = fast_move && has_fast_privs;
2760 void Game::toggleNoClip()
2762 static const wchar_t *msg[] = { L"noclip disabled", L"noclip enabled" };
2763 bool noclip = !g_settings->getBool("noclip");
2764 g_settings->set("noclip", bool_to_cstr(noclip));
2766 runData.statustext_time = 0;
2767 m_statustext = msg[noclip];
2769 if (noclip && !client->checkPrivilege("noclip"))
2770 m_statustext += L" (note: no 'noclip' privilege)";
2773 void Game::toggleCinematic()
2775 static const wchar_t *msg[] = { L"cinematic disabled", L"cinematic enabled" };
2776 bool cinematic = !g_settings->getBool("cinematic");
2777 g_settings->set("cinematic", bool_to_cstr(cinematic));
2779 runData.statustext_time = 0;
2780 m_statustext = msg[cinematic];
2783 // Autoforward by toggling continuous forward.
2784 void Game::toggleAutoforward()
2786 static const wchar_t *msg[] = { L"autoforward disabled", L"autoforward enabled" };
2787 bool autoforward_enabled = !g_settings->getBool("continuous_forward");
2788 g_settings->set("continuous_forward", bool_to_cstr(autoforward_enabled));
2790 runData.statustext_time = 0;
2791 m_statustext = msg[autoforward_enabled ? 1 : 0];
2794 void Game::toggleChat()
2796 static const wchar_t *msg[] = { L"Chat hidden", L"Chat shown" };
2798 flags.show_chat = !flags.show_chat;
2799 runData.statustext_time = 0;
2800 m_statustext = msg[flags.show_chat];
2804 void Game::toggleHud()
2806 static const wchar_t *msg[] = { L"HUD hidden", L"HUD shown" };
2808 flags.show_hud = !flags.show_hud;
2809 runData.statustext_time = 0;
2810 m_statustext = msg[flags.show_hud];
2813 void Game::toggleMinimap(bool shift_pressed)
2815 if (!mapper || !flags.show_hud || !g_settings->getBool("enable_minimap"))
2818 if (shift_pressed) {
2819 mapper->toggleMinimapShape();
2823 u32 hud_flags = client->getEnv().getLocalPlayer()->hud_flags;
2825 MinimapMode mode = MINIMAP_MODE_OFF;
2826 if (hud_flags & HUD_FLAG_MINIMAP_VISIBLE) {
2827 mode = mapper->getMinimapMode();
2828 mode = (MinimapMode)((int)mode + 1);
2831 flags.show_minimap = true;
2833 case MINIMAP_MODE_SURFACEx1:
2834 m_statustext = L"Minimap in surface mode, Zoom x1";
2836 case MINIMAP_MODE_SURFACEx2:
2837 m_statustext = L"Minimap in surface mode, Zoom x2";
2839 case MINIMAP_MODE_SURFACEx4:
2840 m_statustext = L"Minimap in surface mode, Zoom x4";
2842 case MINIMAP_MODE_RADARx1:
2843 m_statustext = L"Minimap in radar mode, Zoom x1";
2845 case MINIMAP_MODE_RADARx2:
2846 m_statustext = L"Minimap in radar mode, Zoom x2";
2848 case MINIMAP_MODE_RADARx4:
2849 m_statustext = L"Minimap in radar mode, Zoom x4";
2852 mode = MINIMAP_MODE_OFF;
2853 flags.show_minimap = false;
2854 m_statustext = (hud_flags & HUD_FLAG_MINIMAP_VISIBLE) ?
2855 L"Minimap hidden" : L"Minimap disabled by server";
2858 runData.statustext_time = 0;
2859 mapper->setMinimapMode(mode);
2862 void Game::toggleFog()
2864 static const wchar_t *msg[] = { L"Fog enabled", L"Fog disabled" };
2866 flags.force_fog_off = !flags.force_fog_off;
2867 runData.statustext_time = 0;
2868 m_statustext = msg[flags.force_fog_off];
2872 void Game::toggleDebug()
2874 // Initial / 4x toggle: Chat only
2875 // 1x toggle: Debug text with chat
2876 // 2x toggle: Debug text with profiler graph
2877 // 3x toggle: Debug text and wireframe
2878 if (!flags.show_debug) {
2879 flags.show_debug = true;
2880 flags.show_profiler_graph = false;
2881 draw_control->show_wireframe = false;
2882 m_statustext = L"Debug info shown";
2883 } else if (!flags.show_profiler_graph && !draw_control->show_wireframe) {
2884 flags.show_profiler_graph = true;
2885 m_statustext = L"Profiler graph shown";
2886 } else if (!draw_control->show_wireframe && client->checkPrivilege("debug")) {
2887 flags.show_profiler_graph = false;
2888 draw_control->show_wireframe = true;
2889 m_statustext = L"Wireframe shown";
2891 flags.show_debug = false;
2892 flags.show_profiler_graph = false;
2893 draw_control->show_wireframe = false;
2894 if (client->checkPrivilege("debug")) {
2895 m_statustext = L"Debug info, profiler graph, and wireframe hidden";
2897 m_statustext = L"Debug info and profiler graph hidden";
2900 runData.statustext_time = 0;
2904 void Game::toggleUpdateCamera()
2906 static const wchar_t *msg[] = {
2907 L"Camera update enabled",
2908 L"Camera update disabled"
2911 flags.disable_camera_update = !flags.disable_camera_update;
2912 runData.statustext_time = 0;
2913 m_statustext = msg[flags.disable_camera_update];
2917 void Game::toggleProfiler()
2919 runData.profiler_current_page =
2920 (runData.profiler_current_page + 1) % (runData.profiler_max_page + 1);
2922 // FIXME: This updates the profiler with incomplete values
2923 update_profiler_gui(guitext_profiler, g_fontengine, runData.profiler_current_page,
2924 runData.profiler_max_page, driver->getScreenSize().Height);
2926 if (runData.profiler_current_page != 0) {
2927 std::wstringstream sstr;
2928 sstr << "Profiler shown (page " << runData.profiler_current_page
2929 << " of " << runData.profiler_max_page << ")";
2930 m_statustext = sstr.str();
2932 m_statustext = L"Profiler hidden";
2934 runData.statustext_time = 0;
2938 void Game::increaseViewRange()
2940 s16 range = g_settings->getS16("viewing_range");
2941 s16 range_new = range + 10;
2943 if (range_new > 4000) {
2945 m_statustext = utf8_to_wide("Viewing range is at maximum: "
2948 m_statustext = utf8_to_wide("Viewing range changed to "
2951 g_settings->set("viewing_range", itos(range_new));
2952 runData.statustext_time = 0;
2956 void Game::decreaseViewRange()
2958 s16 range = g_settings->getS16("viewing_range");
2959 s16 range_new = range - 10;
2961 if (range_new < 20) {
2963 m_statustext = utf8_to_wide("Viewing range is at minimum: "
2966 m_statustext = utf8_to_wide("Viewing range changed to "
2969 g_settings->set("viewing_range", itos(range_new));
2970 runData.statustext_time = 0;
2974 void Game::toggleFullViewRange()
2976 static const wchar_t *msg[] = {
2977 L"Disabled full viewing range",
2978 L"Enabled full viewing range"
2981 draw_control->range_all = !draw_control->range_all;
2982 infostream << msg[draw_control->range_all] << std::endl;
2983 m_statustext = msg[draw_control->range_all];
2984 runData.statustext_time = 0;
2988 void Game::updateCameraDirection(CameraOrientation *cam, float dtime)
2990 if ((device->isWindowActive() && device->isWindowFocused()
2991 && !isMenuActive()) || random_input) {
2994 if (!random_input) {
2995 // Mac OSX gets upset if this is set every frame
2996 if (device->getCursorControl()->isVisible())
2997 device->getCursorControl()->setVisible(false);
3001 if (m_first_loop_after_window_activation)
3002 m_first_loop_after_window_activation = false;
3004 updateCameraOrientation(cam, dtime);
3006 input->setMousePos((driver->getScreenSize().Width / 2),
3007 (driver->getScreenSize().Height / 2));
3011 // Mac OSX gets upset if this is set every frame
3012 if (!device->getCursorControl()->isVisible())
3013 device->getCursorControl()->setVisible(true);
3016 m_first_loop_after_window_activation = true;
3021 void Game::updateCameraOrientation(CameraOrientation *cam, float dtime)
3023 #ifdef HAVE_TOUCHSCREENGUI
3024 if (g_touchscreengui) {
3025 cam->camera_yaw += g_touchscreengui->getYawChange();
3026 cam->camera_pitch = g_touchscreengui->getPitch();
3030 s32 dx = input->getMousePos().X - (driver->getScreenSize().Width / 2);
3031 s32 dy = input->getMousePos().Y - (driver->getScreenSize().Height / 2);
3033 if (m_invert_mouse || camera->getCameraMode() == CAMERA_MODE_THIRD_FRONT) {
3037 cam->camera_yaw -= dx * m_cache_mouse_sensitivity;
3038 cam->camera_pitch += dy * m_cache_mouse_sensitivity;
3040 #ifdef HAVE_TOUCHSCREENGUI
3044 if (m_cache_enable_joysticks) {
3045 f32 c = m_cache_joystick_frustum_sensitivity * (1.f / 32767.f) * dtime;
3046 cam->camera_yaw -= input->joystick.getAxisWithoutDead(JA_FRUSTUM_HORIZONTAL) * c;
3047 cam->camera_pitch += input->joystick.getAxisWithoutDead(JA_FRUSTUM_VERTICAL) * c;
3050 cam->camera_pitch = rangelim(cam->camera_pitch, -89.5, 89.5);
3054 void Game::updatePlayerControl(const CameraOrientation &cam)
3056 //TimeTaker tt("update player control", NULL, PRECISION_NANO);
3058 // DO NOT use the isKeyDown method for the forward, backward, left, right
3059 // buttons, as the code that uses the controls needs to be able to
3060 // distinguish between the two in order to know when to use joysticks.
3062 PlayerControl control(
3063 input->isKeyDown(keycache.key[KeyType::FORWARD]),
3064 input->isKeyDown(keycache.key[KeyType::BACKWARD]),
3065 input->isKeyDown(keycache.key[KeyType::LEFT]),
3066 input->isKeyDown(keycache.key[KeyType::RIGHT]),
3067 isKeyDown(KeyType::JUMP),
3068 isKeyDown(KeyType::SPECIAL1),
3069 isKeyDown(KeyType::SNEAK),
3070 isKeyDown(KeyType::ZOOM),
3075 input->joystick.getAxisWithoutDead(JA_SIDEWARD_MOVE),
3076 input->joystick.getAxisWithoutDead(JA_FORWARD_MOVE)
3080 ( (u32)(isKeyDown(KeyType::FORWARD) & 0x1) << 0) |
3081 ( (u32)(isKeyDown(KeyType::BACKWARD) & 0x1) << 1) |
3082 ( (u32)(isKeyDown(KeyType::LEFT) & 0x1) << 2) |
3083 ( (u32)(isKeyDown(KeyType::RIGHT) & 0x1) << 3) |
3084 ( (u32)(isKeyDown(KeyType::JUMP) & 0x1) << 4) |
3085 ( (u32)(isKeyDown(KeyType::SPECIAL1) & 0x1) << 5) |
3086 ( (u32)(isKeyDown(KeyType::SNEAK) & 0x1) << 6) |
3087 ( (u32)(isLeftPressed() & 0x1) << 7) |
3088 ( (u32)(isRightPressed() & 0x1) << 8
3092 /* For Android, simulate holding down AUX1 (fast move) if the user has
3093 * the fast_move setting toggled on. If there is an aux1 key defined for
3094 * Android then its meaning is inverted (i.e. holding aux1 means walk and
3097 if (m_cache_hold_aux1) {
3098 control.aux1 = control.aux1 ^ true;
3099 keypress_bits ^= ((u32)(1U << 5));
3103 client->setPlayerControl(control);
3104 LocalPlayer *player = client->getEnv().getLocalPlayer();
3105 player->keyPressed = keypress_bits;
3111 inline void Game::step(f32 *dtime)
3113 bool can_be_and_is_paused =
3114 (simple_singleplayer_mode && g_menumgr.pausesGame());
3116 if (can_be_and_is_paused) { // This is for a singleplayer server
3117 *dtime = 0; // No time passes
3119 if (server != NULL) {
3120 //TimeTaker timer("server->step(dtime)");
3121 server->step(*dtime);
3124 //TimeTaker timer("client.step(dtime)");
3125 client->step(*dtime);
3130 void Game::processClientEvents(CameraOrientation *cam)
3132 LocalPlayer *player = client->getEnv().getLocalPlayer();
3134 while (client->hasClientEvents()) {
3135 ClientEvent event = client->getClientEvent();
3137 switch (event.type) {
3138 case CE_PLAYER_DAMAGE:
3139 if (client->getHP() == 0)
3141 if (client->moddingEnabled()) {
3142 client->getScript()->on_damage_taken(event.player_damage.amount);
3145 runData.damage_flash += 95.0 + 3.2 * event.player_damage.amount;
3146 runData.damage_flash = MYMIN(runData.damage_flash, 127.0);
3148 player->hurt_tilt_timer = 1.5;
3149 player->hurt_tilt_strength =
3150 rangelim(event.player_damage.amount / 4, 1.0, 4.0);
3152 client->event()->put(new SimpleTriggerEvent("PlayerDamage"));
3155 case CE_PLAYER_FORCE_MOVE:
3156 cam->camera_yaw = event.player_force_move.yaw;
3157 cam->camera_pitch = event.player_force_move.pitch;
3160 case CE_DEATHSCREEN:
3161 // This should be enabled for death formspec in builtin
3162 client->getScript()->on_death();
3164 /* Handle visualization */
3165 runData.damage_flash = 0;
3166 player->hurt_tilt_timer = 0;
3167 player->hurt_tilt_strength = 0;
3170 case CE_SHOW_FORMSPEC:
3171 if (*(event.show_formspec.formspec) == "") {
3172 if (current_formspec && ( *(event.show_formspec.formname) == "" || *(event.show_formspec.formname) == cur_formname) ){
3173 current_formspec->quitMenu();
3176 FormspecFormSource *fs_src =
3177 new FormspecFormSource(*(event.show_formspec.formspec));
3178 TextDestPlayerInventory *txt_dst =
3179 new TextDestPlayerInventory(client, *(event.show_formspec.formname));
3181 create_formspec_menu(¤t_formspec, client, device, &input->joystick,
3183 cur_formname = *(event.show_formspec.formname);
3186 delete event.show_formspec.formspec;
3187 delete event.show_formspec.formname;
3190 case CE_SHOW_LOCAL_FORMSPEC:
3192 FormspecFormSource *fs_src = new FormspecFormSource(*event.show_formspec.formspec);
3193 LocalFormspecHandler *txt_dst = new LocalFormspecHandler(*event.show_formspec.formname, client);
3194 create_formspec_menu(¤t_formspec, client, device, &input->joystick,
3197 delete event.show_formspec.formspec;
3198 delete event.show_formspec.formname;
3201 case CE_SPAWN_PARTICLE:
3202 case CE_ADD_PARTICLESPAWNER:
3203 case CE_DELETE_PARTICLESPAWNER:
3204 client->getParticleManager()->handleParticleEvent(&event, client,
3210 u32 id = event.hudadd.id;
3212 HudElement *e = player->getHud(id);
3215 delete event.hudadd.pos;
3216 delete event.hudadd.name;
3217 delete event.hudadd.scale;
3218 delete event.hudadd.text;
3219 delete event.hudadd.align;
3220 delete event.hudadd.offset;
3221 delete event.hudadd.world_pos;
3222 delete event.hudadd.size;
3227 e->type = (HudElementType)event.hudadd.type;
3228 e->pos = *event.hudadd.pos;
3229 e->name = *event.hudadd.name;
3230 e->scale = *event.hudadd.scale;
3231 e->text = *event.hudadd.text;
3232 e->number = event.hudadd.number;
3233 e->item = event.hudadd.item;
3234 e->dir = event.hudadd.dir;
3235 e->align = *event.hudadd.align;
3236 e->offset = *event.hudadd.offset;
3237 e->world_pos = *event.hudadd.world_pos;
3238 e->size = *event.hudadd.size;
3240 u32 new_id = player->addHud(e);
3241 //if this isn't true our huds aren't consistent
3242 sanity_check(new_id == id);
3245 delete event.hudadd.pos;
3246 delete event.hudadd.name;
3247 delete event.hudadd.scale;
3248 delete event.hudadd.text;
3249 delete event.hudadd.align;
3250 delete event.hudadd.offset;
3251 delete event.hudadd.world_pos;
3252 delete event.hudadd.size;
3257 HudElement *e = player->removeHud(event.hudrm.id);
3265 u32 id = event.hudchange.id;
3266 HudElement *e = player->getHud(id);
3269 delete event.hudchange.v3fdata;
3270 delete event.hudchange.v2fdata;
3271 delete event.hudchange.sdata;
3272 delete event.hudchange.v2s32data;
3276 switch (event.hudchange.stat) {
3278 e->pos = *event.hudchange.v2fdata;
3282 e->name = *event.hudchange.sdata;
3285 case HUD_STAT_SCALE:
3286 e->scale = *event.hudchange.v2fdata;
3290 e->text = *event.hudchange.sdata;
3293 case HUD_STAT_NUMBER:
3294 e->number = event.hudchange.data;
3298 e->item = event.hudchange.data;
3302 e->dir = event.hudchange.data;
3305 case HUD_STAT_ALIGN:
3306 e->align = *event.hudchange.v2fdata;
3309 case HUD_STAT_OFFSET:
3310 e->offset = *event.hudchange.v2fdata;
3313 case HUD_STAT_WORLD_POS:
3314 e->world_pos = *event.hudchange.v3fdata;
3318 e->size = *event.hudchange.v2s32data;
3323 delete event.hudchange.v3fdata;
3324 delete event.hudchange.v2fdata;
3325 delete event.hudchange.sdata;
3326 delete event.hudchange.v2s32data;
3330 sky->setVisible(false);
3331 // Whether clouds are visible in front of a custom skybox
3332 sky->setCloudsEnabled(event.set_sky.clouds);
3339 // Handle according to type
3340 if (*event.set_sky.type == "regular") {
3341 sky->setVisible(true);
3342 sky->setCloudsEnabled(true);
3343 } else if (*event.set_sky.type == "skybox" &&
3344 event.set_sky.params->size() == 6) {
3345 sky->setFallbackBgColor(*event.set_sky.bgcolor);
3346 skybox = smgr->addSkyBoxSceneNode(
3347 texture_src->getTextureForMesh((*event.set_sky.params)[0]),
3348 texture_src->getTextureForMesh((*event.set_sky.params)[1]),
3349 texture_src->getTextureForMesh((*event.set_sky.params)[2]),
3350 texture_src->getTextureForMesh((*event.set_sky.params)[3]),
3351 texture_src->getTextureForMesh((*event.set_sky.params)[4]),
3352 texture_src->getTextureForMesh((*event.set_sky.params)[5]));
3354 // Handle everything else as plain color
3356 if (*event.set_sky.type != "plain")
3357 infostream << "Unknown sky type: "
3358 << (*event.set_sky.type) << std::endl;
3360 sky->setFallbackBgColor(*event.set_sky.bgcolor);
3363 delete event.set_sky.bgcolor;
3364 delete event.set_sky.type;
3365 delete event.set_sky.params;
3368 case CE_OVERRIDE_DAY_NIGHT_RATIO:
3369 client->getEnv().setDayNightRatioOverride(
3370 event.override_day_night_ratio.do_override,
3371 event.override_day_night_ratio.ratio_f * 1000);
3374 case CE_CLOUD_PARAMS:
3376 clouds->setDensity(event.cloud_params.density);
3377 clouds->setColorBright(video::SColor(event.cloud_params.color_bright));
3378 clouds->setColorAmbient(video::SColor(event.cloud_params.color_ambient));
3379 clouds->setHeight(event.cloud_params.height);
3380 clouds->setThickness(event.cloud_params.thickness);
3381 clouds->setSpeed(v2f(
3382 event.cloud_params.speed_x,
3383 event.cloud_params.speed_y));
3388 // unknown or unhandled type
3396 void Game::updateCamera(u32 busy_time, f32 dtime)
3398 LocalPlayer *player = client->getEnv().getLocalPlayer();
3401 For interaction purposes, get info about the held item
3403 - Is it a usable item?
3404 - Can it point to liquids?
3406 ItemStack playeritem;
3408 InventoryList *mlist = local_inventory->getList("main");
3410 if (mlist && client->getPlayerItem() < mlist->getSize())
3411 playeritem = mlist->getItem(client->getPlayerItem());
3414 if (playeritem.getDefinition(itemdef_manager).name.empty()) { // override the hand
3415 InventoryList *hlist = local_inventory->getList("hand");
3417 playeritem = hlist->getItem(0);
3421 ToolCapabilities playeritem_toolcap =
3422 playeritem.getToolCapabilities(itemdef_manager);
3424 v3s16 old_camera_offset = camera->getOffset();
3426 if (wasKeyDown(KeyType::CAMERA_MODE)) {
3427 GenericCAO *playercao = player->getCAO();
3429 // If playercao not loaded, don't change camera
3433 camera->toggleCameraMode();
3435 playercao->setVisible(camera->getCameraMode() > CAMERA_MODE_FIRST);
3436 playercao->setChildrenVisible(camera->getCameraMode() > CAMERA_MODE_FIRST);
3439 float full_punch_interval = playeritem_toolcap.full_punch_interval;
3440 float tool_reload_ratio = runData.time_from_last_punch / full_punch_interval;
3442 tool_reload_ratio = MYMIN(tool_reload_ratio, 1.0);
3443 camera->update(player, dtime, busy_time / 1000.0f, tool_reload_ratio,
3445 camera->step(dtime);
3447 v3f camera_position = camera->getPosition();
3448 v3f camera_direction = camera->getDirection();
3449 f32 camera_fov = camera->getFovMax();
3450 v3s16 camera_offset = camera->getOffset();
3452 m_camera_offset_changed = (camera_offset != old_camera_offset);
3454 if (!flags.disable_camera_update) {
3455 client->getEnv().getClientMap().updateCamera(camera_position,
3456 camera_direction, camera_fov, camera_offset);
3458 if (m_camera_offset_changed) {
3459 client->updateCameraOffset(camera_offset);
3460 client->getEnv().updateCameraOffset(camera_offset);
3463 clouds->updateCameraOffset(camera_offset);
3469 void Game::updateSound(f32 dtime)
3471 // Update sound listener
3472 v3s16 camera_offset = camera->getOffset();
3473 sound->updateListener(camera->getCameraNode()->getPosition() + intToFloat(camera_offset, BS),
3474 v3f(0, 0, 0), // velocity
3475 camera->getDirection(),
3476 camera->getCameraNode()->getUpVector());
3478 // Check if volume is in the proper range, else fix it.
3479 float old_volume = g_settings->getFloat("sound_volume");
3480 float new_volume = rangelim(old_volume, 0.0f, 1.0f);
3481 sound->setListenerGain(new_volume);
3483 if (old_volume != new_volume) {
3484 g_settings->setFloat("sound_volume", new_volume);
3487 LocalPlayer *player = client->getEnv().getLocalPlayer();
3489 // Tell the sound maker whether to make footstep sounds
3490 soundmaker->makes_footstep_sound = player->makes_footstep_sound;
3492 // Update sound maker
3493 if (player->makes_footstep_sound)
3494 soundmaker->step(dtime);
3496 ClientMap &map = client->getEnv().getClientMap();
3497 MapNode n = map.getNodeNoEx(player->getFootstepNodePos());
3498 soundmaker->m_player_step_sound = nodedef_manager->get(n).sound_footstep;
3502 void Game::processPlayerInteraction(f32 dtime, bool show_hud, bool show_debug)
3504 LocalPlayer *player = client->getEnv().getLocalPlayer();
3506 ItemStack playeritem;
3508 InventoryList *mlist = local_inventory->getList("main");
3510 if (mlist && client->getPlayerItem() < mlist->getSize())
3511 playeritem = mlist->getItem(client->getPlayerItem());
3514 const ItemDefinition &playeritem_def =
3515 playeritem.getDefinition(itemdef_manager);
3516 InventoryList *hlist = local_inventory->getList("hand");
3517 const ItemDefinition &hand_def =
3518 hlist ? hlist->getItem(0).getDefinition(itemdef_manager) : itemdef_manager->get("");
3520 v3f player_position = player->getPosition();
3521 v3f camera_position = camera->getPosition();
3522 v3f camera_direction = camera->getDirection();
3523 v3s16 camera_offset = camera->getOffset();
3527 Calculate what block is the crosshair pointing to
3530 f32 d = playeritem_def.range; // max. distance
3531 f32 d_hand = hand_def.range;
3533 if (d < 0 && d_hand >= 0)
3538 core::line3d<f32> shootline;
3540 if (camera->getCameraMode() != CAMERA_MODE_THIRD_FRONT) {
3541 shootline = core::line3d<f32>(camera_position,
3542 camera_position + camera_direction * BS * d);
3544 // prevent player pointing anything in front-view
3545 shootline = core::line3d<f32>(camera_position,camera_position);
3548 #ifdef HAVE_TOUCHSCREENGUI
3550 if ((g_settings->getBool("touchtarget")) && (g_touchscreengui)) {
3551 shootline = g_touchscreengui->getShootline();
3552 shootline.start += intToFloat(camera_offset, BS);
3553 shootline.end += intToFloat(camera_offset, BS);
3558 PointedThing pointed = updatePointedThing(shootline,
3559 playeritem_def.liquids_pointable,
3560 !runData.ldown_for_dig,
3563 if (pointed != runData.pointed_old) {
3564 infostream << "Pointing at " << pointed.dump() << std::endl;
3565 hud->updateSelectionMesh(camera_offset);
3570 - releasing left mouse button
3571 - pointing away from node
3573 if (runData.digging) {
3574 if (getLeftReleased()) {
3575 infostream << "Left button released"
3576 << " (stopped digging)" << std::endl;
3577 runData.digging = false;
3578 } else if (pointed != runData.pointed_old) {
3579 if (pointed.type == POINTEDTHING_NODE
3580 && runData.pointed_old.type == POINTEDTHING_NODE
3581 && pointed.node_undersurface
3582 == runData.pointed_old.node_undersurface) {
3583 // Still pointing to the same node, but a different face.
3586 infostream << "Pointing away from node"
3587 << " (stopped digging)" << std::endl;
3588 runData.digging = false;
3589 hud->updateSelectionMesh(camera_offset);
3593 if (!runData.digging) {
3594 client->interact(1, runData.pointed_old);
3595 client->setCrack(-1, v3s16(0, 0, 0));
3596 runData.dig_time = 0.0;
3598 } else if (runData.dig_instantly && getLeftReleased()) {
3599 // Remove e.g. torches faster when clicking instead of holding LMB
3600 runData.nodig_delay_timer = 0;
3601 runData.dig_instantly = false;
3604 if (!runData.digging && runData.ldown_for_dig && !isLeftPressed()) {
3605 runData.ldown_for_dig = false;
3608 runData.left_punch = false;
3610 soundmaker->m_player_leftpunch_sound.name = "";
3612 if (isRightPressed())
3613 runData.repeat_rightclick_timer += dtime;
3615 runData.repeat_rightclick_timer = 0;
3617 if (playeritem_def.usable && isLeftPressed()) {
3618 if (getLeftClicked() && (!client->moddingEnabled()
3619 || !client->getScript()->on_item_use(playeritem, pointed)))
3620 client->interact(4, pointed);
3621 } else if (pointed.type == POINTEDTHING_NODE) {
3622 ToolCapabilities playeritem_toolcap =
3623 playeritem.getToolCapabilities(itemdef_manager);
3624 if (playeritem.name.empty() && hand_def.tool_capabilities != NULL) {
3625 playeritem_toolcap = *hand_def.tool_capabilities;
3627 handlePointingAtNode(pointed, playeritem_def, playeritem,
3628 playeritem_toolcap, dtime);
3629 } else if (pointed.type == POINTEDTHING_OBJECT) {
3630 handlePointingAtObject(pointed, playeritem, player_position, show_debug);
3631 } else if (isLeftPressed()) {
3632 // When button is held down in air, show continuous animation
3633 runData.left_punch = true;
3634 } else if (getRightClicked()) {
3635 handlePointingAtNothing(playeritem);
3638 runData.pointed_old = pointed;
3640 if (runData.left_punch || getLeftClicked())
3641 camera->setDigging(0); // left click animation
3643 input->resetLeftClicked();
3644 input->resetRightClicked();
3646 input->joystick.clearWasKeyDown(KeyType::MOUSE_L);
3647 input->joystick.clearWasKeyDown(KeyType::MOUSE_R);
3649 input->resetLeftReleased();
3650 input->resetRightReleased();
3652 input->joystick.clearWasKeyReleased(KeyType::MOUSE_L);
3653 input->joystick.clearWasKeyReleased(KeyType::MOUSE_R);
3657 PointedThing Game::updatePointedThing(
3658 const core::line3d<f32> &shootline,
3659 bool liquids_pointable,
3660 bool look_for_object,
3661 const v3s16 &camera_offset)
3663 std::vector<aabb3f> *selectionboxes = hud->getSelectionBoxes();
3664 selectionboxes->clear();
3665 hud->setSelectedFaceNormal(v3f(0.0, 0.0, 0.0));
3666 static thread_local const bool show_entity_selectionbox = g_settings->getBool(
3667 "show_entity_selectionbox");
3669 ClientMap &map = client->getEnv().getClientMap();
3670 INodeDefManager *nodedef=client->getNodeDefManager();
3672 runData.selected_object = NULL;
3674 PointedThing result=client->getEnv().getPointedThing(
3675 shootline, liquids_pointable, look_for_object);
3676 if (result.type == POINTEDTHING_OBJECT) {
3677 runData.selected_object = client->getEnv().getActiveObject(result.object_id);
3678 if (show_entity_selectionbox && runData.selected_object->doShowSelectionBox()) {
3679 aabb3f *selection_box = runData.selected_object->getSelectionBox();
3681 // Box should exist because object was
3682 // returned in the first place
3684 assert(selection_box);
3686 v3f pos = runData.selected_object->getPosition();
3687 selectionboxes->push_back(aabb3f(
3688 selection_box->MinEdge, selection_box->MaxEdge));
3689 selectionboxes->push_back(
3690 aabb3f(selection_box->MinEdge, selection_box->MaxEdge));
3691 hud->setSelectionPos(pos, camera_offset);
3693 } else if (result.type == POINTEDTHING_NODE) {
3694 // Update selection boxes
3695 MapNode n = map.getNodeNoEx(result.node_undersurface);
3696 std::vector<aabb3f> boxes;
3697 n.getSelectionBoxes(nodedef, &boxes,
3698 n.getNeighbors(result.node_undersurface, &map));
3701 for (std::vector<aabb3f>::const_iterator i = boxes.begin();
3702 i != boxes.end(); ++i) {
3704 box.MinEdge -= v3f(d, d, d);
3705 box.MaxEdge += v3f(d, d, d);
3706 selectionboxes->push_back(box);
3708 hud->setSelectionPos(intToFloat(result.node_undersurface, BS),
3710 hud->setSelectedFaceNormal(v3f(
3711 result.intersection_normal.X,
3712 result.intersection_normal.Y,
3713 result.intersection_normal.Z));
3716 // Update selection mesh light level and vertex colors
3717 if (selectionboxes->size() > 0) {
3718 v3f pf = hud->getSelectionPos();
3719 v3s16 p = floatToInt(pf, BS);
3721 // Get selection mesh light level
3722 MapNode n = map.getNodeNoEx(p);
3723 u16 node_light = getInteriorLight(n, -1, nodedef);
3724 u16 light_level = node_light;
3726 for (u8 i = 0; i < 6; i++) {
3727 n = map.getNodeNoEx(p + g_6dirs[i]);
3728 node_light = getInteriorLight(n, -1, nodedef);
3729 if (node_light > light_level)
3730 light_level = node_light;
3733 u32 daynight_ratio = client->getEnv().getDayNightRatio();
3735 final_color_blend(&c, light_level, daynight_ratio);
3737 // Modify final color a bit with time
3738 u32 timer = porting::getTimeMs() % 5000;
3739 float timerf = (float) (irr::core::PI * ((timer / 2500.0) - 0.5));
3740 float sin_r = 0.08 * sin(timerf);
3741 float sin_g = 0.08 * sin(timerf + irr::core::PI * 0.5);
3742 float sin_b = 0.08 * sin(timerf + irr::core::PI);
3743 c.setRed(core::clamp(core::round32(c.getRed() * (0.8 + sin_r)), 0, 255));
3744 c.setGreen(core::clamp(core::round32(c.getGreen() * (0.8 + sin_g)), 0, 255));
3745 c.setBlue(core::clamp(core::round32(c.getBlue() * (0.8 + sin_b)), 0, 255));
3747 // Set mesh final color
3748 hud->setSelectionMeshColor(c);
3754 void Game::handlePointingAtNothing(const ItemStack &playerItem)
3756 infostream << "Right Clicked in Air" << std::endl;
3757 PointedThing fauxPointed;
3758 fauxPointed.type = POINTEDTHING_NOTHING;
3759 client->interact(5, fauxPointed);
3763 void Game::handlePointingAtNode(const PointedThing &pointed,
3764 const ItemDefinition &playeritem_def, const ItemStack &playeritem,
3765 const ToolCapabilities &playeritem_toolcap, f32 dtime)
3767 v3s16 nodepos = pointed.node_undersurface;
3768 v3s16 neighbourpos = pointed.node_abovesurface;
3771 Check information text of node
3774 ClientMap &map = client->getEnv().getClientMap();
3776 if (runData.nodig_delay_timer <= 0.0 && isLeftPressed()
3777 && client->checkPrivilege("interact")) {
3778 handleDigging(pointed, nodepos, playeritem_toolcap, dtime);
3781 // This should be done after digging handling
3782 NodeMetadata *meta = map.getNodeMetadata(nodepos);
3785 infotext = unescape_enriched(utf8_to_wide(meta->getString("infotext")));
3787 MapNode n = map.getNodeNoEx(nodepos);
3789 if (nodedef_manager->get(n).tiledef[0].name == "unknown_node.png") {
3790 infotext = L"Unknown node: ";
3791 infotext += utf8_to_wide(nodedef_manager->get(n).name);
3795 if ((getRightClicked() ||
3796 runData.repeat_rightclick_timer >= m_repeat_right_click_time) &&
3797 client->checkPrivilege("interact")) {
3798 runData.repeat_rightclick_timer = 0;
3799 infostream << "Ground right-clicked" << std::endl;
3801 if (meta && meta->getString("formspec") != "" && !random_input
3802 && !isKeyDown(KeyType::SNEAK)) {
3803 infostream << "Launching custom inventory view" << std::endl;
3805 InventoryLocation inventoryloc;
3806 inventoryloc.setNodeMeta(nodepos);
3808 NodeMetadataFormSource *fs_src = new NodeMetadataFormSource(
3809 &client->getEnv().getClientMap(), nodepos);
3810 TextDest *txt_dst = new TextDestNodeMetadata(nodepos, client);
3812 create_formspec_menu(¤t_formspec, client,
3813 device, &input->joystick, fs_src, txt_dst);
3816 current_formspec->setFormSpec(meta->getString("formspec"), inventoryloc);
3818 // Report right click to server
3820 camera->setDigging(1); // right click animation (always shown for feedback)
3822 // If the wielded item has node placement prediction,
3824 bool placed = nodePlacementPrediction(*client,
3825 playeritem_def, playeritem,
3826 nodepos, neighbourpos);
3830 client->interact(3, pointed);
3832 soundmaker->m_player_rightpunch_sound =
3833 playeritem_def.sound_place;
3835 if (client->moddingEnabled())
3836 client->getScript()->on_placenode(pointed, playeritem_def);
3838 soundmaker->m_player_rightpunch_sound =
3841 if (playeritem_def.node_placement_prediction == "" ||
3842 nodedef_manager->get(map.getNodeNoEx(nodepos)).rightclickable) {
3843 client->interact(3, pointed); // Report to server
3845 soundmaker->m_player_rightpunch_sound =
3846 playeritem_def.sound_place_failed;
3854 void Game::handlePointingAtObject(const PointedThing &pointed, const ItemStack &playeritem,
3855 const v3f &player_position, bool show_debug)
3857 infotext = unescape_enriched(
3858 utf8_to_wide(runData.selected_object->infoText()));
3861 if (infotext != L"") {
3864 infotext += unescape_enriched(utf8_to_wide(
3865 runData.selected_object->debugInfoText()));
3868 if (isLeftPressed()) {
3869 bool do_punch = false;
3870 bool do_punch_damage = false;
3872 if (runData.object_hit_delay_timer <= 0.0) {
3874 do_punch_damage = true;
3875 runData.object_hit_delay_timer = object_hit_delay;
3878 if (getLeftClicked())
3882 infostream << "Left-clicked object" << std::endl;
3883 runData.left_punch = true;
3886 if (do_punch_damage) {
3887 // Report direct punch
3888 v3f objpos = runData.selected_object->getPosition();
3889 v3f dir = (objpos - player_position).normalize();
3890 ItemStack item = playeritem;
3891 if (playeritem.name.empty()) {
3892 InventoryList *hlist = local_inventory->getList("hand");
3894 item = hlist->getItem(0);
3898 bool disable_send = runData.selected_object->directReportPunch(
3899 dir, &item, runData.time_from_last_punch);
3900 runData.time_from_last_punch = 0;
3903 client->interact(0, pointed);
3905 } else if (getRightClicked()) {
3906 infostream << "Right-clicked object" << std::endl;
3907 client->interact(3, pointed); // place
3912 void Game::handleDigging(const PointedThing &pointed, const v3s16 &nodepos,
3913 const ToolCapabilities &playeritem_toolcap, f32 dtime)
3915 LocalPlayer *player = client->getEnv().getLocalPlayer();
3916 ClientMap &map = client->getEnv().getClientMap();
3917 MapNode n = client->getEnv().getClientMap().getNodeNoEx(nodepos);
3919 // NOTE: Similar piece of code exists on the server side for
3921 // Get digging parameters
3922 DigParams params = getDigParams(nodedef_manager->get(n).groups,
3923 &playeritem_toolcap);
3925 // If can't dig, try hand
3926 if (!params.diggable) {
3927 InventoryList *hlist = local_inventory->getList("hand");
3928 const ItemDefinition &hand =
3929 hlist ? hlist->getItem(0).getDefinition(itemdef_manager) : itemdef_manager->get("");
3930 const ToolCapabilities *tp = hand.tool_capabilities;
3933 params = getDigParams(nodedef_manager->get(n).groups, tp);
3936 if (!params.diggable) {
3937 // I guess nobody will wait for this long
3938 runData.dig_time_complete = 10000000.0;
3940 runData.dig_time_complete = params.time;
3942 if (m_cache_enable_particles) {
3943 const ContentFeatures &features =
3944 client->getNodeDefManager()->get(n);
3945 client->getParticleManager()->addPunchingParticles(client, smgr,
3946 player, nodepos, n, features);
3950 if (!runData.digging) {
3951 infostream << "Started digging" << std::endl;
3952 runData.dig_instantly = runData.dig_time_complete == 0;
3953 if (client->moddingEnabled() && client->getScript()->on_punchnode(nodepos, n))
3955 client->interact(0, pointed);
3956 runData.digging = true;
3957 runData.ldown_for_dig = true;
3960 if (!runData.dig_instantly) {
3961 runData.dig_index = (float)crack_animation_length
3963 / runData.dig_time_complete;
3965 // This is for e.g. torches
3966 runData.dig_index = crack_animation_length;
3969 SimpleSoundSpec sound_dig = nodedef_manager->get(n).sound_dig;
3971 if (sound_dig.exists() && params.diggable) {
3972 if (sound_dig.name == "__group") {
3973 if (params.main_group != "") {
3974 soundmaker->m_player_leftpunch_sound.gain = 0.5;
3975 soundmaker->m_player_leftpunch_sound.name =
3976 std::string("default_dig_") +
3980 soundmaker->m_player_leftpunch_sound = sound_dig;
3984 // Don't show cracks if not diggable
3985 if (runData.dig_time_complete >= 100000.0) {
3986 } else if (runData.dig_index < crack_animation_length) {
3987 //TimeTaker timer("client.setTempMod");
3988 //infostream<<"dig_index="<<dig_index<<std::endl;
3989 client->setCrack(runData.dig_index, nodepos);
3991 infostream << "Digging completed" << std::endl;
3992 client->setCrack(-1, v3s16(0, 0, 0));
3994 runData.dig_time = 0;
3995 runData.digging = false;
3997 runData.nodig_delay_timer =
3998 runData.dig_time_complete / (float)crack_animation_length;
4000 // We don't want a corresponding delay to very time consuming nodes
4001 // and nodes without digging time (e.g. torches) get a fixed delay.
4002 if (runData.nodig_delay_timer > 0.3)
4003 runData.nodig_delay_timer = 0.3;
4004 else if (runData.dig_instantly)
4005 runData.nodig_delay_timer = 0.15;
4007 bool is_valid_position;
4008 MapNode wasnode = map.getNodeNoEx(nodepos, &is_valid_position);
4009 if (is_valid_position) {
4010 if (client->moddingEnabled() &&
4011 client->getScript()->on_dignode(nodepos, wasnode)) {
4014 client->removeNode(nodepos);
4017 client->interact(2, pointed);
4019 if (m_cache_enable_particles) {
4020 const ContentFeatures &features =
4021 client->getNodeDefManager()->get(wasnode);
4022 client->getParticleManager()->addDiggingParticles(client, smgr,
4023 player, nodepos, wasnode, features);
4027 // Send event to trigger sound
4028 MtEvent *e = new NodeDugEvent(nodepos, wasnode);
4029 client->event()->put(e);
4032 if (runData.dig_time_complete < 100000.0) {
4033 runData.dig_time += dtime;
4035 runData.dig_time = 0;
4036 client->setCrack(-1, nodepos);
4039 camera->setDigging(0); // left click animation
4043 void Game::updateFrame(ProfilerGraph *graph, RunStats *stats, f32 dtime,
4044 const CameraOrientation &cam)
4046 LocalPlayer *player = client->getEnv().getLocalPlayer();
4052 if (draw_control->range_all) {
4053 runData.fog_range = 100000 * BS;
4055 runData.fog_range = draw_control->wanted_range * BS;
4059 Calculate general brightness
4061 u32 daynight_ratio = client->getEnv().getDayNightRatio();
4062 float time_brightness = decode_light_f((float)daynight_ratio / 1000.0);
4063 float direct_brightness;
4066 if (m_cache_enable_noclip && m_cache_enable_free_move) {
4067 direct_brightness = time_brightness;
4068 sunlight_seen = true;
4070 ScopeProfiler sp(g_profiler, "Detecting background light", SPT_AVG);
4071 float old_brightness = sky->getBrightness();
4072 direct_brightness = client->getEnv().getClientMap()
4073 .getBackgroundBrightness(MYMIN(runData.fog_range * 1.2, 60 * BS),
4074 daynight_ratio, (int)(old_brightness * 255.5), &sunlight_seen)
4078 float time_of_day_smooth = runData.time_of_day_smooth;
4079 float time_of_day = client->getEnv().getTimeOfDayF();
4081 static const float maxsm = 0.05;
4082 static const float todsm = 0.05;
4084 if (fabs(time_of_day - time_of_day_smooth) > maxsm &&
4085 fabs(time_of_day - time_of_day_smooth + 1.0) > maxsm &&
4086 fabs(time_of_day - time_of_day_smooth - 1.0) > maxsm)
4087 time_of_day_smooth = time_of_day;
4089 if (time_of_day_smooth > 0.8 && time_of_day < 0.2)
4090 time_of_day_smooth = time_of_day_smooth * (1.0 - todsm)
4091 + (time_of_day + 1.0) * todsm;
4093 time_of_day_smooth = time_of_day_smooth * (1.0 - todsm)
4094 + time_of_day * todsm;
4096 runData.time_of_day = time_of_day;
4097 runData.time_of_day_smooth = time_of_day_smooth;
4099 sky->update(time_of_day_smooth, time_brightness, direct_brightness,
4100 sunlight_seen, camera->getCameraMode(), player->getYaw(),
4101 player->getPitch());
4107 v3f player_position = player->getPosition();
4108 if (sky->getCloudsVisible()) {
4109 clouds->setVisible(true);
4110 clouds->step(dtime);
4111 clouds->update(v2f(player_position.X, player_position.Z),
4112 sky->getCloudColor());
4114 clouds->setVisible(false);
4121 client->getParticleManager()->step(dtime);
4127 if (m_cache_enable_fog && !flags.force_fog_off) {
4130 video::EFT_FOG_LINEAR,
4131 runData.fog_range * m_cache_fog_start,
4132 runData.fog_range * 1.0,
4140 video::EFT_FOG_LINEAR,
4150 Get chat messages from client
4153 v2u32 screensize = driver->getScreenSize();
4155 updateChat(*client, dtime, flags.show_debug, screensize,
4156 flags.show_chat, runData.profiler_current_page,
4157 *chat_backend, guitext_chat);
4163 if (client->getPlayerItem() != runData.new_playeritem)
4164 client->selectPlayerItem(runData.new_playeritem);
4166 // Update local inventory if it has changed
4167 if (client->getLocalInventoryUpdated()) {
4168 //infostream<<"Updating local inventory"<<std::endl;
4169 client->getLocalInventory(*local_inventory);
4170 runData.update_wielded_item_trigger = true;
4173 if (runData.update_wielded_item_trigger) {
4174 // Update wielded tool
4175 InventoryList *mlist = local_inventory->getList("main");
4177 if (mlist && (client->getPlayerItem() < mlist->getSize())) {
4178 ItemStack item = mlist->getItem(client->getPlayerItem());
4179 if (item.getDefinition(itemdef_manager).name.empty()) { // override the hand
4180 InventoryList *hlist = local_inventory->getList("hand");
4182 item = hlist->getItem(0);
4184 camera->wield(item);
4187 runData.update_wielded_item_trigger = false;
4191 Update block draw list every 200ms or when camera direction has
4194 runData.update_draw_list_timer += dtime;
4196 v3f camera_direction = camera->getDirection();
4197 if (runData.update_draw_list_timer >= 0.2
4198 || runData.update_draw_list_last_cam_dir.getDistanceFrom(camera_direction) > 0.2
4199 || m_camera_offset_changed) {
4200 runData.update_draw_list_timer = 0;
4201 client->getEnv().getClientMap().updateDrawList(driver);
4202 runData.update_draw_list_last_cam_dir = camera_direction;
4205 updateGui(*stats, dtime, cam);
4208 make sure menu is on top
4209 1. Delete formspec menu reference if menu was removed
4210 2. Else, make sure formspec menu is on top
4212 if (current_formspec) {
4213 if (current_formspec->getReferenceCount() == 1) {
4214 current_formspec->drop();
4215 current_formspec = NULL;
4216 } else if (isMenuActive()) {
4217 guiroot->bringToFront(current_formspec);
4225 const video::SColor &skycolor = sky->getSkyColor();
4227 TimeTaker tt_draw("mainloop: draw");
4228 driver->beginScene(true, true, skycolor);
4230 draw_scene(driver, smgr, *camera, *client, player, *hud, mapper,
4231 guienv, screensize, skycolor, flags.show_hud,
4232 flags.show_minimap);
4237 if (flags.show_profiler_graph)
4238 graph->draw(10, screensize.Y - 10, driver, g_fontengine->getFont());
4243 if (runData.damage_flash > 0.0) {
4244 video::SColor color(runData.damage_flash, 180, 0, 0);
4245 driver->draw2DRectangle(color,
4246 core::rect<s32>(0, 0, screensize.X, screensize.Y),
4249 runData.damage_flash -= 100.0 * dtime;
4255 if (player->hurt_tilt_timer > 0.0) {
4256 player->hurt_tilt_timer -= dtime * 5;
4258 if (player->hurt_tilt_timer < 0)
4259 player->hurt_tilt_strength = 0;
4263 Update minimap pos and rotation
4265 if (mapper && flags.show_minimap && flags.show_hud) {
4266 mapper->setPos(floatToInt(player->getPosition(), BS));
4267 mapper->setAngle(player->getYaw());
4275 stats->drawtime = tt_draw.stop(true);
4276 g_profiler->graphAdd("mainloop_draw", stats->drawtime / 1000.0f);
4280 inline static const char *yawToDirectionString(int yaw)
4282 static const char *direction[4] = {"North [+Z]", "West [-X]", "South [-Z]", "East [+X]"};
4284 yaw = wrapDegrees_0_360(yaw);
4285 yaw = (yaw + 45) % 360 / 90;
4287 return direction[yaw];
4291 void Game::updateGui(const RunStats &stats, f32 dtime, const CameraOrientation &cam)
4293 v2u32 screensize = driver->getScreenSize();
4294 LocalPlayer *player = client->getEnv().getLocalPlayer();
4295 v3f player_position = player->getPosition();
4297 if (flags.show_debug) {
4298 static float drawtime_avg = 0;
4299 drawtime_avg = drawtime_avg * 0.95 + stats.drawtime * 0.05;
4301 u16 fps = 1.0 / stats.dtime_jitter.avg;
4303 std::ostringstream os(std::ios_base::binary);
4305 << PROJECT_NAME_C " " << g_version_hash
4307 << " (R: range_all=" << draw_control->range_all << ")"
4308 << std::setprecision(0)
4309 << " drawtime = " << drawtime_avg
4310 << std::setprecision(1)
4311 << ", dtime_jitter = "
4312 << (stats.dtime_jitter.max_fraction * 100.0) << " %"
4313 << std::setprecision(1)
4314 << ", v_range = " << draw_control->wanted_range
4315 << std::setprecision(3)
4316 << ", RTT = " << client->getRTT();
4317 setStaticText(guitext, utf8_to_wide(os.str()).c_str());
4318 guitext->setVisible(true);
4320 guitext->setVisible(false);
4323 if (guitext->isVisible()) {
4324 core::rect<s32> rect(
4326 screensize.X, 5 + g_fontengine->getTextHeight()
4328 guitext->setRelativePosition(rect);
4331 if (flags.show_debug) {
4332 std::ostringstream os(std::ios_base::binary);
4333 os << std::setprecision(1) << std::fixed
4334 << "(" << (player_position.X / BS)
4335 << ", " << (player_position.Y / BS)
4336 << ", " << (player_position.Z / BS)
4337 << ") (yaw=" << (wrapDegrees_0_360(cam.camera_yaw))
4338 << " " << yawToDirectionString(cam.camera_yaw)
4339 << ") (seed = " << ((u64)client->getMapSeed())
4342 if (runData.pointed_old.type == POINTEDTHING_NODE) {
4343 ClientMap &map = client->getEnv().getClientMap();
4344 const INodeDefManager *nodedef = client->getNodeDefManager();
4345 MapNode n = map.getNodeNoEx(runData.pointed_old.node_undersurface);
4346 if (n.getContent() != CONTENT_IGNORE && nodedef->get(n).name != "unknown") {
4347 const ContentFeatures &features = nodedef->get(n);
4348 os << " (pointing_at = " << nodedef->get(n).name
4349 << " - " << features.tiledef[0].name.c_str()
4354 setStaticText(guitext2, utf8_to_wide(os.str()).c_str());
4355 guitext2->setVisible(true);
4357 core::rect<s32> rect(
4358 5, 5 + g_fontengine->getTextHeight(),
4359 screensize.X, 5 + g_fontengine->getTextHeight() * 2
4361 guitext2->setRelativePosition(rect);
4363 guitext2->setVisible(false);
4366 setStaticText(guitext_info, infotext.c_str());
4367 guitext_info->setVisible(flags.show_hud && g_menumgr.menuCount() == 0);
4369 float statustext_time_max = 1.5;
4371 if (!m_statustext.empty()) {
4372 runData.statustext_time += dtime;
4374 if (runData.statustext_time >= statustext_time_max) {
4376 runData.statustext_time = 0;
4380 setStaticText(guitext_status, m_statustext.c_str());
4381 guitext_status->setVisible(!m_statustext.empty());
4383 if (!m_statustext.empty()) {
4384 s32 status_width = guitext_status->getTextWidth();
4385 s32 status_height = guitext_status->getTextHeight();
4386 s32 status_y = screensize.Y - 150;
4387 s32 status_x = (screensize.X - status_width) / 2;
4388 core::rect<s32> rect(
4389 status_x , status_y - status_height,
4390 status_x + status_width, status_y
4392 guitext_status->setRelativePosition(rect);
4395 video::SColor initial_color(255, 0, 0, 0);
4397 if (guienv->getSkin())
4398 initial_color = guienv->getSkin()->getColor(gui::EGDC_BUTTON_TEXT);
4400 video::SColor final_color = initial_color;
4401 final_color.setAlpha(0);
4402 video::SColor fade_color = initial_color.getInterpolated_quadratic(
4403 initial_color, final_color,
4404 pow(runData.statustext_time / statustext_time_max, 2.0f));
4405 guitext_status->setOverrideColor(fade_color);
4406 guitext_status->enableOverrideColor(true);
4411 /* Log times and stuff for visualization */
4412 inline void Game::updateProfilerGraphs(ProfilerGraph *graph)
4414 Profiler::GraphValues values;
4415 g_profiler->graphGet(values);
4421 /****************************************************************************
4423 ****************************************************************************/
4425 /* On some computers framerate doesn't seem to be automatically limited
4427 inline void Game::limitFps(FpsControl *fps_timings, f32 *dtime)
4429 // not using getRealTime is necessary for wine
4430 device->getTimer()->tick(); // Maker sure device time is up-to-date
4431 u32 time = device->getTimer()->getTime();
4432 u32 last_time = fps_timings->last_time;
4434 if (time > last_time) // Make sure time hasn't overflowed
4435 fps_timings->busy_time = time - last_time;
4437 fps_timings->busy_time = 0;
4439 u32 frametime_min = 1000 / (g_menumgr.pausesGame()
4440 ? g_settings->getFloat("pause_fps_max")
4441 : g_settings->getFloat("fps_max"));
4443 if (fps_timings->busy_time < frametime_min) {
4444 fps_timings->sleep_time = frametime_min - fps_timings->busy_time;
4445 device->sleep(fps_timings->sleep_time);
4447 fps_timings->sleep_time = 0;
4450 /* Get the new value of the device timer. Note that device->sleep() may
4451 * not sleep for the entire requested time as sleep may be interrupted and
4452 * therefore it is arguably more accurate to get the new time from the
4453 * device rather than calculating it by adding sleep_time to time.
4456 device->getTimer()->tick(); // Update device timer
4457 time = device->getTimer()->getTime();
4459 if (time > last_time) // Make sure last_time hasn't overflowed
4460 *dtime = (time - last_time) / 1000.0;
4464 fps_timings->last_time = time;
4467 // Note: This will free (using delete[])! \p msg. If you want to use it later,
4468 // pass a copy of it to this function
4469 // Note: \p msg must be allocated using new (not malloc())
4470 void Game::showOverlayMessage(const wchar_t *msg, float dtime,
4471 int percent, bool draw_clouds)
4473 draw_load_screen(msg, device, guienv, texture_src, dtime, percent,
4478 void Game::settingChangedCallback(const std::string &setting_name, void *data)
4480 ((Game *)data)->readSettings();
4483 void Game::readSettings()
4485 m_cache_doubletap_jump = g_settings->getBool("doubletap_jump");
4486 m_cache_enable_clouds = g_settings->getBool("enable_clouds");
4487 m_cache_enable_joysticks = g_settings->getBool("enable_joysticks");
4488 m_cache_enable_particles = g_settings->getBool("enable_particles");
4489 m_cache_enable_fog = g_settings->getBool("enable_fog");
4490 m_cache_mouse_sensitivity = g_settings->getFloat("mouse_sensitivity");
4491 m_cache_joystick_frustum_sensitivity = g_settings->getFloat("joystick_frustum_sensitivity");
4492 m_repeat_right_click_time = g_settings->getFloat("repeat_rightclick_time");
4494 m_cache_enable_noclip = g_settings->getBool("noclip");
4495 m_cache_enable_free_move = g_settings->getBool("free_move");
4497 m_cache_fog_start = g_settings->getFloat("fog_start");
4499 m_cache_cam_smoothing = 0;
4500 if (g_settings->getBool("cinematic"))
4501 m_cache_cam_smoothing = 1 - g_settings->getFloat("cinematic_camera_smoothing");
4503 m_cache_cam_smoothing = 1 - g_settings->getFloat("camera_smoothing");
4505 m_cache_fog_start = rangelim(m_cache_fog_start, 0.0f, 0.99f);
4506 m_cache_cam_smoothing = rangelim(m_cache_cam_smoothing, 0.01f, 1.0f);
4507 m_cache_mouse_sensitivity = rangelim(m_cache_mouse_sensitivity, 0.001, 100.0);
4511 /****************************************************************************/
4512 /****************************************************************************
4514 ****************************************************************************/
4515 /****************************************************************************/
4517 void Game::extendedResourceCleanup()
4519 // Extended resource accounting
4520 infostream << "Irrlicht resources after cleanup:" << std::endl;
4521 infostream << "\tRemaining meshes : "
4522 << device->getSceneManager()->getMeshCache()->getMeshCount() << std::endl;
4523 infostream << "\tRemaining textures : "
4524 << driver->getTextureCount() << std::endl;
4526 for (unsigned int i = 0; i < driver->getTextureCount(); i++) {
4527 irr::video::ITexture *texture = driver->getTextureByIndex(i);
4528 infostream << "\t\t" << i << ":" << texture->getName().getPath().c_str()
4532 clearTextureNameCache();
4533 infostream << "\tRemaining materials: "
4534 << driver-> getMaterialRendererCount()
4535 << " (note: irrlicht doesn't support removing renderers)" << std::endl;
4538 #define GET_KEY_NAME(KEY) gettext(getKeySetting(#KEY).name())
4539 void Game::showPauseMenu()
4542 static const std::string control_text = strgettext("Default Controls:\n"
4543 "No menu visible:\n"
4544 "- single tap: button activate\n"
4545 "- double tap: place/use\n"
4546 "- slide finger: look around\n"
4547 "Menu/Inventory visible:\n"
4548 "- double tap (outside):\n"
4550 "- touch stack, touch slot:\n"
4552 "- touch&drag, tap 2nd finger\n"
4553 " --> place single item to slot\n"
4556 static const std::string control_text_template = strgettext("Controls:\n"
4557 "- %s: move forwards\n"
4558 "- %s: move backwards\n"
4560 "- %s: move right\n"
4561 "- %s: jump/climb\n"
4562 "- %s: sneak/go down\n"
4565 "- Mouse: turn/look\n"
4566 "- Mouse left: dig/punch\n"
4567 "- Mouse right: place/use\n"
4568 "- Mouse wheel: select item\n"
4572 char control_text_buf[600];
4574 snprintf(control_text_buf, ARRLEN(control_text_buf), control_text_template.c_str(),
4575 GET_KEY_NAME(keymap_forward),
4576 GET_KEY_NAME(keymap_backward),
4577 GET_KEY_NAME(keymap_left),
4578 GET_KEY_NAME(keymap_right),
4579 GET_KEY_NAME(keymap_jump),
4580 GET_KEY_NAME(keymap_sneak),
4581 GET_KEY_NAME(keymap_drop),
4582 GET_KEY_NAME(keymap_inventory),
4583 GET_KEY_NAME(keymap_chat)
4586 std::string control_text = std::string(control_text_buf);
4587 str_formspec_escape(control_text);
4590 float ypos = simple_singleplayer_mode ? 0.7f : 0.1f;
4591 std::ostringstream os;
4593 os << FORMSPEC_VERSION_STRING << SIZE_TAG
4594 << "button_exit[4," << (ypos++) << ";3,0.5;btn_continue;"
4595 << strgettext("Continue") << "]";
4597 if (!simple_singleplayer_mode) {
4598 os << "button_exit[4," << (ypos++) << ";3,0.5;btn_change_password;"
4599 << strgettext("Change Password") << "]";
4601 os << "field[4.95,0;5,1.5;;" << strgettext("Game paused") << ";]";
4605 os << "button_exit[4," << (ypos++) << ";3,0.5;btn_sound;"
4606 << strgettext("Sound Volume") << "]";
4607 os << "button_exit[4," << (ypos++) << ";3,0.5;btn_key_config;"
4608 << strgettext("Change Keys") << "]";
4610 os << "button_exit[4," << (ypos++) << ";3,0.5;btn_exit_menu;"
4611 << strgettext("Exit to Menu") << "]";
4612 os << "button_exit[4," << (ypos++) << ";3,0.5;btn_exit_os;"
4613 << strgettext("Exit to OS") << "]"
4614 << "textarea[7.5,0.25;3.9,6.25;;" << control_text << ";]"
4615 << "textarea[0.4,0.25;3.9,6.25;;" << PROJECT_NAME_C " " VERSION_STRING "\n"
4617 << strgettext("Game info:") << "\n";
4618 const std::string &address = client->getAddressName();
4619 static const std::string mode = strgettext("- Mode: ");
4620 if (!simple_singleplayer_mode) {
4621 Address serverAddress = client->getServerAddress();
4622 if (address != "") {
4623 os << mode << strgettext("Remote server") << "\n"
4624 << strgettext("- Address: ") << address;
4626 os << mode << strgettext("Hosting server");
4628 os << "\n" << strgettext("- Port: ") << serverAddress.getPort() << "\n";
4630 os << mode << strgettext("Singleplayer") << "\n";
4632 if (simple_singleplayer_mode || address == "") {
4633 static const std::string on = strgettext("On");
4634 static const std::string off = strgettext("Off");
4635 const std::string &damage = g_settings->getBool("enable_damage") ? on : off;
4636 const std::string &creative = g_settings->getBool("creative_mode") ? on : off;
4637 const std::string &announced = g_settings->getBool("server_announce") ? on : off;
4638 os << strgettext("- Damage: ") << damage << "\n"
4639 << strgettext("- Creative Mode: ") << creative << "\n";
4640 if (!simple_singleplayer_mode) {
4641 const std::string &pvp = g_settings->getBool("enable_pvp") ? on : off;
4642 os << strgettext("- PvP: ") << pvp << "\n"
4643 << strgettext("- Public: ") << announced << "\n";
4644 std::string server_name = g_settings->get("server_name");
4645 str_formspec_escape(server_name);
4646 if (announced == on && server_name != "")
4647 os << strgettext("- Server Name: ") << server_name;
4654 /* Note: FormspecFormSource and LocalFormspecHandler *
4655 * are deleted by guiFormSpecMenu */
4656 FormspecFormSource *fs_src = new FormspecFormSource(os.str());
4657 LocalFormspecHandler *txt_dst = new LocalFormspecHandler("MT_PAUSE_MENU");
4659 create_formspec_menu(¤t_formspec, client, device, &input->joystick, fs_src, txt_dst);
4660 current_formspec->setFocus("btn_continue");
4661 current_formspec->doPause = true;
4664 /****************************************************************************/
4665 /****************************************************************************
4666 extern function for launching the game
4667 ****************************************************************************/
4668 /****************************************************************************/
4670 void the_game(bool *kill,
4672 InputHandler *input,
4673 IrrlichtDevice *device,
4675 const std::string &map_dir,
4676 const std::string &playername,
4677 const std::string &password,
4678 const std::string &address, // If empty local server is created
4681 std::string &error_message,
4682 ChatBackend &chat_backend,
4683 bool *reconnect_requested,
4684 const SubgameSpec &gamespec, // Used for local game
4685 bool simple_singleplayer_mode)
4689 /* Make a copy of the server address because if a local singleplayer server
4690 * is created then this is updated and we don't want to change the value
4691 * passed to us by the calling function
4693 std::string server_address = address;
4697 if (game.startup(kill, random_input, input, device, map_dir,
4698 playername, password, &server_address, port, error_message,
4699 reconnect_requested, &chat_backend, gamespec,
4700 simple_singleplayer_mode)) {
4705 } catch (SerializationError &e) {
4706 error_message = std::string("A serialization error occurred:\n")
4707 + e.what() + "\n\nThe server is probably "
4708 " running a different version of " PROJECT_NAME_C ".";
4709 errorstream << error_message << std::endl;
4710 } catch (ServerError &e) {
4711 error_message = e.what();
4712 errorstream << "ServerError: " << error_message << std::endl;
4713 } catch (ModError &e) {
4714 error_message = e.what() + strgettext("\nCheck debug.txt for details.");
4715 errorstream << "ModError: " << error_message << std::endl;