3 Copyright (C) 2010-2013 celeron55, Perttu Ahola <celeron55@gmail.com>
5 This program is free software; you can redistribute it and/or modify
6 it under the terms of the GNU Lesser General Public License as published by
7 the Free Software Foundation; either version 2.1 of the License, or
8 (at your option) any later version.
10 This program is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 GNU Lesser General Public License for more details.
15 You should have received a copy of the GNU Lesser General Public License along
16 with this program; if not, write to the Free Software Foundation, Inc.,
17 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
24 #include "client/renderingengine.h"
27 #include "client/inputhandler.h"
28 #include "client/tile.h" // For TextureSource
29 #include "client/keys.h"
30 #include "client/joystick_controller.h"
31 #include "clientmap.h"
34 #include "content_cao.h"
35 #include "event_manager.h"
36 #include "fontengine.h"
41 #include "guiChatConsole.h"
42 #include "guiFormSpecMenu.h"
43 #include "guiKeyChangeMenu.h"
44 #include "guiPasswordChange.h"
45 #include "guiVolumeChange.h"
46 #include "mainmenumanager.h"
49 #include "nodedef.h" // Needed for determining pointing to nodes
50 #include "nodemetadata.h"
51 #include "particles.h"
53 #include "quicktune_shortcutter.h"
60 #include "util/basic_macros.h"
61 #include "util/directiontables.h"
62 #include "util/pointedthing.h"
63 #include "irrlicht_changes/static_text.h"
65 #include "script/scripting_client.h"
68 #include "sound_openal.h"
71 extern Settings *g_settings;
72 extern Profiler *g_profiler;
78 struct TextDestNodeMetadata : public TextDest
80 TextDestNodeMetadata(v3s16 p, Client *client)
85 // This is deprecated I guess? -celeron55
86 void gotText(const std::wstring &text)
88 std::string ntext = wide_to_utf8(text);
89 infostream << "Submitting 'text' field of node at (" << m_p.X << ","
90 << m_p.Y << "," << m_p.Z << "): " << ntext << std::endl;
92 fields["text"] = ntext;
93 m_client->sendNodemetaFields(m_p, "", fields);
95 void gotText(const StringMap &fields)
97 m_client->sendNodemetaFields(m_p, "", fields);
104 struct TextDestPlayerInventory : public TextDest
106 TextDestPlayerInventory(Client *client)
111 TextDestPlayerInventory(Client *client, const std::string &formname)
114 m_formname = formname;
116 void gotText(const StringMap &fields)
118 m_client->sendInventoryFields(m_formname, fields);
124 struct LocalFormspecHandler : public TextDest
126 LocalFormspecHandler(const std::string &formname)
128 m_formname = formname;
131 LocalFormspecHandler(const std::string &formname, Client *client):
134 m_formname = formname;
137 void gotText(const StringMap &fields)
139 if (m_formname == "MT_PAUSE_MENU") {
140 if (fields.find("btn_sound") != fields.end()) {
141 g_gamecallback->changeVolume();
145 if (fields.find("btn_key_config") != fields.end()) {
146 g_gamecallback->keyConfig();
150 if (fields.find("btn_exit_menu") != fields.end()) {
151 g_gamecallback->disconnect();
155 if (fields.find("btn_exit_os") != fields.end()) {
156 g_gamecallback->exitToOS();
158 RenderingEngine::get_raw_device()->closeDevice();
163 if (fields.find("btn_change_password") != fields.end()) {
164 g_gamecallback->changePassword();
168 if (fields.find("quit") != fields.end()) {
172 if (fields.find("btn_continue") != fields.end()) {
177 // Don't disable this part when modding is disabled, it's used in builtin
178 if (m_client && m_client->getScript())
179 m_client->getScript()->on_formspec_input(m_formname, fields);
182 Client *m_client = nullptr;
185 /* Form update callback */
187 class NodeMetadataFormSource: public IFormSource
190 NodeMetadataFormSource(ClientMap *map, v3s16 p):
195 std::string getForm()
197 NodeMetadata *meta = m_map->getNodeMetadata(m_p);
202 return meta->getString("formspec");
205 virtual std::string resolveText(const std::string &str)
207 NodeMetadata *meta = m_map->getNodeMetadata(m_p);
212 return meta->resolveString(str);
219 class PlayerInventoryFormSource: public IFormSource
222 PlayerInventoryFormSource(Client *client):
226 std::string getForm()
228 LocalPlayer *player = m_client->getEnv().getLocalPlayer();
229 return player->inventory_formspec;
235 /* Profiler display */
237 void update_profiler_gui(gui::IGUIStaticText *guitext_profiler, FontEngine *fe,
238 u32 show_profiler, u32 show_profiler_max, s32 screen_height)
240 if (show_profiler == 0) {
241 guitext_profiler->setVisible(false);
244 std::ostringstream os(std::ios_base::binary);
245 g_profiler->printPage(os, show_profiler, show_profiler_max);
246 std::wstring text = utf8_to_wide(os.str());
247 setStaticText(guitext_profiler, text.c_str());
248 guitext_profiler->setVisible(true);
250 s32 w = fe->getTextWidth(text.c_str());
255 unsigned text_height = fe->getTextHeight();
257 core::position2di upper_left, lower_right;
260 upper_left.Y = (text_height + 5) * 2;
261 lower_right.X = 12 + w;
262 lower_right.Y = upper_left.Y + (text_height + 1) * MAX_PROFILER_TEXT_ROWS;
264 if (lower_right.Y > screen_height * 2 / 3)
265 lower_right.Y = screen_height * 2 / 3;
267 core::rect<s32> rect(upper_left, lower_right);
269 guitext_profiler->setRelativePosition(rect);
270 guitext_profiler->setVisible(true);
278 Profiler::GraphValues values;
284 Meta(float initial = 0,
285 video::SColor color = video::SColor(255, 255, 255, 255)):
291 std::deque<Piece> m_log;
299 void put(const Profiler::GraphValues &values)
302 piece.values = values;
303 m_log.push_back(piece);
305 while (m_log.size() > m_log_max_size)
306 m_log.erase(m_log.begin());
309 void draw(s32 x_left, s32 y_bottom, video::IVideoDriver *driver,
310 gui::IGUIFont *font) const
312 // Do *not* use UNORDERED_MAP here as the order needs
313 // to be the same for each call to prevent flickering
314 std::map<std::string, Meta> m_meta;
316 for (std::deque<Piece>::const_iterator k = m_log.begin();
317 k != m_log.end(); ++k) {
318 const Piece &piece = *k;
320 for (Profiler::GraphValues::const_iterator i = piece.values.begin();
321 i != piece.values.end(); ++i) {
322 const std::string &id = i->first;
323 const float &value = i->second;
324 std::map<std::string, Meta>::iterator j = m_meta.find(id);
326 if (j == m_meta.end()) {
327 m_meta[id] = Meta(value);
331 if (value < j->second.min)
332 j->second.min = value;
334 if (value > j->second.max)
335 j->second.max = value;
340 static const video::SColor usable_colors[] = {
341 video::SColor(255, 255, 100, 100),
342 video::SColor(255, 90, 225, 90),
343 video::SColor(255, 100, 100, 255),
344 video::SColor(255, 255, 150, 50),
345 video::SColor(255, 220, 220, 100)
347 static const u32 usable_colors_count =
348 sizeof(usable_colors) / sizeof(*usable_colors);
349 u32 next_color_i = 0;
351 for (std::map<std::string, Meta>::iterator i = m_meta.begin();
352 i != m_meta.end(); ++i) {
353 Meta &meta = i->second;
354 video::SColor color(255, 200, 200, 200);
356 if (next_color_i < usable_colors_count)
357 color = usable_colors[next_color_i++];
363 s32 textx = x_left + m_log_max_size + 15;
364 s32 textx2 = textx + 200 - 15;
367 for (std::map<std::string, Meta>::const_iterator i = m_meta.begin();
368 i != m_meta.end(); ++i) {
369 const std::string &id = i->first;
370 const Meta &meta = i->second;
372 s32 y = y_bottom - meta_i * 50;
373 float show_min = meta.min;
374 float show_max = meta.max;
376 if (show_min >= -0.0001 && show_max >= -0.0001) {
377 if (show_min <= show_max * 0.5)
383 snprintf(buf, 10, "%.3g", show_max);
384 font->draw(utf8_to_wide(buf).c_str(),
385 core::rect<s32>(textx, y - graphh,
386 textx2, y - graphh + texth),
388 snprintf(buf, 10, "%.3g", show_min);
389 font->draw(utf8_to_wide(buf).c_str(),
390 core::rect<s32>(textx, y - texth,
393 font->draw(utf8_to_wide(id).c_str(),
394 core::rect<s32>(textx, y - graphh / 2 - texth / 2,
395 textx2, y - graphh / 2 + texth / 2),
398 s32 graph1h = graphh;
399 bool relativegraph = (show_min != 0 && show_min != show_max);
400 float lastscaledvalue = 0.0;
401 bool lastscaledvalue_exists = false;
403 for (std::deque<Piece>::const_iterator j = m_log.begin();
404 j != m_log.end(); ++j) {
405 const Piece &piece = *j;
407 bool value_exists = false;
408 Profiler::GraphValues::const_iterator k =
409 piece.values.find(id);
411 if (k != piece.values.end()) {
418 lastscaledvalue_exists = false;
422 float scaledvalue = 1.0;
424 if (show_max != show_min)
425 scaledvalue = (value - show_min) / (show_max - show_min);
427 if (scaledvalue == 1.0 && value == 0) {
429 lastscaledvalue_exists = false;
434 if (lastscaledvalue_exists) {
435 s32 ivalue1 = lastscaledvalue * graph1h;
436 s32 ivalue2 = scaledvalue * graph1h;
437 driver->draw2DLine(v2s32(x - 1, graph1y - ivalue1),
438 v2s32(x, graph1y - ivalue2), meta.color);
441 lastscaledvalue = scaledvalue;
442 lastscaledvalue_exists = true;
444 s32 ivalue = scaledvalue * graph1h;
445 driver->draw2DLine(v2s32(x, graph1y),
446 v2s32(x, graph1y - ivalue), meta.color);
457 class NodeDugEvent: public MtEvent
463 NodeDugEvent(v3s16 p, MapNode n):
467 const char *getType() const
475 ISoundManager *m_sound;
476 INodeDefManager *m_ndef;
478 bool makes_footstep_sound;
479 float m_player_step_timer;
481 SimpleSoundSpec m_player_step_sound;
482 SimpleSoundSpec m_player_leftpunch_sound;
483 SimpleSoundSpec m_player_rightpunch_sound;
485 SoundMaker(ISoundManager *sound, INodeDefManager *ndef):
488 makes_footstep_sound(true),
489 m_player_step_timer(0)
493 void playPlayerStep()
495 if (m_player_step_timer <= 0 && m_player_step_sound.exists()) {
496 m_player_step_timer = 0.03;
497 if (makes_footstep_sound)
498 m_sound->playSound(m_player_step_sound, false);
502 static void viewBobbingStep(MtEvent *e, void *data)
504 SoundMaker *sm = (SoundMaker *)data;
505 sm->playPlayerStep();
508 static void playerRegainGround(MtEvent *e, void *data)
510 SoundMaker *sm = (SoundMaker *)data;
511 sm->playPlayerStep();
514 static void playerJump(MtEvent *e, void *data)
516 //SoundMaker *sm = (SoundMaker*)data;
519 static void cameraPunchLeft(MtEvent *e, void *data)
521 SoundMaker *sm = (SoundMaker *)data;
522 sm->m_sound->playSound(sm->m_player_leftpunch_sound, false);
525 static void cameraPunchRight(MtEvent *e, void *data)
527 SoundMaker *sm = (SoundMaker *)data;
528 sm->m_sound->playSound(sm->m_player_rightpunch_sound, false);
531 static void nodeDug(MtEvent *e, void *data)
533 SoundMaker *sm = (SoundMaker *)data;
534 NodeDugEvent *nde = (NodeDugEvent *)e;
535 sm->m_sound->playSound(sm->m_ndef->get(nde->n).sound_dug, false);
538 static void playerDamage(MtEvent *e, void *data)
540 SoundMaker *sm = (SoundMaker *)data;
541 sm->m_sound->playSound(SimpleSoundSpec("player_damage", 0.5), false);
544 static void playerFallingDamage(MtEvent *e, void *data)
546 SoundMaker *sm = (SoundMaker *)data;
547 sm->m_sound->playSound(SimpleSoundSpec("player_falling_damage", 0.5), false);
550 void registerReceiver(MtEventManager *mgr)
552 mgr->reg("ViewBobbingStep", SoundMaker::viewBobbingStep, this);
553 mgr->reg("PlayerRegainGround", SoundMaker::playerRegainGround, this);
554 mgr->reg("PlayerJump", SoundMaker::playerJump, this);
555 mgr->reg("CameraPunchLeft", SoundMaker::cameraPunchLeft, this);
556 mgr->reg("CameraPunchRight", SoundMaker::cameraPunchRight, this);
557 mgr->reg("NodeDug", SoundMaker::nodeDug, this);
558 mgr->reg("PlayerDamage", SoundMaker::playerDamage, this);
559 mgr->reg("PlayerFallingDamage", SoundMaker::playerFallingDamage, this);
562 void step(float dtime)
564 m_player_step_timer -= dtime;
568 // Locally stored sounds don't need to be preloaded because of this
569 class GameOnDemandSoundFetcher: public OnDemandSoundFetcher
571 std::set<std::string> m_fetched;
573 void paths_insert(std::set<std::string> &dst_paths,
574 const std::string &base,
575 const std::string &name)
577 dst_paths.insert(base + DIR_DELIM + "sounds" + DIR_DELIM + name + ".ogg");
578 dst_paths.insert(base + DIR_DELIM + "sounds" + DIR_DELIM + name + ".0.ogg");
579 dst_paths.insert(base + DIR_DELIM + "sounds" + DIR_DELIM + name + ".1.ogg");
580 dst_paths.insert(base + DIR_DELIM + "sounds" + DIR_DELIM + name + ".2.ogg");
581 dst_paths.insert(base + DIR_DELIM + "sounds" + DIR_DELIM + name + ".3.ogg");
582 dst_paths.insert(base + DIR_DELIM + "sounds" + DIR_DELIM + name + ".4.ogg");
583 dst_paths.insert(base + DIR_DELIM + "sounds" + DIR_DELIM + name + ".5.ogg");
584 dst_paths.insert(base + DIR_DELIM + "sounds" + DIR_DELIM + name + ".6.ogg");
585 dst_paths.insert(base + DIR_DELIM + "sounds" + DIR_DELIM + name + ".7.ogg");
586 dst_paths.insert(base + DIR_DELIM + "sounds" + DIR_DELIM + name + ".8.ogg");
587 dst_paths.insert(base + DIR_DELIM + "sounds" + DIR_DELIM + name + ".9.ogg");
590 void fetchSounds(const std::string &name,
591 std::set<std::string> &dst_paths,
592 std::set<std::string> &dst_datas)
594 if (m_fetched.count(name))
597 m_fetched.insert(name);
599 paths_insert(dst_paths, porting::path_share, name);
600 paths_insert(dst_paths, porting::path_user, name);
605 // before 1.8 there isn't a "integer interface", only float
606 #if (IRRLICHT_VERSION_MAJOR == 1 && IRRLICHT_VERSION_MINOR < 8)
607 typedef f32 SamplerLayer_t;
609 typedef s32 SamplerLayer_t;
613 class GameGlobalShaderConstantSetter : public IShaderConstantSetter
616 bool *m_force_fog_off;
619 CachedPixelShaderSetting<float, 4> m_sky_bg_color;
620 CachedPixelShaderSetting<float> m_fog_distance;
621 CachedVertexShaderSetting<float> m_animation_timer_vertex;
622 CachedPixelShaderSetting<float> m_animation_timer_pixel;
623 CachedPixelShaderSetting<float, 3> m_day_light;
624 CachedPixelShaderSetting<float, 3> m_eye_position_pixel;
625 CachedVertexShaderSetting<float, 3> m_eye_position_vertex;
626 CachedPixelShaderSetting<float, 3> m_minimap_yaw;
627 CachedPixelShaderSetting<SamplerLayer_t> m_base_texture;
628 CachedPixelShaderSetting<SamplerLayer_t> m_normal_texture;
629 CachedPixelShaderSetting<SamplerLayer_t> m_texture_flags;
633 void onSettingsChange(const std::string &name)
635 if (name == "enable_fog")
636 m_fog_enabled = g_settings->getBool("enable_fog");
639 static void settingsCallback(const std::string &name, void *userdata)
641 reinterpret_cast<GameGlobalShaderConstantSetter*>(userdata)->onSettingsChange(name);
644 void setSky(Sky *sky) { m_sky = sky; }
646 GameGlobalShaderConstantSetter(Sky *sky, bool *force_fog_off,
647 f32 *fog_range, Client *client) :
649 m_force_fog_off(force_fog_off),
650 m_fog_range(fog_range),
651 m_sky_bg_color("skyBgColor"),
652 m_fog_distance("fogDistance"),
653 m_animation_timer_vertex("animationTimer"),
654 m_animation_timer_pixel("animationTimer"),
655 m_day_light("dayLight"),
656 m_eye_position_pixel("eyePosition"),
657 m_eye_position_vertex("eyePosition"),
658 m_minimap_yaw("yawVec"),
659 m_base_texture("baseTexture"),
660 m_normal_texture("normalTexture"),
661 m_texture_flags("textureFlags"),
664 g_settings->registerChangedCallback("enable_fog", settingsCallback, this);
665 m_fog_enabled = g_settings->getBool("enable_fog");
668 ~GameGlobalShaderConstantSetter()
670 g_settings->deregisterChangedCallback("enable_fog", settingsCallback, this);
673 virtual void onSetConstants(video::IMaterialRendererServices *services,
680 video::SColor bgcolor = m_sky->getBgColor();
681 video::SColorf bgcolorf(bgcolor);
682 float bgcolorfa[4] = {
688 m_sky_bg_color.set(bgcolorfa, services);
691 float fog_distance = 10000 * BS;
693 if (m_fog_enabled && !*m_force_fog_off)
694 fog_distance = *m_fog_range;
696 m_fog_distance.set(&fog_distance, services);
698 u32 daynight_ratio = (float)m_client->getEnv().getDayNightRatio();
699 video::SColorf sunlight;
700 get_sunlight_color(&sunlight, daynight_ratio);
705 m_day_light.set(dnc, services);
707 u32 animation_timer = porting::getTimeMs() % 100000;
708 float animation_timer_f = (float)animation_timer / 100000.f;
709 m_animation_timer_vertex.set(&animation_timer_f, services);
710 m_animation_timer_pixel.set(&animation_timer_f, services);
712 float eye_position_array[3];
713 v3f epos = m_client->getEnv().getLocalPlayer()->getEyePosition();
714 #if (IRRLICHT_VERSION_MAJOR == 1 && IRRLICHT_VERSION_MINOR < 8)
715 eye_position_array[0] = epos.X;
716 eye_position_array[1] = epos.Y;
717 eye_position_array[2] = epos.Z;
719 epos.getAs3Values(eye_position_array);
721 m_eye_position_pixel.set(eye_position_array, services);
722 m_eye_position_vertex.set(eye_position_array, services);
724 if (m_client->getMinimap()) {
725 float minimap_yaw_array[3];
726 v3f minimap_yaw = m_client->getMinimap()->getYawVec();
727 #if (IRRLICHT_VERSION_MAJOR == 1 && IRRLICHT_VERSION_MINOR < 8)
728 minimap_yaw_array[0] = minimap_yaw.X;
729 minimap_yaw_array[1] = minimap_yaw.Y;
730 minimap_yaw_array[2] = minimap_yaw.Z;
732 minimap_yaw.getAs3Values(minimap_yaw_array);
734 m_minimap_yaw.set(minimap_yaw_array, services);
737 SamplerLayer_t base_tex = 0,
740 m_base_texture.set(&base_tex, services);
741 m_normal_texture.set(&normal_tex, services);
742 m_texture_flags.set(&flags_tex, services);
747 class GameGlobalShaderConstantSetterFactory : public IShaderConstantSetterFactory
750 bool *m_force_fog_off;
753 std::vector<GameGlobalShaderConstantSetter *> created_nosky;
755 GameGlobalShaderConstantSetterFactory(bool *force_fog_off,
756 f32 *fog_range, Client *client) :
758 m_force_fog_off(force_fog_off),
759 m_fog_range(fog_range),
763 void setSky(Sky *sky) {
765 for (size_t i = 0; i < created_nosky.size(); ++i) {
766 created_nosky[i]->setSky(m_sky);
768 created_nosky.clear();
771 virtual IShaderConstantSetter* create()
773 GameGlobalShaderConstantSetter *scs = new GameGlobalShaderConstantSetter(
774 m_sky, m_force_fog_off, m_fog_range, m_client);
776 created_nosky.push_back(scs);
782 bool nodePlacementPrediction(Client &client, const ItemDefinition &playeritem_def,
783 const ItemStack &playeritem, v3s16 nodepos, v3s16 neighbourpos)
785 std::string prediction = playeritem_def.node_placement_prediction;
786 INodeDefManager *nodedef = client.ndef();
787 ClientMap &map = client.getEnv().getClientMap();
789 bool is_valid_position;
791 node = map.getNodeNoEx(nodepos, &is_valid_position);
792 if (!is_valid_position)
795 if (prediction != "" && !nodedef->get(node).rightclickable) {
796 verbosestream << "Node placement prediction for "
797 << playeritem_def.name << " is "
798 << prediction << std::endl;
799 v3s16 p = neighbourpos;
801 // Place inside node itself if buildable_to
802 MapNode n_under = map.getNodeNoEx(nodepos, &is_valid_position);
803 if (is_valid_position)
805 if (nodedef->get(n_under).buildable_to)
808 node = map.getNodeNoEx(p, &is_valid_position);
809 if (is_valid_position &&!nodedef->get(node).buildable_to)
814 // Find id of predicted node
816 bool found = nodedef->getId(prediction, id);
819 errorstream << "Node placement prediction failed for "
820 << playeritem_def.name << " (places "
822 << ") - Name not known" << std::endl;
826 const ContentFeatures &predicted_f = nodedef->get(id);
828 // Predict param2 for facedir and wallmounted nodes
831 if (predicted_f.param_type_2 == CPT2_WALLMOUNTED ||
832 predicted_f.param_type_2 == CPT2_COLORED_WALLMOUNTED) {
833 v3s16 dir = nodepos - neighbourpos;
835 if (abs(dir.Y) > MYMAX(abs(dir.X), abs(dir.Z))) {
836 param2 = dir.Y < 0 ? 1 : 0;
837 } else if (abs(dir.X) > abs(dir.Z)) {
838 param2 = dir.X < 0 ? 3 : 2;
840 param2 = dir.Z < 0 ? 5 : 4;
844 if (predicted_f.param_type_2 == CPT2_FACEDIR ||
845 predicted_f.param_type_2 == CPT2_COLORED_FACEDIR) {
846 v3s16 dir = nodepos - floatToInt(client.getEnv().getLocalPlayer()->getPosition(), BS);
848 if (abs(dir.X) > abs(dir.Z)) {
849 param2 = dir.X < 0 ? 3 : 1;
851 param2 = dir.Z < 0 ? 2 : 0;
857 //Check attachment if node is in group attached_node
858 if (((ItemGroupList) predicted_f.groups)["attached_node"] != 0) {
859 static v3s16 wallmounted_dirs[8] = {
869 if (predicted_f.param_type_2 == CPT2_WALLMOUNTED ||
870 predicted_f.param_type_2 == CPT2_COLORED_WALLMOUNTED)
871 pp = p + wallmounted_dirs[param2];
873 pp = p + v3s16(0, -1, 0);
875 if (!nodedef->get(map.getNodeNoEx(pp)).walkable)
880 if ((predicted_f.param_type_2 == CPT2_COLOR
881 || predicted_f.param_type_2 == CPT2_COLORED_FACEDIR
882 || predicted_f.param_type_2 == CPT2_COLORED_WALLMOUNTED)) {
883 const std::string &indexstr = playeritem.metadata.getString(
885 if (!indexstr.empty()) {
886 s32 index = mystoi(indexstr);
887 if (predicted_f.param_type_2 == CPT2_COLOR) {
889 } else if (predicted_f.param_type_2
890 == CPT2_COLORED_WALLMOUNTED) {
891 // param2 = pure palette index + other
892 param2 = (index & 0xf8) | (param2 & 0x07);
893 } else if (predicted_f.param_type_2
894 == CPT2_COLORED_FACEDIR) {
895 // param2 = pure palette index + other
896 param2 = (index & 0xe0) | (param2 & 0x1f);
901 // Add node to client map
902 MapNode n(id, 0, param2);
905 LocalPlayer *player = client.getEnv().getLocalPlayer();
907 // Dont place node when player would be inside new node
908 // NOTE: This is to be eventually implemented by a mod as client-side Lua
909 if (!nodedef->get(n).walkable ||
910 g_settings->getBool("enable_build_where_you_stand") ||
911 (client.checkPrivilege("noclip") && g_settings->getBool("noclip")) ||
912 (nodedef->get(n).walkable &&
913 neighbourpos != player->getStandingNodePos() + v3s16(0, 1, 0) &&
914 neighbourpos != player->getStandingNodePos() + v3s16(0, 2, 0))) {
916 // This triggers the required mesh update too
917 client.addNode(p, n);
920 } catch (InvalidPositionException &e) {
921 errorstream << "Node placement prediction failed for "
922 << playeritem_def.name << " (places "
924 << ") - Position not loaded" << std::endl;
931 static inline void create_formspec_menu(GUIFormSpecMenu **cur_formspec,
932 Client *client, JoystickController *joystick,
933 IFormSource *fs_src, TextDest *txt_dest)
936 if (*cur_formspec == 0) {
937 *cur_formspec = new GUIFormSpecMenu(joystick, guiroot, -1, &g_menumgr,
938 client, client->getTextureSource(), fs_src, txt_dest);
939 (*cur_formspec)->doPause = false;
942 Caution: do not call (*cur_formspec)->drop() here --
943 the reference might outlive the menu, so we will
944 periodically check if *cur_formspec is the only
945 remaining reference (i.e. the menu was removed)
946 and delete it in that case.
950 (*cur_formspec)->setFormSource(fs_src);
951 (*cur_formspec)->setTextDest(txt_dest);
957 #define SIZE_TAG "size[11,5.5]"
959 #define SIZE_TAG "size[11,5.5,true]" // Fixed size on desktop
962 /******************************************************************************/
963 static void updateChat(Client &client, f32 dtime, bool show_debug,
964 const v2u32 &screensize, bool show_chat, u32 show_profiler,
965 ChatBackend &chat_backend, gui::IGUIStaticText *guitext_chat)
967 // Add chat log output for errors to be shown in chat
968 static LogOutputBuffer chat_log_error_buf(g_logger, LL_ERROR);
970 // Get new messages from error log buffer
971 while (!chat_log_error_buf.empty()) {
972 std::wstring error_message = utf8_to_wide(chat_log_error_buf.get());
973 if (!g_settings->getBool("disable_escape_sequences")) {
974 error_message = L"\x1b(c@red)" + error_message + L"\x1b(c@white)";
976 chat_backend.addMessage(L"", error_message);
979 // Get new messages from client
980 std::wstring message = L"";
981 while (client.getChatMessage(message)) {
982 chat_backend.addUnparsedMessage(message);
985 // Remove old messages
986 chat_backend.step(dtime);
988 // Display all messages in a static text element
989 unsigned int recent_chat_count = chat_backend.getRecentBuffer().getLineCount();
990 EnrichedString recent_chat = chat_backend.getRecentChat();
991 unsigned int line_height = g_fontengine->getLineHeight();
993 setStaticText(guitext_chat, recent_chat);
995 // Update gui element size and position
999 chat_y += 3 * line_height;
1001 // first pass to calculate height of text to be set
1002 const v2u32 &window_size = RenderingEngine::get_instance()->getWindowSize();
1003 s32 width = std::min(g_fontengine->getTextWidth(recent_chat.c_str()) + 10,
1004 window_size.X - 20);
1005 core::rect<s32> rect(10, chat_y, width, chat_y + window_size.Y);
1006 guitext_chat->setRelativePosition(rect);
1008 //now use real height of text and adjust rect according to this size
1009 rect = core::rect<s32>(10, chat_y, width,
1010 chat_y + guitext_chat->getTextHeight());
1013 guitext_chat->setRelativePosition(rect);
1014 // Don't show chat if disabled or empty or profiler is enabled
1015 guitext_chat->setVisible(
1016 show_chat && recent_chat_count != 0 && !show_profiler);
1020 /****************************************************************************
1021 Fast key cache for main game loop
1022 ****************************************************************************/
1024 /* This is faster than using getKeySetting with the tradeoff that functions
1025 * using it must make sure that it's initialised before using it and there is
1026 * no error handling (for example bounds checking). This is really intended for
1027 * use only in the main running loop of the client (the_game()) where the faster
1028 * (up to 10x faster) key lookup is an asset. Other parts of the codebase
1029 * (e.g. formspecs) should continue using getKeySetting().
1037 populate_nonchanging();
1042 // Keys that are not settings dependent
1043 void populate_nonchanging();
1045 KeyPress key[KeyType::INTERNAL_ENUM_COUNT];
1046 InputHandler *handler;
1049 void KeyCache::populate_nonchanging()
1051 key[KeyType::ESC] = EscapeKey;
1054 void KeyCache::populate()
1056 key[KeyType::FORWARD] = getKeySetting("keymap_forward");
1057 key[KeyType::BACKWARD] = getKeySetting("keymap_backward");
1058 key[KeyType::LEFT] = getKeySetting("keymap_left");
1059 key[KeyType::RIGHT] = getKeySetting("keymap_right");
1060 key[KeyType::JUMP] = getKeySetting("keymap_jump");
1061 key[KeyType::SPECIAL1] = getKeySetting("keymap_special1");
1062 key[KeyType::SNEAK] = getKeySetting("keymap_sneak");
1064 key[KeyType::AUTOFORWARD] = getKeySetting("keymap_autoforward");
1066 key[KeyType::DROP] = getKeySetting("keymap_drop");
1067 key[KeyType::INVENTORY] = getKeySetting("keymap_inventory");
1068 key[KeyType::CHAT] = getKeySetting("keymap_chat");
1069 key[KeyType::CMD] = getKeySetting("keymap_cmd");
1070 key[KeyType::CMD_LOCAL] = getKeySetting("keymap_cmd_local");
1071 key[KeyType::CONSOLE] = getKeySetting("keymap_console");
1072 key[KeyType::MINIMAP] = getKeySetting("keymap_minimap");
1073 key[KeyType::FREEMOVE] = getKeySetting("keymap_freemove");
1074 key[KeyType::FASTMOVE] = getKeySetting("keymap_fastmove");
1075 key[KeyType::NOCLIP] = getKeySetting("keymap_noclip");
1076 key[KeyType::HOTBAR_PREV] = getKeySetting("keymap_hotbar_previous");
1077 key[KeyType::HOTBAR_NEXT] = getKeySetting("keymap_hotbar_next");
1078 key[KeyType::MUTE] = getKeySetting("keymap_mute");
1079 key[KeyType::INC_VOLUME] = getKeySetting("keymap_increase_volume");
1080 key[KeyType::DEC_VOLUME] = getKeySetting("keymap_decrease_volume");
1081 key[KeyType::CINEMATIC] = getKeySetting("keymap_cinematic");
1082 key[KeyType::SCREENSHOT] = getKeySetting("keymap_screenshot");
1083 key[KeyType::TOGGLE_HUD] = getKeySetting("keymap_toggle_hud");
1084 key[KeyType::TOGGLE_CHAT] = getKeySetting("keymap_toggle_chat");
1085 key[KeyType::TOGGLE_FORCE_FOG_OFF]
1086 = getKeySetting("keymap_toggle_force_fog_off");
1087 key[KeyType::TOGGLE_UPDATE_CAMERA]
1088 = getKeySetting("keymap_toggle_update_camera");
1089 key[KeyType::TOGGLE_DEBUG]
1090 = getKeySetting("keymap_toggle_debug");
1091 key[KeyType::TOGGLE_PROFILER]
1092 = getKeySetting("keymap_toggle_profiler");
1093 key[KeyType::CAMERA_MODE]
1094 = getKeySetting("keymap_camera_mode");
1095 key[KeyType::INCREASE_VIEWING_RANGE]
1096 = getKeySetting("keymap_increase_viewing_range_min");
1097 key[KeyType::DECREASE_VIEWING_RANGE]
1098 = getKeySetting("keymap_decrease_viewing_range_min");
1099 key[KeyType::RANGESELECT]
1100 = getKeySetting("keymap_rangeselect");
1101 key[KeyType::ZOOM] = getKeySetting("keymap_zoom");
1103 key[KeyType::QUICKTUNE_NEXT] = getKeySetting("keymap_quicktune_next");
1104 key[KeyType::QUICKTUNE_PREV] = getKeySetting("keymap_quicktune_prev");
1105 key[KeyType::QUICKTUNE_INC] = getKeySetting("keymap_quicktune_inc");
1106 key[KeyType::QUICKTUNE_DEC] = getKeySetting("keymap_quicktune_dec");
1108 key[KeyType::DEBUG_STACKS] = getKeySetting("keymap_print_debug_stacks");
1111 // First clear all keys, then re-add the ones we listen for
1112 handler->dontListenForKeys();
1113 for (size_t i = 0; i < KeyType::INTERNAL_ENUM_COUNT; i++) {
1114 handler->listenForKey(key[i]);
1116 handler->listenForKey(EscapeKey);
1117 handler->listenForKey(CancelKey);
1118 for (size_t i = 0; i < 10; i++) {
1119 handler->listenForKey(NumberKey[i]);
1125 /****************************************************************************
1127 ****************************************************************************/
1129 const float object_hit_delay = 0.2;
1132 u32 last_time, busy_time, sleep_time;
1136 /* The reason the following structs are not anonymous structs within the
1137 * class is that they are not used by the majority of member functions and
1138 * many functions that do require objects of thse types do not modify them
1139 * (so they can be passed as a const qualified parameter)
1141 struct CameraOrientation {
1142 f32 camera_yaw; // "right/left"
1143 f32 camera_pitch; // "up/down"
1146 struct GameRunData {
1149 PointedThing pointed_old;
1154 bool update_wielded_item_trigger;
1155 bool reset_jump_timer;
1156 float nodig_delay_timer;
1158 float dig_time_complete;
1159 float repeat_rightclick_timer;
1160 float object_hit_delay_timer;
1161 float time_from_last_punch;
1162 ClientActiveObject *selected_object;
1166 float update_draw_list_timer;
1167 float statustext_time;
1171 v3f update_draw_list_last_cam_dir;
1173 u32 profiler_current_page;
1174 u32 profiler_max_page; // Number of pages
1177 float time_of_day_smooth;
1181 f32 max, min, avg, counter, max_sample, min_sample, max_fraction;
1187 Jitter dtime_jitter, busy_time_jitter;
1190 /****************************************************************************
1192 ****************************************************************************/
1194 /* This is not intended to be a public class. If a public class becomes
1195 * desirable then it may be better to create another 'wrapper' class that
1196 * hides most of the stuff in this class (nothing in this class is required
1197 * by any other file) but exposes the public methods/data only.
1204 bool startup(bool *kill,
1206 InputHandler *input,
1207 const std::string &map_dir,
1208 const std::string &playername,
1209 const std::string &password,
1210 // If address is "", local server is used and address is updated
1211 std::string *address,
1213 std::string &error_message,
1215 ChatBackend *chat_backend,
1216 const SubgameSpec &gamespec, // Used for local game
1217 bool simple_singleplayer_mode);
1224 void extendedResourceCleanup();
1226 // Basic initialisation
1227 bool init(const std::string &map_dir, std::string *address,
1229 const SubgameSpec &gamespec);
1231 bool createSingleplayerServer(const std::string &map_dir,
1232 const SubgameSpec &gamespec, u16 port, std::string *address);
1235 bool createClient(const std::string &playername,
1236 const std::string &password, std::string *address, u16 port);
1239 // Client connection
1240 bool connectToServer(const std::string &playername,
1241 const std::string &password, std::string *address, u16 port,
1242 bool *connect_ok, bool *aborted);
1243 bool getServerContent(bool *aborted);
1247 void updateInteractTimers(f32 dtime);
1248 bool checkConnection();
1249 bool handleCallbacks();
1250 void processQueues();
1251 void updateProfilers(const RunStats &stats, const FpsControl &draw_times, f32 dtime);
1252 void addProfilerGraphs(const RunStats &stats, const FpsControl &draw_times, f32 dtime);
1253 void updateStats(RunStats *stats, const FpsControl &draw_times, f32 dtime);
1256 void processUserInput(f32 dtime);
1257 void processKeyInput();
1258 void processItemSelection(u16 *new_playeritem);
1260 void dropSelectedItem();
1261 void openInventory();
1262 void openConsole(float scale, const wchar_t *line=NULL);
1263 void toggleFreeMove();
1264 void toggleFreeMoveAlt();
1266 void toggleNoClip();
1267 void toggleCinematic();
1268 void toggleAutoforward();
1272 void toggleMinimap(bool shift_pressed);
1275 void toggleUpdateCamera();
1276 void toggleProfiler();
1278 void increaseViewRange();
1279 void decreaseViewRange();
1280 void toggleFullViewRange();
1282 void updateCameraDirection(CameraOrientation *cam, float dtime);
1283 void updateCameraOrientation(CameraOrientation *cam, float dtime);
1284 void updatePlayerControl(const CameraOrientation &cam);
1285 void step(f32 *dtime);
1286 void processClientEvents(CameraOrientation *cam);
1287 void updateCamera(u32 busy_time, f32 dtime);
1288 void updateSound(f32 dtime);
1289 void processPlayerInteraction(f32 dtime, bool show_hud, bool show_debug);
1291 * Returns the object or node the player is pointing at.
1292 * Also updates the selected thing in the Hud.
1294 * @param[in] shootline the shootline, starting from
1295 * the camera position. This also gives the maximal distance
1297 * @param[in] liquids_pointable if false, liquids are ignored
1298 * @param[in] look_for_object if false, objects are ignored
1299 * @param[in] camera_offset offset of the camera
1300 * @param[out] selected_object the selected object or
1303 PointedThing updatePointedThing(
1304 const core::line3d<f32> &shootline, bool liquids_pointable,
1305 bool look_for_object, const v3s16 &camera_offset);
1306 void handlePointingAtNothing(const ItemStack &playerItem);
1307 void handlePointingAtNode(const PointedThing &pointed,
1308 const ItemDefinition &playeritem_def, const ItemStack &playeritem,
1309 const ToolCapabilities &playeritem_toolcap, f32 dtime);
1310 void handlePointingAtObject(const PointedThing &pointed, const ItemStack &playeritem,
1311 const v3f &player_position, bool show_debug);
1312 void handleDigging(const PointedThing &pointed, const v3s16 &nodepos,
1313 const ToolCapabilities &playeritem_toolcap, f32 dtime);
1314 void updateFrame(ProfilerGraph *graph, RunStats *stats, f32 dtime,
1315 const CameraOrientation &cam);
1316 void updateGui(const RunStats &stats, f32 dtime, const CameraOrientation &cam);
1317 void updateProfilerGraphs(ProfilerGraph *graph);
1320 void limitFps(FpsControl *fps_timings, f32 *dtime);
1322 void showOverlayMessage(const char *msg, float dtime, int percent,
1323 bool draw_clouds = true);
1325 static void settingChangedCallback(const std::string &setting_name, void *data);
1326 void readSettings();
1328 inline bool getLeftClicked()
1330 return input->getLeftClicked() ||
1331 input->joystick.getWasKeyDown(KeyType::MOUSE_L);
1333 inline bool getRightClicked()
1335 return input->getRightClicked() ||
1336 input->joystick.getWasKeyDown(KeyType::MOUSE_R);
1338 inline bool isLeftPressed()
1340 return input->getLeftState() ||
1341 input->joystick.isKeyDown(KeyType::MOUSE_L);
1343 inline bool isRightPressed()
1345 return input->getRightState() ||
1346 input->joystick.isKeyDown(KeyType::MOUSE_R);
1348 inline bool getLeftReleased()
1350 return input->getLeftReleased() ||
1351 input->joystick.wasKeyReleased(KeyType::MOUSE_L);
1354 inline bool isKeyDown(GameKeyType k)
1356 return input->isKeyDown(keycache.key[k]) || input->joystick.isKeyDown(k);
1358 inline bool wasKeyDown(GameKeyType k)
1360 return input->wasKeyDown(keycache.key[k]) || input->joystick.wasKeyDown(k);
1364 void handleAndroidChatInput();
1368 void showPauseMenu();
1370 InputHandler *input;
1375 IWritableTextureSource *texture_src;
1376 IWritableShaderSource *shader_src;
1378 // When created, these will be filled with data received from the server
1379 IWritableItemDefManager *itemdef_manager;
1380 IWritableNodeDefManager *nodedef_manager;
1382 GameOnDemandSoundFetcher soundfetcher; // useful when testing
1383 ISoundManager *sound;
1384 bool sound_is_dummy;
1385 SoundMaker *soundmaker;
1387 ChatBackend *chat_backend;
1389 GUIFormSpecMenu *current_formspec;
1390 //default: "". If other than "", empty show_formspec packets will only close the formspec when the formname matches
1391 std::string cur_formname;
1393 EventManager *eventmgr;
1394 QuicktuneShortcutter *quicktune;
1396 GUIChatConsole *gui_chat_console; // Free using ->Drop()
1397 MapDrawControl *draw_control;
1399 Clouds *clouds; // Free using ->Drop()
1400 Sky *sky; // Free using ->Drop()
1401 Inventory *local_inventory;
1405 GameRunData runData;
1409 This class does take ownership/responsibily for cleaning up etc of any of
1410 these items (e.g. device)
1412 IrrlichtDevice *device;
1413 video::IVideoDriver *driver;
1414 scene::ISceneManager *smgr;
1416 std::string *error_message;
1417 bool *reconnect_requested;
1418 scene::ISceneNode *skybox;
1421 bool simple_singleplayer_mode;
1424 /* Pre-calculated values
1426 int crack_animation_length;
1430 gui::IGUIStaticText *guitext; // First line of debug text
1431 gui::IGUIStaticText *guitext2; // Second line of debug text
1432 gui::IGUIStaticText *guitext3; // Third line of debug text
1433 gui::IGUIStaticText *guitext_info; // At the middle of the screen
1434 gui::IGUIStaticText *guitext_status;
1435 gui::IGUIStaticText *guitext_chat; // Chat text
1436 gui::IGUIStaticText *guitext_profiler; // Profiler text
1438 std::wstring infotext;
1439 std::wstring m_statustext;
1443 IntervalLimiter profiler_interval;
1446 * TODO: Local caching of settings is not optimal and should at some stage
1447 * be updated to use a global settings object for getting thse values
1448 * (as opposed to the this local caching). This can be addressed in
1451 bool m_cache_doubletap_jump;
1452 bool m_cache_enable_clouds;
1453 bool m_cache_enable_joysticks;
1454 bool m_cache_enable_particles;
1455 bool m_cache_enable_fog;
1456 bool m_cache_enable_noclip;
1457 bool m_cache_enable_free_move;
1458 f32 m_cache_mouse_sensitivity;
1459 f32 m_cache_joystick_frustum_sensitivity;
1460 f32 m_repeat_right_click_time;
1461 f32 m_cache_cam_smoothing;
1462 f32 m_cache_fog_start;
1464 bool m_invert_mouse;
1465 bool m_first_loop_after_window_activation;
1466 bool m_camera_offset_changed;
1469 bool m_cache_hold_aux1;
1470 bool m_android_chat_open;
1479 itemdef_manager(NULL),
1480 nodedef_manager(NULL),
1482 sound_is_dummy(false),
1485 current_formspec(NULL),
1489 gui_chat_console(NULL),
1494 local_inventory(NULL),
1497 m_invert_mouse(false),
1498 m_first_loop_after_window_activation(false),
1499 m_camera_offset_changed(false)
1501 g_settings->registerChangedCallback("doubletap_jump",
1502 &settingChangedCallback, this);
1503 g_settings->registerChangedCallback("enable_clouds",
1504 &settingChangedCallback, this);
1505 g_settings->registerChangedCallback("doubletap_joysticks",
1506 &settingChangedCallback, this);
1507 g_settings->registerChangedCallback("enable_particles",
1508 &settingChangedCallback, this);
1509 g_settings->registerChangedCallback("enable_fog",
1510 &settingChangedCallback, this);
1511 g_settings->registerChangedCallback("mouse_sensitivity",
1512 &settingChangedCallback, this);
1513 g_settings->registerChangedCallback("joystick_frustum_sensitivity",
1514 &settingChangedCallback, this);
1515 g_settings->registerChangedCallback("repeat_rightclick_time",
1516 &settingChangedCallback, this);
1517 g_settings->registerChangedCallback("noclip",
1518 &settingChangedCallback, this);
1519 g_settings->registerChangedCallback("free_move",
1520 &settingChangedCallback, this);
1521 g_settings->registerChangedCallback("cinematic",
1522 &settingChangedCallback, this);
1523 g_settings->registerChangedCallback("cinematic_camera_smoothing",
1524 &settingChangedCallback, this);
1525 g_settings->registerChangedCallback("camera_smoothing",
1526 &settingChangedCallback, this);
1531 m_cache_hold_aux1 = false; // This is initialised properly later
1538 /****************************************************************************
1540 ****************************************************************************/
1546 if (!sound_is_dummy)
1549 delete server; // deleted first to stop all server threads
1552 delete local_inventory;
1558 delete nodedef_manager;
1559 delete itemdef_manager;
1560 delete draw_control;
1562 extendedResourceCleanup();
1564 g_settings->deregisterChangedCallback("doubletap_jump",
1565 &settingChangedCallback, this);
1566 g_settings->deregisterChangedCallback("enable_clouds",
1567 &settingChangedCallback, this);
1568 g_settings->deregisterChangedCallback("enable_particles",
1569 &settingChangedCallback, this);
1570 g_settings->deregisterChangedCallback("enable_fog",
1571 &settingChangedCallback, this);
1572 g_settings->deregisterChangedCallback("mouse_sensitivity",
1573 &settingChangedCallback, this);
1574 g_settings->deregisterChangedCallback("repeat_rightclick_time",
1575 &settingChangedCallback, this);
1576 g_settings->deregisterChangedCallback("noclip",
1577 &settingChangedCallback, this);
1578 g_settings->deregisterChangedCallback("free_move",
1579 &settingChangedCallback, this);
1580 g_settings->deregisterChangedCallback("cinematic",
1581 &settingChangedCallback, this);
1582 g_settings->deregisterChangedCallback("cinematic_camera_smoothing",
1583 &settingChangedCallback, this);
1584 g_settings->deregisterChangedCallback("camera_smoothing",
1585 &settingChangedCallback, this);
1588 bool Game::startup(bool *kill,
1590 InputHandler *input,
1591 const std::string &map_dir,
1592 const std::string &playername,
1593 const std::string &password,
1594 std::string *address, // can change if simple_singleplayer_mode
1596 std::string &error_message,
1598 ChatBackend *chat_backend,
1599 const SubgameSpec &gamespec,
1600 bool simple_singleplayer_mode)
1603 this->device = RenderingEngine::get_raw_device();
1605 this->error_message = &error_message;
1606 this->reconnect_requested = reconnect;
1607 this->random_input = random_input;
1608 this->input = input;
1609 this->chat_backend = chat_backend;
1610 this->simple_singleplayer_mode = simple_singleplayer_mode;
1612 keycache.handler = input;
1613 keycache.populate();
1615 driver = device->getVideoDriver();
1616 smgr = RenderingEngine::get_scene_manager();
1618 RenderingEngine::get_scene_manager()->getParameters()->
1619 setAttribute(scene::OBJ_LOADER_IGNORE_MATERIAL_FILES, true);
1621 memset(&runData, 0, sizeof(runData));
1622 runData.time_from_last_punch = 10.0;
1623 runData.profiler_max_page = 3;
1624 runData.update_wielded_item_trigger = true;
1626 memset(&flags, 0, sizeof(flags));
1627 flags.show_chat = true;
1628 flags.show_hud = true;
1629 flags.show_debug = g_settings->getBool("show_debug");
1630 m_invert_mouse = g_settings->getBool("invert_mouse");
1631 m_first_loop_after_window_activation = true;
1633 if (!init(map_dir, address, port, gamespec))
1636 if (!createClient(playername, password, address, port))
1645 ProfilerGraph graph;
1646 RunStats stats = { 0 };
1647 CameraOrientation cam_view_target = { 0 };
1648 CameraOrientation cam_view = { 0 };
1649 FpsControl draw_times = { 0 };
1650 f32 dtime; // in seconds
1652 /* Clear the profiler */
1653 Profiler::GraphValues dummyvalues;
1654 g_profiler->graphGet(dummyvalues);
1656 draw_times.last_time = RenderingEngine::get_timer_time();
1658 set_light_table(g_settings->getFloat("display_gamma"));
1661 m_cache_hold_aux1 = g_settings->getBool("fast_move")
1662 && client->checkPrivilege("fast");
1665 irr::core::dimension2d<u32> previous_screen_size(g_settings->getU16("screen_w"),
1666 g_settings->getU16("screen_h"));
1668 while (RenderingEngine::run()
1669 && !(*kill || g_gamecallback->shutdown_requested
1670 || (server && server->getShutdownRequested()))) {
1672 const irr::core::dimension2d<u32> ¤t_screen_size =
1673 RenderingEngine::get_video_driver()->getScreenSize();
1674 // Verify if window size has changed and save it if it's the case
1675 // Ensure evaluating settings->getBool after verifying screensize
1676 // First condition is cheaper
1677 if (previous_screen_size != current_screen_size &&
1678 current_screen_size != irr::core::dimension2d<u32>(0,0) &&
1679 g_settings->getBool("autosave_screensize")) {
1680 g_settings->setU16("screen_w", current_screen_size.Width);
1681 g_settings->setU16("screen_h", current_screen_size.Height);
1682 previous_screen_size = current_screen_size;
1685 /* Must be called immediately after a device->run() call because it
1686 * uses device->getTimer()->getTime()
1688 limitFps(&draw_times, &dtime);
1690 updateStats(&stats, draw_times, dtime);
1691 updateInteractTimers(dtime);
1693 if (!checkConnection())
1695 if (!handleCallbacks())
1701 hud->resizeHotbar();
1703 updateProfilers(stats, draw_times, dtime);
1704 processUserInput(dtime);
1705 // Update camera before player movement to avoid camera lag of one frame
1706 updateCameraDirection(&cam_view_target, dtime);
1707 cam_view.camera_yaw += (cam_view_target.camera_yaw -
1708 cam_view.camera_yaw) * m_cache_cam_smoothing;
1709 cam_view.camera_pitch += (cam_view_target.camera_pitch -
1710 cam_view.camera_pitch) * m_cache_cam_smoothing;
1711 updatePlayerControl(cam_view);
1713 processClientEvents(&cam_view_target);
1714 updateCamera(draw_times.busy_time, dtime);
1716 processPlayerInteraction(dtime, flags.show_hud, flags.show_debug);
1717 updateFrame(&graph, &stats, dtime, cam_view);
1718 updateProfilerGraphs(&graph);
1720 // Update if minimap has been disabled by the server
1721 flags.show_minimap &= client->shouldShowMinimap();
1726 void Game::shutdown()
1728 #if IRRLICHT_VERSION_MAJOR == 1 && IRRLICHT_VERSION_MINOR <= 8
1729 if (g_settings->get("3d_mode") == "pageflip") {
1730 driver->setRenderTarget(irr::video::ERT_STEREO_BOTH_BUFFERS);
1733 if (current_formspec)
1734 current_formspec->quitMenu();
1736 showOverlayMessage("Shutting down...", 0, 0, false);
1741 if (gui_chat_console)
1742 gui_chat_console->drop();
1748 while (g_menumgr.menuCount() > 0) {
1749 g_menumgr.m_stack.front()->setVisible(false);
1750 g_menumgr.deletingMenu(g_menumgr.m_stack.front());
1753 if (current_formspec) {
1754 current_formspec->drop();
1755 current_formspec = NULL;
1758 chat_backend->addMessage(L"", L"# Disconnected.");
1759 chat_backend->addMessage(L"", L"");
1763 while (!client->isShutdown()) {
1764 assert(texture_src != NULL);
1765 assert(shader_src != NULL);
1766 texture_src->processQueue();
1767 shader_src->processQueue();
1774 /****************************************************************************/
1775 /****************************************************************************
1777 ****************************************************************************/
1778 /****************************************************************************/
1781 const std::string &map_dir,
1782 std::string *address,
1784 const SubgameSpec &gamespec)
1786 texture_src = createTextureSource();
1788 showOverlayMessage("Loading...", 0, 0);
1790 shader_src = createShaderSource();
1792 itemdef_manager = createItemDefManager();
1793 nodedef_manager = createNodeDefManager();
1795 eventmgr = new EventManager();
1796 quicktune = new QuicktuneShortcutter();
1798 if (!(texture_src && shader_src && itemdef_manager && nodedef_manager
1799 && eventmgr && quicktune))
1805 // Create a server if not connecting to an existing one
1806 if (*address == "") {
1807 if (!createSingleplayerServer(map_dir, gamespec, port, address))
1814 bool Game::initSound()
1817 if (g_settings->getBool("enable_sound")) {
1818 infostream << "Attempting to use OpenAL audio" << std::endl;
1819 sound = createOpenALSoundManager(&soundfetcher);
1821 infostream << "Failed to initialize OpenAL audio" << std::endl;
1823 infostream << "Sound disabled." << std::endl;
1827 infostream << "Using dummy audio." << std::endl;
1828 sound = &dummySoundManager;
1829 sound_is_dummy = true;
1832 soundmaker = new SoundMaker(sound, nodedef_manager);
1836 soundmaker->registerReceiver(eventmgr);
1841 bool Game::createSingleplayerServer(const std::string &map_dir,
1842 const SubgameSpec &gamespec, u16 port, std::string *address)
1844 showOverlayMessage("Creating server...", 0, 5);
1846 std::string bind_str = g_settings->get("bind_address");
1847 Address bind_addr(0, 0, 0, 0, port);
1849 if (g_settings->getBool("ipv6_server")) {
1850 bind_addr.setAddress((IPv6AddressBytes *) NULL);
1854 bind_addr.Resolve(bind_str.c_str());
1855 } catch (ResolveError &e) {
1856 infostream << "Resolving bind address \"" << bind_str
1857 << "\" failed: " << e.what()
1858 << " -- Listening on all addresses." << std::endl;
1861 if (bind_addr.isIPv6() && !g_settings->getBool("enable_ipv6")) {
1862 *error_message = "Unable to listen on " +
1863 bind_addr.serializeString() +
1864 " because IPv6 is disabled";
1865 errorstream << *error_message << std::endl;
1869 server = new Server(map_dir, gamespec, simple_singleplayer_mode,
1870 bind_addr.isIPv6(), false);
1872 server->start(bind_addr);
1877 bool Game::createClient(const std::string &playername,
1878 const std::string &password, std::string *address, u16 port)
1880 showOverlayMessage("Creating client...", 0, 10);
1882 draw_control = new MapDrawControl;
1886 bool could_connect, connect_aborted;
1888 if (!connectToServer(playername, password, address, port,
1889 &could_connect, &connect_aborted))
1892 if (!could_connect) {
1893 if (error_message->empty() && !connect_aborted) {
1894 // Should not happen if error messages are set properly
1895 *error_message = "Connection failed for unknown reason";
1896 errorstream << *error_message << std::endl;
1901 if (!getServerContent(&connect_aborted)) {
1902 if (error_message->empty() && !connect_aborted) {
1903 // Should not happen if error messages are set properly
1904 *error_message = "Connection failed for unknown reason";
1905 errorstream << *error_message << std::endl;
1910 GameGlobalShaderConstantSetterFactory *scsf = new GameGlobalShaderConstantSetterFactory(
1911 &flags.force_fog_off, &runData.fog_range, client);
1912 shader_src->addShaderConstantSetterFactory(scsf);
1914 // Update cached textures, meshes and materials
1915 client->afterContentReceived();
1919 camera = new Camera(*draw_control, client);
1920 if (!camera || !camera->successfullyCreated(*error_message))
1922 client->setCamera(camera);
1926 if (m_cache_enable_clouds) {
1927 clouds = new Clouds(smgr, -1, time(0));
1929 *error_message = "Memory allocation error (clouds)";
1930 errorstream << *error_message << std::endl;
1937 sky = new Sky(-1, texture_src);
1939 skybox = NULL; // This is used/set later on in the main run loop
1941 local_inventory = new Inventory(itemdef_manager);
1943 if (!(sky && local_inventory)) {
1944 *error_message = "Memory allocation error (sky or local inventory)";
1945 errorstream << *error_message << std::endl;
1949 /* Pre-calculated values
1951 video::ITexture *t = texture_src->getTexture("crack_anylength.png");
1953 v2u32 size = t->getOriginalSize();
1954 crack_animation_length = size.Y / size.X;
1956 crack_animation_length = 5;
1962 /* Set window caption
1964 std::wstring str = utf8_to_wide(PROJECT_NAME_C);
1966 str += utf8_to_wide(g_version_hash);
1968 str += driver->getName();
1970 device->setWindowCaption(str.c_str());
1972 LocalPlayer *player = client->getEnv().getLocalPlayer();
1973 player->hurt_tilt_timer = 0;
1974 player->hurt_tilt_strength = 0;
1976 hud = new Hud(guienv, client, player, local_inventory);
1979 *error_message = "Memory error: could not create HUD";
1980 errorstream << *error_message << std::endl;
1984 mapper = client->getMinimap();
1986 mapper->setMinimapMode(MINIMAP_MODE_OFF);
1991 bool Game::initGui()
1993 // First line of debug text
1994 guitext = addStaticText(guienv,
1995 utf8_to_wide(PROJECT_NAME_C).c_str(),
1996 core::rect<s32>(0, 0, 0, 0),
1997 false, false, guiroot);
1999 // Second line of debug text
2000 guitext2 = addStaticText(guienv,
2002 core::rect<s32>(0, 0, 0, 0),
2003 false, false, guiroot);
2005 // Third line of debug text
2006 guitext3 = addStaticText(guienv,
2008 core::rect<s32>(0, 0, 0, 0),
2009 false, false, guiroot);
2011 // At the middle of the screen
2012 // Object infos are shown in this
2013 guitext_info = addStaticText(guienv,
2015 core::rect<s32>(0, 0, 400, g_fontengine->getTextHeight() * 5 + 5) + v2s32(100, 200),
2016 false, true, guiroot);
2018 // Status text (displays info when showing and hiding GUI stuff, etc.)
2019 guitext_status = addStaticText(guienv,
2021 core::rect<s32>(0, 0, 0, 0),
2022 false, false, guiroot);
2023 guitext_status->setVisible(false);
2026 guitext_chat = addStaticText(
2029 core::rect<s32>(0, 0, 0, 0),
2030 //false, false); // Disable word wrap as of now
2031 false, true, guiroot);
2033 // Remove stale "recent" chat messages from previous connections
2034 chat_backend->clearRecentChat();
2036 // Chat backend and console
2037 gui_chat_console = new GUIChatConsole(guienv, guienv->getRootGUIElement(),
2038 -1, chat_backend, client, &g_menumgr);
2039 if (!gui_chat_console) {
2040 *error_message = "Could not allocate memory for chat console";
2041 errorstream << *error_message << std::endl;
2045 // Profiler text (size is updated when text is updated)
2046 guitext_profiler = addStaticText(guienv,
2048 core::rect<s32>(0, 0, 0, 0),
2049 false, false, guiroot);
2050 guitext_profiler->setBackgroundColor(video::SColor(120, 0, 0, 0));
2051 guitext_profiler->setVisible(false);
2052 guitext_profiler->setWordWrap(true);
2054 #ifdef HAVE_TOUCHSCREENGUI
2056 if (g_touchscreengui)
2057 g_touchscreengui->init(texture_src);
2064 bool Game::connectToServer(const std::string &playername,
2065 const std::string &password, std::string *address, u16 port,
2066 bool *connect_ok, bool *aborted)
2068 *connect_ok = false; // Let's not be overly optimistic
2070 bool local_server_mode = false;
2072 showOverlayMessage("Resolving address...", 0, 15);
2074 Address connect_address(0, 0, 0, 0, port);
2077 connect_address.Resolve(address->c_str());
2079 if (connect_address.isZero()) { // i.e. INADDR_ANY, IN6ADDR_ANY
2080 //connect_address.Resolve("localhost");
2081 if (connect_address.isIPv6()) {
2082 IPv6AddressBytes addr_bytes;
2083 addr_bytes.bytes[15] = 1;
2084 connect_address.setAddress(&addr_bytes);
2086 connect_address.setAddress(127, 0, 0, 1);
2088 local_server_mode = true;
2090 } catch (ResolveError &e) {
2091 *error_message = std::string("Couldn't resolve address: ") + e.what();
2092 errorstream << *error_message << std::endl;
2096 if (connect_address.isIPv6() && !g_settings->getBool("enable_ipv6")) {
2097 *error_message = "Unable to connect to " +
2098 connect_address.serializeString() +
2099 " because IPv6 is disabled";
2100 errorstream << *error_message << std::endl;
2104 client = new Client(playername.c_str(), password, *address,
2105 *draw_control, texture_src, shader_src,
2106 itemdef_manager, nodedef_manager, sound, eventmgr,
2107 connect_address.isIPv6(), &flags);
2112 infostream << "Connecting to server at ";
2113 connect_address.print(&infostream);
2114 infostream << std::endl;
2116 client->connect(connect_address,
2117 simple_singleplayer_mode || local_server_mode);
2120 Wait for server to accept connection
2126 FpsControl fps_control = { 0 };
2128 f32 wait_time = 0; // in seconds
2130 fps_control.last_time = RenderingEngine::get_timer_time();
2135 while (RenderingEngine::run()) {
2137 limitFps(&fps_control, &dtime);
2139 // Update client and server
2140 client->step(dtime);
2143 server->step(dtime);
2146 if (client->getState() == LC_Init) {
2152 if (client->accessDenied()) {
2153 *error_message = "Access denied. Reason: "
2154 + client->accessDeniedReason();
2155 *reconnect_requested = client->reconnectRequested();
2156 errorstream << *error_message << std::endl;
2160 if (wasKeyDown(KeyType::ESC) || input->wasKeyDown(CancelKey)) {
2162 infostream << "Connect aborted [Escape]" << std::endl;
2167 // Only time out if we aren't waiting for the server we started
2168 if ((*address != "") && (wait_time > 10)) {
2169 bool sent_old_init = g_settings->getFlag("send_pre_v25_init");
2170 // If no pre v25 init was sent, and no answer was received,
2171 // but the low level connection could be established
2172 // (meaning that we have a peer id), then we probably wanted
2173 // to connect to a legacy server. In this case, tell the user
2174 // to enable the option to be able to connect.
2175 if (!sent_old_init &&
2176 (client->getProtoVersion() == 0) &&
2177 client->connectedToServer()) {
2178 *error_message = "Connection failure: init packet not "
2179 "recognized by server.\n"
2180 "Most likely the server uses an old protocol version (<v25).\n"
2181 "Please ask the server owner to update to 0.4.13 or later.\n"
2182 "To still connect to the server in the meantime,\n"
2183 "you can enable the 'send_pre_v25_init' setting by editing minetest.conf,\n"
2184 "or by enabling the 'Client -> Network -> Support older Servers'\n"
2185 "entry in the advanced settings menu.";
2187 *error_message = "Connection timed out.";
2189 errorstream << *error_message << std::endl;
2194 showOverlayMessage("Connecting to server...", dtime, 20);
2196 } catch (con::PeerNotFoundException &e) {
2197 // TODO: Should something be done here? At least an info/error
2205 bool Game::getServerContent(bool *aborted)
2209 FpsControl fps_control = { 0 };
2210 f32 dtime; // in seconds
2212 fps_control.last_time = RenderingEngine::get_timer_time();
2214 while (RenderingEngine::run()) {
2216 limitFps(&fps_control, &dtime);
2218 // Update client and server
2219 client->step(dtime);
2222 server->step(dtime);
2225 if (client->mediaReceived() && client->itemdefReceived() &&
2226 client->nodedefReceived()) {
2231 if (!checkConnection())
2234 if (client->getState() < LC_Init) {
2235 *error_message = "Client disconnected";
2236 errorstream << *error_message << std::endl;
2240 if (wasKeyDown(KeyType::ESC) || input->wasKeyDown(CancelKey)) {
2242 infostream << "Connect aborted [Escape]" << std::endl;
2249 if (!client->itemdefReceived()) {
2250 const wchar_t *text = wgettext("Item definitions...");
2252 RenderingEngine::draw_load_screen(text, guienv, texture_src,
2255 } else if (!client->nodedefReceived()) {
2256 const wchar_t *text = wgettext("Node definitions...");
2258 RenderingEngine::draw_load_screen(text, guienv, texture_src,
2262 std::stringstream message;
2263 std::fixed(message);
2264 message.precision(0);
2265 message << gettext("Media...") << " " << (client->mediaReceiveProgress()*100) << "%";
2266 message.precision(2);
2268 if ((USE_CURL == 0) ||
2269 (!g_settings->getBool("enable_remote_media_server"))) {
2270 float cur = client->getCurRate();
2271 std::string cur_unit = gettext("KiB/s");
2275 cur_unit = gettext("MiB/s");
2278 message << " (" << cur << ' ' << cur_unit << ")";
2281 progress = 30 + client->mediaReceiveProgress() * 35 + 0.5;
2282 RenderingEngine::draw_load_screen(utf8_to_wide(message.str()), guienv,
2283 texture_src, dtime, progress);
2291 /****************************************************************************/
2292 /****************************************************************************
2294 ****************************************************************************/
2295 /****************************************************************************/
2297 inline void Game::updateInteractTimers(f32 dtime)
2299 if (runData.nodig_delay_timer >= 0)
2300 runData.nodig_delay_timer -= dtime;
2302 if (runData.object_hit_delay_timer >= 0)
2303 runData.object_hit_delay_timer -= dtime;
2305 runData.time_from_last_punch += dtime;
2309 /* returns false if game should exit, otherwise true
2311 inline bool Game::checkConnection()
2313 if (client->accessDenied()) {
2314 *error_message = "Access denied. Reason: "
2315 + client->accessDeniedReason();
2316 *reconnect_requested = client->reconnectRequested();
2317 errorstream << *error_message << std::endl;
2325 /* returns false if game should exit, otherwise true
2327 inline bool Game::handleCallbacks()
2329 if (g_gamecallback->disconnect_requested) {
2330 g_gamecallback->disconnect_requested = false;
2334 if (g_gamecallback->changepassword_requested) {
2335 (new GUIPasswordChange(guienv, guiroot, -1,
2336 &g_menumgr, client))->drop();
2337 g_gamecallback->changepassword_requested = false;
2340 if (g_gamecallback->changevolume_requested) {
2341 (new GUIVolumeChange(guienv, guiroot, -1,
2342 &g_menumgr))->drop();
2343 g_gamecallback->changevolume_requested = false;
2346 if (g_gamecallback->keyconfig_requested) {
2347 (new GUIKeyChangeMenu(guienv, guiroot, -1,
2348 &g_menumgr))->drop();
2349 g_gamecallback->keyconfig_requested = false;
2352 if (g_gamecallback->keyconfig_changed) {
2353 keycache.populate(); // update the cache with new settings
2354 g_gamecallback->keyconfig_changed = false;
2361 void Game::processQueues()
2363 texture_src->processQueue();
2364 itemdef_manager->processQueue(client);
2365 shader_src->processQueue();
2369 void Game::updateProfilers(const RunStats &stats, const FpsControl &draw_times, f32 dtime)
2371 float profiler_print_interval =
2372 g_settings->getFloat("profiler_print_interval");
2373 bool print_to_log = true;
2375 if (profiler_print_interval == 0) {
2376 print_to_log = false;
2377 profiler_print_interval = 5;
2380 if (profiler_interval.step(dtime, profiler_print_interval)) {
2382 infostream << "Profiler:" << std::endl;
2383 g_profiler->print(infostream);
2386 update_profiler_gui(guitext_profiler, g_fontengine,
2387 runData.profiler_current_page, runData.profiler_max_page,
2388 driver->getScreenSize().Height);
2390 g_profiler->clear();
2393 addProfilerGraphs(stats, draw_times, dtime);
2397 void Game::addProfilerGraphs(const RunStats &stats,
2398 const FpsControl &draw_times, f32 dtime)
2400 g_profiler->graphAdd("mainloop_other",
2401 draw_times.busy_time / 1000.0f - stats.drawtime / 1000.0f);
2403 if (draw_times.sleep_time != 0)
2404 g_profiler->graphAdd("mainloop_sleep", draw_times.sleep_time / 1000.0f);
2405 g_profiler->graphAdd("mainloop_dtime", dtime);
2407 g_profiler->add("Elapsed time", dtime);
2408 g_profiler->avg("FPS", 1. / dtime);
2412 void Game::updateStats(RunStats *stats, const FpsControl &draw_times,
2419 /* Time average and jitter calculation
2421 jp = &stats->dtime_jitter;
2422 jp->avg = jp->avg * 0.96 + dtime * 0.04;
2424 jitter = dtime - jp->avg;
2426 if (jitter > jp->max)
2429 jp->counter += dtime;
2431 if (jp->counter > 0.0) {
2433 jp->max_sample = jp->max;
2434 jp->max_fraction = jp->max_sample / (jp->avg + 0.001);
2438 /* Busytime average and jitter calculation
2440 jp = &stats->busy_time_jitter;
2441 jp->avg = jp->avg + draw_times.busy_time * 0.02;
2443 jitter = draw_times.busy_time - jp->avg;
2445 if (jitter > jp->max)
2447 if (jitter < jp->min)
2450 jp->counter += dtime;
2452 if (jp->counter > 0.0) {
2454 jp->max_sample = jp->max;
2455 jp->min_sample = jp->min;
2463 /****************************************************************************
2465 ****************************************************************************/
2467 void Game::processUserInput(f32 dtime)
2469 // Reset input if window not active or some menu is active
2470 if (!device->isWindowActive() || isMenuActive() || guienv->hasFocus(gui_chat_console)) {
2472 #ifdef HAVE_TOUCHSCREENGUI
2473 g_touchscreengui->hide();
2476 #ifdef HAVE_TOUCHSCREENGUI
2477 else if (g_touchscreengui) {
2478 /* on touchscreengui step may generate own input events which ain't
2479 * what we want in case we just did clear them */
2480 g_touchscreengui->step(dtime);
2484 if (!guienv->hasFocus(gui_chat_console) && gui_chat_console->isOpen()) {
2485 gui_chat_console->closeConsoleAtOnce();
2488 // Input handler step() (used by the random input generator)
2492 if (current_formspec != NULL)
2493 current_formspec->getAndroidUIInput();
2495 handleAndroidChatInput();
2498 // Increase timer for double tap of "keymap_jump"
2499 if (m_cache_doubletap_jump && runData.jump_timer <= 0.2f)
2500 runData.jump_timer += dtime;
2503 processItemSelection(&runData.new_playeritem);
2507 void Game::processKeyInput()
2509 if (wasKeyDown(KeyType::DROP)) {
2511 } else if (wasKeyDown(KeyType::AUTOFORWARD)) {
2512 toggleAutoforward();
2513 } else if (wasKeyDown(KeyType::INVENTORY)) {
2515 } else if (wasKeyDown(KeyType::ESC) || input->wasKeyDown(CancelKey)) {
2516 if (!gui_chat_console->isOpenInhibited()) {
2519 } else if (wasKeyDown(KeyType::CHAT)) {
2520 openConsole(0.2, L"");
2521 } else if (wasKeyDown(KeyType::CMD)) {
2522 openConsole(0.2, L"/");
2523 } else if (wasKeyDown(KeyType::CMD_LOCAL)) {
2524 openConsole(0.2, L".");
2525 } else if (wasKeyDown(KeyType::CONSOLE)) {
2526 openConsole(core::clamp(g_settings->getFloat("console_height"), 0.1f, 1.0f));
2527 } else if (wasKeyDown(KeyType::FREEMOVE)) {
2529 } else if (wasKeyDown(KeyType::JUMP)) {
2530 toggleFreeMoveAlt();
2531 } else if (wasKeyDown(KeyType::FASTMOVE)) {
2533 } else if (wasKeyDown(KeyType::NOCLIP)) {
2535 } else if (wasKeyDown(KeyType::MUTE)) {
2536 float volume = g_settings->getFloat("sound_volume");
2537 if (volume < 0.001f) {
2538 g_settings->setFloat("sound_volume", 1.0f);
2539 m_statustext = narrow_to_wide(gettext("Volume changed to 100%"));
2541 g_settings->setFloat("sound_volume", 0.0f);
2542 m_statustext = narrow_to_wide(gettext("Volume changed to 0%"));
2544 runData.statustext_time = 0;
2545 } else if (wasKeyDown(KeyType::INC_VOLUME)) {
2546 float new_volume = rangelim(g_settings->getFloat("sound_volume") + 0.1f, 0.0f, 1.0f);
2548 g_settings->setFloat("sound_volume", new_volume);
2549 snprintf(buf, sizeof(buf), gettext("Volume changed to %d%%"), myround(new_volume * 100));
2550 m_statustext = narrow_to_wide(buf);
2551 runData.statustext_time = 0;
2552 } else if (wasKeyDown(KeyType::DEC_VOLUME)) {
2553 float new_volume = rangelim(g_settings->getFloat("sound_volume") - 0.1f, 0.0f, 1.0f);
2555 g_settings->setFloat("sound_volume", new_volume);
2556 snprintf(buf, sizeof(buf), gettext("Volume changed to %d%%"), myround(new_volume * 100));
2557 m_statustext = narrow_to_wide(buf);
2558 runData.statustext_time = 0;
2559 } else if (wasKeyDown(KeyType::CINEMATIC)) {
2561 } else if (wasKeyDown(KeyType::SCREENSHOT)) {
2562 client->makeScreenshot();
2563 } else if (wasKeyDown(KeyType::TOGGLE_HUD)) {
2565 } else if (wasKeyDown(KeyType::MINIMAP)) {
2566 toggleMinimap(isKeyDown(KeyType::SNEAK));
2567 } else if (wasKeyDown(KeyType::TOGGLE_CHAT)) {
2569 } else if (wasKeyDown(KeyType::TOGGLE_FORCE_FOG_OFF)) {
2571 } else if (wasKeyDown(KeyType::TOGGLE_UPDATE_CAMERA)) {
2572 toggleUpdateCamera();
2573 } else if (wasKeyDown(KeyType::TOGGLE_DEBUG)) {
2575 } else if (wasKeyDown(KeyType::TOGGLE_PROFILER)) {
2577 } else if (wasKeyDown(KeyType::INCREASE_VIEWING_RANGE)) {
2578 increaseViewRange();
2579 } else if (wasKeyDown(KeyType::DECREASE_VIEWING_RANGE)) {
2580 decreaseViewRange();
2581 } else if (wasKeyDown(KeyType::RANGESELECT)) {
2582 toggleFullViewRange();
2583 } else if (wasKeyDown(KeyType::QUICKTUNE_NEXT)) {
2585 } else if (wasKeyDown(KeyType::QUICKTUNE_PREV)) {
2587 } else if (wasKeyDown(KeyType::QUICKTUNE_INC)) {
2589 } else if (wasKeyDown(KeyType::QUICKTUNE_DEC)) {
2591 } else if (wasKeyDown(KeyType::DEBUG_STACKS)) {
2592 // Print debug stacks
2593 dstream << "-----------------------------------------"
2595 dstream << "Printing debug stacks:" << std::endl;
2596 dstream << "-----------------------------------------"
2598 debug_stacks_print();
2601 if (!isKeyDown(KeyType::JUMP) && runData.reset_jump_timer) {
2602 runData.reset_jump_timer = false;
2603 runData.jump_timer = 0.0f;
2606 if (quicktune->hasMessage()) {
2607 m_statustext = utf8_to_wide(quicktune->getMessage());
2608 runData.statustext_time = 0.0f;
2612 void Game::processItemSelection(u16 *new_playeritem)
2614 LocalPlayer *player = client->getEnv().getLocalPlayer();
2616 /* Item selection using mouse wheel
2618 *new_playeritem = client->getPlayerItem();
2620 s32 wheel = input->getMouseWheel();
2621 u16 max_item = MYMIN(PLAYER_INVENTORY_SIZE - 1,
2622 player->hud_hotbar_itemcount - 1);
2626 if (input->joystick.wasKeyDown(KeyType::SCROLL_DOWN) ||
2627 wasKeyDown(KeyType::HOTBAR_NEXT)) {
2631 if (input->joystick.wasKeyDown(KeyType::SCROLL_UP) ||
2632 wasKeyDown(KeyType::HOTBAR_PREV)) {
2637 *new_playeritem = *new_playeritem < max_item ? *new_playeritem + 1 : 0;
2639 *new_playeritem = *new_playeritem > 0 ? *new_playeritem - 1 : max_item;
2642 /* Item selection using keyboard
2644 for (u16 i = 0; i < 10; i++) {
2645 static const KeyPress *item_keys[10] = {
2646 NumberKey + 1, NumberKey + 2, NumberKey + 3, NumberKey + 4,
2647 NumberKey + 5, NumberKey + 6, NumberKey + 7, NumberKey + 8,
2648 NumberKey + 9, NumberKey + 0,
2651 if (input->wasKeyDown(*item_keys[i])) {
2652 if (i < PLAYER_INVENTORY_SIZE && i < player->hud_hotbar_itemcount) {
2653 *new_playeritem = i;
2654 infostream << "Selected item: " << new_playeritem << std::endl;
2662 void Game::dropSelectedItem()
2664 IDropAction *a = new IDropAction();
2666 a->from_inv.setCurrentPlayer();
2667 a->from_list = "main";
2668 a->from_i = client->getPlayerItem();
2669 client->inventoryAction(a);
2673 void Game::openInventory()
2676 * Don't permit to open inventory is CAO or player doesn't exists.
2677 * This prevent showing an empty inventory at player load
2680 LocalPlayer *player = client->getEnv().getLocalPlayer();
2681 if (!player || !player->getCAO())
2684 infostream << "the_game: " << "Launching inventory" << std::endl;
2686 PlayerInventoryFormSource *fs_src = new PlayerInventoryFormSource(client);
2687 TextDest *txt_dst = new TextDestPlayerInventory(client);
2689 create_formspec_menu(¤t_formspec, client, &input->joystick, fs_src, txt_dst);
2692 InventoryLocation inventoryloc;
2693 inventoryloc.setCurrentPlayer();
2694 current_formspec->setFormSpec(fs_src->getForm(), inventoryloc);
2698 void Game::openConsole(float scale, const wchar_t *line)
2700 assert(scale > 0.0f && scale <= 1.0f);
2703 porting::showInputDialog(gettext("ok"), "", "", 2);
2704 m_android_chat_open = true;
2706 if (gui_chat_console->isOpenInhibited())
2708 gui_chat_console->openConsole(scale);
2710 gui_chat_console->setCloseOnEnter(true);
2711 gui_chat_console->replaceAndAddToHistory(line);
2717 void Game::handleAndroidChatInput()
2719 if (m_android_chat_open && porting::getInputDialogState() == 0) {
2720 std::string text = porting::getInputDialogValue();
2721 client->typeChatMessage(utf8_to_wide(text));
2727 void Game::toggleFreeMove()
2729 static const wchar_t *msg[] = { L"free_move disabled", L"free_move enabled" };
2731 bool free_move = !g_settings->getBool("free_move");
2732 g_settings->set("free_move", bool_to_cstr(free_move));
2734 runData.statustext_time = 0;
2735 m_statustext = msg[free_move];
2736 if (free_move && !client->checkPrivilege("fly"))
2737 m_statustext += L" (note: no 'fly' privilege)";
2741 void Game::toggleFreeMoveAlt()
2743 if (m_cache_doubletap_jump && runData.jump_timer < 0.2f)
2746 runData.reset_jump_timer = true;
2750 void Game::toggleFast()
2752 static const wchar_t *msg[] = { L"fast_move disabled", L"fast_move enabled" };
2753 bool fast_move = !g_settings->getBool("fast_move");
2754 g_settings->set("fast_move", bool_to_cstr(fast_move));
2756 runData.statustext_time = 0;
2757 m_statustext = msg[fast_move];
2759 bool has_fast_privs = client->checkPrivilege("fast");
2761 if (fast_move && !has_fast_privs)
2762 m_statustext += L" (note: no 'fast' privilege)";
2765 m_cache_hold_aux1 = fast_move && has_fast_privs;
2770 void Game::toggleNoClip()
2772 static const wchar_t *msg[] = { L"noclip disabled", L"noclip enabled" };
2773 bool noclip = !g_settings->getBool("noclip");
2774 g_settings->set("noclip", bool_to_cstr(noclip));
2776 runData.statustext_time = 0;
2777 m_statustext = msg[noclip];
2779 if (noclip && !client->checkPrivilege("noclip"))
2780 m_statustext += L" (note: no 'noclip' privilege)";
2783 void Game::toggleCinematic()
2785 static const wchar_t *msg[] = { L"cinematic disabled", L"cinematic enabled" };
2786 bool cinematic = !g_settings->getBool("cinematic");
2787 g_settings->set("cinematic", bool_to_cstr(cinematic));
2789 runData.statustext_time = 0;
2790 m_statustext = msg[cinematic];
2793 // Autoforward by toggling continuous forward.
2794 void Game::toggleAutoforward()
2796 static const wchar_t *msg[] = { L"autoforward disabled", L"autoforward enabled" };
2797 bool autoforward_enabled = !g_settings->getBool("continuous_forward");
2798 g_settings->set("continuous_forward", bool_to_cstr(autoforward_enabled));
2800 runData.statustext_time = 0;
2801 m_statustext = msg[autoforward_enabled ? 1 : 0];
2804 void Game::toggleChat()
2806 static const wchar_t *msg[] = { L"Chat hidden", L"Chat shown" };
2808 flags.show_chat = !flags.show_chat;
2809 runData.statustext_time = 0;
2810 m_statustext = msg[flags.show_chat];
2814 void Game::toggleHud()
2816 static const wchar_t *msg[] = { L"HUD hidden", L"HUD shown" };
2818 flags.show_hud = !flags.show_hud;
2819 runData.statustext_time = 0;
2820 m_statustext = msg[flags.show_hud];
2823 void Game::toggleMinimap(bool shift_pressed)
2825 if (!mapper || !flags.show_hud || !g_settings->getBool("enable_minimap"))
2828 if (shift_pressed) {
2829 mapper->toggleMinimapShape();
2833 u32 hud_flags = client->getEnv().getLocalPlayer()->hud_flags;
2835 MinimapMode mode = MINIMAP_MODE_OFF;
2836 if (hud_flags & HUD_FLAG_MINIMAP_VISIBLE) {
2837 mode = mapper->getMinimapMode();
2838 mode = (MinimapMode)((int)mode + 1);
2841 flags.show_minimap = true;
2843 case MINIMAP_MODE_SURFACEx1:
2844 m_statustext = L"Minimap in surface mode, Zoom x1";
2846 case MINIMAP_MODE_SURFACEx2:
2847 m_statustext = L"Minimap in surface mode, Zoom x2";
2849 case MINIMAP_MODE_SURFACEx4:
2850 m_statustext = L"Minimap in surface mode, Zoom x4";
2852 case MINIMAP_MODE_RADARx1:
2853 m_statustext = L"Minimap in radar mode, Zoom x1";
2855 case MINIMAP_MODE_RADARx2:
2856 m_statustext = L"Minimap in radar mode, Zoom x2";
2858 case MINIMAP_MODE_RADARx4:
2859 m_statustext = L"Minimap in radar mode, Zoom x4";
2862 mode = MINIMAP_MODE_OFF;
2863 flags.show_minimap = false;
2864 m_statustext = (hud_flags & HUD_FLAG_MINIMAP_VISIBLE) ?
2865 L"Minimap hidden" : L"Minimap disabled by server";
2868 runData.statustext_time = 0;
2869 mapper->setMinimapMode(mode);
2872 void Game::toggleFog()
2874 static const wchar_t *msg[] = { L"Fog enabled", L"Fog disabled" };
2876 flags.force_fog_off = !flags.force_fog_off;
2877 runData.statustext_time = 0;
2878 m_statustext = msg[flags.force_fog_off];
2882 void Game::toggleDebug()
2884 // Initial / 4x toggle: Chat only
2885 // 1x toggle: Debug text with chat
2886 // 2x toggle: Debug text with profiler graph
2887 // 3x toggle: Debug text and wireframe
2888 if (!flags.show_debug) {
2889 flags.show_debug = true;
2890 flags.show_profiler_graph = false;
2891 draw_control->show_wireframe = false;
2892 m_statustext = L"Debug info shown";
2893 } else if (!flags.show_profiler_graph && !draw_control->show_wireframe) {
2894 flags.show_profiler_graph = true;
2895 m_statustext = L"Profiler graph shown";
2896 } else if (!draw_control->show_wireframe && client->checkPrivilege("debug")) {
2897 flags.show_profiler_graph = false;
2898 draw_control->show_wireframe = true;
2899 m_statustext = L"Wireframe shown";
2901 flags.show_debug = false;
2902 flags.show_profiler_graph = false;
2903 draw_control->show_wireframe = false;
2904 if (client->checkPrivilege("debug")) {
2905 m_statustext = L"Debug info, profiler graph, and wireframe hidden";
2907 m_statustext = L"Debug info and profiler graph hidden";
2910 runData.statustext_time = 0;
2914 void Game::toggleUpdateCamera()
2916 static const wchar_t *msg[] = {
2917 L"Camera update enabled",
2918 L"Camera update disabled"
2921 flags.disable_camera_update = !flags.disable_camera_update;
2922 runData.statustext_time = 0;
2923 m_statustext = msg[flags.disable_camera_update];
2927 void Game::toggleProfiler()
2929 runData.profiler_current_page =
2930 (runData.profiler_current_page + 1) % (runData.profiler_max_page + 1);
2932 // FIXME: This updates the profiler with incomplete values
2933 update_profiler_gui(guitext_profiler, g_fontengine, runData.profiler_current_page,
2934 runData.profiler_max_page, driver->getScreenSize().Height);
2936 if (runData.profiler_current_page != 0) {
2937 std::wstringstream sstr;
2938 sstr << "Profiler shown (page " << runData.profiler_current_page
2939 << " of " << runData.profiler_max_page << ")";
2940 m_statustext = sstr.str();
2942 m_statustext = L"Profiler hidden";
2944 runData.statustext_time = 0;
2948 void Game::increaseViewRange()
2950 s16 range = g_settings->getS16("viewing_range");
2951 s16 range_new = range + 10;
2953 if (range_new > 4000) {
2955 m_statustext = utf8_to_wide("Viewing range is at maximum: "
2958 m_statustext = utf8_to_wide("Viewing range changed to "
2961 g_settings->set("viewing_range", itos(range_new));
2962 runData.statustext_time = 0;
2966 void Game::decreaseViewRange()
2968 s16 range = g_settings->getS16("viewing_range");
2969 s16 range_new = range - 10;
2971 if (range_new < 20) {
2973 m_statustext = utf8_to_wide("Viewing range is at minimum: "
2976 m_statustext = utf8_to_wide("Viewing range changed to "
2979 g_settings->set("viewing_range", itos(range_new));
2980 runData.statustext_time = 0;
2984 void Game::toggleFullViewRange()
2986 static const wchar_t *msg[] = {
2987 L"Disabled full viewing range",
2988 L"Enabled full viewing range"
2991 draw_control->range_all = !draw_control->range_all;
2992 infostream << msg[draw_control->range_all] << std::endl;
2993 m_statustext = msg[draw_control->range_all];
2994 runData.statustext_time = 0;
2998 void Game::updateCameraDirection(CameraOrientation *cam, float dtime)
3000 if ((device->isWindowActive() && device->isWindowFocused()
3001 && !isMenuActive()) || random_input) {
3004 if (!random_input) {
3005 // Mac OSX gets upset if this is set every frame
3006 if (device->getCursorControl()->isVisible())
3007 device->getCursorControl()->setVisible(false);
3011 if (m_first_loop_after_window_activation)
3012 m_first_loop_after_window_activation = false;
3014 updateCameraOrientation(cam, dtime);
3016 input->setMousePos((driver->getScreenSize().Width / 2),
3017 (driver->getScreenSize().Height / 2));
3021 // Mac OSX gets upset if this is set every frame
3022 if (!device->getCursorControl()->isVisible())
3023 device->getCursorControl()->setVisible(true);
3026 m_first_loop_after_window_activation = true;
3031 void Game::updateCameraOrientation(CameraOrientation *cam, float dtime)
3033 #ifdef HAVE_TOUCHSCREENGUI
3034 if (g_touchscreengui) {
3035 cam->camera_yaw += g_touchscreengui->getYawChange();
3036 cam->camera_pitch = g_touchscreengui->getPitch();
3040 s32 dx = input->getMousePos().X - (driver->getScreenSize().Width / 2);
3041 s32 dy = input->getMousePos().Y - (driver->getScreenSize().Height / 2);
3043 if (m_invert_mouse || camera->getCameraMode() == CAMERA_MODE_THIRD_FRONT) {
3047 cam->camera_yaw -= dx * m_cache_mouse_sensitivity;
3048 cam->camera_pitch += dy * m_cache_mouse_sensitivity;
3050 #ifdef HAVE_TOUCHSCREENGUI
3054 if (m_cache_enable_joysticks) {
3055 f32 c = m_cache_joystick_frustum_sensitivity * (1.f / 32767.f) * dtime;
3056 cam->camera_yaw -= input->joystick.getAxisWithoutDead(JA_FRUSTUM_HORIZONTAL) * c;
3057 cam->camera_pitch += input->joystick.getAxisWithoutDead(JA_FRUSTUM_VERTICAL) * c;
3060 cam->camera_pitch = rangelim(cam->camera_pitch, -89.5, 89.5);
3064 void Game::updatePlayerControl(const CameraOrientation &cam)
3066 //TimeTaker tt("update player control", NULL, PRECISION_NANO);
3068 // DO NOT use the isKeyDown method for the forward, backward, left, right
3069 // buttons, as the code that uses the controls needs to be able to
3070 // distinguish between the two in order to know when to use joysticks.
3072 PlayerControl control(
3073 input->isKeyDown(keycache.key[KeyType::FORWARD]),
3074 input->isKeyDown(keycache.key[KeyType::BACKWARD]),
3075 input->isKeyDown(keycache.key[KeyType::LEFT]),
3076 input->isKeyDown(keycache.key[KeyType::RIGHT]),
3077 isKeyDown(KeyType::JUMP),
3078 isKeyDown(KeyType::SPECIAL1),
3079 isKeyDown(KeyType::SNEAK),
3080 isKeyDown(KeyType::ZOOM),
3085 input->joystick.getAxisWithoutDead(JA_SIDEWARD_MOVE),
3086 input->joystick.getAxisWithoutDead(JA_FORWARD_MOVE)
3090 ( (u32)(isKeyDown(KeyType::FORWARD) & 0x1) << 0) |
3091 ( (u32)(isKeyDown(KeyType::BACKWARD) & 0x1) << 1) |
3092 ( (u32)(isKeyDown(KeyType::LEFT) & 0x1) << 2) |
3093 ( (u32)(isKeyDown(KeyType::RIGHT) & 0x1) << 3) |
3094 ( (u32)(isKeyDown(KeyType::JUMP) & 0x1) << 4) |
3095 ( (u32)(isKeyDown(KeyType::SPECIAL1) & 0x1) << 5) |
3096 ( (u32)(isKeyDown(KeyType::SNEAK) & 0x1) << 6) |
3097 ( (u32)(isLeftPressed() & 0x1) << 7) |
3098 ( (u32)(isRightPressed() & 0x1) << 8
3102 /* For Android, simulate holding down AUX1 (fast move) if the user has
3103 * the fast_move setting toggled on. If there is an aux1 key defined for
3104 * Android then its meaning is inverted (i.e. holding aux1 means walk and
3107 if (m_cache_hold_aux1) {
3108 control.aux1 = control.aux1 ^ true;
3109 keypress_bits ^= ((u32)(1U << 5));
3113 client->setPlayerControl(control);
3114 LocalPlayer *player = client->getEnv().getLocalPlayer();
3115 player->keyPressed = keypress_bits;
3121 inline void Game::step(f32 *dtime)
3123 bool can_be_and_is_paused =
3124 (simple_singleplayer_mode && g_menumgr.pausesGame());
3126 if (can_be_and_is_paused) { // This is for a singleplayer server
3127 *dtime = 0; // No time passes
3129 if (server != NULL) {
3130 //TimeTaker timer("server->step(dtime)");
3131 server->step(*dtime);
3134 //TimeTaker timer("client.step(dtime)");
3135 client->step(*dtime);
3140 void Game::processClientEvents(CameraOrientation *cam)
3142 LocalPlayer *player = client->getEnv().getLocalPlayer();
3144 while (client->hasClientEvents()) {
3145 ClientEvent event = client->getClientEvent();
3147 switch (event.type) {
3148 case CE_PLAYER_DAMAGE:
3149 if (client->getHP() == 0)
3151 if (client->moddingEnabled()) {
3152 client->getScript()->on_damage_taken(event.player_damage.amount);
3155 runData.damage_flash += 95.0 + 3.2 * event.player_damage.amount;
3156 runData.damage_flash = MYMIN(runData.damage_flash, 127.0);
3158 player->hurt_tilt_timer = 1.5;
3159 player->hurt_tilt_strength =
3160 rangelim(event.player_damage.amount / 4, 1.0, 4.0);
3162 client->event()->put(new SimpleTriggerEvent("PlayerDamage"));
3165 case CE_PLAYER_FORCE_MOVE:
3166 cam->camera_yaw = event.player_force_move.yaw;
3167 cam->camera_pitch = event.player_force_move.pitch;
3170 case CE_DEATHSCREEN:
3171 // This should be enabled for death formspec in builtin
3172 client->getScript()->on_death();
3174 /* Handle visualization */
3175 runData.damage_flash = 0;
3176 player->hurt_tilt_timer = 0;
3177 player->hurt_tilt_strength = 0;
3180 case CE_SHOW_FORMSPEC:
3181 if (*(event.show_formspec.formspec) == "") {
3182 if (current_formspec && ( *(event.show_formspec.formname) == "" || *(event.show_formspec.formname) == cur_formname) ){
3183 current_formspec->quitMenu();
3186 FormspecFormSource *fs_src =
3187 new FormspecFormSource(*(event.show_formspec.formspec));
3188 TextDestPlayerInventory *txt_dst =
3189 new TextDestPlayerInventory(client, *(event.show_formspec.formname));
3191 create_formspec_menu(¤t_formspec, client, &input->joystick,
3193 cur_formname = *(event.show_formspec.formname);
3196 delete event.show_formspec.formspec;
3197 delete event.show_formspec.formname;
3200 case CE_SHOW_LOCAL_FORMSPEC:
3202 FormspecFormSource *fs_src = new FormspecFormSource(*event.show_formspec.formspec);
3203 LocalFormspecHandler *txt_dst = new LocalFormspecHandler(*event.show_formspec.formname, client);
3204 create_formspec_menu(¤t_formspec, client, &input->joystick,
3207 delete event.show_formspec.formspec;
3208 delete event.show_formspec.formname;
3211 case CE_SPAWN_PARTICLE:
3212 case CE_ADD_PARTICLESPAWNER:
3213 case CE_DELETE_PARTICLESPAWNER:
3214 client->getParticleManager()->handleParticleEvent(&event, client, player);
3219 u32 id = event.hudadd.id;
3221 HudElement *e = player->getHud(id);
3224 delete event.hudadd.pos;
3225 delete event.hudadd.name;
3226 delete event.hudadd.scale;
3227 delete event.hudadd.text;
3228 delete event.hudadd.align;
3229 delete event.hudadd.offset;
3230 delete event.hudadd.world_pos;
3231 delete event.hudadd.size;
3236 e->type = (HudElementType)event.hudadd.type;
3237 e->pos = *event.hudadd.pos;
3238 e->name = *event.hudadd.name;
3239 e->scale = *event.hudadd.scale;
3240 e->text = *event.hudadd.text;
3241 e->number = event.hudadd.number;
3242 e->item = event.hudadd.item;
3243 e->dir = event.hudadd.dir;
3244 e->align = *event.hudadd.align;
3245 e->offset = *event.hudadd.offset;
3246 e->world_pos = *event.hudadd.world_pos;
3247 e->size = *event.hudadd.size;
3249 u32 new_id = player->addHud(e);
3250 //if this isn't true our huds aren't consistent
3251 sanity_check(new_id == id);
3254 delete event.hudadd.pos;
3255 delete event.hudadd.name;
3256 delete event.hudadd.scale;
3257 delete event.hudadd.text;
3258 delete event.hudadd.align;
3259 delete event.hudadd.offset;
3260 delete event.hudadd.world_pos;
3261 delete event.hudadd.size;
3266 HudElement *e = player->removeHud(event.hudrm.id);
3274 u32 id = event.hudchange.id;
3275 HudElement *e = player->getHud(id);
3278 delete event.hudchange.v3fdata;
3279 delete event.hudchange.v2fdata;
3280 delete event.hudchange.sdata;
3281 delete event.hudchange.v2s32data;
3285 switch (event.hudchange.stat) {
3287 e->pos = *event.hudchange.v2fdata;
3291 e->name = *event.hudchange.sdata;
3294 case HUD_STAT_SCALE:
3295 e->scale = *event.hudchange.v2fdata;
3299 e->text = *event.hudchange.sdata;
3302 case HUD_STAT_NUMBER:
3303 e->number = event.hudchange.data;
3307 e->item = event.hudchange.data;
3311 e->dir = event.hudchange.data;
3314 case HUD_STAT_ALIGN:
3315 e->align = *event.hudchange.v2fdata;
3318 case HUD_STAT_OFFSET:
3319 e->offset = *event.hudchange.v2fdata;
3322 case HUD_STAT_WORLD_POS:
3323 e->world_pos = *event.hudchange.v3fdata;
3327 e->size = *event.hudchange.v2s32data;
3332 delete event.hudchange.v3fdata;
3333 delete event.hudchange.v2fdata;
3334 delete event.hudchange.sdata;
3335 delete event.hudchange.v2s32data;
3339 sky->setVisible(false);
3340 // Whether clouds are visible in front of a custom skybox
3341 sky->setCloudsEnabled(event.set_sky.clouds);
3348 // Handle according to type
3349 if (*event.set_sky.type == "regular") {
3350 sky->setVisible(true);
3351 sky->setCloudsEnabled(true);
3352 } else if (*event.set_sky.type == "skybox" &&
3353 event.set_sky.params->size() == 6) {
3354 sky->setFallbackBgColor(*event.set_sky.bgcolor);
3355 skybox = RenderingEngine::get_scene_manager()->addSkyBoxSceneNode(
3356 texture_src->getTextureForMesh((*event.set_sky.params)[0]),
3357 texture_src->getTextureForMesh((*event.set_sky.params)[1]),
3358 texture_src->getTextureForMesh((*event.set_sky.params)[2]),
3359 texture_src->getTextureForMesh((*event.set_sky.params)[3]),
3360 texture_src->getTextureForMesh((*event.set_sky.params)[4]),
3361 texture_src->getTextureForMesh((*event.set_sky.params)[5]));
3363 // Handle everything else as plain color
3365 if (*event.set_sky.type != "plain")
3366 infostream << "Unknown sky type: "
3367 << (*event.set_sky.type) << std::endl;
3369 sky->setFallbackBgColor(*event.set_sky.bgcolor);
3372 delete event.set_sky.bgcolor;
3373 delete event.set_sky.type;
3374 delete event.set_sky.params;
3377 case CE_OVERRIDE_DAY_NIGHT_RATIO:
3378 client->getEnv().setDayNightRatioOverride(
3379 event.override_day_night_ratio.do_override,
3380 event.override_day_night_ratio.ratio_f * 1000);
3383 case CE_CLOUD_PARAMS:
3385 clouds->setDensity(event.cloud_params.density);
3386 clouds->setColorBright(video::SColor(event.cloud_params.color_bright));
3387 clouds->setColorAmbient(video::SColor(event.cloud_params.color_ambient));
3388 clouds->setHeight(event.cloud_params.height);
3389 clouds->setThickness(event.cloud_params.thickness);
3390 clouds->setSpeed(v2f(
3391 event.cloud_params.speed_x,
3392 event.cloud_params.speed_y));
3397 // unknown or unhandled type
3405 void Game::updateCamera(u32 busy_time, f32 dtime)
3407 LocalPlayer *player = client->getEnv().getLocalPlayer();
3410 For interaction purposes, get info about the held item
3412 - Is it a usable item?
3413 - Can it point to liquids?
3415 ItemStack playeritem;
3417 InventoryList *mlist = local_inventory->getList("main");
3419 if (mlist && client->getPlayerItem() < mlist->getSize())
3420 playeritem = mlist->getItem(client->getPlayerItem());
3423 if (playeritem.getDefinition(itemdef_manager).name.empty()) { // override the hand
3424 InventoryList *hlist = local_inventory->getList("hand");
3426 playeritem = hlist->getItem(0);
3430 ToolCapabilities playeritem_toolcap =
3431 playeritem.getToolCapabilities(itemdef_manager);
3433 v3s16 old_camera_offset = camera->getOffset();
3435 if (wasKeyDown(KeyType::CAMERA_MODE)) {
3436 GenericCAO *playercao = player->getCAO();
3438 // If playercao not loaded, don't change camera
3442 camera->toggleCameraMode();
3444 playercao->setVisible(camera->getCameraMode() > CAMERA_MODE_FIRST);
3445 playercao->setChildrenVisible(camera->getCameraMode() > CAMERA_MODE_FIRST);
3448 float full_punch_interval = playeritem_toolcap.full_punch_interval;
3449 float tool_reload_ratio = runData.time_from_last_punch / full_punch_interval;
3451 tool_reload_ratio = MYMIN(tool_reload_ratio, 1.0);
3452 camera->update(player, dtime, busy_time / 1000.0f, tool_reload_ratio,
3454 camera->step(dtime);
3456 v3f camera_position = camera->getPosition();
3457 v3f camera_direction = camera->getDirection();
3458 f32 camera_fov = camera->getFovMax();
3459 v3s16 camera_offset = camera->getOffset();
3461 m_camera_offset_changed = (camera_offset != old_camera_offset);
3463 if (!flags.disable_camera_update) {
3464 client->getEnv().getClientMap().updateCamera(camera_position,
3465 camera_direction, camera_fov, camera_offset);
3467 if (m_camera_offset_changed) {
3468 client->updateCameraOffset(camera_offset);
3469 client->getEnv().updateCameraOffset(camera_offset);
3472 clouds->updateCameraOffset(camera_offset);
3478 void Game::updateSound(f32 dtime)
3480 // Update sound listener
3481 v3s16 camera_offset = camera->getOffset();
3482 sound->updateListener(camera->getCameraNode()->getPosition() + intToFloat(camera_offset, BS),
3483 v3f(0, 0, 0), // velocity
3484 camera->getDirection(),
3485 camera->getCameraNode()->getUpVector());
3487 // Check if volume is in the proper range, else fix it.
3488 float old_volume = g_settings->getFloat("sound_volume");
3489 float new_volume = rangelim(old_volume, 0.0f, 1.0f);
3490 sound->setListenerGain(new_volume);
3492 if (old_volume != new_volume) {
3493 g_settings->setFloat("sound_volume", new_volume);
3496 LocalPlayer *player = client->getEnv().getLocalPlayer();
3498 // Tell the sound maker whether to make footstep sounds
3499 soundmaker->makes_footstep_sound = player->makes_footstep_sound;
3501 // Update sound maker
3502 if (player->makes_footstep_sound)
3503 soundmaker->step(dtime);
3505 ClientMap &map = client->getEnv().getClientMap();
3506 MapNode n = map.getNodeNoEx(player->getFootstepNodePos());
3507 soundmaker->m_player_step_sound = nodedef_manager->get(n).sound_footstep;
3511 void Game::processPlayerInteraction(f32 dtime, bool show_hud, bool show_debug)
3513 LocalPlayer *player = client->getEnv().getLocalPlayer();
3515 ItemStack playeritem;
3517 InventoryList *mlist = local_inventory->getList("main");
3519 if (mlist && client->getPlayerItem() < mlist->getSize())
3520 playeritem = mlist->getItem(client->getPlayerItem());
3523 const ItemDefinition &playeritem_def =
3524 playeritem.getDefinition(itemdef_manager);
3525 InventoryList *hlist = local_inventory->getList("hand");
3526 const ItemDefinition &hand_def =
3527 hlist ? hlist->getItem(0).getDefinition(itemdef_manager) : itemdef_manager->get("");
3529 v3f player_position = player->getPosition();
3530 v3f camera_position = camera->getPosition();
3531 v3f camera_direction = camera->getDirection();
3532 v3s16 camera_offset = camera->getOffset();
3536 Calculate what block is the crosshair pointing to
3539 f32 d = playeritem_def.range; // max. distance
3540 f32 d_hand = hand_def.range;
3542 if (d < 0 && d_hand >= 0)
3547 core::line3d<f32> shootline;
3549 if (camera->getCameraMode() != CAMERA_MODE_THIRD_FRONT) {
3550 shootline = core::line3d<f32>(camera_position,
3551 camera_position + camera_direction * BS * d);
3553 // prevent player pointing anything in front-view
3554 shootline = core::line3d<f32>(camera_position,camera_position);
3557 #ifdef HAVE_TOUCHSCREENGUI
3559 if ((g_settings->getBool("touchtarget")) && (g_touchscreengui)) {
3560 shootline = g_touchscreengui->getShootline();
3561 shootline.start += intToFloat(camera_offset, BS);
3562 shootline.end += intToFloat(camera_offset, BS);
3567 PointedThing pointed = updatePointedThing(shootline,
3568 playeritem_def.liquids_pointable,
3569 !runData.ldown_for_dig,
3572 if (pointed != runData.pointed_old) {
3573 infostream << "Pointing at " << pointed.dump() << std::endl;
3574 hud->updateSelectionMesh(camera_offset);
3579 - releasing left mouse button
3580 - pointing away from node
3582 if (runData.digging) {
3583 if (getLeftReleased()) {
3584 infostream << "Left button released"
3585 << " (stopped digging)" << std::endl;
3586 runData.digging = false;
3587 } else if (pointed != runData.pointed_old) {
3588 if (pointed.type == POINTEDTHING_NODE
3589 && runData.pointed_old.type == POINTEDTHING_NODE
3590 && pointed.node_undersurface
3591 == runData.pointed_old.node_undersurface) {
3592 // Still pointing to the same node, but a different face.
3595 infostream << "Pointing away from node"
3596 << " (stopped digging)" << std::endl;
3597 runData.digging = false;
3598 hud->updateSelectionMesh(camera_offset);
3602 if (!runData.digging) {
3603 client->interact(1, runData.pointed_old);
3604 client->setCrack(-1, v3s16(0, 0, 0));
3605 runData.dig_time = 0.0;
3607 } else if (runData.dig_instantly && getLeftReleased()) {
3608 // Remove e.g. torches faster when clicking instead of holding LMB
3609 runData.nodig_delay_timer = 0;
3610 runData.dig_instantly = false;
3613 if (!runData.digging && runData.ldown_for_dig && !isLeftPressed()) {
3614 runData.ldown_for_dig = false;
3617 runData.left_punch = false;
3619 soundmaker->m_player_leftpunch_sound.name = "";
3621 if (isRightPressed())
3622 runData.repeat_rightclick_timer += dtime;
3624 runData.repeat_rightclick_timer = 0;
3626 if (playeritem_def.usable && isLeftPressed()) {
3627 if (getLeftClicked() && (!client->moddingEnabled()
3628 || !client->getScript()->on_item_use(playeritem, pointed)))
3629 client->interact(4, pointed);
3630 } else if (pointed.type == POINTEDTHING_NODE) {
3631 ToolCapabilities playeritem_toolcap =
3632 playeritem.getToolCapabilities(itemdef_manager);
3633 if (playeritem.name.empty() && hand_def.tool_capabilities != NULL) {
3634 playeritem_toolcap = *hand_def.tool_capabilities;
3636 handlePointingAtNode(pointed, playeritem_def, playeritem,
3637 playeritem_toolcap, dtime);
3638 } else if (pointed.type == POINTEDTHING_OBJECT) {
3639 handlePointingAtObject(pointed, playeritem, player_position, show_debug);
3640 } else if (isLeftPressed()) {
3641 // When button is held down in air, show continuous animation
3642 runData.left_punch = true;
3643 } else if (getRightClicked()) {
3644 handlePointingAtNothing(playeritem);
3647 runData.pointed_old = pointed;
3649 if (runData.left_punch || getLeftClicked())
3650 camera->setDigging(0); // left click animation
3652 input->resetLeftClicked();
3653 input->resetRightClicked();
3655 input->joystick.clearWasKeyDown(KeyType::MOUSE_L);
3656 input->joystick.clearWasKeyDown(KeyType::MOUSE_R);
3658 input->resetLeftReleased();
3659 input->resetRightReleased();
3661 input->joystick.clearWasKeyReleased(KeyType::MOUSE_L);
3662 input->joystick.clearWasKeyReleased(KeyType::MOUSE_R);
3666 PointedThing Game::updatePointedThing(
3667 const core::line3d<f32> &shootline,
3668 bool liquids_pointable,
3669 bool look_for_object,
3670 const v3s16 &camera_offset)
3672 std::vector<aabb3f> *selectionboxes = hud->getSelectionBoxes();
3673 selectionboxes->clear();
3674 hud->setSelectedFaceNormal(v3f(0.0, 0.0, 0.0));
3675 static thread_local const bool show_entity_selectionbox = g_settings->getBool(
3676 "show_entity_selectionbox");
3678 ClientEnvironment &env = client->getEnv();
3679 ClientMap &map = env.getClientMap();
3680 INodeDefManager *nodedef = map.getNodeDefManager();
3682 runData.selected_object = NULL;
3684 RaycastState s(shootline, look_for_object, liquids_pointable);
3685 PointedThing result;
3686 env.continueRaycast(&s, &result);
3687 if (result.type == POINTEDTHING_OBJECT) {
3688 runData.selected_object = client->getEnv().getActiveObject(result.object_id);
3689 aabb3f selection_box;
3690 if (show_entity_selectionbox && runData.selected_object->doShowSelectionBox() &&
3691 runData.selected_object->getSelectionBox(&selection_box)) {
3692 v3f pos = runData.selected_object->getPosition();
3693 selectionboxes->push_back(aabb3f(selection_box));
3694 hud->setSelectionPos(pos, camera_offset);
3696 } else if (result.type == POINTEDTHING_NODE) {
3697 // Update selection boxes
3698 MapNode n = map.getNodeNoEx(result.node_undersurface);
3699 std::vector<aabb3f> boxes;
3700 n.getSelectionBoxes(nodedef, &boxes,
3701 n.getNeighbors(result.node_undersurface, &map));
3704 for (std::vector<aabb3f>::const_iterator i = boxes.begin();
3705 i != boxes.end(); ++i) {
3707 box.MinEdge -= v3f(d, d, d);
3708 box.MaxEdge += v3f(d, d, d);
3709 selectionboxes->push_back(box);
3711 hud->setSelectionPos(intToFloat(result.node_undersurface, BS),
3713 hud->setSelectedFaceNormal(v3f(
3714 result.intersection_normal.X,
3715 result.intersection_normal.Y,
3716 result.intersection_normal.Z));
3719 // Update selection mesh light level and vertex colors
3720 if (selectionboxes->size() > 0) {
3721 v3f pf = hud->getSelectionPos();
3722 v3s16 p = floatToInt(pf, BS);
3724 // Get selection mesh light level
3725 MapNode n = map.getNodeNoEx(p);
3726 u16 node_light = getInteriorLight(n, -1, nodedef);
3727 u16 light_level = node_light;
3729 for (u8 i = 0; i < 6; i++) {
3730 n = map.getNodeNoEx(p + g_6dirs[i]);
3731 node_light = getInteriorLight(n, -1, nodedef);
3732 if (node_light > light_level)
3733 light_level = node_light;
3736 u32 daynight_ratio = client->getEnv().getDayNightRatio();
3738 final_color_blend(&c, light_level, daynight_ratio);
3740 // Modify final color a bit with time
3741 u32 timer = porting::getTimeMs() % 5000;
3742 float timerf = (float) (irr::core::PI * ((timer / 2500.0) - 0.5));
3743 float sin_r = 0.08 * sin(timerf);
3744 float sin_g = 0.08 * sin(timerf + irr::core::PI * 0.5);
3745 float sin_b = 0.08 * sin(timerf + irr::core::PI);
3746 c.setRed(core::clamp(core::round32(c.getRed() * (0.8 + sin_r)), 0, 255));
3747 c.setGreen(core::clamp(core::round32(c.getGreen() * (0.8 + sin_g)), 0, 255));
3748 c.setBlue(core::clamp(core::round32(c.getBlue() * (0.8 + sin_b)), 0, 255));
3750 // Set mesh final color
3751 hud->setSelectionMeshColor(c);
3757 void Game::handlePointingAtNothing(const ItemStack &playerItem)
3759 infostream << "Right Clicked in Air" << std::endl;
3760 PointedThing fauxPointed;
3761 fauxPointed.type = POINTEDTHING_NOTHING;
3762 client->interact(5, fauxPointed);
3766 void Game::handlePointingAtNode(const PointedThing &pointed,
3767 const ItemDefinition &playeritem_def, const ItemStack &playeritem,
3768 const ToolCapabilities &playeritem_toolcap, f32 dtime)
3770 v3s16 nodepos = pointed.node_undersurface;
3771 v3s16 neighbourpos = pointed.node_abovesurface;
3774 Check information text of node
3777 ClientMap &map = client->getEnv().getClientMap();
3779 if (runData.nodig_delay_timer <= 0.0 && isLeftPressed()
3780 && client->checkPrivilege("interact")) {
3781 handleDigging(pointed, nodepos, playeritem_toolcap, dtime);
3784 // This should be done after digging handling
3785 NodeMetadata *meta = map.getNodeMetadata(nodepos);
3788 infotext = unescape_enriched(utf8_to_wide(meta->getString("infotext")));
3790 MapNode n = map.getNodeNoEx(nodepos);
3792 if (nodedef_manager->get(n).tiledef[0].name == "unknown_node.png") {
3793 infotext = L"Unknown node: ";
3794 infotext += utf8_to_wide(nodedef_manager->get(n).name);
3798 if ((getRightClicked() ||
3799 runData.repeat_rightclick_timer >= m_repeat_right_click_time) &&
3800 client->checkPrivilege("interact")) {
3801 runData.repeat_rightclick_timer = 0;
3802 infostream << "Ground right-clicked" << std::endl;
3804 if (meta && meta->getString("formspec") != "" && !random_input
3805 && !isKeyDown(KeyType::SNEAK)) {
3806 infostream << "Launching custom inventory view" << std::endl;
3808 InventoryLocation inventoryloc;
3809 inventoryloc.setNodeMeta(nodepos);
3811 NodeMetadataFormSource *fs_src = new NodeMetadataFormSource(
3812 &client->getEnv().getClientMap(), nodepos);
3813 TextDest *txt_dst = new TextDestNodeMetadata(nodepos, client);
3815 create_formspec_menu(¤t_formspec, client,
3816 &input->joystick, fs_src, txt_dst);
3819 current_formspec->setFormSpec(meta->getString("formspec"), inventoryloc);
3821 // Report right click to server
3823 camera->setDigging(1); // right click animation (always shown for feedback)
3825 // If the wielded item has node placement prediction,
3827 bool placed = nodePlacementPrediction(*client,
3828 playeritem_def, playeritem,
3829 nodepos, neighbourpos);
3833 client->interact(3, pointed);
3835 soundmaker->m_player_rightpunch_sound =
3836 playeritem_def.sound_place;
3838 if (client->moddingEnabled())
3839 client->getScript()->on_placenode(pointed, playeritem_def);
3841 soundmaker->m_player_rightpunch_sound =
3844 if (playeritem_def.node_placement_prediction == "" ||
3845 nodedef_manager->get(map.getNodeNoEx(nodepos)).rightclickable) {
3846 client->interact(3, pointed); // Report to server
3848 soundmaker->m_player_rightpunch_sound =
3849 playeritem_def.sound_place_failed;
3857 void Game::handlePointingAtObject(const PointedThing &pointed, const ItemStack &playeritem,
3858 const v3f &player_position, bool show_debug)
3860 infotext = unescape_enriched(
3861 utf8_to_wide(runData.selected_object->infoText()));
3864 if (infotext != L"") {
3867 infotext += unescape_enriched(utf8_to_wide(
3868 runData.selected_object->debugInfoText()));
3871 if (isLeftPressed()) {
3872 bool do_punch = false;
3873 bool do_punch_damage = false;
3875 if (runData.object_hit_delay_timer <= 0.0) {
3877 do_punch_damage = true;
3878 runData.object_hit_delay_timer = object_hit_delay;
3881 if (getLeftClicked())
3885 infostream << "Left-clicked object" << std::endl;
3886 runData.left_punch = true;
3889 if (do_punch_damage) {
3890 // Report direct punch
3891 v3f objpos = runData.selected_object->getPosition();
3892 v3f dir = (objpos - player_position).normalize();
3893 ItemStack item = playeritem;
3894 if (playeritem.name.empty()) {
3895 InventoryList *hlist = local_inventory->getList("hand");
3897 item = hlist->getItem(0);
3901 bool disable_send = runData.selected_object->directReportPunch(
3902 dir, &item, runData.time_from_last_punch);
3903 runData.time_from_last_punch = 0;
3906 client->interact(0, pointed);
3908 } else if (getRightClicked()) {
3909 infostream << "Right-clicked object" << std::endl;
3910 client->interact(3, pointed); // place
3915 void Game::handleDigging(const PointedThing &pointed, const v3s16 &nodepos,
3916 const ToolCapabilities &playeritem_toolcap, f32 dtime)
3918 LocalPlayer *player = client->getEnv().getLocalPlayer();
3919 ClientMap &map = client->getEnv().getClientMap();
3920 MapNode n = client->getEnv().getClientMap().getNodeNoEx(nodepos);
3922 // NOTE: Similar piece of code exists on the server side for
3924 // Get digging parameters
3925 DigParams params = getDigParams(nodedef_manager->get(n).groups,
3926 &playeritem_toolcap);
3928 // If can't dig, try hand
3929 if (!params.diggable) {
3930 InventoryList *hlist = local_inventory->getList("hand");
3931 const ItemDefinition &hand =
3932 hlist ? hlist->getItem(0).getDefinition(itemdef_manager) : itemdef_manager->get("");
3933 const ToolCapabilities *tp = hand.tool_capabilities;
3936 params = getDigParams(nodedef_manager->get(n).groups, tp);
3939 if (!params.diggable) {
3940 // I guess nobody will wait for this long
3941 runData.dig_time_complete = 10000000.0;
3943 runData.dig_time_complete = params.time;
3945 if (m_cache_enable_particles) {
3946 const ContentFeatures &features = client->getNodeDefManager()->get(n);
3947 client->getParticleManager()->addPunchingParticles(client,
3948 player, nodepos, n, features);
3952 if (!runData.digging) {
3953 infostream << "Started digging" << std::endl;
3954 runData.dig_instantly = runData.dig_time_complete == 0;
3955 if (client->moddingEnabled() && client->getScript()->on_punchnode(nodepos, n))
3957 client->interact(0, pointed);
3958 runData.digging = true;
3959 runData.ldown_for_dig = true;
3962 if (!runData.dig_instantly) {
3963 runData.dig_index = (float)crack_animation_length
3965 / runData.dig_time_complete;
3967 // This is for e.g. torches
3968 runData.dig_index = crack_animation_length;
3971 SimpleSoundSpec sound_dig = nodedef_manager->get(n).sound_dig;
3973 if (sound_dig.exists() && params.diggable) {
3974 if (sound_dig.name == "__group") {
3975 if (params.main_group != "") {
3976 soundmaker->m_player_leftpunch_sound.gain = 0.5;
3977 soundmaker->m_player_leftpunch_sound.name =
3978 std::string("default_dig_") +
3982 soundmaker->m_player_leftpunch_sound = sound_dig;
3986 // Don't show cracks if not diggable
3987 if (runData.dig_time_complete >= 100000.0) {
3988 } else if (runData.dig_index < crack_animation_length) {
3989 //TimeTaker timer("client.setTempMod");
3990 //infostream<<"dig_index="<<dig_index<<std::endl;
3991 client->setCrack(runData.dig_index, nodepos);
3993 infostream << "Digging completed" << std::endl;
3994 client->setCrack(-1, v3s16(0, 0, 0));
3996 runData.dig_time = 0;
3997 runData.digging = false;
3999 runData.nodig_delay_timer =
4000 runData.dig_time_complete / (float)crack_animation_length;
4002 // We don't want a corresponding delay to very time consuming nodes
4003 // and nodes without digging time (e.g. torches) get a fixed delay.
4004 if (runData.nodig_delay_timer > 0.3)
4005 runData.nodig_delay_timer = 0.3;
4006 else if (runData.dig_instantly)
4007 runData.nodig_delay_timer = 0.15;
4009 bool is_valid_position;
4010 MapNode wasnode = map.getNodeNoEx(nodepos, &is_valid_position);
4011 if (is_valid_position) {
4012 if (client->moddingEnabled() &&
4013 client->getScript()->on_dignode(nodepos, wasnode)) {
4016 client->removeNode(nodepos);
4019 client->interact(2, pointed);
4021 if (m_cache_enable_particles) {
4022 const ContentFeatures &features =
4023 client->getNodeDefManager()->get(wasnode);
4024 client->getParticleManager()->addDiggingParticles(client,
4025 player, nodepos, wasnode, features);
4029 // Send event to trigger sound
4030 MtEvent *e = new NodeDugEvent(nodepos, wasnode);
4031 client->event()->put(e);
4034 if (runData.dig_time_complete < 100000.0) {
4035 runData.dig_time += dtime;
4037 runData.dig_time = 0;
4038 client->setCrack(-1, nodepos);
4041 camera->setDigging(0); // left click animation
4045 void Game::updateFrame(ProfilerGraph *graph, RunStats *stats, f32 dtime,
4046 const CameraOrientation &cam)
4048 LocalPlayer *player = client->getEnv().getLocalPlayer();
4054 if (draw_control->range_all) {
4055 runData.fog_range = 100000 * BS;
4057 runData.fog_range = draw_control->wanted_range * BS;
4061 Calculate general brightness
4063 u32 daynight_ratio = client->getEnv().getDayNightRatio();
4064 float time_brightness = decode_light_f((float)daynight_ratio / 1000.0);
4065 float direct_brightness;
4068 if (m_cache_enable_noclip && m_cache_enable_free_move) {
4069 direct_brightness = time_brightness;
4070 sunlight_seen = true;
4072 ScopeProfiler sp(g_profiler, "Detecting background light", SPT_AVG);
4073 float old_brightness = sky->getBrightness();
4074 direct_brightness = client->getEnv().getClientMap()
4075 .getBackgroundBrightness(MYMIN(runData.fog_range * 1.2, 60 * BS),
4076 daynight_ratio, (int)(old_brightness * 255.5), &sunlight_seen)
4080 float time_of_day_smooth = runData.time_of_day_smooth;
4081 float time_of_day = client->getEnv().getTimeOfDayF();
4083 static const float maxsm = 0.05;
4084 static const float todsm = 0.05;
4086 if (fabs(time_of_day - time_of_day_smooth) > maxsm &&
4087 fabs(time_of_day - time_of_day_smooth + 1.0) > maxsm &&
4088 fabs(time_of_day - time_of_day_smooth - 1.0) > maxsm)
4089 time_of_day_smooth = time_of_day;
4091 if (time_of_day_smooth > 0.8 && time_of_day < 0.2)
4092 time_of_day_smooth = time_of_day_smooth * (1.0 - todsm)
4093 + (time_of_day + 1.0) * todsm;
4095 time_of_day_smooth = time_of_day_smooth * (1.0 - todsm)
4096 + time_of_day * todsm;
4098 runData.time_of_day = time_of_day;
4099 runData.time_of_day_smooth = time_of_day_smooth;
4101 sky->update(time_of_day_smooth, time_brightness, direct_brightness,
4102 sunlight_seen, camera->getCameraMode(), player->getYaw(),
4103 player->getPitch());
4109 if (sky->getCloudsVisible()) {
4110 clouds->setVisible(true);
4111 clouds->step(dtime);
4112 // camera->getPosition is not enough for 3rd person views
4113 v3f camera_node_position = camera->getCameraNode()->getPosition();
4114 v3s16 camera_offset = camera->getOffset();
4115 camera_node_position.X = camera_node_position.X + camera_offset.X * BS;
4116 camera_node_position.Y = camera_node_position.Y + camera_offset.Y * BS;
4117 camera_node_position.Z = camera_node_position.Z + camera_offset.Z * BS;
4118 clouds->update(camera_node_position,
4119 sky->getCloudColor());
4120 if (clouds->isCameraInsideCloud() && m_cache_enable_fog &&
4121 !flags.force_fog_off) {
4122 // if inside clouds, and fog enabled, use that as sky
4124 video::SColor clouds_dark = clouds->getColor()
4125 .getInterpolated(video::SColor(255, 0, 0, 0), 0.9);
4126 sky->overrideColors(clouds_dark, clouds->getColor());
4127 sky->setBodiesVisible(false);
4128 runData.fog_range = std::fmin(runData.fog_range * 0.5f, 32.0f * BS);
4129 // do not draw clouds after all
4130 clouds->setVisible(false);
4133 clouds->setVisible(false);
4140 client->getParticleManager()->step(dtime);
4146 if (m_cache_enable_fog && !flags.force_fog_off) {
4149 video::EFT_FOG_LINEAR,
4150 runData.fog_range * m_cache_fog_start,
4151 runData.fog_range * 1.0,
4159 video::EFT_FOG_LINEAR,
4169 Get chat messages from client
4172 v2u32 screensize = driver->getScreenSize();
4174 updateChat(*client, dtime, flags.show_debug, screensize,
4175 flags.show_chat, runData.profiler_current_page,
4176 *chat_backend, guitext_chat);
4182 if (client->getPlayerItem() != runData.new_playeritem)
4183 client->selectPlayerItem(runData.new_playeritem);
4185 // Update local inventory if it has changed
4186 if (client->getLocalInventoryUpdated()) {
4187 //infostream<<"Updating local inventory"<<std::endl;
4188 client->getLocalInventory(*local_inventory);
4189 runData.update_wielded_item_trigger = true;
4192 if (runData.update_wielded_item_trigger) {
4193 // Update wielded tool
4194 InventoryList *mlist = local_inventory->getList("main");
4196 if (mlist && (client->getPlayerItem() < mlist->getSize())) {
4197 ItemStack item = mlist->getItem(client->getPlayerItem());
4198 if (item.getDefinition(itemdef_manager).name.empty()) { // override the hand
4199 InventoryList *hlist = local_inventory->getList("hand");
4201 item = hlist->getItem(0);
4203 camera->wield(item);
4206 runData.update_wielded_item_trigger = false;
4210 Update block draw list every 200ms or when camera direction has
4213 runData.update_draw_list_timer += dtime;
4215 v3f camera_direction = camera->getDirection();
4216 if (runData.update_draw_list_timer >= 0.2
4217 || runData.update_draw_list_last_cam_dir.getDistanceFrom(camera_direction) > 0.2
4218 || m_camera_offset_changed) {
4219 runData.update_draw_list_timer = 0;
4220 client->getEnv().getClientMap().updateDrawList(driver);
4221 runData.update_draw_list_last_cam_dir = camera_direction;
4224 updateGui(*stats, dtime, cam);
4227 make sure menu is on top
4228 1. Delete formspec menu reference if menu was removed
4229 2. Else, make sure formspec menu is on top
4231 if (current_formspec) {
4232 if (current_formspec->getReferenceCount() == 1) {
4233 current_formspec->drop();
4234 current_formspec = NULL;
4235 } else if (isMenuActive()) {
4236 guiroot->bringToFront(current_formspec);
4243 const video::SColor &skycolor = sky->getSkyColor();
4245 TimeTaker tt_draw("mainloop: draw");
4246 driver->beginScene(true, true, skycolor);
4248 RenderingEngine::draw_scene(camera, client, player, hud, mapper,
4249 guienv, screensize, skycolor, flags.show_hud,
4250 flags.show_minimap);
4255 if (flags.show_profiler_graph)
4256 graph->draw(10, screensize.Y - 10, driver, g_fontengine->getFont());
4261 if (runData.damage_flash > 0.0) {
4262 video::SColor color(runData.damage_flash, 180, 0, 0);
4263 driver->draw2DRectangle(color,
4264 core::rect<s32>(0, 0, screensize.X, screensize.Y),
4267 runData.damage_flash -= 100.0 * dtime;
4273 if (player->hurt_tilt_timer > 0.0) {
4274 player->hurt_tilt_timer -= dtime * 5;
4276 if (player->hurt_tilt_timer < 0)
4277 player->hurt_tilt_strength = 0;
4281 Update minimap pos and rotation
4283 if (mapper && flags.show_minimap && flags.show_hud) {
4284 mapper->setPos(floatToInt(player->getPosition(), BS));
4285 mapper->setAngle(player->getYaw());
4293 stats->drawtime = tt_draw.stop(true);
4294 g_profiler->graphAdd("mainloop_draw", stats->drawtime / 1000.0f);
4298 inline static const char *yawToDirectionString(int yaw)
4300 static const char *direction[4] = {"North [+Z]", "West [-X]", "South [-Z]", "East [+X]"};
4302 yaw = wrapDegrees_0_360(yaw);
4303 yaw = (yaw + 45) % 360 / 90;
4305 return direction[yaw];
4309 void Game::updateGui(const RunStats &stats, f32 dtime, const CameraOrientation &cam)
4311 v2u32 screensize = driver->getScreenSize();
4312 LocalPlayer *player = client->getEnv().getLocalPlayer();
4313 v3f player_position = player->getPosition();
4315 if (flags.show_debug) {
4316 static float drawtime_avg = 0;
4317 drawtime_avg = drawtime_avg * 0.95 + stats.drawtime * 0.05;
4318 u16 fps = 1.0 / stats.dtime_jitter.avg;
4320 std::ostringstream os(std::ios_base::binary);
4322 << PROJECT_NAME_C " " << g_version_hash
4323 << ", FPS = " << fps
4324 << ", range_all = " << draw_control->range_all
4325 << std::setprecision(0)
4326 << ", drawtime = " << drawtime_avg << " ms"
4327 << std::setprecision(1)
4328 << ", dtime_jitter = "
4329 << (stats.dtime_jitter.max_fraction * 100.0) << " %"
4330 << std::setprecision(1)
4331 << ", view_range = " << draw_control->wanted_range
4332 << std::setprecision(3)
4333 << ", RTT = " << client->getRTT() << " s";
4334 setStaticText(guitext, utf8_to_wide(os.str()).c_str());
4335 guitext->setVisible(true);
4337 guitext->setVisible(false);
4340 if (guitext->isVisible()) {
4341 core::rect<s32> rect(
4343 screensize.X, 5 + g_fontengine->getTextHeight()
4345 guitext->setRelativePosition(rect);
4348 if (flags.show_debug) {
4349 std::ostringstream os(std::ios_base::binary);
4350 os << std::setprecision(1) << std::fixed
4351 << "pos = (" << (player_position.X / BS)
4352 << ", " << (player_position.Y / BS)
4353 << ", " << (player_position.Z / BS)
4354 << "), yaw = " << (wrapDegrees_0_360(cam.camera_yaw)) << "°"
4355 << " " << yawToDirectionString(cam.camera_yaw)
4356 << ", seed = " << ((u64)client->getMapSeed());
4357 setStaticText(guitext2, utf8_to_wide(os.str()).c_str());
4358 guitext2->setVisible(true);
4360 guitext2->setVisible(false);
4363 if (guitext2->isVisible()) {
4364 core::rect<s32> rect(
4365 5, 5 + g_fontengine->getTextHeight(),
4366 screensize.X, 5 + g_fontengine->getTextHeight() * 2
4368 guitext2->setRelativePosition(rect);
4371 if (flags.show_debug && runData.pointed_old.type == POINTEDTHING_NODE) {
4372 ClientMap &map = client->getEnv().getClientMap();
4373 const INodeDefManager *nodedef = client->getNodeDefManager();
4374 MapNode n = map.getNodeNoEx(runData.pointed_old.node_undersurface);
4376 if (n.getContent() != CONTENT_IGNORE && nodedef->get(n).name != "unknown") {
4377 std::ostringstream os(std::ios_base::binary);
4378 os << "pointing_at = (" << nodedef->get(n).name
4379 << ", param2 = " << (u64) n.getParam2()
4381 setStaticText(guitext3, utf8_to_wide(os.str()).c_str());
4382 guitext3->setVisible(true);
4384 guitext3->setVisible(false);
4387 guitext3->setVisible(false);
4390 if (guitext3->isVisible()) {
4391 core::rect<s32> rect(
4392 5, 5 + g_fontengine->getTextHeight() * 2,
4393 screensize.X, 5 + g_fontengine->getTextHeight() * 3
4395 guitext3->setRelativePosition(rect);
4398 setStaticText(guitext_info, infotext.c_str());
4399 guitext_info->setVisible(flags.show_hud && g_menumgr.menuCount() == 0);
4401 float statustext_time_max = 1.5;
4403 if (!m_statustext.empty()) {
4404 runData.statustext_time += dtime;
4406 if (runData.statustext_time >= statustext_time_max) {
4408 runData.statustext_time = 0;
4412 setStaticText(guitext_status, m_statustext.c_str());
4413 guitext_status->setVisible(!m_statustext.empty());
4415 if (!m_statustext.empty()) {
4416 s32 status_width = guitext_status->getTextWidth();
4417 s32 status_height = guitext_status->getTextHeight();
4418 s32 status_y = screensize.Y - 150;
4419 s32 status_x = (screensize.X - status_width) / 2;
4420 core::rect<s32> rect(
4421 status_x , status_y - status_height,
4422 status_x + status_width, status_y
4424 guitext_status->setRelativePosition(rect);
4427 video::SColor initial_color(255, 0, 0, 0);
4429 if (guienv->getSkin())
4430 initial_color = guienv->getSkin()->getColor(gui::EGDC_BUTTON_TEXT);
4432 video::SColor final_color = initial_color;
4433 final_color.setAlpha(0);
4434 video::SColor fade_color = initial_color.getInterpolated_quadratic(
4435 initial_color, final_color,
4436 pow(runData.statustext_time / statustext_time_max, 2.0f));
4437 guitext_status->setOverrideColor(fade_color);
4438 guitext_status->enableOverrideColor(true);
4443 /* Log times and stuff for visualization */
4444 inline void Game::updateProfilerGraphs(ProfilerGraph *graph)
4446 Profiler::GraphValues values;
4447 g_profiler->graphGet(values);
4453 /****************************************************************************
4455 ****************************************************************************/
4457 /* On some computers framerate doesn't seem to be automatically limited
4459 inline void Game::limitFps(FpsControl *fps_timings, f32 *dtime)
4461 // not using getRealTime is necessary for wine
4462 device->getTimer()->tick(); // Maker sure device time is up-to-date
4463 u32 time = device->getTimer()->getTime();
4464 u32 last_time = fps_timings->last_time;
4466 if (time > last_time) // Make sure time hasn't overflowed
4467 fps_timings->busy_time = time - last_time;
4469 fps_timings->busy_time = 0;
4471 u32 frametime_min = 1000 / (g_menumgr.pausesGame()
4472 ? g_settings->getFloat("pause_fps_max")
4473 : g_settings->getFloat("fps_max"));
4475 if (fps_timings->busy_time < frametime_min) {
4476 fps_timings->sleep_time = frametime_min - fps_timings->busy_time;
4477 device->sleep(fps_timings->sleep_time);
4479 fps_timings->sleep_time = 0;
4482 /* Get the new value of the device timer. Note that device->sleep() may
4483 * not sleep for the entire requested time as sleep may be interrupted and
4484 * therefore it is arguably more accurate to get the new time from the
4485 * device rather than calculating it by adding sleep_time to time.
4488 device->getTimer()->tick(); // Update device timer
4489 time = device->getTimer()->getTime();
4491 if (time > last_time) // Make sure last_time hasn't overflowed
4492 *dtime = (time - last_time) / 1000.0;
4496 fps_timings->last_time = time;
4499 void Game::showOverlayMessage(const char *msg, float dtime, int percent, bool draw_clouds)
4501 const wchar_t *wmsg = wgettext(msg);
4502 RenderingEngine::draw_load_screen(wmsg, guienv, texture_src, dtime, percent,
4507 void Game::settingChangedCallback(const std::string &setting_name, void *data)
4509 ((Game *)data)->readSettings();
4512 void Game::readSettings()
4514 m_cache_doubletap_jump = g_settings->getBool("doubletap_jump");
4515 m_cache_enable_clouds = g_settings->getBool("enable_clouds");
4516 m_cache_enable_joysticks = g_settings->getBool("enable_joysticks");
4517 m_cache_enable_particles = g_settings->getBool("enable_particles");
4518 m_cache_enable_fog = g_settings->getBool("enable_fog");
4519 m_cache_mouse_sensitivity = g_settings->getFloat("mouse_sensitivity");
4520 m_cache_joystick_frustum_sensitivity = g_settings->getFloat("joystick_frustum_sensitivity");
4521 m_repeat_right_click_time = g_settings->getFloat("repeat_rightclick_time");
4523 m_cache_enable_noclip = g_settings->getBool("noclip");
4524 m_cache_enable_free_move = g_settings->getBool("free_move");
4526 m_cache_fog_start = g_settings->getFloat("fog_start");
4528 m_cache_cam_smoothing = 0;
4529 if (g_settings->getBool("cinematic"))
4530 m_cache_cam_smoothing = 1 - g_settings->getFloat("cinematic_camera_smoothing");
4532 m_cache_cam_smoothing = 1 - g_settings->getFloat("camera_smoothing");
4534 m_cache_fog_start = rangelim(m_cache_fog_start, 0.0f, 0.99f);
4535 m_cache_cam_smoothing = rangelim(m_cache_cam_smoothing, 0.01f, 1.0f);
4536 m_cache_mouse_sensitivity = rangelim(m_cache_mouse_sensitivity, 0.001, 100.0);
4540 /****************************************************************************/
4541 /****************************************************************************
4543 ****************************************************************************/
4544 /****************************************************************************/
4546 void Game::extendedResourceCleanup()
4548 // Extended resource accounting
4549 infostream << "Irrlicht resources after cleanup:" << std::endl;
4550 infostream << "\tRemaining meshes : "
4551 << RenderingEngine::get_mesh_cache()->getMeshCount() << std::endl;
4552 infostream << "\tRemaining textures : "
4553 << driver->getTextureCount() << std::endl;
4555 for (unsigned int i = 0; i < driver->getTextureCount(); i++) {
4556 irr::video::ITexture *texture = driver->getTextureByIndex(i);
4557 infostream << "\t\t" << i << ":" << texture->getName().getPath().c_str()
4561 clearTextureNameCache();
4562 infostream << "\tRemaining materials: "
4563 << driver-> getMaterialRendererCount()
4564 << " (note: irrlicht doesn't support removing renderers)" << std::endl;
4567 #define GET_KEY_NAME(KEY) gettext(getKeySetting(#KEY).name())
4568 void Game::showPauseMenu()
4571 static const std::string control_text = strgettext("Default Controls:\n"
4572 "No menu visible:\n"
4573 "- single tap: button activate\n"
4574 "- double tap: place/use\n"
4575 "- slide finger: look around\n"
4576 "Menu/Inventory visible:\n"
4577 "- double tap (outside):\n"
4579 "- touch stack, touch slot:\n"
4581 "- touch&drag, tap 2nd finger\n"
4582 " --> place single item to slot\n"
4585 static const std::string control_text_template = strgettext("Controls:\n"
4586 "- %s: move forwards\n"
4587 "- %s: move backwards\n"
4589 "- %s: move right\n"
4590 "- %s: jump/climb\n"
4591 "- %s: sneak/go down\n"
4594 "- Mouse: turn/look\n"
4595 "- Mouse left: dig/punch\n"
4596 "- Mouse right: place/use\n"
4597 "- Mouse wheel: select item\n"
4601 char control_text_buf[600];
4603 snprintf(control_text_buf, ARRLEN(control_text_buf), control_text_template.c_str(),
4604 GET_KEY_NAME(keymap_forward),
4605 GET_KEY_NAME(keymap_backward),
4606 GET_KEY_NAME(keymap_left),
4607 GET_KEY_NAME(keymap_right),
4608 GET_KEY_NAME(keymap_jump),
4609 GET_KEY_NAME(keymap_sneak),
4610 GET_KEY_NAME(keymap_drop),
4611 GET_KEY_NAME(keymap_inventory),
4612 GET_KEY_NAME(keymap_chat)
4615 std::string control_text = std::string(control_text_buf);
4616 str_formspec_escape(control_text);
4619 float ypos = simple_singleplayer_mode ? 0.7f : 0.1f;
4620 std::ostringstream os;
4622 os << FORMSPEC_VERSION_STRING << SIZE_TAG
4623 << "button_exit[4," << (ypos++) << ";3,0.5;btn_continue;"
4624 << strgettext("Continue") << "]";
4626 if (!simple_singleplayer_mode) {
4627 os << "button_exit[4," << (ypos++) << ";3,0.5;btn_change_password;"
4628 << strgettext("Change Password") << "]";
4630 os << "field[4.95,0;5,1.5;;" << strgettext("Game paused") << ";]";
4634 os << "button_exit[4," << (ypos++) << ";3,0.5;btn_sound;"
4635 << strgettext("Sound Volume") << "]";
4636 os << "button_exit[4," << (ypos++) << ";3,0.5;btn_key_config;"
4637 << strgettext("Change Keys") << "]";
4639 os << "button_exit[4," << (ypos++) << ";3,0.5;btn_exit_menu;"
4640 << strgettext("Exit to Menu") << "]";
4641 os << "button_exit[4," << (ypos++) << ";3,0.5;btn_exit_os;"
4642 << strgettext("Exit to OS") << "]"
4643 << "textarea[7.5,0.25;3.9,6.25;;" << control_text << ";]"
4644 << "textarea[0.4,0.25;3.9,6.25;;" << PROJECT_NAME_C " " VERSION_STRING "\n"
4646 << strgettext("Game info:") << "\n";
4647 const std::string &address = client->getAddressName();
4648 static const std::string mode = strgettext("- Mode: ");
4649 if (!simple_singleplayer_mode) {
4650 Address serverAddress = client->getServerAddress();
4651 if (address != "") {
4652 os << mode << strgettext("Remote server") << "\n"
4653 << strgettext("- Address: ") << address;
4655 os << mode << strgettext("Hosting server");
4657 os << "\n" << strgettext("- Port: ") << serverAddress.getPort() << "\n";
4659 os << mode << strgettext("Singleplayer") << "\n";
4661 if (simple_singleplayer_mode || address == "") {
4662 static const std::string on = strgettext("On");
4663 static const std::string off = strgettext("Off");
4664 const std::string &damage = g_settings->getBool("enable_damage") ? on : off;
4665 const std::string &creative = g_settings->getBool("creative_mode") ? on : off;
4666 const std::string &announced = g_settings->getBool("server_announce") ? on : off;
4667 os << strgettext("- Damage: ") << damage << "\n"
4668 << strgettext("- Creative Mode: ") << creative << "\n";
4669 if (!simple_singleplayer_mode) {
4670 const std::string &pvp = g_settings->getBool("enable_pvp") ? on : off;
4671 os << strgettext("- PvP: ") << pvp << "\n"
4672 << strgettext("- Public: ") << announced << "\n";
4673 std::string server_name = g_settings->get("server_name");
4674 str_formspec_escape(server_name);
4675 if (announced == on && server_name != "")
4676 os << strgettext("- Server Name: ") << server_name;
4683 /* Note: FormspecFormSource and LocalFormspecHandler *
4684 * are deleted by guiFormSpecMenu */
4685 FormspecFormSource *fs_src = new FormspecFormSource(os.str());
4686 LocalFormspecHandler *txt_dst = new LocalFormspecHandler("MT_PAUSE_MENU");
4688 create_formspec_menu(¤t_formspec, client, &input->joystick, fs_src, txt_dst);
4689 current_formspec->setFocus("btn_continue");
4690 current_formspec->doPause = true;
4693 /****************************************************************************/
4694 /****************************************************************************
4695 extern function for launching the game
4696 ****************************************************************************/
4697 /****************************************************************************/
4699 void the_game(bool *kill,
4701 InputHandler *input,
4702 const std::string &map_dir,
4703 const std::string &playername,
4704 const std::string &password,
4705 const std::string &address, // If empty local server is created
4708 std::string &error_message,
4709 ChatBackend &chat_backend,
4710 bool *reconnect_requested,
4711 const SubgameSpec &gamespec, // Used for local game
4712 bool simple_singleplayer_mode)
4716 /* Make a copy of the server address because if a local singleplayer server
4717 * is created then this is updated and we don't want to change the value
4718 * passed to us by the calling function
4720 std::string server_address = address;
4724 if (game.startup(kill, random_input, input, map_dir,
4725 playername, password, &server_address, port, error_message,
4726 reconnect_requested, &chat_backend, gamespec,
4727 simple_singleplayer_mode)) {
4732 } catch (SerializationError &e) {
4733 error_message = std::string("A serialization error occurred:\n")
4734 + e.what() + "\n\nThe server is probably "
4735 " running a different version of " PROJECT_NAME_C ".";
4736 errorstream << error_message << std::endl;
4737 } catch (ServerError &e) {
4738 error_message = e.what();
4739 errorstream << "ServerError: " << error_message << std::endl;
4740 } catch (ModError &e) {
4741 error_message = e.what() + strgettext("\nCheck debug.txt for details.");
4742 errorstream << "ModError: " << error_message << std::endl;