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.
23 #include "client/renderingengine.h"
26 #include "client/inputhandler.h"
27 #include "client/tile.h" // For TextureSource
28 #include "client/keys.h"
29 #include "client/joystick_controller.h"
30 #include "clientmap.h"
33 #include "content_cao.h"
34 #include "event_manager.h"
35 #include "fontengine.h"
40 #include "guiChatConsole.h"
41 #include "guiFormSpecMenu.h"
42 #include "guiKeyChangeMenu.h"
43 #include "guiPasswordChange.h"
44 #include "guiVolumeChange.h"
45 #include "mainmenumanager.h"
48 #include "nodedef.h" // Needed for determining pointing to nodes
49 #include "nodemetadata.h"
50 #include "particles.h"
52 #include "quicktune_shortcutter.h"
58 #include "util/basic_macros.h"
59 #include "util/directiontables.h"
60 #include "util/pointedthing.h"
61 #include "irrlicht_changes/static_text.h"
63 #include "script/scripting_client.h"
66 #include "sound_openal.h"
69 extern Settings *g_settings;
70 extern Profiler *g_profiler;
76 struct TextDestNodeMetadata : public TextDest
78 TextDestNodeMetadata(v3s16 p, Client *client)
83 // This is deprecated I guess? -celeron55
84 void gotText(const std::wstring &text)
86 std::string ntext = wide_to_utf8(text);
87 infostream << "Submitting 'text' field of node at (" << m_p.X << ","
88 << m_p.Y << "," << m_p.Z << "): " << ntext << std::endl;
90 fields["text"] = ntext;
91 m_client->sendNodemetaFields(m_p, "", fields);
93 void gotText(const StringMap &fields)
95 m_client->sendNodemetaFields(m_p, "", fields);
102 struct TextDestPlayerInventory : public TextDest
104 TextDestPlayerInventory(Client *client)
109 TextDestPlayerInventory(Client *client, const std::string &formname)
112 m_formname = formname;
114 void gotText(const StringMap &fields)
116 m_client->sendInventoryFields(m_formname, fields);
122 struct LocalFormspecHandler : public TextDest
124 LocalFormspecHandler(const std::string &formname):
127 m_formname = formname;
130 LocalFormspecHandler(const std::string &formname, Client *client):
133 m_formname = formname;
136 void gotText(const StringMap &fields)
138 if (m_formname == "MT_PAUSE_MENU") {
139 if (fields.find("btn_sound") != fields.end()) {
140 g_gamecallback->changeVolume();
144 if (fields.find("btn_key_config") != fields.end()) {
145 g_gamecallback->keyConfig();
149 if (fields.find("btn_exit_menu") != fields.end()) {
150 g_gamecallback->disconnect();
154 if (fields.find("btn_exit_os") != fields.end()) {
155 g_gamecallback->exitToOS();
157 RenderingEngine::get_raw_device()->closeDevice();
162 if (fields.find("btn_change_password") != fields.end()) {
163 g_gamecallback->changePassword();
167 if (fields.find("quit") != fields.end()) {
171 if (fields.find("btn_continue") != fields.end()) {
176 // Don't disable this part when modding is disabled, it's used in builtin
177 m_client->getScript()->on_formspec_input(m_formname, fields);
183 /* Form update callback */
185 class NodeMetadataFormSource: public IFormSource
188 NodeMetadataFormSource(ClientMap *map, v3s16 p):
193 std::string getForm()
195 NodeMetadata *meta = m_map->getNodeMetadata(m_p);
200 return meta->getString("formspec");
203 virtual std::string resolveText(const std::string &str)
205 NodeMetadata *meta = m_map->getNodeMetadata(m_p);
210 return meta->resolveString(str);
217 class PlayerInventoryFormSource: public IFormSource
220 PlayerInventoryFormSource(Client *client):
224 std::string getForm()
226 LocalPlayer *player = m_client->getEnv().getLocalPlayer();
227 return player->inventory_formspec;
233 /* Profiler display */
235 void update_profiler_gui(gui::IGUIStaticText *guitext_profiler, FontEngine *fe,
236 u32 show_profiler, u32 show_profiler_max, s32 screen_height)
238 if (show_profiler == 0) {
239 guitext_profiler->setVisible(false);
242 std::ostringstream os(std::ios_base::binary);
243 g_profiler->printPage(os, show_profiler, show_profiler_max);
244 std::wstring text = utf8_to_wide(os.str());
245 setStaticText(guitext_profiler, text.c_str());
246 guitext_profiler->setVisible(true);
248 s32 w = fe->getTextWidth(text.c_str());
253 unsigned text_height = fe->getTextHeight();
255 core::position2di upper_left, lower_right;
258 upper_left.Y = (text_height + 5) * 2;
259 lower_right.X = 12 + w;
260 lower_right.Y = upper_left.Y + (text_height + 1) * MAX_PROFILER_TEXT_ROWS;
262 if (lower_right.Y > screen_height * 2 / 3)
263 lower_right.Y = screen_height * 2 / 3;
265 core::rect<s32> rect(upper_left, lower_right);
267 guitext_profiler->setRelativePosition(rect);
268 guitext_profiler->setVisible(true);
276 Profiler::GraphValues values;
282 Meta(float initial = 0,
283 video::SColor color = video::SColor(255, 255, 255, 255)):
289 std::deque<Piece> m_log;
297 void put(const Profiler::GraphValues &values)
300 piece.values = values;
301 m_log.push_back(piece);
303 while (m_log.size() > m_log_max_size)
304 m_log.erase(m_log.begin());
307 void draw(s32 x_left, s32 y_bottom, video::IVideoDriver *driver,
308 gui::IGUIFont *font) const
310 // Do *not* use UNORDERED_MAP here as the order needs
311 // to be the same for each call to prevent flickering
312 std::map<std::string, Meta> m_meta;
314 for (std::deque<Piece>::const_iterator k = m_log.begin();
315 k != m_log.end(); ++k) {
316 const Piece &piece = *k;
318 for (Profiler::GraphValues::const_iterator i = piece.values.begin();
319 i != piece.values.end(); ++i) {
320 const std::string &id = i->first;
321 const float &value = i->second;
322 std::map<std::string, Meta>::iterator j = m_meta.find(id);
324 if (j == m_meta.end()) {
325 m_meta[id] = Meta(value);
329 if (value < j->second.min)
330 j->second.min = value;
332 if (value > j->second.max)
333 j->second.max = value;
338 static const video::SColor usable_colors[] = {
339 video::SColor(255, 255, 100, 100),
340 video::SColor(255, 90, 225, 90),
341 video::SColor(255, 100, 100, 255),
342 video::SColor(255, 255, 150, 50),
343 video::SColor(255, 220, 220, 100)
345 static const u32 usable_colors_count =
346 sizeof(usable_colors) / sizeof(*usable_colors);
347 u32 next_color_i = 0;
349 for (std::map<std::string, Meta>::iterator i = m_meta.begin();
350 i != m_meta.end(); ++i) {
351 Meta &meta = i->second;
352 video::SColor color(255, 200, 200, 200);
354 if (next_color_i < usable_colors_count)
355 color = usable_colors[next_color_i++];
361 s32 textx = x_left + m_log_max_size + 15;
362 s32 textx2 = textx + 200 - 15;
365 for (std::map<std::string, Meta>::const_iterator i = m_meta.begin();
366 i != m_meta.end(); ++i) {
367 const std::string &id = i->first;
368 const Meta &meta = i->second;
370 s32 y = y_bottom - meta_i * 50;
371 float show_min = meta.min;
372 float show_max = meta.max;
374 if (show_min >= -0.0001 && show_max >= -0.0001) {
375 if (show_min <= show_max * 0.5)
381 snprintf(buf, 10, "%.3g", show_max);
382 font->draw(utf8_to_wide(buf).c_str(),
383 core::rect<s32>(textx, y - graphh,
384 textx2, y - graphh + texth),
386 snprintf(buf, 10, "%.3g", show_min);
387 font->draw(utf8_to_wide(buf).c_str(),
388 core::rect<s32>(textx, y - texth,
391 font->draw(utf8_to_wide(id).c_str(),
392 core::rect<s32>(textx, y - graphh / 2 - texth / 2,
393 textx2, y - graphh / 2 + texth / 2),
396 s32 graph1h = graphh;
397 bool relativegraph = (show_min != 0 && show_min != show_max);
398 float lastscaledvalue = 0.0;
399 bool lastscaledvalue_exists = false;
401 for (std::deque<Piece>::const_iterator j = m_log.begin();
402 j != m_log.end(); ++j) {
403 const Piece &piece = *j;
405 bool value_exists = false;
406 Profiler::GraphValues::const_iterator k =
407 piece.values.find(id);
409 if (k != piece.values.end()) {
416 lastscaledvalue_exists = false;
420 float scaledvalue = 1.0;
422 if (show_max != show_min)
423 scaledvalue = (value - show_min) / (show_max - show_min);
425 if (scaledvalue == 1.0 && value == 0) {
427 lastscaledvalue_exists = false;
432 if (lastscaledvalue_exists) {
433 s32 ivalue1 = lastscaledvalue * graph1h;
434 s32 ivalue2 = scaledvalue * graph1h;
435 driver->draw2DLine(v2s32(x - 1, graph1y - ivalue1),
436 v2s32(x, graph1y - ivalue2), meta.color);
439 lastscaledvalue = scaledvalue;
440 lastscaledvalue_exists = true;
442 s32 ivalue = scaledvalue * graph1h;
443 driver->draw2DLine(v2s32(x, graph1y),
444 v2s32(x, graph1y - ivalue), meta.color);
455 class NodeDugEvent: public MtEvent
461 NodeDugEvent(v3s16 p, MapNode n):
465 const char *getType() const
473 ISoundManager *m_sound;
474 INodeDefManager *m_ndef;
476 bool makes_footstep_sound;
477 float m_player_step_timer;
479 SimpleSoundSpec m_player_step_sound;
480 SimpleSoundSpec m_player_leftpunch_sound;
481 SimpleSoundSpec m_player_rightpunch_sound;
483 SoundMaker(ISoundManager *sound, INodeDefManager *ndef):
486 makes_footstep_sound(true),
487 m_player_step_timer(0)
491 void playPlayerStep()
493 if (m_player_step_timer <= 0 && m_player_step_sound.exists()) {
494 m_player_step_timer = 0.03;
495 if (makes_footstep_sound)
496 m_sound->playSound(m_player_step_sound, false);
500 static void viewBobbingStep(MtEvent *e, void *data)
502 SoundMaker *sm = (SoundMaker *)data;
503 sm->playPlayerStep();
506 static void playerRegainGround(MtEvent *e, void *data)
508 SoundMaker *sm = (SoundMaker *)data;
509 sm->playPlayerStep();
512 static void playerJump(MtEvent *e, void *data)
514 //SoundMaker *sm = (SoundMaker*)data;
517 static void cameraPunchLeft(MtEvent *e, void *data)
519 SoundMaker *sm = (SoundMaker *)data;
520 sm->m_sound->playSound(sm->m_player_leftpunch_sound, false);
523 static void cameraPunchRight(MtEvent *e, void *data)
525 SoundMaker *sm = (SoundMaker *)data;
526 sm->m_sound->playSound(sm->m_player_rightpunch_sound, false);
529 static void nodeDug(MtEvent *e, void *data)
531 SoundMaker *sm = (SoundMaker *)data;
532 NodeDugEvent *nde = (NodeDugEvent *)e;
533 sm->m_sound->playSound(sm->m_ndef->get(nde->n).sound_dug, false);
536 static void playerDamage(MtEvent *e, void *data)
538 SoundMaker *sm = (SoundMaker *)data;
539 sm->m_sound->playSound(SimpleSoundSpec("player_damage", 0.5), false);
542 static void playerFallingDamage(MtEvent *e, void *data)
544 SoundMaker *sm = (SoundMaker *)data;
545 sm->m_sound->playSound(SimpleSoundSpec("player_falling_damage", 0.5), false);
548 void registerReceiver(MtEventManager *mgr)
550 mgr->reg("ViewBobbingStep", SoundMaker::viewBobbingStep, this);
551 mgr->reg("PlayerRegainGround", SoundMaker::playerRegainGround, this);
552 mgr->reg("PlayerJump", SoundMaker::playerJump, this);
553 mgr->reg("CameraPunchLeft", SoundMaker::cameraPunchLeft, this);
554 mgr->reg("CameraPunchRight", SoundMaker::cameraPunchRight, this);
555 mgr->reg("NodeDug", SoundMaker::nodeDug, this);
556 mgr->reg("PlayerDamage", SoundMaker::playerDamage, this);
557 mgr->reg("PlayerFallingDamage", SoundMaker::playerFallingDamage, this);
560 void step(float dtime)
562 m_player_step_timer -= dtime;
566 // Locally stored sounds don't need to be preloaded because of this
567 class GameOnDemandSoundFetcher: public OnDemandSoundFetcher
569 std::set<std::string> m_fetched;
571 void paths_insert(std::set<std::string> &dst_paths,
572 const std::string &base,
573 const std::string &name)
575 dst_paths.insert(base + DIR_DELIM + "sounds" + DIR_DELIM + name + ".ogg");
576 dst_paths.insert(base + DIR_DELIM + "sounds" + DIR_DELIM + name + ".0.ogg");
577 dst_paths.insert(base + DIR_DELIM + "sounds" + DIR_DELIM + name + ".1.ogg");
578 dst_paths.insert(base + DIR_DELIM + "sounds" + DIR_DELIM + name + ".2.ogg");
579 dst_paths.insert(base + DIR_DELIM + "sounds" + DIR_DELIM + name + ".3.ogg");
580 dst_paths.insert(base + DIR_DELIM + "sounds" + DIR_DELIM + name + ".4.ogg");
581 dst_paths.insert(base + DIR_DELIM + "sounds" + DIR_DELIM + name + ".5.ogg");
582 dst_paths.insert(base + DIR_DELIM + "sounds" + DIR_DELIM + name + ".6.ogg");
583 dst_paths.insert(base + DIR_DELIM + "sounds" + DIR_DELIM + name + ".7.ogg");
584 dst_paths.insert(base + DIR_DELIM + "sounds" + DIR_DELIM + name + ".8.ogg");
585 dst_paths.insert(base + DIR_DELIM + "sounds" + DIR_DELIM + name + ".9.ogg");
588 void fetchSounds(const std::string &name,
589 std::set<std::string> &dst_paths,
590 std::set<std::string> &dst_datas)
592 if (m_fetched.count(name))
595 m_fetched.insert(name);
597 paths_insert(dst_paths, porting::path_share, name);
598 paths_insert(dst_paths, porting::path_user, name);
603 // before 1.8 there isn't a "integer interface", only float
604 #if (IRRLICHT_VERSION_MAJOR == 1 && IRRLICHT_VERSION_MINOR < 8)
605 typedef f32 SamplerLayer_t;
607 typedef s32 SamplerLayer_t;
611 class GameGlobalShaderConstantSetter : public IShaderConstantSetter
614 bool *m_force_fog_off;
617 CachedPixelShaderSetting<float, 4> m_sky_bg_color;
618 CachedPixelShaderSetting<float> m_fog_distance;
619 CachedVertexShaderSetting<float> m_animation_timer_vertex;
620 CachedPixelShaderSetting<float> m_animation_timer_pixel;
621 CachedPixelShaderSetting<float, 3> m_day_light;
622 CachedPixelShaderSetting<float, 3> m_eye_position_pixel;
623 CachedVertexShaderSetting<float, 3> m_eye_position_vertex;
624 CachedPixelShaderSetting<float, 3> m_minimap_yaw;
625 CachedPixelShaderSetting<SamplerLayer_t> m_base_texture;
626 CachedPixelShaderSetting<SamplerLayer_t> m_normal_texture;
627 CachedPixelShaderSetting<SamplerLayer_t> m_texture_flags;
631 void onSettingsChange(const std::string &name)
633 if (name == "enable_fog")
634 m_fog_enabled = g_settings->getBool("enable_fog");
637 static void settingsCallback(const std::string &name, void *userdata)
639 reinterpret_cast<GameGlobalShaderConstantSetter*>(userdata)->onSettingsChange(name);
642 void setSky(Sky *sky) { m_sky = sky; }
644 GameGlobalShaderConstantSetter(Sky *sky, bool *force_fog_off,
645 f32 *fog_range, Client *client) :
647 m_force_fog_off(force_fog_off),
648 m_fog_range(fog_range),
649 m_sky_bg_color("skyBgColor"),
650 m_fog_distance("fogDistance"),
651 m_animation_timer_vertex("animationTimer"),
652 m_animation_timer_pixel("animationTimer"),
653 m_day_light("dayLight"),
654 m_eye_position_pixel("eyePosition"),
655 m_eye_position_vertex("eyePosition"),
656 m_minimap_yaw("yawVec"),
657 m_base_texture("baseTexture"),
658 m_normal_texture("normalTexture"),
659 m_texture_flags("textureFlags"),
662 g_settings->registerChangedCallback("enable_fog", settingsCallback, this);
663 m_fog_enabled = g_settings->getBool("enable_fog");
666 ~GameGlobalShaderConstantSetter()
668 g_settings->deregisterChangedCallback("enable_fog", settingsCallback, this);
671 virtual void onSetConstants(video::IMaterialRendererServices *services,
678 video::SColor bgcolor = m_sky->getBgColor();
679 video::SColorf bgcolorf(bgcolor);
680 float bgcolorfa[4] = {
686 m_sky_bg_color.set(bgcolorfa, services);
689 float fog_distance = 10000 * BS;
691 if (m_fog_enabled && !*m_force_fog_off)
692 fog_distance = *m_fog_range;
694 m_fog_distance.set(&fog_distance, services);
696 u32 daynight_ratio = (float)m_client->getEnv().getDayNightRatio();
697 video::SColorf sunlight;
698 get_sunlight_color(&sunlight, daynight_ratio);
703 m_day_light.set(dnc, services);
705 u32 animation_timer = porting::getTimeMs() % 100000;
706 float animation_timer_f = (float)animation_timer / 100000.f;
707 m_animation_timer_vertex.set(&animation_timer_f, services);
708 m_animation_timer_pixel.set(&animation_timer_f, services);
710 float eye_position_array[3];
711 v3f epos = m_client->getEnv().getLocalPlayer()->getEyePosition();
712 #if (IRRLICHT_VERSION_MAJOR == 1 && IRRLICHT_VERSION_MINOR < 8)
713 eye_position_array[0] = epos.X;
714 eye_position_array[1] = epos.Y;
715 eye_position_array[2] = epos.Z;
717 epos.getAs3Values(eye_position_array);
719 m_eye_position_pixel.set(eye_position_array, services);
720 m_eye_position_vertex.set(eye_position_array, services);
722 if (m_client->getMinimap()) {
723 float minimap_yaw_array[3];
724 v3f minimap_yaw = m_client->getMinimap()->getYawVec();
725 #if (IRRLICHT_VERSION_MAJOR == 1 && IRRLICHT_VERSION_MINOR < 8)
726 minimap_yaw_array[0] = minimap_yaw.X;
727 minimap_yaw_array[1] = minimap_yaw.Y;
728 minimap_yaw_array[2] = minimap_yaw.Z;
730 minimap_yaw.getAs3Values(minimap_yaw_array);
732 m_minimap_yaw.set(minimap_yaw_array, services);
735 SamplerLayer_t base_tex = 0,
738 m_base_texture.set(&base_tex, services);
739 m_normal_texture.set(&normal_tex, services);
740 m_texture_flags.set(&flags_tex, services);
745 class GameGlobalShaderConstantSetterFactory : public IShaderConstantSetterFactory
748 bool *m_force_fog_off;
751 std::vector<GameGlobalShaderConstantSetter *> created_nosky;
753 GameGlobalShaderConstantSetterFactory(bool *force_fog_off,
754 f32 *fog_range, Client *client) :
756 m_force_fog_off(force_fog_off),
757 m_fog_range(fog_range),
761 void setSky(Sky *sky) {
763 for (size_t i = 0; i < created_nosky.size(); ++i) {
764 created_nosky[i]->setSky(m_sky);
766 created_nosky.clear();
769 virtual IShaderConstantSetter* create()
771 GameGlobalShaderConstantSetter *scs = new GameGlobalShaderConstantSetter(
772 m_sky, m_force_fog_off, m_fog_range, m_client);
774 created_nosky.push_back(scs);
780 bool nodePlacementPrediction(Client &client, const ItemDefinition &playeritem_def,
781 const ItemStack &playeritem, v3s16 nodepos, v3s16 neighbourpos)
783 std::string prediction = playeritem_def.node_placement_prediction;
784 INodeDefManager *nodedef = client.ndef();
785 ClientMap &map = client.getEnv().getClientMap();
787 bool is_valid_position;
789 node = map.getNodeNoEx(nodepos, &is_valid_position);
790 if (!is_valid_position)
793 if (prediction != "" && !nodedef->get(node).rightclickable) {
794 verbosestream << "Node placement prediction for "
795 << playeritem_def.name << " is "
796 << prediction << std::endl;
797 v3s16 p = neighbourpos;
799 // Place inside node itself if buildable_to
800 MapNode n_under = map.getNodeNoEx(nodepos, &is_valid_position);
801 if (is_valid_position)
803 if (nodedef->get(n_under).buildable_to)
806 node = map.getNodeNoEx(p, &is_valid_position);
807 if (is_valid_position &&!nodedef->get(node).buildable_to)
812 // Find id of predicted node
814 bool found = nodedef->getId(prediction, id);
817 errorstream << "Node placement prediction failed for "
818 << playeritem_def.name << " (places "
820 << ") - Name not known" << std::endl;
824 const ContentFeatures &predicted_f = nodedef->get(id);
826 // Predict param2 for facedir and wallmounted nodes
829 if (predicted_f.param_type_2 == CPT2_WALLMOUNTED ||
830 predicted_f.param_type_2 == CPT2_COLORED_WALLMOUNTED) {
831 v3s16 dir = nodepos - neighbourpos;
833 if (abs(dir.Y) > MYMAX(abs(dir.X), abs(dir.Z))) {
834 param2 = dir.Y < 0 ? 1 : 0;
835 } else if (abs(dir.X) > abs(dir.Z)) {
836 param2 = dir.X < 0 ? 3 : 2;
838 param2 = dir.Z < 0 ? 5 : 4;
842 if (predicted_f.param_type_2 == CPT2_FACEDIR ||
843 predicted_f.param_type_2 == CPT2_COLORED_FACEDIR) {
844 v3s16 dir = nodepos - floatToInt(client.getEnv().getLocalPlayer()->getPosition(), BS);
846 if (abs(dir.X) > abs(dir.Z)) {
847 param2 = dir.X < 0 ? 3 : 1;
849 param2 = dir.Z < 0 ? 2 : 0;
855 //Check attachment if node is in group attached_node
856 if (((ItemGroupList) predicted_f.groups)["attached_node"] != 0) {
857 static v3s16 wallmounted_dirs[8] = {
867 if (predicted_f.param_type_2 == CPT2_WALLMOUNTED ||
868 predicted_f.param_type_2 == CPT2_COLORED_WALLMOUNTED)
869 pp = p + wallmounted_dirs[param2];
871 pp = p + v3s16(0, -1, 0);
873 if (!nodedef->get(map.getNodeNoEx(pp)).walkable)
878 if ((predicted_f.param_type_2 == CPT2_COLOR
879 || predicted_f.param_type_2 == CPT2_COLORED_FACEDIR
880 || predicted_f.param_type_2 == CPT2_COLORED_WALLMOUNTED)) {
881 const std::string &indexstr = playeritem.metadata.getString(
883 if (!indexstr.empty()) {
884 s32 index = mystoi(indexstr);
885 if (predicted_f.param_type_2 == CPT2_COLOR) {
887 } else if (predicted_f.param_type_2
888 == CPT2_COLORED_WALLMOUNTED) {
889 // param2 = pure palette index + other
890 param2 = (index & 0xf8) | (param2 & 0x07);
891 } else if (predicted_f.param_type_2
892 == CPT2_COLORED_FACEDIR) {
893 // param2 = pure palette index + other
894 param2 = (index & 0xe0) | (param2 & 0x1f);
899 // Add node to client map
900 MapNode n(id, 0, param2);
903 LocalPlayer *player = client.getEnv().getLocalPlayer();
905 // Dont place node when player would be inside new node
906 // NOTE: This is to be eventually implemented by a mod as client-side Lua
907 if (!nodedef->get(n).walkable ||
908 g_settings->getBool("enable_build_where_you_stand") ||
909 (client.checkPrivilege("noclip") && g_settings->getBool("noclip")) ||
910 (nodedef->get(n).walkable &&
911 neighbourpos != player->getStandingNodePos() + v3s16(0, 1, 0) &&
912 neighbourpos != player->getStandingNodePos() + v3s16(0, 2, 0))) {
914 // This triggers the required mesh update too
915 client.addNode(p, n);
918 } catch (InvalidPositionException &e) {
919 errorstream << "Node placement prediction failed for "
920 << playeritem_def.name << " (places "
922 << ") - Position not loaded" << std::endl;
929 static inline void create_formspec_menu(GUIFormSpecMenu **cur_formspec,
930 Client *client, JoystickController *joystick,
931 IFormSource *fs_src, TextDest *txt_dest)
934 if (*cur_formspec == 0) {
935 *cur_formspec = new GUIFormSpecMenu(joystick, guiroot, -1, &g_menumgr,
936 client, client->getTextureSource(), fs_src, txt_dest);
937 (*cur_formspec)->doPause = false;
940 Caution: do not call (*cur_formspec)->drop() here --
941 the reference might outlive the menu, so we will
942 periodically check if *cur_formspec is the only
943 remaining reference (i.e. the menu was removed)
944 and delete it in that case.
948 (*cur_formspec)->setFormSource(fs_src);
949 (*cur_formspec)->setTextDest(txt_dest);
955 #define SIZE_TAG "size[11,5.5]"
957 #define SIZE_TAG "size[11,5.5,true]" // Fixed size on desktop
960 /******************************************************************************/
961 static void updateChat(Client &client, f32 dtime, bool show_debug,
962 const v2u32 &screensize, bool show_chat, u32 show_profiler,
963 ChatBackend &chat_backend, gui::IGUIStaticText *guitext_chat)
965 // Add chat log output for errors to be shown in chat
966 static LogOutputBuffer chat_log_error_buf(g_logger, LL_ERROR);
968 // Get new messages from error log buffer
969 while (!chat_log_error_buf.empty()) {
970 std::wstring error_message = utf8_to_wide(chat_log_error_buf.get());
971 if (!g_settings->getBool("disable_escape_sequences")) {
972 error_message = L"\x1b(c@red)" + error_message + L"\x1b(c@white)";
974 chat_backend.addMessage(L"", error_message);
977 // Get new messages from client
978 std::wstring message;
980 while (client.getChatMessage(message)) {
981 chat_backend.addUnparsedMessage(message);
984 // Remove old messages
985 chat_backend.step(dtime);
987 // Display all messages in a static text element
988 unsigned int recent_chat_count = chat_backend.getRecentBuffer().getLineCount();
989 EnrichedString recent_chat = chat_backend.getRecentChat();
990 unsigned int line_height = g_fontengine->getLineHeight();
992 setStaticText(guitext_chat, recent_chat);
994 // Update gui element size and position
998 chat_y += 2 * line_height;
1000 // first pass to calculate height of text to be set
1001 const v2u32 &window_size = RenderingEngine::get_instance()->getWindowSize();
1002 s32 width = std::min(g_fontengine->getTextWidth(recent_chat.c_str()) + 10,
1003 window_size.X - 20);
1004 core::rect<s32> rect(10, chat_y, width, chat_y + window_size.Y);
1005 guitext_chat->setRelativePosition(rect);
1007 //now use real height of text and adjust rect according to this size
1008 rect = core::rect<s32>(10, chat_y, width,
1009 chat_y + guitext_chat->getTextHeight());
1012 guitext_chat->setRelativePosition(rect);
1013 // Don't show chat if disabled or empty or profiler is enabled
1014 guitext_chat->setVisible(
1015 show_chat && recent_chat_count != 0 && !show_profiler);
1019 /****************************************************************************
1020 Fast key cache for main game loop
1021 ****************************************************************************/
1023 /* This is faster than using getKeySetting with the tradeoff that functions
1024 * using it must make sure that it's initialised before using it and there is
1025 * no error handling (for example bounds checking). This is really intended for
1026 * use only in the main running loop of the client (the_game()) where the faster
1027 * (up to 10x faster) key lookup is an asset. Other parts of the codebase
1028 * (e.g. formspecs) should continue using getKeySetting().
1036 populate_nonchanging();
1041 // Keys that are not settings dependent
1042 void populate_nonchanging();
1044 KeyPress key[KeyType::INTERNAL_ENUM_COUNT];
1045 InputHandler *handler;
1048 void KeyCache::populate_nonchanging()
1050 key[KeyType::ESC] = EscapeKey;
1053 void KeyCache::populate()
1055 key[KeyType::FORWARD] = getKeySetting("keymap_forward");
1056 key[KeyType::BACKWARD] = getKeySetting("keymap_backward");
1057 key[KeyType::LEFT] = getKeySetting("keymap_left");
1058 key[KeyType::RIGHT] = getKeySetting("keymap_right");
1059 key[KeyType::JUMP] = getKeySetting("keymap_jump");
1060 key[KeyType::SPECIAL1] = getKeySetting("keymap_special1");
1061 key[KeyType::SNEAK] = getKeySetting("keymap_sneak");
1063 key[KeyType::AUTOFORWARD] = getKeySetting("keymap_autoforward");
1065 key[KeyType::DROP] = getKeySetting("keymap_drop");
1066 key[KeyType::INVENTORY] = getKeySetting("keymap_inventory");
1067 key[KeyType::CHAT] = getKeySetting("keymap_chat");
1068 key[KeyType::CMD] = getKeySetting("keymap_cmd");
1069 key[KeyType::CMD_LOCAL] = getKeySetting("keymap_cmd_local");
1070 key[KeyType::CONSOLE] = getKeySetting("keymap_console");
1071 key[KeyType::MINIMAP] = getKeySetting("keymap_minimap");
1072 key[KeyType::FREEMOVE] = getKeySetting("keymap_freemove");
1073 key[KeyType::FASTMOVE] = getKeySetting("keymap_fastmove");
1074 key[KeyType::NOCLIP] = getKeySetting("keymap_noclip");
1075 key[KeyType::HOTBAR_PREV] = getKeySetting("keymap_hotbar_previous");
1076 key[KeyType::HOTBAR_NEXT] = getKeySetting("keymap_hotbar_next");
1077 key[KeyType::MUTE] = getKeySetting("keymap_mute");
1078 key[KeyType::INC_VOLUME] = getKeySetting("keymap_increase_volume");
1079 key[KeyType::DEC_VOLUME] = getKeySetting("keymap_decrease_volume");
1080 key[KeyType::CINEMATIC] = getKeySetting("keymap_cinematic");
1081 key[KeyType::SCREENSHOT] = getKeySetting("keymap_screenshot");
1082 key[KeyType::TOGGLE_HUD] = getKeySetting("keymap_toggle_hud");
1083 key[KeyType::TOGGLE_CHAT] = getKeySetting("keymap_toggle_chat");
1084 key[KeyType::TOGGLE_FORCE_FOG_OFF]
1085 = getKeySetting("keymap_toggle_force_fog_off");
1086 key[KeyType::TOGGLE_UPDATE_CAMERA]
1087 = getKeySetting("keymap_toggle_update_camera");
1088 key[KeyType::TOGGLE_DEBUG]
1089 = getKeySetting("keymap_toggle_debug");
1090 key[KeyType::TOGGLE_PROFILER]
1091 = getKeySetting("keymap_toggle_profiler");
1092 key[KeyType::CAMERA_MODE]
1093 = getKeySetting("keymap_camera_mode");
1094 key[KeyType::INCREASE_VIEWING_RANGE]
1095 = getKeySetting("keymap_increase_viewing_range_min");
1096 key[KeyType::DECREASE_VIEWING_RANGE]
1097 = getKeySetting("keymap_decrease_viewing_range_min");
1098 key[KeyType::RANGESELECT]
1099 = getKeySetting("keymap_rangeselect");
1100 key[KeyType::ZOOM] = getKeySetting("keymap_zoom");
1102 key[KeyType::QUICKTUNE_NEXT] = getKeySetting("keymap_quicktune_next");
1103 key[KeyType::QUICKTUNE_PREV] = getKeySetting("keymap_quicktune_prev");
1104 key[KeyType::QUICKTUNE_INC] = getKeySetting("keymap_quicktune_inc");
1105 key[KeyType::QUICKTUNE_DEC] = getKeySetting("keymap_quicktune_dec");
1107 key[KeyType::DEBUG_STACKS] = getKeySetting("keymap_print_debug_stacks");
1110 // First clear all keys, then re-add the ones we listen for
1111 handler->dontListenForKeys();
1112 for (size_t i = 0; i < KeyType::INTERNAL_ENUM_COUNT; i++) {
1113 handler->listenForKey(key[i]);
1115 handler->listenForKey(EscapeKey);
1116 handler->listenForKey(CancelKey);
1117 for (size_t i = 0; i < 10; i++) {
1118 handler->listenForKey(NumberKey[i]);
1124 /****************************************************************************
1126 ****************************************************************************/
1128 const float object_hit_delay = 0.2;
1131 u32 last_time, busy_time, sleep_time;
1135 /* The reason the following structs are not anonymous structs within the
1136 * class is that they are not used by the majority of member functions and
1137 * many functions that do require objects of thse types do not modify them
1138 * (so they can be passed as a const qualified parameter)
1140 struct CameraOrientation {
1141 f32 camera_yaw; // "right/left"
1142 f32 camera_pitch; // "up/down"
1145 struct GameRunData {
1148 PointedThing pointed_old;
1153 bool update_wielded_item_trigger;
1154 bool reset_jump_timer;
1155 float nodig_delay_timer;
1157 float dig_time_complete;
1158 float repeat_rightclick_timer;
1159 float object_hit_delay_timer;
1160 float time_from_last_punch;
1161 ClientActiveObject *selected_object;
1165 float update_draw_list_timer;
1166 float statustext_time;
1170 v3f update_draw_list_last_cam_dir;
1172 u32 profiler_current_page;
1173 u32 profiler_max_page; // Number of pages
1176 float time_of_day_smooth;
1180 f32 max, min, avg, counter, max_sample, min_sample, max_fraction;
1186 Jitter dtime_jitter, busy_time_jitter;
1189 /****************************************************************************
1191 ****************************************************************************/
1193 /* This is not intended to be a public class. If a public class becomes
1194 * desirable then it may be better to create another 'wrapper' class that
1195 * hides most of the stuff in this class (nothing in this class is required
1196 * by any other file) but exposes the public methods/data only.
1203 bool startup(bool *kill,
1205 InputHandler *input,
1206 const std::string &map_dir,
1207 const std::string &playername,
1208 const std::string &password,
1209 // If address is "", local server is used and address is updated
1210 std::string *address,
1212 std::string &error_message,
1214 ChatBackend *chat_backend,
1215 const SubgameSpec &gamespec, // Used for local game
1216 bool simple_singleplayer_mode);
1223 void extendedResourceCleanup();
1225 // Basic initialisation
1226 bool init(const std::string &map_dir, std::string *address,
1228 const SubgameSpec &gamespec);
1230 bool createSingleplayerServer(const std::string &map_dir,
1231 const SubgameSpec &gamespec, u16 port, std::string *address);
1234 bool createClient(const std::string &playername,
1235 const std::string &password, std::string *address, u16 port);
1238 // Client connection
1239 bool connectToServer(const std::string &playername,
1240 const std::string &password, std::string *address, u16 port,
1241 bool *connect_ok, bool *aborted);
1242 bool getServerContent(bool *aborted);
1246 void updateInteractTimers(f32 dtime);
1247 bool checkConnection();
1248 bool handleCallbacks();
1249 void processQueues();
1250 void updateProfilers(const RunStats &stats, const FpsControl &draw_times, f32 dtime);
1251 void addProfilerGraphs(const RunStats &stats, const FpsControl &draw_times, f32 dtime);
1252 void updateStats(RunStats *stats, const FpsControl &draw_times, f32 dtime);
1255 void processUserInput(f32 dtime);
1256 void processKeyInput();
1257 void processItemSelection(u16 *new_playeritem);
1259 void dropSelectedItem();
1260 void openInventory();
1261 void openConsole(float scale, const wchar_t *line=NULL);
1262 void toggleFreeMove();
1263 void toggleFreeMoveAlt();
1265 void toggleNoClip();
1266 void toggleCinematic();
1267 void toggleAutoforward();
1271 void toggleMinimap(bool shift_pressed);
1274 void toggleUpdateCamera();
1275 void toggleProfiler();
1277 void increaseViewRange();
1278 void decreaseViewRange();
1279 void toggleFullViewRange();
1281 void updateCameraDirection(CameraOrientation *cam, float dtime);
1282 void updateCameraOrientation(CameraOrientation *cam, float dtime);
1283 void updatePlayerControl(const CameraOrientation &cam);
1284 void step(f32 *dtime);
1285 void processClientEvents(CameraOrientation *cam);
1286 void updateCamera(u32 busy_time, f32 dtime);
1287 void updateSound(f32 dtime);
1288 void processPlayerInteraction(f32 dtime, bool show_hud, bool show_debug);
1290 * Returns the object or node the player is pointing at.
1291 * Also updates the selected thing in the Hud.
1293 * @param[in] shootline the shootline, starting from
1294 * the camera position. This also gives the maximal distance
1296 * @param[in] liquids_pointable if false, liquids are ignored
1297 * @param[in] look_for_object if false, objects are ignored
1298 * @param[in] camera_offset offset of the camera
1299 * @param[out] selected_object the selected object or
1302 PointedThing updatePointedThing(
1303 const core::line3d<f32> &shootline, bool liquids_pointable,
1304 bool look_for_object, const v3s16 &camera_offset);
1305 void handlePointingAtNothing(const ItemStack &playerItem);
1306 void handlePointingAtNode(const PointedThing &pointed,
1307 const ItemDefinition &playeritem_def, const ItemStack &playeritem,
1308 const ToolCapabilities &playeritem_toolcap, f32 dtime);
1309 void handlePointingAtObject(const PointedThing &pointed, const ItemStack &playeritem,
1310 const v3f &player_position, bool show_debug);
1311 void handleDigging(const PointedThing &pointed, const v3s16 &nodepos,
1312 const ToolCapabilities &playeritem_toolcap, f32 dtime);
1313 void updateFrame(ProfilerGraph *graph, RunStats *stats, f32 dtime,
1314 const CameraOrientation &cam);
1315 void updateGui(const RunStats &stats, f32 dtime, const CameraOrientation &cam);
1316 void updateProfilerGraphs(ProfilerGraph *graph);
1319 void limitFps(FpsControl *fps_timings, f32 *dtime);
1321 void showOverlayMessage(const char *msg, float dtime, int percent,
1322 bool draw_clouds = true);
1324 static void settingChangedCallback(const std::string &setting_name, void *data);
1325 void readSettings();
1327 inline bool getLeftClicked()
1329 return input->getLeftClicked() ||
1330 input->joystick.getWasKeyDown(KeyType::MOUSE_L);
1332 inline bool getRightClicked()
1334 return input->getRightClicked() ||
1335 input->joystick.getWasKeyDown(KeyType::MOUSE_R);
1337 inline bool isLeftPressed()
1339 return input->getLeftState() ||
1340 input->joystick.isKeyDown(KeyType::MOUSE_L);
1342 inline bool isRightPressed()
1344 return input->getRightState() ||
1345 input->joystick.isKeyDown(KeyType::MOUSE_R);
1347 inline bool getLeftReleased()
1349 return input->getLeftReleased() ||
1350 input->joystick.wasKeyReleased(KeyType::MOUSE_L);
1353 inline bool isKeyDown(GameKeyType k)
1355 return input->isKeyDown(keycache.key[k]) || input->joystick.isKeyDown(k);
1357 inline bool wasKeyDown(GameKeyType k)
1359 return input->wasKeyDown(keycache.key[k]) || input->joystick.wasKeyDown(k);
1363 void handleAndroidChatInput();
1367 void showPauseMenu();
1369 InputHandler *input;
1374 IWritableTextureSource *texture_src;
1375 IWritableShaderSource *shader_src;
1377 // When created, these will be filled with data received from the server
1378 IWritableItemDefManager *itemdef_manager;
1379 IWritableNodeDefManager *nodedef_manager;
1381 GameOnDemandSoundFetcher soundfetcher; // useful when testing
1382 ISoundManager *sound;
1383 bool sound_is_dummy;
1384 SoundMaker *soundmaker;
1386 ChatBackend *chat_backend;
1388 GUIFormSpecMenu *current_formspec;
1389 //default: "". If other than "", empty show_formspec packets will only close the formspec when the formname matches
1390 std::string cur_formname;
1392 EventManager *eventmgr;
1393 QuicktuneShortcutter *quicktune;
1395 GUIChatConsole *gui_chat_console; // Free using ->Drop()
1396 MapDrawControl *draw_control;
1398 Clouds *clouds; // Free using ->Drop()
1399 Sky *sky; // Free using ->Drop()
1400 Inventory *local_inventory;
1404 GameRunData runData;
1408 This class does take ownership/responsibily for cleaning up etc of any of
1409 these items (e.g. device)
1411 IrrlichtDevice *device;
1412 video::IVideoDriver *driver;
1413 scene::ISceneManager *smgr;
1415 std::string *error_message;
1416 bool *reconnect_requested;
1417 scene::ISceneNode *skybox;
1420 bool simple_singleplayer_mode;
1423 /* Pre-calculated values
1425 int crack_animation_length;
1429 gui::IGUIStaticText *guitext; // First line of debug text
1430 gui::IGUIStaticText *guitext2; // Second line of debug text
1431 gui::IGUIStaticText *guitext_info; // At the middle of the screen
1432 gui::IGUIStaticText *guitext_status;
1433 gui::IGUIStaticText *guitext_chat; // Chat text
1434 gui::IGUIStaticText *guitext_profiler; // Profiler text
1436 std::wstring infotext;
1437 std::wstring m_statustext;
1441 IntervalLimiter profiler_interval;
1444 * TODO: Local caching of settings is not optimal and should at some stage
1445 * be updated to use a global settings object for getting thse values
1446 * (as opposed to the this local caching). This can be addressed in
1449 bool m_cache_doubletap_jump;
1450 bool m_cache_enable_clouds;
1451 bool m_cache_enable_joysticks;
1452 bool m_cache_enable_particles;
1453 bool m_cache_enable_fog;
1454 bool m_cache_enable_noclip;
1455 bool m_cache_enable_free_move;
1456 f32 m_cache_mouse_sensitivity;
1457 f32 m_cache_joystick_frustum_sensitivity;
1458 f32 m_repeat_right_click_time;
1459 f32 m_cache_cam_smoothing;
1460 f32 m_cache_fog_start;
1462 bool m_invert_mouse;
1463 bool m_first_loop_after_window_activation;
1464 bool m_camera_offset_changed;
1467 bool m_cache_hold_aux1;
1468 bool m_android_chat_open;
1477 itemdef_manager(NULL),
1478 nodedef_manager(NULL),
1480 sound_is_dummy(false),
1483 current_formspec(NULL),
1487 gui_chat_console(NULL),
1492 local_inventory(NULL),
1495 m_invert_mouse(false),
1496 m_first_loop_after_window_activation(false),
1497 m_camera_offset_changed(false)
1499 g_settings->registerChangedCallback("doubletap_jump",
1500 &settingChangedCallback, this);
1501 g_settings->registerChangedCallback("enable_clouds",
1502 &settingChangedCallback, this);
1503 g_settings->registerChangedCallback("doubletap_joysticks",
1504 &settingChangedCallback, this);
1505 g_settings->registerChangedCallback("enable_particles",
1506 &settingChangedCallback, this);
1507 g_settings->registerChangedCallback("enable_fog",
1508 &settingChangedCallback, this);
1509 g_settings->registerChangedCallback("mouse_sensitivity",
1510 &settingChangedCallback, this);
1511 g_settings->registerChangedCallback("joystick_frustum_sensitivity",
1512 &settingChangedCallback, this);
1513 g_settings->registerChangedCallback("repeat_rightclick_time",
1514 &settingChangedCallback, this);
1515 g_settings->registerChangedCallback("noclip",
1516 &settingChangedCallback, this);
1517 g_settings->registerChangedCallback("free_move",
1518 &settingChangedCallback, this);
1519 g_settings->registerChangedCallback("cinematic",
1520 &settingChangedCallback, this);
1521 g_settings->registerChangedCallback("cinematic_camera_smoothing",
1522 &settingChangedCallback, this);
1523 g_settings->registerChangedCallback("camera_smoothing",
1524 &settingChangedCallback, this);
1529 m_cache_hold_aux1 = false; // This is initialised properly later
1536 /****************************************************************************
1538 ****************************************************************************/
1544 if (!sound_is_dummy)
1547 delete server; // deleted first to stop all server threads
1550 delete local_inventory;
1556 delete nodedef_manager;
1557 delete itemdef_manager;
1558 delete draw_control;
1560 extendedResourceCleanup();
1562 g_settings->deregisterChangedCallback("doubletap_jump",
1563 &settingChangedCallback, this);
1564 g_settings->deregisterChangedCallback("enable_clouds",
1565 &settingChangedCallback, this);
1566 g_settings->deregisterChangedCallback("enable_particles",
1567 &settingChangedCallback, this);
1568 g_settings->deregisterChangedCallback("enable_fog",
1569 &settingChangedCallback, this);
1570 g_settings->deregisterChangedCallback("mouse_sensitivity",
1571 &settingChangedCallback, this);
1572 g_settings->deregisterChangedCallback("repeat_rightclick_time",
1573 &settingChangedCallback, this);
1574 g_settings->deregisterChangedCallback("noclip",
1575 &settingChangedCallback, this);
1576 g_settings->deregisterChangedCallback("free_move",
1577 &settingChangedCallback, this);
1578 g_settings->deregisterChangedCallback("cinematic",
1579 &settingChangedCallback, this);
1580 g_settings->deregisterChangedCallback("cinematic_camera_smoothing",
1581 &settingChangedCallback, this);
1582 g_settings->deregisterChangedCallback("camera_smoothing",
1583 &settingChangedCallback, this);
1586 bool Game::startup(bool *kill,
1588 InputHandler *input,
1589 const std::string &map_dir,
1590 const std::string &playername,
1591 const std::string &password,
1592 std::string *address, // can change if simple_singleplayer_mode
1594 std::string &error_message,
1596 ChatBackend *chat_backend,
1597 const SubgameSpec &gamespec,
1598 bool simple_singleplayer_mode)
1601 this->device = RenderingEngine::get_raw_device();
1603 this->error_message = &error_message;
1604 this->reconnect_requested = reconnect;
1605 this->random_input = random_input;
1606 this->input = input;
1607 this->chat_backend = chat_backend;
1608 this->simple_singleplayer_mode = simple_singleplayer_mode;
1610 keycache.handler = input;
1611 keycache.populate();
1613 driver = device->getVideoDriver();
1614 smgr = RenderingEngine::get_scene_manager();
1616 RenderingEngine::get_scene_manager()->getParameters()->
1617 setAttribute(scene::OBJ_LOADER_IGNORE_MATERIAL_FILES, true);
1619 memset(&runData, 0, sizeof(runData));
1620 runData.time_from_last_punch = 10.0;
1621 runData.profiler_max_page = 3;
1622 runData.update_wielded_item_trigger = true;
1624 memset(&flags, 0, sizeof(flags));
1625 flags.show_chat = true;
1626 flags.show_hud = true;
1627 flags.show_debug = g_settings->getBool("show_debug");
1628 m_invert_mouse = g_settings->getBool("invert_mouse");
1629 m_first_loop_after_window_activation = true;
1631 if (!init(map_dir, address, port, gamespec))
1634 if (!createClient(playername, password, address, port))
1643 ProfilerGraph graph;
1644 RunStats stats = { 0 };
1645 CameraOrientation cam_view_target = { 0 };
1646 CameraOrientation cam_view = { 0 };
1647 FpsControl draw_times = { 0 };
1648 f32 dtime; // in seconds
1650 /* Clear the profiler */
1651 Profiler::GraphValues dummyvalues;
1652 g_profiler->graphGet(dummyvalues);
1654 draw_times.last_time = RenderingEngine::get_timer_time();
1656 set_light_table(g_settings->getFloat("display_gamma"));
1659 m_cache_hold_aux1 = g_settings->getBool("fast_move")
1660 && client->checkPrivilege("fast");
1663 irr::core::dimension2d<u32> previous_screen_size(g_settings->getU16("screen_w"),
1664 g_settings->getU16("screen_h"));
1666 while (RenderingEngine::run()
1667 && !(*kill || g_gamecallback->shutdown_requested
1668 || (server && server->getShutdownRequested()))) {
1670 const irr::core::dimension2d<u32> ¤t_screen_size =
1671 RenderingEngine::get_video_driver()->getScreenSize();
1672 // Verify if window size has changed and save it if it's the case
1673 // Ensure evaluating settings->getBool after verifying screensize
1674 // First condition is cheaper
1675 if (previous_screen_size != current_screen_size &&
1676 current_screen_size != irr::core::dimension2d<u32>(0,0) &&
1677 g_settings->getBool("autosave_screensize")) {
1678 g_settings->setU16("screen_w", current_screen_size.Width);
1679 g_settings->setU16("screen_h", current_screen_size.Height);
1680 previous_screen_size = current_screen_size;
1683 /* Must be called immediately after a device->run() call because it
1684 * uses device->getTimer()->getTime()
1686 limitFps(&draw_times, &dtime);
1688 updateStats(&stats, draw_times, dtime);
1689 updateInteractTimers(dtime);
1691 if (!checkConnection())
1693 if (!handleCallbacks())
1699 hud->resizeHotbar();
1701 updateProfilers(stats, draw_times, dtime);
1702 processUserInput(dtime);
1703 // Update camera before player movement to avoid camera lag of one frame
1704 updateCameraDirection(&cam_view_target, dtime);
1705 cam_view.camera_yaw += (cam_view_target.camera_yaw -
1706 cam_view.camera_yaw) * m_cache_cam_smoothing;
1707 cam_view.camera_pitch += (cam_view_target.camera_pitch -
1708 cam_view.camera_pitch) * m_cache_cam_smoothing;
1709 updatePlayerControl(cam_view);
1711 processClientEvents(&cam_view_target);
1712 updateCamera(draw_times.busy_time, dtime);
1714 processPlayerInteraction(dtime, flags.show_hud, flags.show_debug);
1715 updateFrame(&graph, &stats, dtime, cam_view);
1716 updateProfilerGraphs(&graph);
1718 // Update if minimap has been disabled by the server
1719 flags.show_minimap &= client->shouldShowMinimap();
1724 void Game::shutdown()
1726 #if IRRLICHT_VERSION_MAJOR == 1 && IRRLICHT_VERSION_MINOR <= 8
1727 if (g_settings->get("3d_mode") == "pageflip") {
1728 driver->setRenderTarget(irr::video::ERT_STEREO_BOTH_BUFFERS);
1731 if (current_formspec)
1732 current_formspec->quitMenu();
1734 showOverlayMessage("Shutting down...", 0, 0, false);
1739 if (gui_chat_console)
1740 gui_chat_console->drop();
1746 while (g_menumgr.menuCount() > 0) {
1747 g_menumgr.m_stack.front()->setVisible(false);
1748 g_menumgr.deletingMenu(g_menumgr.m_stack.front());
1751 if (current_formspec) {
1752 current_formspec->drop();
1753 current_formspec = NULL;
1756 chat_backend->addMessage(L"", L"# Disconnected.");
1757 chat_backend->addMessage(L"", L"");
1761 while (!client->isShutdown()) {
1762 assert(texture_src != NULL);
1763 assert(shader_src != NULL);
1764 texture_src->processQueue();
1765 shader_src->processQueue();
1772 /****************************************************************************/
1773 /****************************************************************************
1775 ****************************************************************************/
1776 /****************************************************************************/
1779 const std::string &map_dir,
1780 std::string *address,
1782 const SubgameSpec &gamespec)
1784 texture_src = createTextureSource();
1786 showOverlayMessage("Loading...", 0, 0);
1788 shader_src = createShaderSource();
1790 itemdef_manager = createItemDefManager();
1791 nodedef_manager = createNodeDefManager();
1793 eventmgr = new EventManager();
1794 quicktune = new QuicktuneShortcutter();
1796 if (!(texture_src && shader_src && itemdef_manager && nodedef_manager
1797 && eventmgr && quicktune))
1803 // Create a server if not connecting to an existing one
1804 if (*address == "") {
1805 if (!createSingleplayerServer(map_dir, gamespec, port, address))
1812 bool Game::initSound()
1815 if (g_settings->getBool("enable_sound")) {
1816 infostream << "Attempting to use OpenAL audio" << std::endl;
1817 sound = createOpenALSoundManager(&soundfetcher);
1819 infostream << "Failed to initialize OpenAL audio" << std::endl;
1821 infostream << "Sound disabled." << std::endl;
1825 infostream << "Using dummy audio." << std::endl;
1826 sound = &dummySoundManager;
1827 sound_is_dummy = true;
1830 soundmaker = new SoundMaker(sound, nodedef_manager);
1834 soundmaker->registerReceiver(eventmgr);
1839 bool Game::createSingleplayerServer(const std::string &map_dir,
1840 const SubgameSpec &gamespec, u16 port, std::string *address)
1842 showOverlayMessage("Creating server...", 0, 5);
1844 std::string bind_str = g_settings->get("bind_address");
1845 Address bind_addr(0, 0, 0, 0, port);
1847 if (g_settings->getBool("ipv6_server")) {
1848 bind_addr.setAddress((IPv6AddressBytes *) NULL);
1852 bind_addr.Resolve(bind_str.c_str());
1853 } catch (ResolveError &e) {
1854 infostream << "Resolving bind address \"" << bind_str
1855 << "\" failed: " << e.what()
1856 << " -- Listening on all addresses." << std::endl;
1859 if (bind_addr.isIPv6() && !g_settings->getBool("enable_ipv6")) {
1860 *error_message = "Unable to listen on " +
1861 bind_addr.serializeString() +
1862 " because IPv6 is disabled";
1863 errorstream << *error_message << std::endl;
1867 server = new Server(map_dir, gamespec, simple_singleplayer_mode,
1868 bind_addr.isIPv6(), false);
1870 server->start(bind_addr);
1875 bool Game::createClient(const std::string &playername,
1876 const std::string &password, std::string *address, u16 port)
1878 showOverlayMessage("Creating client...", 0, 10);
1880 draw_control = new MapDrawControl;
1884 bool could_connect, connect_aborted;
1886 if (!connectToServer(playername, password, address, port,
1887 &could_connect, &connect_aborted))
1890 if (!could_connect) {
1891 if (error_message->empty() && !connect_aborted) {
1892 // Should not happen if error messages are set properly
1893 *error_message = "Connection failed for unknown reason";
1894 errorstream << *error_message << std::endl;
1899 if (!getServerContent(&connect_aborted)) {
1900 if (error_message->empty() && !connect_aborted) {
1901 // Should not happen if error messages are set properly
1902 *error_message = "Connection failed for unknown reason";
1903 errorstream << *error_message << std::endl;
1908 GameGlobalShaderConstantSetterFactory *scsf = new GameGlobalShaderConstantSetterFactory(
1909 &flags.force_fog_off, &runData.fog_range, client);
1910 shader_src->addShaderConstantSetterFactory(scsf);
1912 // Update cached textures, meshes and materials
1913 client->afterContentReceived();
1917 camera = new Camera(smgr, *draw_control, client);
1918 if (!camera || !camera->successfullyCreated(*error_message))
1920 client->setCamera(camera);
1924 if (m_cache_enable_clouds) {
1925 clouds = new Clouds(smgr, -1, time(0));
1927 *error_message = "Memory allocation error (clouds)";
1928 errorstream << *error_message << std::endl;
1935 sky = new Sky(-1, texture_src);
1937 skybox = NULL; // This is used/set later on in the main run loop
1939 local_inventory = new Inventory(itemdef_manager);
1941 if (!(sky && local_inventory)) {
1942 *error_message = "Memory allocation error (sky or local inventory)";
1943 errorstream << *error_message << std::endl;
1947 /* Pre-calculated values
1949 video::ITexture *t = texture_src->getTexture("crack_anylength.png");
1951 v2u32 size = t->getOriginalSize();
1952 crack_animation_length = size.Y / size.X;
1954 crack_animation_length = 5;
1960 /* Set window caption
1962 std::wstring str = utf8_to_wide(PROJECT_NAME_C);
1964 str += utf8_to_wide(g_version_hash);
1966 str += driver->getName();
1968 device->setWindowCaption(str.c_str());
1970 LocalPlayer *player = client->getEnv().getLocalPlayer();
1971 player->hurt_tilt_timer = 0;
1972 player->hurt_tilt_strength = 0;
1974 hud = new Hud(driver, smgr, guienv, client, player, local_inventory);
1977 *error_message = "Memory error: could not create HUD";
1978 errorstream << *error_message << std::endl;
1982 mapper = client->getMinimap();
1984 mapper->setMinimapMode(MINIMAP_MODE_OFF);
1989 bool Game::initGui()
1991 // First line of debug text
1992 guitext = addStaticText(guienv,
1993 utf8_to_wide(PROJECT_NAME_C).c_str(),
1994 core::rect<s32>(0, 0, 0, 0),
1995 false, false, guiroot);
1997 // Second line of debug text
1998 guitext2 = addStaticText(guienv,
2000 core::rect<s32>(0, 0, 0, 0),
2001 false, false, guiroot);
2003 // At the middle of the screen
2004 // Object infos are shown in this
2005 guitext_info = addStaticText(guienv,
2007 core::rect<s32>(0, 0, 400, g_fontengine->getTextHeight() * 5 + 5) + v2s32(100, 200),
2008 false, true, guiroot);
2010 // Status text (displays info when showing and hiding GUI stuff, etc.)
2011 guitext_status = addStaticText(guienv,
2013 core::rect<s32>(0, 0, 0, 0),
2014 false, false, guiroot);
2015 guitext_status->setVisible(false);
2018 guitext_chat = addStaticText(
2021 core::rect<s32>(0, 0, 0, 0),
2022 //false, false); // Disable word wrap as of now
2023 false, true, guiroot);
2025 // Remove stale "recent" chat messages from previous connections
2026 chat_backend->clearRecentChat();
2028 // Chat backend and console
2029 gui_chat_console = new GUIChatConsole(guienv, guienv->getRootGUIElement(),
2030 -1, chat_backend, client, &g_menumgr);
2031 if (!gui_chat_console) {
2032 *error_message = "Could not allocate memory for chat console";
2033 errorstream << *error_message << std::endl;
2037 // Profiler text (size is updated when text is updated)
2038 guitext_profiler = addStaticText(guienv,
2040 core::rect<s32>(0, 0, 0, 0),
2041 false, false, guiroot);
2042 guitext_profiler->setBackgroundColor(video::SColor(120, 0, 0, 0));
2043 guitext_profiler->setVisible(false);
2044 guitext_profiler->setWordWrap(true);
2046 #ifdef HAVE_TOUCHSCREENGUI
2048 if (g_touchscreengui)
2049 g_touchscreengui->init(texture_src);
2056 bool Game::connectToServer(const std::string &playername,
2057 const std::string &password, std::string *address, u16 port,
2058 bool *connect_ok, bool *aborted)
2060 *connect_ok = false; // Let's not be overly optimistic
2062 bool local_server_mode = false;
2064 showOverlayMessage("Resolving address...", 0, 15);
2066 Address connect_address(0, 0, 0, 0, port);
2069 connect_address.Resolve(address->c_str());
2071 if (connect_address.isZero()) { // i.e. INADDR_ANY, IN6ADDR_ANY
2072 //connect_address.Resolve("localhost");
2073 if (connect_address.isIPv6()) {
2074 IPv6AddressBytes addr_bytes;
2075 addr_bytes.bytes[15] = 1;
2076 connect_address.setAddress(&addr_bytes);
2078 connect_address.setAddress(127, 0, 0, 1);
2080 local_server_mode = true;
2082 } catch (ResolveError &e) {
2083 *error_message = std::string("Couldn't resolve address: ") + e.what();
2084 errorstream << *error_message << std::endl;
2088 if (connect_address.isIPv6() && !g_settings->getBool("enable_ipv6")) {
2089 *error_message = "Unable to connect to " +
2090 connect_address.serializeString() +
2091 " because IPv6 is disabled";
2092 errorstream << *error_message << std::endl;
2096 client = new Client(playername.c_str(), password, *address,
2097 *draw_control, texture_src, shader_src,
2098 itemdef_manager, nodedef_manager, sound, eventmgr,
2099 connect_address.isIPv6(), &flags);
2104 infostream << "Connecting to server at ";
2105 connect_address.print(&infostream);
2106 infostream << std::endl;
2108 client->connect(connect_address,
2109 simple_singleplayer_mode || local_server_mode);
2112 Wait for server to accept connection
2118 FpsControl fps_control = { 0 };
2120 f32 wait_time = 0; // in seconds
2122 fps_control.last_time = RenderingEngine::get_timer_time();
2126 while (RenderingEngine::run()) {
2128 limitFps(&fps_control, &dtime);
2130 // Update client and server
2131 client->step(dtime);
2134 server->step(dtime);
2137 if (client->getState() == LC_Init) {
2143 if (client->accessDenied()) {
2144 *error_message = "Access denied. Reason: "
2145 + client->accessDeniedReason();
2146 *reconnect_requested = client->reconnectRequested();
2147 errorstream << *error_message << std::endl;
2151 if (wasKeyDown(KeyType::ESC) || input->wasKeyDown(CancelKey)) {
2153 infostream << "Connect aborted [Escape]" << std::endl;
2158 // Only time out if we aren't waiting for the server we started
2159 if ((*address != "") && (wait_time > 10)) {
2160 bool sent_old_init = g_settings->getFlag("send_pre_v25_init");
2161 // If no pre v25 init was sent, and no answer was received,
2162 // but the low level connection could be established
2163 // (meaning that we have a peer id), then we probably wanted
2164 // to connect to a legacy server. In this case, tell the user
2165 // to enable the option to be able to connect.
2166 if (!sent_old_init &&
2167 (client->getProtoVersion() == 0) &&
2168 client->connectedToServer()) {
2169 *error_message = "Connection failure: init packet not "
2170 "recognized by server.\n"
2171 "Most likely the server uses an old protocol version (<v25).\n"
2172 "Please ask the server owner to update to 0.4.13 or later.\n"
2173 "To still connect to the server in the meantime,\n"
2174 "you can enable the 'send_pre_v25_init' setting by editing minetest.conf,\n"
2175 "or by enabling the 'Client -> Network -> Support older Servers'\n"
2176 "entry in the advanced settings menu.";
2178 *error_message = "Connection timed out.";
2180 errorstream << *error_message << std::endl;
2185 showOverlayMessage("Connecting to server...", dtime, 20);
2187 } catch (con::PeerNotFoundException &e) {
2188 // TODO: Should something be done here? At least an info/error
2196 bool Game::getServerContent(bool *aborted)
2200 FpsControl fps_control = { 0 };
2201 f32 dtime; // in seconds
2203 fps_control.last_time = RenderingEngine::get_timer_time();
2205 while (RenderingEngine::run()) {
2207 limitFps(&fps_control, &dtime);
2209 // Update client and server
2210 client->step(dtime);
2213 server->step(dtime);
2216 if (client->mediaReceived() && client->itemdefReceived() &&
2217 client->nodedefReceived()) {
2222 if (!checkConnection())
2225 if (client->getState() < LC_Init) {
2226 *error_message = "Client disconnected";
2227 errorstream << *error_message << std::endl;
2231 if (wasKeyDown(KeyType::ESC) || input->wasKeyDown(CancelKey)) {
2233 infostream << "Connect aborted [Escape]" << std::endl;
2240 if (!client->itemdefReceived()) {
2241 const wchar_t *text = wgettext("Item definitions...");
2243 RenderingEngine::draw_load_screen(text, guienv, texture_src,
2246 } else if (!client->nodedefReceived()) {
2247 const wchar_t *text = wgettext("Node definitions...");
2249 RenderingEngine::draw_load_screen(text, guienv, texture_src,
2253 std::stringstream message;
2254 std::fixed(message);
2255 message.precision(0);
2256 message << gettext("Media...") << " " << (client->mediaReceiveProgress()*100) << "%";
2257 message.precision(2);
2259 if ((USE_CURL == 0) ||
2260 (!g_settings->getBool("enable_remote_media_server"))) {
2261 float cur = client->getCurRate();
2262 std::string cur_unit = gettext("KiB/s");
2266 cur_unit = gettext("MiB/s");
2269 message << " (" << cur << ' ' << cur_unit << ")";
2272 progress = 30 + client->mediaReceiveProgress() * 35 + 0.5;
2273 RenderingEngine::draw_load_screen(utf8_to_wide(message.str()), guienv,
2274 texture_src, dtime, progress);
2282 /****************************************************************************/
2283 /****************************************************************************
2285 ****************************************************************************/
2286 /****************************************************************************/
2288 inline void Game::updateInteractTimers(f32 dtime)
2290 if (runData.nodig_delay_timer >= 0)
2291 runData.nodig_delay_timer -= dtime;
2293 if (runData.object_hit_delay_timer >= 0)
2294 runData.object_hit_delay_timer -= dtime;
2296 runData.time_from_last_punch += dtime;
2300 /* returns false if game should exit, otherwise true
2302 inline bool Game::checkConnection()
2304 if (client->accessDenied()) {
2305 *error_message = "Access denied. Reason: "
2306 + client->accessDeniedReason();
2307 *reconnect_requested = client->reconnectRequested();
2308 errorstream << *error_message << std::endl;
2316 /* returns false if game should exit, otherwise true
2318 inline bool Game::handleCallbacks()
2320 if (g_gamecallback->disconnect_requested) {
2321 g_gamecallback->disconnect_requested = false;
2325 if (g_gamecallback->changepassword_requested) {
2326 (new GUIPasswordChange(guienv, guiroot, -1,
2327 &g_menumgr, client))->drop();
2328 g_gamecallback->changepassword_requested = false;
2331 if (g_gamecallback->changevolume_requested) {
2332 (new GUIVolumeChange(guienv, guiroot, -1,
2333 &g_menumgr))->drop();
2334 g_gamecallback->changevolume_requested = false;
2337 if (g_gamecallback->keyconfig_requested) {
2338 (new GUIKeyChangeMenu(guienv, guiroot, -1,
2339 &g_menumgr))->drop();
2340 g_gamecallback->keyconfig_requested = false;
2343 if (g_gamecallback->keyconfig_changed) {
2344 keycache.populate(); // update the cache with new settings
2345 g_gamecallback->keyconfig_changed = false;
2352 void Game::processQueues()
2354 texture_src->processQueue();
2355 itemdef_manager->processQueue(client);
2356 shader_src->processQueue();
2360 void Game::updateProfilers(const RunStats &stats, const FpsControl &draw_times, f32 dtime)
2362 float profiler_print_interval =
2363 g_settings->getFloat("profiler_print_interval");
2364 bool print_to_log = true;
2366 if (profiler_print_interval == 0) {
2367 print_to_log = false;
2368 profiler_print_interval = 5;
2371 if (profiler_interval.step(dtime, profiler_print_interval)) {
2373 infostream << "Profiler:" << std::endl;
2374 g_profiler->print(infostream);
2377 update_profiler_gui(guitext_profiler, g_fontengine,
2378 runData.profiler_current_page, runData.profiler_max_page,
2379 driver->getScreenSize().Height);
2381 g_profiler->clear();
2384 addProfilerGraphs(stats, draw_times, dtime);
2388 void Game::addProfilerGraphs(const RunStats &stats,
2389 const FpsControl &draw_times, f32 dtime)
2391 g_profiler->graphAdd("mainloop_other",
2392 draw_times.busy_time / 1000.0f - stats.drawtime / 1000.0f);
2394 if (draw_times.sleep_time != 0)
2395 g_profiler->graphAdd("mainloop_sleep", draw_times.sleep_time / 1000.0f);
2396 g_profiler->graphAdd("mainloop_dtime", dtime);
2398 g_profiler->add("Elapsed time", dtime);
2399 g_profiler->avg("FPS", 1. / dtime);
2403 void Game::updateStats(RunStats *stats, const FpsControl &draw_times,
2410 /* Time average and jitter calculation
2412 jp = &stats->dtime_jitter;
2413 jp->avg = jp->avg * 0.96 + dtime * 0.04;
2415 jitter = dtime - jp->avg;
2417 if (jitter > jp->max)
2420 jp->counter += dtime;
2422 if (jp->counter > 0.0) {
2424 jp->max_sample = jp->max;
2425 jp->max_fraction = jp->max_sample / (jp->avg + 0.001);
2429 /* Busytime average and jitter calculation
2431 jp = &stats->busy_time_jitter;
2432 jp->avg = jp->avg + draw_times.busy_time * 0.02;
2434 jitter = draw_times.busy_time - jp->avg;
2436 if (jitter > jp->max)
2438 if (jitter < jp->min)
2441 jp->counter += dtime;
2443 if (jp->counter > 0.0) {
2445 jp->max_sample = jp->max;
2446 jp->min_sample = jp->min;
2454 /****************************************************************************
2456 ****************************************************************************/
2458 void Game::processUserInput(f32 dtime)
2460 // Reset input if window not active or some menu is active
2461 if (!device->isWindowActive() || isMenuActive() || guienv->hasFocus(gui_chat_console)) {
2463 #ifdef HAVE_TOUCHSCREENGUI
2464 g_touchscreengui->hide();
2467 #ifdef HAVE_TOUCHSCREENGUI
2468 else if (g_touchscreengui) {
2469 /* on touchscreengui step may generate own input events which ain't
2470 * what we want in case we just did clear them */
2471 g_touchscreengui->step(dtime);
2475 if (!guienv->hasFocus(gui_chat_console) && gui_chat_console->isOpen()) {
2476 gui_chat_console->closeConsoleAtOnce();
2479 // Input handler step() (used by the random input generator)
2483 if (current_formspec != NULL)
2484 current_formspec->getAndroidUIInput();
2486 handleAndroidChatInput();
2489 // Increase timer for double tap of "keymap_jump"
2490 if (m_cache_doubletap_jump && runData.jump_timer <= 0.2f)
2491 runData.jump_timer += dtime;
2494 processItemSelection(&runData.new_playeritem);
2498 void Game::processKeyInput()
2500 if (wasKeyDown(KeyType::DROP)) {
2502 } else if (wasKeyDown(KeyType::AUTOFORWARD)) {
2503 toggleAutoforward();
2504 } else if (wasKeyDown(KeyType::INVENTORY)) {
2506 } else if (wasKeyDown(KeyType::ESC) || input->wasKeyDown(CancelKey)) {
2507 if (!gui_chat_console->isOpenInhibited()) {
2510 } else if (wasKeyDown(KeyType::CHAT)) {
2511 openConsole(0.2, L"");
2512 } else if (wasKeyDown(KeyType::CMD)) {
2513 openConsole(0.2, L"/");
2514 } else if (wasKeyDown(KeyType::CMD_LOCAL)) {
2515 openConsole(0.2, L".");
2516 } else if (wasKeyDown(KeyType::CONSOLE)) {
2517 openConsole(core::clamp(g_settings->getFloat("console_height"), 0.1f, 1.0f));
2518 } else if (wasKeyDown(KeyType::FREEMOVE)) {
2520 } else if (wasKeyDown(KeyType::JUMP)) {
2521 toggleFreeMoveAlt();
2522 } else if (wasKeyDown(KeyType::FASTMOVE)) {
2524 } else if (wasKeyDown(KeyType::NOCLIP)) {
2526 } else if (wasKeyDown(KeyType::MUTE)) {
2527 float volume = g_settings->getFloat("sound_volume");
2528 if (volume < 0.001f) {
2529 g_settings->setFloat("sound_volume", 1.0f);
2530 m_statustext = narrow_to_wide(gettext("Volume changed to 100%"));
2532 g_settings->setFloat("sound_volume", 0.0f);
2533 m_statustext = narrow_to_wide(gettext("Volume changed to 0%"));
2535 runData.statustext_time = 0;
2536 } else if (wasKeyDown(KeyType::INC_VOLUME)) {
2537 float new_volume = rangelim(g_settings->getFloat("sound_volume") + 0.1f, 0.0f, 1.0f);
2539 g_settings->setFloat("sound_volume", new_volume);
2540 snprintf(buf, sizeof(buf), gettext("Volume changed to %d%%"), myround(new_volume * 100));
2541 m_statustext = narrow_to_wide(buf);
2542 runData.statustext_time = 0;
2543 } else if (wasKeyDown(KeyType::DEC_VOLUME)) {
2544 float new_volume = rangelim(g_settings->getFloat("sound_volume") - 0.1f, 0.0f, 1.0f);
2546 g_settings->setFloat("sound_volume", new_volume);
2547 snprintf(buf, sizeof(buf), gettext("Volume changed to %d%%"), myround(new_volume * 100));
2548 m_statustext = narrow_to_wide(buf);
2549 runData.statustext_time = 0;
2550 } else if (wasKeyDown(KeyType::CINEMATIC)) {
2552 } else if (wasKeyDown(KeyType::SCREENSHOT)) {
2553 client->makeScreenshot();
2554 } else if (wasKeyDown(KeyType::TOGGLE_HUD)) {
2556 } else if (wasKeyDown(KeyType::MINIMAP)) {
2557 toggleMinimap(isKeyDown(KeyType::SNEAK));
2558 } else if (wasKeyDown(KeyType::TOGGLE_CHAT)) {
2560 } else if (wasKeyDown(KeyType::TOGGLE_FORCE_FOG_OFF)) {
2562 } else if (wasKeyDown(KeyType::TOGGLE_UPDATE_CAMERA)) {
2563 toggleUpdateCamera();
2564 } else if (wasKeyDown(KeyType::TOGGLE_DEBUG)) {
2566 } else if (wasKeyDown(KeyType::TOGGLE_PROFILER)) {
2568 } else if (wasKeyDown(KeyType::INCREASE_VIEWING_RANGE)) {
2569 increaseViewRange();
2570 } else if (wasKeyDown(KeyType::DECREASE_VIEWING_RANGE)) {
2571 decreaseViewRange();
2572 } else if (wasKeyDown(KeyType::RANGESELECT)) {
2573 toggleFullViewRange();
2574 } else if (wasKeyDown(KeyType::QUICKTUNE_NEXT)) {
2576 } else if (wasKeyDown(KeyType::QUICKTUNE_PREV)) {
2578 } else if (wasKeyDown(KeyType::QUICKTUNE_INC)) {
2580 } else if (wasKeyDown(KeyType::QUICKTUNE_DEC)) {
2582 } else if (wasKeyDown(KeyType::DEBUG_STACKS)) {
2583 // Print debug stacks
2584 dstream << "-----------------------------------------"
2586 dstream << "Printing debug stacks:" << std::endl;
2587 dstream << "-----------------------------------------"
2589 debug_stacks_print();
2592 if (!isKeyDown(KeyType::JUMP) && runData.reset_jump_timer) {
2593 runData.reset_jump_timer = false;
2594 runData.jump_timer = 0.0f;
2597 if (quicktune->hasMessage()) {
2598 m_statustext = utf8_to_wide(quicktune->getMessage());
2599 runData.statustext_time = 0.0f;
2603 void Game::processItemSelection(u16 *new_playeritem)
2605 LocalPlayer *player = client->getEnv().getLocalPlayer();
2607 /* Item selection using mouse wheel
2609 *new_playeritem = client->getPlayerItem();
2611 s32 wheel = input->getMouseWheel();
2612 u16 max_item = MYMIN(PLAYER_INVENTORY_SIZE - 1,
2613 player->hud_hotbar_itemcount - 1);
2617 if (input->joystick.wasKeyDown(KeyType::SCROLL_DOWN) ||
2618 wasKeyDown(KeyType::HOTBAR_NEXT)) {
2622 if (input->joystick.wasKeyDown(KeyType::SCROLL_UP) ||
2623 wasKeyDown(KeyType::HOTBAR_PREV)) {
2628 *new_playeritem = *new_playeritem < max_item ? *new_playeritem + 1 : 0;
2630 *new_playeritem = *new_playeritem > 0 ? *new_playeritem - 1 : max_item;
2633 /* Item selection using keyboard
2635 for (u16 i = 0; i < 10; i++) {
2636 static const KeyPress *item_keys[10] = {
2637 NumberKey + 1, NumberKey + 2, NumberKey + 3, NumberKey + 4,
2638 NumberKey + 5, NumberKey + 6, NumberKey + 7, NumberKey + 8,
2639 NumberKey + 9, NumberKey + 0,
2642 if (input->wasKeyDown(*item_keys[i])) {
2643 if (i < PLAYER_INVENTORY_SIZE && i < player->hud_hotbar_itemcount) {
2644 *new_playeritem = i;
2645 infostream << "Selected item: " << new_playeritem << std::endl;
2653 void Game::dropSelectedItem()
2655 IDropAction *a = new IDropAction();
2657 a->from_inv.setCurrentPlayer();
2658 a->from_list = "main";
2659 a->from_i = client->getPlayerItem();
2660 client->inventoryAction(a);
2664 void Game::openInventory()
2667 * Don't permit to open inventory is CAO or player doesn't exists.
2668 * This prevent showing an empty inventory at player load
2671 LocalPlayer *player = client->getEnv().getLocalPlayer();
2672 if (!player || !player->getCAO())
2675 infostream << "the_game: " << "Launching inventory" << std::endl;
2677 PlayerInventoryFormSource *fs_src = new PlayerInventoryFormSource(client);
2678 TextDest *txt_dst = new TextDestPlayerInventory(client);
2680 create_formspec_menu(¤t_formspec, client, &input->joystick, fs_src, txt_dst);
2683 InventoryLocation inventoryloc;
2684 inventoryloc.setCurrentPlayer();
2685 current_formspec->setFormSpec(fs_src->getForm(), inventoryloc);
2689 void Game::openConsole(float scale, const wchar_t *line)
2691 assert(scale > 0.0f && scale <= 1.0f);
2694 porting::showInputDialog(gettext("ok"), "", "", 2);
2695 m_android_chat_open = true;
2697 if (gui_chat_console->isOpenInhibited())
2699 gui_chat_console->openConsole(scale);
2701 gui_chat_console->setCloseOnEnter(true);
2702 gui_chat_console->replaceAndAddToHistory(line);
2708 void Game::handleAndroidChatInput()
2710 if (m_android_chat_open && porting::getInputDialogState() == 0) {
2711 std::string text = porting::getInputDialogValue();
2712 client->typeChatMessage(utf8_to_wide(text));
2718 void Game::toggleFreeMove()
2720 static const wchar_t *msg[] = { L"free_move disabled", L"free_move enabled" };
2722 bool free_move = !g_settings->getBool("free_move");
2723 g_settings->set("free_move", bool_to_cstr(free_move));
2725 runData.statustext_time = 0;
2726 m_statustext = msg[free_move];
2727 if (free_move && !client->checkPrivilege("fly"))
2728 m_statustext += L" (note: no 'fly' privilege)";
2732 void Game::toggleFreeMoveAlt()
2734 if (m_cache_doubletap_jump && runData.jump_timer < 0.2f)
2737 runData.reset_jump_timer = true;
2741 void Game::toggleFast()
2743 static const wchar_t *msg[] = { L"fast_move disabled", L"fast_move enabled" };
2744 bool fast_move = !g_settings->getBool("fast_move");
2745 g_settings->set("fast_move", bool_to_cstr(fast_move));
2747 runData.statustext_time = 0;
2748 m_statustext = msg[fast_move];
2750 bool has_fast_privs = client->checkPrivilege("fast");
2752 if (fast_move && !has_fast_privs)
2753 m_statustext += L" (note: no 'fast' privilege)";
2756 m_cache_hold_aux1 = fast_move && has_fast_privs;
2761 void Game::toggleNoClip()
2763 static const wchar_t *msg[] = { L"noclip disabled", L"noclip enabled" };
2764 bool noclip = !g_settings->getBool("noclip");
2765 g_settings->set("noclip", bool_to_cstr(noclip));
2767 runData.statustext_time = 0;
2768 m_statustext = msg[noclip];
2770 if (noclip && !client->checkPrivilege("noclip"))
2771 m_statustext += L" (note: no 'noclip' privilege)";
2774 void Game::toggleCinematic()
2776 static const wchar_t *msg[] = { L"cinematic disabled", L"cinematic enabled" };
2777 bool cinematic = !g_settings->getBool("cinematic");
2778 g_settings->set("cinematic", bool_to_cstr(cinematic));
2780 runData.statustext_time = 0;
2781 m_statustext = msg[cinematic];
2784 // Autoforward by toggling continuous forward.
2785 void Game::toggleAutoforward()
2787 static const wchar_t *msg[] = { L"autoforward disabled", L"autoforward enabled" };
2788 bool autoforward_enabled = !g_settings->getBool("continuous_forward");
2789 g_settings->set("continuous_forward", bool_to_cstr(autoforward_enabled));
2791 runData.statustext_time = 0;
2792 m_statustext = msg[autoforward_enabled ? 1 : 0];
2795 void Game::toggleChat()
2797 static const wchar_t *msg[] = { L"Chat hidden", L"Chat shown" };
2799 flags.show_chat = !flags.show_chat;
2800 runData.statustext_time = 0;
2801 m_statustext = msg[flags.show_chat];
2805 void Game::toggleHud()
2807 static const wchar_t *msg[] = { L"HUD hidden", L"HUD shown" };
2809 flags.show_hud = !flags.show_hud;
2810 runData.statustext_time = 0;
2811 m_statustext = msg[flags.show_hud];
2814 void Game::toggleMinimap(bool shift_pressed)
2816 if (!mapper || !flags.show_hud || !g_settings->getBool("enable_minimap"))
2819 if (shift_pressed) {
2820 mapper->toggleMinimapShape();
2824 u32 hud_flags = client->getEnv().getLocalPlayer()->hud_flags;
2826 MinimapMode mode = MINIMAP_MODE_OFF;
2827 if (hud_flags & HUD_FLAG_MINIMAP_VISIBLE) {
2828 mode = mapper->getMinimapMode();
2829 mode = (MinimapMode)((int)mode + 1);
2832 flags.show_minimap = true;
2834 case MINIMAP_MODE_SURFACEx1:
2835 m_statustext = L"Minimap in surface mode, Zoom x1";
2837 case MINIMAP_MODE_SURFACEx2:
2838 m_statustext = L"Minimap in surface mode, Zoom x2";
2840 case MINIMAP_MODE_SURFACEx4:
2841 m_statustext = L"Minimap in surface mode, Zoom x4";
2843 case MINIMAP_MODE_RADARx1:
2844 m_statustext = L"Minimap in radar mode, Zoom x1";
2846 case MINIMAP_MODE_RADARx2:
2847 m_statustext = L"Minimap in radar mode, Zoom x2";
2849 case MINIMAP_MODE_RADARx4:
2850 m_statustext = L"Minimap in radar mode, Zoom x4";
2853 mode = MINIMAP_MODE_OFF;
2854 flags.show_minimap = false;
2855 m_statustext = (hud_flags & HUD_FLAG_MINIMAP_VISIBLE) ?
2856 L"Minimap hidden" : L"Minimap disabled by server";
2859 runData.statustext_time = 0;
2860 mapper->setMinimapMode(mode);
2863 void Game::toggleFog()
2865 static const wchar_t *msg[] = { L"Fog enabled", L"Fog disabled" };
2867 flags.force_fog_off = !flags.force_fog_off;
2868 runData.statustext_time = 0;
2869 m_statustext = msg[flags.force_fog_off];
2873 void Game::toggleDebug()
2875 // Initial / 4x toggle: Chat only
2876 // 1x toggle: Debug text with chat
2877 // 2x toggle: Debug text with profiler graph
2878 // 3x toggle: Debug text and wireframe
2879 if (!flags.show_debug) {
2880 flags.show_debug = true;
2881 flags.show_profiler_graph = false;
2882 draw_control->show_wireframe = false;
2883 m_statustext = L"Debug info shown";
2884 } else if (!flags.show_profiler_graph && !draw_control->show_wireframe) {
2885 flags.show_profiler_graph = true;
2886 m_statustext = L"Profiler graph shown";
2887 } else if (!draw_control->show_wireframe && client->checkPrivilege("debug")) {
2888 flags.show_profiler_graph = false;
2889 draw_control->show_wireframe = true;
2890 m_statustext = L"Wireframe shown";
2892 flags.show_debug = false;
2893 flags.show_profiler_graph = false;
2894 draw_control->show_wireframe = false;
2895 if (client->checkPrivilege("debug")) {
2896 m_statustext = L"Debug info, profiler graph, and wireframe hidden";
2898 m_statustext = L"Debug info and profiler graph hidden";
2901 runData.statustext_time = 0;
2905 void Game::toggleUpdateCamera()
2907 static const wchar_t *msg[] = {
2908 L"Camera update enabled",
2909 L"Camera update disabled"
2912 flags.disable_camera_update = !flags.disable_camera_update;
2913 runData.statustext_time = 0;
2914 m_statustext = msg[flags.disable_camera_update];
2918 void Game::toggleProfiler()
2920 runData.profiler_current_page =
2921 (runData.profiler_current_page + 1) % (runData.profiler_max_page + 1);
2923 // FIXME: This updates the profiler with incomplete values
2924 update_profiler_gui(guitext_profiler, g_fontengine, runData.profiler_current_page,
2925 runData.profiler_max_page, driver->getScreenSize().Height);
2927 if (runData.profiler_current_page != 0) {
2928 std::wstringstream sstr;
2929 sstr << "Profiler shown (page " << runData.profiler_current_page
2930 << " of " << runData.profiler_max_page << ")";
2931 m_statustext = sstr.str();
2933 m_statustext = L"Profiler hidden";
2935 runData.statustext_time = 0;
2939 void Game::increaseViewRange()
2941 s16 range = g_settings->getS16("viewing_range");
2942 s16 range_new = range + 10;
2944 if (range_new > 4000) {
2946 m_statustext = utf8_to_wide("Viewing range is at maximum: "
2949 m_statustext = utf8_to_wide("Viewing range changed to "
2952 g_settings->set("viewing_range", itos(range_new));
2953 runData.statustext_time = 0;
2957 void Game::decreaseViewRange()
2959 s16 range = g_settings->getS16("viewing_range");
2960 s16 range_new = range - 10;
2962 if (range_new < 20) {
2964 m_statustext = utf8_to_wide("Viewing range is at minimum: "
2967 m_statustext = utf8_to_wide("Viewing range changed to "
2970 g_settings->set("viewing_range", itos(range_new));
2971 runData.statustext_time = 0;
2975 void Game::toggleFullViewRange()
2977 static const wchar_t *msg[] = {
2978 L"Disabled full viewing range",
2979 L"Enabled full viewing range"
2982 draw_control->range_all = !draw_control->range_all;
2983 infostream << msg[draw_control->range_all] << std::endl;
2984 m_statustext = msg[draw_control->range_all];
2985 runData.statustext_time = 0;
2989 void Game::updateCameraDirection(CameraOrientation *cam, float dtime)
2991 if ((device->isWindowActive() && device->isWindowFocused()
2992 && !isMenuActive()) || random_input) {
2995 if (!random_input) {
2996 // Mac OSX gets upset if this is set every frame
2997 if (device->getCursorControl()->isVisible())
2998 device->getCursorControl()->setVisible(false);
3002 if (m_first_loop_after_window_activation)
3003 m_first_loop_after_window_activation = false;
3005 updateCameraOrientation(cam, dtime);
3007 input->setMousePos((driver->getScreenSize().Width / 2),
3008 (driver->getScreenSize().Height / 2));
3012 // Mac OSX gets upset if this is set every frame
3013 if (!device->getCursorControl()->isVisible())
3014 device->getCursorControl()->setVisible(true);
3017 m_first_loop_after_window_activation = true;
3022 void Game::updateCameraOrientation(CameraOrientation *cam, float dtime)
3024 #ifdef HAVE_TOUCHSCREENGUI
3025 if (g_touchscreengui) {
3026 cam->camera_yaw += g_touchscreengui->getYawChange();
3027 cam->camera_pitch = g_touchscreengui->getPitch();
3031 s32 dx = input->getMousePos().X - (driver->getScreenSize().Width / 2);
3032 s32 dy = input->getMousePos().Y - (driver->getScreenSize().Height / 2);
3034 if (m_invert_mouse || camera->getCameraMode() == CAMERA_MODE_THIRD_FRONT) {
3038 cam->camera_yaw -= dx * m_cache_mouse_sensitivity;
3039 cam->camera_pitch += dy * m_cache_mouse_sensitivity;
3041 #ifdef HAVE_TOUCHSCREENGUI
3045 if (m_cache_enable_joysticks) {
3046 f32 c = m_cache_joystick_frustum_sensitivity * (1.f / 32767.f) * dtime;
3047 cam->camera_yaw -= input->joystick.getAxisWithoutDead(JA_FRUSTUM_HORIZONTAL) * c;
3048 cam->camera_pitch += input->joystick.getAxisWithoutDead(JA_FRUSTUM_VERTICAL) * c;
3051 cam->camera_pitch = rangelim(cam->camera_pitch, -89.5, 89.5);
3055 void Game::updatePlayerControl(const CameraOrientation &cam)
3057 //TimeTaker tt("update player control", NULL, PRECISION_NANO);
3059 // DO NOT use the isKeyDown method for the forward, backward, left, right
3060 // buttons, as the code that uses the controls needs to be able to
3061 // distinguish between the two in order to know when to use joysticks.
3063 PlayerControl control(
3064 input->isKeyDown(keycache.key[KeyType::FORWARD]),
3065 input->isKeyDown(keycache.key[KeyType::BACKWARD]),
3066 input->isKeyDown(keycache.key[KeyType::LEFT]),
3067 input->isKeyDown(keycache.key[KeyType::RIGHT]),
3068 isKeyDown(KeyType::JUMP),
3069 isKeyDown(KeyType::SPECIAL1),
3070 isKeyDown(KeyType::SNEAK),
3071 isKeyDown(KeyType::ZOOM),
3076 input->joystick.getAxisWithoutDead(JA_SIDEWARD_MOVE),
3077 input->joystick.getAxisWithoutDead(JA_FORWARD_MOVE)
3081 ( (u32)(isKeyDown(KeyType::FORWARD) & 0x1) << 0) |
3082 ( (u32)(isKeyDown(KeyType::BACKWARD) & 0x1) << 1) |
3083 ( (u32)(isKeyDown(KeyType::LEFT) & 0x1) << 2) |
3084 ( (u32)(isKeyDown(KeyType::RIGHT) & 0x1) << 3) |
3085 ( (u32)(isKeyDown(KeyType::JUMP) & 0x1) << 4) |
3086 ( (u32)(isKeyDown(KeyType::SPECIAL1) & 0x1) << 5) |
3087 ( (u32)(isKeyDown(KeyType::SNEAK) & 0x1) << 6) |
3088 ( (u32)(isLeftPressed() & 0x1) << 7) |
3089 ( (u32)(isRightPressed() & 0x1) << 8
3093 /* For Android, simulate holding down AUX1 (fast move) if the user has
3094 * the fast_move setting toggled on. If there is an aux1 key defined for
3095 * Android then its meaning is inverted (i.e. holding aux1 means walk and
3098 if (m_cache_hold_aux1) {
3099 control.aux1 = control.aux1 ^ true;
3100 keypress_bits ^= ((u32)(1U << 5));
3104 client->setPlayerControl(control);
3105 LocalPlayer *player = client->getEnv().getLocalPlayer();
3106 player->keyPressed = keypress_bits;
3112 inline void Game::step(f32 *dtime)
3114 bool can_be_and_is_paused =
3115 (simple_singleplayer_mode && g_menumgr.pausesGame());
3117 if (can_be_and_is_paused) { // This is for a singleplayer server
3118 *dtime = 0; // No time passes
3120 if (server != NULL) {
3121 //TimeTaker timer("server->step(dtime)");
3122 server->step(*dtime);
3125 //TimeTaker timer("client.step(dtime)");
3126 client->step(*dtime);
3131 void Game::processClientEvents(CameraOrientation *cam)
3133 LocalPlayer *player = client->getEnv().getLocalPlayer();
3135 while (client->hasClientEvents()) {
3136 ClientEvent event = client->getClientEvent();
3138 switch (event.type) {
3139 case CE_PLAYER_DAMAGE:
3140 if (client->getHP() == 0)
3142 if (client->moddingEnabled()) {
3143 client->getScript()->on_damage_taken(event.player_damage.amount);
3146 runData.damage_flash += 95.0 + 3.2 * event.player_damage.amount;
3147 runData.damage_flash = MYMIN(runData.damage_flash, 127.0);
3149 player->hurt_tilt_timer = 1.5;
3150 player->hurt_tilt_strength =
3151 rangelim(event.player_damage.amount / 4, 1.0, 4.0);
3153 client->event()->put(new SimpleTriggerEvent("PlayerDamage"));
3156 case CE_PLAYER_FORCE_MOVE:
3157 cam->camera_yaw = event.player_force_move.yaw;
3158 cam->camera_pitch = event.player_force_move.pitch;
3161 case CE_DEATHSCREEN:
3162 // This should be enabled for death formspec in builtin
3163 client->getScript()->on_death();
3165 /* Handle visualization */
3166 runData.damage_flash = 0;
3167 player->hurt_tilt_timer = 0;
3168 player->hurt_tilt_strength = 0;
3171 case CE_SHOW_FORMSPEC:
3172 if (*(event.show_formspec.formspec) == "") {
3173 if (current_formspec && ( *(event.show_formspec.formname) == "" || *(event.show_formspec.formname) == cur_formname) ){
3174 current_formspec->quitMenu();
3177 FormspecFormSource *fs_src =
3178 new FormspecFormSource(*(event.show_formspec.formspec));
3179 TextDestPlayerInventory *txt_dst =
3180 new TextDestPlayerInventory(client, *(event.show_formspec.formname));
3182 create_formspec_menu(¤t_formspec, client, &input->joystick,
3184 cur_formname = *(event.show_formspec.formname);
3187 delete event.show_formspec.formspec;
3188 delete event.show_formspec.formname;
3191 case CE_SHOW_LOCAL_FORMSPEC:
3193 FormspecFormSource *fs_src = new FormspecFormSource(*event.show_formspec.formspec);
3194 LocalFormspecHandler *txt_dst = new LocalFormspecHandler(*event.show_formspec.formname, client);
3195 create_formspec_menu(¤t_formspec, client, &input->joystick,
3198 delete event.show_formspec.formspec;
3199 delete event.show_formspec.formname;
3202 case CE_SPAWN_PARTICLE:
3203 case CE_ADD_PARTICLESPAWNER:
3204 case CE_DELETE_PARTICLESPAWNER:
3205 client->getParticleManager()->handleParticleEvent(&event, client, player);
3210 u32 id = event.hudadd.id;
3212 HudElement *e = player->getHud(id);
3215 delete event.hudadd.pos;
3216 delete event.hudadd.name;
3217 delete event.hudadd.scale;
3218 delete event.hudadd.text;
3219 delete event.hudadd.align;
3220 delete event.hudadd.offset;
3221 delete event.hudadd.world_pos;
3222 delete event.hudadd.size;
3227 e->type = (HudElementType)event.hudadd.type;
3228 e->pos = *event.hudadd.pos;
3229 e->name = *event.hudadd.name;
3230 e->scale = *event.hudadd.scale;
3231 e->text = *event.hudadd.text;
3232 e->number = event.hudadd.number;
3233 e->item = event.hudadd.item;
3234 e->dir = event.hudadd.dir;
3235 e->align = *event.hudadd.align;
3236 e->offset = *event.hudadd.offset;
3237 e->world_pos = *event.hudadd.world_pos;
3238 e->size = *event.hudadd.size;
3240 u32 new_id = player->addHud(e);
3241 //if this isn't true our huds aren't consistent
3242 sanity_check(new_id == id);
3245 delete event.hudadd.pos;
3246 delete event.hudadd.name;
3247 delete event.hudadd.scale;
3248 delete event.hudadd.text;
3249 delete event.hudadd.align;
3250 delete event.hudadd.offset;
3251 delete event.hudadd.world_pos;
3252 delete event.hudadd.size;
3257 HudElement *e = player->removeHud(event.hudrm.id);
3265 u32 id = event.hudchange.id;
3266 HudElement *e = player->getHud(id);
3269 delete event.hudchange.v3fdata;
3270 delete event.hudchange.v2fdata;
3271 delete event.hudchange.sdata;
3272 delete event.hudchange.v2s32data;
3276 switch (event.hudchange.stat) {
3278 e->pos = *event.hudchange.v2fdata;
3282 e->name = *event.hudchange.sdata;
3285 case HUD_STAT_SCALE:
3286 e->scale = *event.hudchange.v2fdata;
3290 e->text = *event.hudchange.sdata;
3293 case HUD_STAT_NUMBER:
3294 e->number = event.hudchange.data;
3298 e->item = event.hudchange.data;
3302 e->dir = event.hudchange.data;
3305 case HUD_STAT_ALIGN:
3306 e->align = *event.hudchange.v2fdata;
3309 case HUD_STAT_OFFSET:
3310 e->offset = *event.hudchange.v2fdata;
3313 case HUD_STAT_WORLD_POS:
3314 e->world_pos = *event.hudchange.v3fdata;
3318 e->size = *event.hudchange.v2s32data;
3323 delete event.hudchange.v3fdata;
3324 delete event.hudchange.v2fdata;
3325 delete event.hudchange.sdata;
3326 delete event.hudchange.v2s32data;
3330 sky->setVisible(false);
3331 // Whether clouds are visible in front of a custom skybox
3332 sky->setCloudsEnabled(event.set_sky.clouds);
3339 // Handle according to type
3340 if (*event.set_sky.type == "regular") {
3341 sky->setVisible(true);
3342 sky->setCloudsEnabled(true);
3343 } else if (*event.set_sky.type == "skybox" &&
3344 event.set_sky.params->size() == 6) {
3345 sky->setFallbackBgColor(*event.set_sky.bgcolor);
3346 skybox = RenderingEngine::get_scene_manager()->addSkyBoxSceneNode(
3347 texture_src->getTextureForMesh((*event.set_sky.params)[0]),
3348 texture_src->getTextureForMesh((*event.set_sky.params)[1]),
3349 texture_src->getTextureForMesh((*event.set_sky.params)[2]),
3350 texture_src->getTextureForMesh((*event.set_sky.params)[3]),
3351 texture_src->getTextureForMesh((*event.set_sky.params)[4]),
3352 texture_src->getTextureForMesh((*event.set_sky.params)[5]));
3354 // Handle everything else as plain color
3356 if (*event.set_sky.type != "plain")
3357 infostream << "Unknown sky type: "
3358 << (*event.set_sky.type) << std::endl;
3360 sky->setFallbackBgColor(*event.set_sky.bgcolor);
3363 delete event.set_sky.bgcolor;
3364 delete event.set_sky.type;
3365 delete event.set_sky.params;
3368 case CE_OVERRIDE_DAY_NIGHT_RATIO:
3369 client->getEnv().setDayNightRatioOverride(
3370 event.override_day_night_ratio.do_override,
3371 event.override_day_night_ratio.ratio_f * 1000);
3374 case CE_CLOUD_PARAMS:
3376 clouds->setDensity(event.cloud_params.density);
3377 clouds->setColorBright(video::SColor(event.cloud_params.color_bright));
3378 clouds->setColorAmbient(video::SColor(event.cloud_params.color_ambient));
3379 clouds->setHeight(event.cloud_params.height);
3380 clouds->setThickness(event.cloud_params.thickness);
3381 clouds->setSpeed(v2f(
3382 event.cloud_params.speed_x,
3383 event.cloud_params.speed_y));
3388 // unknown or unhandled type
3396 void Game::updateCamera(u32 busy_time, f32 dtime)
3398 LocalPlayer *player = client->getEnv().getLocalPlayer();
3401 For interaction purposes, get info about the held item
3403 - Is it a usable item?
3404 - Can it point to liquids?
3406 ItemStack playeritem;
3408 InventoryList *mlist = local_inventory->getList("main");
3410 if (mlist && client->getPlayerItem() < mlist->getSize())
3411 playeritem = mlist->getItem(client->getPlayerItem());
3414 if (playeritem.getDefinition(itemdef_manager).name.empty()) { // override the hand
3415 InventoryList *hlist = local_inventory->getList("hand");
3417 playeritem = hlist->getItem(0);
3421 ToolCapabilities playeritem_toolcap =
3422 playeritem.getToolCapabilities(itemdef_manager);
3424 v3s16 old_camera_offset = camera->getOffset();
3426 if (wasKeyDown(KeyType::CAMERA_MODE)) {
3427 GenericCAO *playercao = player->getCAO();
3429 // If playercao not loaded, don't change camera
3433 camera->toggleCameraMode();
3435 playercao->setVisible(camera->getCameraMode() > CAMERA_MODE_FIRST);
3436 playercao->setChildrenVisible(camera->getCameraMode() > CAMERA_MODE_FIRST);
3439 float full_punch_interval = playeritem_toolcap.full_punch_interval;
3440 float tool_reload_ratio = runData.time_from_last_punch / full_punch_interval;
3442 tool_reload_ratio = MYMIN(tool_reload_ratio, 1.0);
3443 camera->update(player, dtime, busy_time / 1000.0f, tool_reload_ratio,
3445 camera->step(dtime);
3447 v3f camera_position = camera->getPosition();
3448 v3f camera_direction = camera->getDirection();
3449 f32 camera_fov = camera->getFovMax();
3450 v3s16 camera_offset = camera->getOffset();
3452 m_camera_offset_changed = (camera_offset != old_camera_offset);
3454 if (!flags.disable_camera_update) {
3455 client->getEnv().getClientMap().updateCamera(camera_position,
3456 camera_direction, camera_fov, camera_offset);
3458 if (m_camera_offset_changed) {
3459 client->updateCameraOffset(camera_offset);
3460 client->getEnv().updateCameraOffset(camera_offset);
3463 clouds->updateCameraOffset(camera_offset);
3469 void Game::updateSound(f32 dtime)
3471 // Update sound listener
3472 v3s16 camera_offset = camera->getOffset();
3473 sound->updateListener(camera->getCameraNode()->getPosition() + intToFloat(camera_offset, BS),
3474 v3f(0, 0, 0), // velocity
3475 camera->getDirection(),
3476 camera->getCameraNode()->getUpVector());
3478 // Check if volume is in the proper range, else fix it.
3479 float old_volume = g_settings->getFloat("sound_volume");
3480 float new_volume = rangelim(old_volume, 0.0f, 1.0f);
3481 sound->setListenerGain(new_volume);
3483 if (old_volume != new_volume) {
3484 g_settings->setFloat("sound_volume", new_volume);
3487 LocalPlayer *player = client->getEnv().getLocalPlayer();
3489 // Tell the sound maker whether to make footstep sounds
3490 soundmaker->makes_footstep_sound = player->makes_footstep_sound;
3492 // Update sound maker
3493 if (player->makes_footstep_sound)
3494 soundmaker->step(dtime);
3496 ClientMap &map = client->getEnv().getClientMap();
3497 MapNode n = map.getNodeNoEx(player->getFootstepNodePos());
3498 soundmaker->m_player_step_sound = nodedef_manager->get(n).sound_footstep;
3502 void Game::processPlayerInteraction(f32 dtime, bool show_hud, bool show_debug)
3504 LocalPlayer *player = client->getEnv().getLocalPlayer();
3506 ItemStack playeritem;
3508 InventoryList *mlist = local_inventory->getList("main");
3510 if (mlist && client->getPlayerItem() < mlist->getSize())
3511 playeritem = mlist->getItem(client->getPlayerItem());
3514 const ItemDefinition &playeritem_def =
3515 playeritem.getDefinition(itemdef_manager);
3516 InventoryList *hlist = local_inventory->getList("hand");
3517 const ItemDefinition &hand_def =
3518 hlist ? hlist->getItem(0).getDefinition(itemdef_manager) : itemdef_manager->get("");
3520 v3f player_position = player->getPosition();
3521 v3f camera_position = camera->getPosition();
3522 v3f camera_direction = camera->getDirection();
3523 v3s16 camera_offset = camera->getOffset();
3527 Calculate what block is the crosshair pointing to
3530 f32 d = playeritem_def.range; // max. distance
3531 f32 d_hand = hand_def.range;
3533 if (d < 0 && d_hand >= 0)
3538 core::line3d<f32> shootline;
3540 if (camera->getCameraMode() != CAMERA_MODE_THIRD_FRONT) {
3541 shootline = core::line3d<f32>(camera_position,
3542 camera_position + camera_direction * BS * d);
3544 // prevent player pointing anything in front-view
3545 shootline = core::line3d<f32>(camera_position,camera_position);
3548 #ifdef HAVE_TOUCHSCREENGUI
3550 if ((g_settings->getBool("touchtarget")) && (g_touchscreengui)) {
3551 shootline = g_touchscreengui->getShootline();
3552 shootline.start += intToFloat(camera_offset, BS);
3553 shootline.end += intToFloat(camera_offset, BS);
3558 PointedThing pointed = updatePointedThing(shootline,
3559 playeritem_def.liquids_pointable,
3560 !runData.ldown_for_dig,
3563 if (pointed != runData.pointed_old) {
3564 infostream << "Pointing at " << pointed.dump() << std::endl;
3565 hud->updateSelectionMesh(camera_offset);
3570 - releasing left mouse button
3571 - pointing away from node
3573 if (runData.digging) {
3574 if (getLeftReleased()) {
3575 infostream << "Left button released"
3576 << " (stopped digging)" << std::endl;
3577 runData.digging = false;
3578 } else if (pointed != runData.pointed_old) {
3579 if (pointed.type == POINTEDTHING_NODE
3580 && runData.pointed_old.type == POINTEDTHING_NODE
3581 && pointed.node_undersurface
3582 == runData.pointed_old.node_undersurface) {
3583 // Still pointing to the same node, but a different face.
3586 infostream << "Pointing away from node"
3587 << " (stopped digging)" << std::endl;
3588 runData.digging = false;
3589 hud->updateSelectionMesh(camera_offset);
3593 if (!runData.digging) {
3594 client->interact(1, runData.pointed_old);
3595 client->setCrack(-1, v3s16(0, 0, 0));
3596 runData.dig_time = 0.0;
3598 } else if (runData.dig_instantly && getLeftReleased()) {
3599 // Remove e.g. torches faster when clicking instead of holding LMB
3600 runData.nodig_delay_timer = 0;
3601 runData.dig_instantly = false;
3604 if (!runData.digging && runData.ldown_for_dig && !isLeftPressed()) {
3605 runData.ldown_for_dig = false;
3608 runData.left_punch = false;
3610 soundmaker->m_player_leftpunch_sound.name = "";
3612 if (isRightPressed())
3613 runData.repeat_rightclick_timer += dtime;
3615 runData.repeat_rightclick_timer = 0;
3617 if (playeritem_def.usable && isLeftPressed()) {
3618 if (getLeftClicked() && (!client->moddingEnabled()
3619 || !client->getScript()->on_item_use(playeritem, pointed)))
3620 client->interact(4, pointed);
3621 } else if (pointed.type == POINTEDTHING_NODE) {
3622 ToolCapabilities playeritem_toolcap =
3623 playeritem.getToolCapabilities(itemdef_manager);
3624 if (playeritem.name.empty() && hand_def.tool_capabilities != NULL) {
3625 playeritem_toolcap = *hand_def.tool_capabilities;
3627 handlePointingAtNode(pointed, playeritem_def, playeritem,
3628 playeritem_toolcap, dtime);
3629 } else if (pointed.type == POINTEDTHING_OBJECT) {
3630 handlePointingAtObject(pointed, playeritem, player_position, show_debug);
3631 } else if (isLeftPressed()) {
3632 // When button is held down in air, show continuous animation
3633 runData.left_punch = true;
3634 } else if (getRightClicked()) {
3635 handlePointingAtNothing(playeritem);
3638 runData.pointed_old = pointed;
3640 if (runData.left_punch || getLeftClicked())
3641 camera->setDigging(0); // left click animation
3643 input->resetLeftClicked();
3644 input->resetRightClicked();
3646 input->joystick.clearWasKeyDown(KeyType::MOUSE_L);
3647 input->joystick.clearWasKeyDown(KeyType::MOUSE_R);
3649 input->resetLeftReleased();
3650 input->resetRightReleased();
3652 input->joystick.clearWasKeyReleased(KeyType::MOUSE_L);
3653 input->joystick.clearWasKeyReleased(KeyType::MOUSE_R);
3657 PointedThing Game::updatePointedThing(
3658 const core::line3d<f32> &shootline,
3659 bool liquids_pointable,
3660 bool look_for_object,
3661 const v3s16 &camera_offset)
3663 std::vector<aabb3f> *selectionboxes = hud->getSelectionBoxes();
3664 selectionboxes->clear();
3665 hud->setSelectedFaceNormal(v3f(0.0, 0.0, 0.0));
3666 static thread_local const bool show_entity_selectionbox = g_settings->getBool(
3667 "show_entity_selectionbox");
3669 ClientMap &map = client->getEnv().getClientMap();
3670 INodeDefManager *nodedef=client->getNodeDefManager();
3672 runData.selected_object = NULL;
3674 PointedThing result=client->getEnv().getPointedThing(
3675 shootline, liquids_pointable, look_for_object);
3676 if (result.type == POINTEDTHING_OBJECT) {
3677 runData.selected_object = client->getEnv().getActiveObject(result.object_id);
3678 if (show_entity_selectionbox && runData.selected_object->doShowSelectionBox()) {
3679 aabb3f *selection_box = runData.selected_object->getSelectionBox();
3681 // Box should exist because object was
3682 // returned in the first place
3684 assert(selection_box);
3686 v3f pos = runData.selected_object->getPosition();
3687 selectionboxes->push_back(aabb3f(
3688 selection_box->MinEdge, selection_box->MaxEdge));
3689 selectionboxes->push_back(
3690 aabb3f(selection_box->MinEdge, selection_box->MaxEdge));
3691 hud->setSelectionPos(pos, camera_offset);
3693 } else if (result.type == POINTEDTHING_NODE) {
3694 // Update selection boxes
3695 MapNode n = map.getNodeNoEx(result.node_undersurface);
3696 std::vector<aabb3f> boxes;
3697 n.getSelectionBoxes(nodedef, &boxes,
3698 n.getNeighbors(result.node_undersurface, &map));
3701 for (std::vector<aabb3f>::const_iterator i = boxes.begin();
3702 i != boxes.end(); ++i) {
3704 box.MinEdge -= v3f(d, d, d);
3705 box.MaxEdge += v3f(d, d, d);
3706 selectionboxes->push_back(box);
3708 hud->setSelectionPos(intToFloat(result.node_undersurface, BS),
3710 hud->setSelectedFaceNormal(v3f(
3711 result.intersection_normal.X,
3712 result.intersection_normal.Y,
3713 result.intersection_normal.Z));
3716 // Update selection mesh light level and vertex colors
3717 if (selectionboxes->size() > 0) {
3718 v3f pf = hud->getSelectionPos();
3719 v3s16 p = floatToInt(pf, BS);
3721 // Get selection mesh light level
3722 MapNode n = map.getNodeNoEx(p);
3723 u16 node_light = getInteriorLight(n, -1, nodedef);
3724 u16 light_level = node_light;
3726 for (u8 i = 0; i < 6; i++) {
3727 n = map.getNodeNoEx(p + g_6dirs[i]);
3728 node_light = getInteriorLight(n, -1, nodedef);
3729 if (node_light > light_level)
3730 light_level = node_light;
3733 u32 daynight_ratio = client->getEnv().getDayNightRatio();
3735 final_color_blend(&c, light_level, daynight_ratio);
3737 // Modify final color a bit with time
3738 u32 timer = porting::getTimeMs() % 5000;
3739 float timerf = (float) (irr::core::PI * ((timer / 2500.0) - 0.5));
3740 float sin_r = 0.08 * sin(timerf);
3741 float sin_g = 0.08 * sin(timerf + irr::core::PI * 0.5);
3742 float sin_b = 0.08 * sin(timerf + irr::core::PI);
3743 c.setRed(core::clamp(core::round32(c.getRed() * (0.8 + sin_r)), 0, 255));
3744 c.setGreen(core::clamp(core::round32(c.getGreen() * (0.8 + sin_g)), 0, 255));
3745 c.setBlue(core::clamp(core::round32(c.getBlue() * (0.8 + sin_b)), 0, 255));
3747 // Set mesh final color
3748 hud->setSelectionMeshColor(c);
3754 void Game::handlePointingAtNothing(const ItemStack &playerItem)
3756 infostream << "Right Clicked in Air" << std::endl;
3757 PointedThing fauxPointed;
3758 fauxPointed.type = POINTEDTHING_NOTHING;
3759 client->interact(5, fauxPointed);
3763 void Game::handlePointingAtNode(const PointedThing &pointed,
3764 const ItemDefinition &playeritem_def, const ItemStack &playeritem,
3765 const ToolCapabilities &playeritem_toolcap, f32 dtime)
3767 v3s16 nodepos = pointed.node_undersurface;
3768 v3s16 neighbourpos = pointed.node_abovesurface;
3771 Check information text of node
3774 ClientMap &map = client->getEnv().getClientMap();
3776 if (runData.nodig_delay_timer <= 0.0 && isLeftPressed()
3777 && client->checkPrivilege("interact")) {
3778 handleDigging(pointed, nodepos, playeritem_toolcap, dtime);
3781 // This should be done after digging handling
3782 NodeMetadata *meta = map.getNodeMetadata(nodepos);
3785 infotext = unescape_enriched(utf8_to_wide(meta->getString("infotext")));
3787 MapNode n = map.getNodeNoEx(nodepos);
3789 if (nodedef_manager->get(n).tiledef[0].name == "unknown_node.png") {
3790 infotext = L"Unknown node: ";
3791 infotext += utf8_to_wide(nodedef_manager->get(n).name);
3795 if ((getRightClicked() ||
3796 runData.repeat_rightclick_timer >= m_repeat_right_click_time) &&
3797 client->checkPrivilege("interact")) {
3798 runData.repeat_rightclick_timer = 0;
3799 infostream << "Ground right-clicked" << std::endl;
3801 if (meta && meta->getString("formspec") != "" && !random_input
3802 && !isKeyDown(KeyType::SNEAK)) {
3803 infostream << "Launching custom inventory view" << std::endl;
3805 InventoryLocation inventoryloc;
3806 inventoryloc.setNodeMeta(nodepos);
3808 NodeMetadataFormSource *fs_src = new NodeMetadataFormSource(
3809 &client->getEnv().getClientMap(), nodepos);
3810 TextDest *txt_dst = new TextDestNodeMetadata(nodepos, client);
3812 create_formspec_menu(¤t_formspec, client,
3813 &input->joystick, fs_src, txt_dst);
3816 current_formspec->setFormSpec(meta->getString("formspec"), inventoryloc);
3818 // Report right click to server
3820 camera->setDigging(1); // right click animation (always shown for feedback)
3822 // If the wielded item has node placement prediction,
3824 bool placed = nodePlacementPrediction(*client,
3825 playeritem_def, playeritem,
3826 nodepos, neighbourpos);
3830 client->interact(3, pointed);
3832 soundmaker->m_player_rightpunch_sound =
3833 playeritem_def.sound_place;
3835 if (client->moddingEnabled())
3836 client->getScript()->on_placenode(pointed, playeritem_def);
3838 soundmaker->m_player_rightpunch_sound =
3841 if (playeritem_def.node_placement_prediction == "" ||
3842 nodedef_manager->get(map.getNodeNoEx(nodepos)).rightclickable) {
3843 client->interact(3, pointed); // Report to server
3845 soundmaker->m_player_rightpunch_sound =
3846 playeritem_def.sound_place_failed;
3854 void Game::handlePointingAtObject(const PointedThing &pointed, const ItemStack &playeritem,
3855 const v3f &player_position, bool show_debug)
3857 infotext = unescape_enriched(
3858 utf8_to_wide(runData.selected_object->infoText()));
3861 if (infotext != L"") {
3864 infotext += unescape_enriched(utf8_to_wide(
3865 runData.selected_object->debugInfoText()));
3868 if (isLeftPressed()) {
3869 bool do_punch = false;
3870 bool do_punch_damage = false;
3872 if (runData.object_hit_delay_timer <= 0.0) {
3874 do_punch_damage = true;
3875 runData.object_hit_delay_timer = object_hit_delay;
3878 if (getLeftClicked())
3882 infostream << "Left-clicked object" << std::endl;
3883 runData.left_punch = true;
3886 if (do_punch_damage) {
3887 // Report direct punch
3888 v3f objpos = runData.selected_object->getPosition();
3889 v3f dir = (objpos - player_position).normalize();
3890 ItemStack item = playeritem;
3891 if (playeritem.name.empty()) {
3892 InventoryList *hlist = local_inventory->getList("hand");
3894 item = hlist->getItem(0);
3898 bool disable_send = runData.selected_object->directReportPunch(
3899 dir, &item, runData.time_from_last_punch);
3900 runData.time_from_last_punch = 0;
3903 client->interact(0, pointed);
3905 } else if (getRightClicked()) {
3906 infostream << "Right-clicked object" << std::endl;
3907 client->interact(3, pointed); // place
3912 void Game::handleDigging(const PointedThing &pointed, const v3s16 &nodepos,
3913 const ToolCapabilities &playeritem_toolcap, f32 dtime)
3915 LocalPlayer *player = client->getEnv().getLocalPlayer();
3916 ClientMap &map = client->getEnv().getClientMap();
3917 MapNode n = client->getEnv().getClientMap().getNodeNoEx(nodepos);
3919 // NOTE: Similar piece of code exists on the server side for
3921 // Get digging parameters
3922 DigParams params = getDigParams(nodedef_manager->get(n).groups,
3923 &playeritem_toolcap);
3925 // If can't dig, try hand
3926 if (!params.diggable) {
3927 InventoryList *hlist = local_inventory->getList("hand");
3928 const ItemDefinition &hand =
3929 hlist ? hlist->getItem(0).getDefinition(itemdef_manager) : itemdef_manager->get("");
3930 const ToolCapabilities *tp = hand.tool_capabilities;
3933 params = getDigParams(nodedef_manager->get(n).groups, tp);
3936 if (!params.diggable) {
3937 // I guess nobody will wait for this long
3938 runData.dig_time_complete = 10000000.0;
3940 runData.dig_time_complete = params.time;
3942 if (m_cache_enable_particles) {
3943 const ContentFeatures &features = client->getNodeDefManager()->get(n);
3944 client->getParticleManager()->addPunchingParticles(client,
3945 player, nodepos, n, features);
3949 if (!runData.digging) {
3950 infostream << "Started digging" << std::endl;
3951 runData.dig_instantly = runData.dig_time_complete == 0;
3952 if (client->moddingEnabled() && client->getScript()->on_punchnode(nodepos, n))
3954 client->interact(0, pointed);
3955 runData.digging = true;
3956 runData.ldown_for_dig = true;
3959 if (!runData.dig_instantly) {
3960 runData.dig_index = (float)crack_animation_length
3962 / runData.dig_time_complete;
3964 // This is for e.g. torches
3965 runData.dig_index = crack_animation_length;
3968 SimpleSoundSpec sound_dig = nodedef_manager->get(n).sound_dig;
3970 if (sound_dig.exists() && params.diggable) {
3971 if (sound_dig.name == "__group") {
3972 if (params.main_group != "") {
3973 soundmaker->m_player_leftpunch_sound.gain = 0.5;
3974 soundmaker->m_player_leftpunch_sound.name =
3975 std::string("default_dig_") +
3979 soundmaker->m_player_leftpunch_sound = sound_dig;
3983 // Don't show cracks if not diggable
3984 if (runData.dig_time_complete >= 100000.0) {
3985 } else if (runData.dig_index < crack_animation_length) {
3986 //TimeTaker timer("client.setTempMod");
3987 //infostream<<"dig_index="<<dig_index<<std::endl;
3988 client->setCrack(runData.dig_index, nodepos);
3990 infostream << "Digging completed" << std::endl;
3991 client->setCrack(-1, v3s16(0, 0, 0));
3993 runData.dig_time = 0;
3994 runData.digging = false;
3996 runData.nodig_delay_timer =
3997 runData.dig_time_complete / (float)crack_animation_length;
3999 // We don't want a corresponding delay to very time consuming nodes
4000 // and nodes without digging time (e.g. torches) get a fixed delay.
4001 if (runData.nodig_delay_timer > 0.3)
4002 runData.nodig_delay_timer = 0.3;
4003 else if (runData.dig_instantly)
4004 runData.nodig_delay_timer = 0.15;
4006 bool is_valid_position;
4007 MapNode wasnode = map.getNodeNoEx(nodepos, &is_valid_position);
4008 if (is_valid_position) {
4009 if (client->moddingEnabled() &&
4010 client->getScript()->on_dignode(nodepos, wasnode)) {
4013 client->removeNode(nodepos);
4016 client->interact(2, pointed);
4018 if (m_cache_enable_particles) {
4019 const ContentFeatures &features =
4020 client->getNodeDefManager()->get(wasnode);
4021 client->getParticleManager()->addDiggingParticles(client,
4022 player, nodepos, wasnode, features);
4026 // Send event to trigger sound
4027 MtEvent *e = new NodeDugEvent(nodepos, wasnode);
4028 client->event()->put(e);
4031 if (runData.dig_time_complete < 100000.0) {
4032 runData.dig_time += dtime;
4034 runData.dig_time = 0;
4035 client->setCrack(-1, nodepos);
4038 camera->setDigging(0); // left click animation
4042 void Game::updateFrame(ProfilerGraph *graph, RunStats *stats, f32 dtime,
4043 const CameraOrientation &cam)
4045 LocalPlayer *player = client->getEnv().getLocalPlayer();
4051 if (draw_control->range_all) {
4052 runData.fog_range = 100000 * BS;
4054 runData.fog_range = draw_control->wanted_range * BS;
4058 Calculate general brightness
4060 u32 daynight_ratio = client->getEnv().getDayNightRatio();
4061 float time_brightness = decode_light_f((float)daynight_ratio / 1000.0);
4062 float direct_brightness;
4065 if (m_cache_enable_noclip && m_cache_enable_free_move) {
4066 direct_brightness = time_brightness;
4067 sunlight_seen = true;
4069 ScopeProfiler sp(g_profiler, "Detecting background light", SPT_AVG);
4070 float old_brightness = sky->getBrightness();
4071 direct_brightness = client->getEnv().getClientMap()
4072 .getBackgroundBrightness(MYMIN(runData.fog_range * 1.2, 60 * BS),
4073 daynight_ratio, (int)(old_brightness * 255.5), &sunlight_seen)
4077 float time_of_day_smooth = runData.time_of_day_smooth;
4078 float time_of_day = client->getEnv().getTimeOfDayF();
4080 static const float maxsm = 0.05;
4081 static const float todsm = 0.05;
4083 if (fabs(time_of_day - time_of_day_smooth) > maxsm &&
4084 fabs(time_of_day - time_of_day_smooth + 1.0) > maxsm &&
4085 fabs(time_of_day - time_of_day_smooth - 1.0) > maxsm)
4086 time_of_day_smooth = time_of_day;
4088 if (time_of_day_smooth > 0.8 && time_of_day < 0.2)
4089 time_of_day_smooth = time_of_day_smooth * (1.0 - todsm)
4090 + (time_of_day + 1.0) * todsm;
4092 time_of_day_smooth = time_of_day_smooth * (1.0 - todsm)
4093 + time_of_day * todsm;
4095 runData.time_of_day = time_of_day;
4096 runData.time_of_day_smooth = time_of_day_smooth;
4098 sky->update(time_of_day_smooth, time_brightness, direct_brightness,
4099 sunlight_seen, camera->getCameraMode(), player->getYaw(),
4100 player->getPitch());
4106 v3f player_position = player->getPosition();
4107 if (sky->getCloudsVisible()) {
4108 clouds->setVisible(true);
4109 clouds->step(dtime);
4110 clouds->update(v2f(player_position.X, player_position.Z),
4111 sky->getCloudColor());
4113 clouds->setVisible(false);
4120 client->getParticleManager()->step(dtime);
4126 if (m_cache_enable_fog && !flags.force_fog_off) {
4129 video::EFT_FOG_LINEAR,
4130 runData.fog_range * m_cache_fog_start,
4131 runData.fog_range * 1.0,
4139 video::EFT_FOG_LINEAR,
4149 Get chat messages from client
4152 v2u32 screensize = driver->getScreenSize();
4154 updateChat(*client, dtime, flags.show_debug, screensize,
4155 flags.show_chat, runData.profiler_current_page,
4156 *chat_backend, guitext_chat);
4162 if (client->getPlayerItem() != runData.new_playeritem)
4163 client->selectPlayerItem(runData.new_playeritem);
4165 // Update local inventory if it has changed
4166 if (client->getLocalInventoryUpdated()) {
4167 //infostream<<"Updating local inventory"<<std::endl;
4168 client->getLocalInventory(*local_inventory);
4169 runData.update_wielded_item_trigger = true;
4172 if (runData.update_wielded_item_trigger) {
4173 // Update wielded tool
4174 InventoryList *mlist = local_inventory->getList("main");
4176 if (mlist && (client->getPlayerItem() < mlist->getSize())) {
4177 ItemStack item = mlist->getItem(client->getPlayerItem());
4178 if (item.getDefinition(itemdef_manager).name.empty()) { // override the hand
4179 InventoryList *hlist = local_inventory->getList("hand");
4181 item = hlist->getItem(0);
4183 camera->wield(item);
4186 runData.update_wielded_item_trigger = false;
4190 Update block draw list every 200ms or when camera direction has
4193 runData.update_draw_list_timer += dtime;
4195 v3f camera_direction = camera->getDirection();
4196 if (runData.update_draw_list_timer >= 0.2
4197 || runData.update_draw_list_last_cam_dir.getDistanceFrom(camera_direction) > 0.2
4198 || m_camera_offset_changed) {
4199 runData.update_draw_list_timer = 0;
4200 client->getEnv().getClientMap().updateDrawList(driver);
4201 runData.update_draw_list_last_cam_dir = camera_direction;
4204 updateGui(*stats, dtime, cam);
4207 make sure menu is on top
4208 1. Delete formspec menu reference if menu was removed
4209 2. Else, make sure formspec menu is on top
4211 if (current_formspec) {
4212 if (current_formspec->getReferenceCount() == 1) {
4213 current_formspec->drop();
4214 current_formspec = NULL;
4215 } else if (isMenuActive()) {
4216 guiroot->bringToFront(current_formspec);
4224 const video::SColor &skycolor = sky->getSkyColor();
4226 TimeTaker tt_draw("mainloop: draw");
4227 driver->beginScene(true, true, skycolor);
4229 RenderingEngine::draw_scene(camera, client, player, hud, mapper,
4230 guienv, screensize, skycolor, flags.show_hud,
4231 flags.show_minimap);
4236 if (flags.show_profiler_graph)
4237 graph->draw(10, screensize.Y - 10, driver, g_fontengine->getFont());
4242 if (runData.damage_flash > 0.0) {
4243 video::SColor color(runData.damage_flash, 180, 0, 0);
4244 driver->draw2DRectangle(color,
4245 core::rect<s32>(0, 0, screensize.X, screensize.Y),
4248 runData.damage_flash -= 100.0 * dtime;
4254 if (player->hurt_tilt_timer > 0.0) {
4255 player->hurt_tilt_timer -= dtime * 5;
4257 if (player->hurt_tilt_timer < 0)
4258 player->hurt_tilt_strength = 0;
4262 Update minimap pos and rotation
4264 if (mapper && flags.show_minimap && flags.show_hud) {
4265 mapper->setPos(floatToInt(player->getPosition(), BS));
4266 mapper->setAngle(player->getYaw());
4274 stats->drawtime = tt_draw.stop(true);
4275 g_profiler->graphAdd("mainloop_draw", stats->drawtime / 1000.0f);
4279 inline static const char *yawToDirectionString(int yaw)
4281 static const char *direction[4] = {"North [+Z]", "West [-X]", "South [-Z]", "East [+X]"};
4283 yaw = wrapDegrees_0_360(yaw);
4284 yaw = (yaw + 45) % 360 / 90;
4286 return direction[yaw];
4290 void Game::updateGui(const RunStats &stats, f32 dtime, const CameraOrientation &cam)
4292 v2u32 screensize = driver->getScreenSize();
4293 LocalPlayer *player = client->getEnv().getLocalPlayer();
4294 v3f player_position = player->getPosition();
4296 if (flags.show_debug) {
4297 static float drawtime_avg = 0;
4298 drawtime_avg = drawtime_avg * 0.95 + stats.drawtime * 0.05;
4300 u16 fps = 1.0 / stats.dtime_jitter.avg;
4302 std::ostringstream os(std::ios_base::binary);
4304 << PROJECT_NAME_C " " << g_version_hash
4305 << "; " << fps << " FPS"
4306 << ", (R: range_all=" << draw_control->range_all << ")"
4307 << std::setprecision(0)
4308 << ", drawtime = " << drawtime_avg << " ms"
4309 << std::setprecision(1)
4310 << ", dtime_jitter = "
4311 << (stats.dtime_jitter.max_fraction * 100.0) << " %"
4312 << std::setprecision(1)
4313 << ", v_range = " << draw_control->wanted_range
4314 << std::setprecision(3)
4315 << ", RTT = " << client->getRTT() << " s";
4316 setStaticText(guitext, utf8_to_wide(os.str()).c_str());
4317 guitext->setVisible(true);
4319 guitext->setVisible(false);
4322 if (guitext->isVisible()) {
4323 core::rect<s32> rect(
4325 screensize.X, 5 + g_fontengine->getTextHeight()
4327 guitext->setRelativePosition(rect);
4330 if (flags.show_debug) {
4331 std::ostringstream os(std::ios_base::binary);
4332 os << std::setprecision(1) << std::fixed
4333 << "(" << (player_position.X / BS)
4334 << ", " << (player_position.Y / BS)
4335 << ", " << (player_position.Z / BS)
4336 << ") (yaw=" << (wrapDegrees_0_360(cam.camera_yaw)) << "°"
4337 << " " << yawToDirectionString(cam.camera_yaw)
4338 << ") (seed = " << ((u64)client->getMapSeed())
4341 if (runData.pointed_old.type == POINTEDTHING_NODE) {
4342 ClientMap &map = client->getEnv().getClientMap();
4343 const INodeDefManager *nodedef = client->getNodeDefManager();
4344 MapNode n = map.getNodeNoEx(runData.pointed_old.node_undersurface);
4345 if (n.getContent() != CONTENT_IGNORE && nodedef->get(n).name != "unknown") {
4346 const ContentFeatures &features = nodedef->get(n);
4347 os << " (pointing_at = \"" << nodedef->get(n).name
4348 << "\", param1 = " << (u64) n.getParam1()
4349 << ", param2 = " << (u64) n.getParam2()
4350 << ", tiledef[0] = \"" << features.tiledef[0].name.c_str()
4355 setStaticText(guitext2, utf8_to_wide(os.str()).c_str());
4356 guitext2->setVisible(true);
4358 core::rect<s32> rect(
4359 5, 5 + g_fontengine->getTextHeight(),
4360 screensize.X, 5 + g_fontengine->getTextHeight() * 2
4362 guitext2->setRelativePosition(rect);
4364 guitext2->setVisible(false);
4367 setStaticText(guitext_info, infotext.c_str());
4368 guitext_info->setVisible(flags.show_hud && g_menumgr.menuCount() == 0);
4370 float statustext_time_max = 1.5;
4372 if (!m_statustext.empty()) {
4373 runData.statustext_time += dtime;
4375 if (runData.statustext_time >= statustext_time_max) {
4377 runData.statustext_time = 0;
4381 setStaticText(guitext_status, m_statustext.c_str());
4382 guitext_status->setVisible(!m_statustext.empty());
4384 if (!m_statustext.empty()) {
4385 s32 status_width = guitext_status->getTextWidth();
4386 s32 status_height = guitext_status->getTextHeight();
4387 s32 status_y = screensize.Y - 150;
4388 s32 status_x = (screensize.X - status_width) / 2;
4389 core::rect<s32> rect(
4390 status_x , status_y - status_height,
4391 status_x + status_width, status_y
4393 guitext_status->setRelativePosition(rect);
4396 video::SColor initial_color(255, 0, 0, 0);
4398 if (guienv->getSkin())
4399 initial_color = guienv->getSkin()->getColor(gui::EGDC_BUTTON_TEXT);
4401 video::SColor final_color = initial_color;
4402 final_color.setAlpha(0);
4403 video::SColor fade_color = initial_color.getInterpolated_quadratic(
4404 initial_color, final_color,
4405 pow(runData.statustext_time / statustext_time_max, 2.0f));
4406 guitext_status->setOverrideColor(fade_color);
4407 guitext_status->enableOverrideColor(true);
4412 /* Log times and stuff for visualization */
4413 inline void Game::updateProfilerGraphs(ProfilerGraph *graph)
4415 Profiler::GraphValues values;
4416 g_profiler->graphGet(values);
4422 /****************************************************************************
4424 ****************************************************************************/
4426 /* On some computers framerate doesn't seem to be automatically limited
4428 inline void Game::limitFps(FpsControl *fps_timings, f32 *dtime)
4430 // not using getRealTime is necessary for wine
4431 device->getTimer()->tick(); // Maker sure device time is up-to-date
4432 u32 time = device->getTimer()->getTime();
4433 u32 last_time = fps_timings->last_time;
4435 if (time > last_time) // Make sure time hasn't overflowed
4436 fps_timings->busy_time = time - last_time;
4438 fps_timings->busy_time = 0;
4440 u32 frametime_min = 1000 / (g_menumgr.pausesGame()
4441 ? g_settings->getFloat("pause_fps_max")
4442 : g_settings->getFloat("fps_max"));
4444 if (fps_timings->busy_time < frametime_min) {
4445 fps_timings->sleep_time = frametime_min - fps_timings->busy_time;
4446 device->sleep(fps_timings->sleep_time);
4448 fps_timings->sleep_time = 0;
4451 /* Get the new value of the device timer. Note that device->sleep() may
4452 * not sleep for the entire requested time as sleep may be interrupted and
4453 * therefore it is arguably more accurate to get the new time from the
4454 * device rather than calculating it by adding sleep_time to time.
4457 device->getTimer()->tick(); // Update device timer
4458 time = device->getTimer()->getTime();
4460 if (time > last_time) // Make sure last_time hasn't overflowed
4461 *dtime = (time - last_time) / 1000.0;
4465 fps_timings->last_time = time;
4468 void Game::showOverlayMessage(const char *msg, float dtime, int percent, bool draw_clouds)
4470 const wchar_t *wmsg = wgettext(msg);
4471 RenderingEngine::draw_load_screen(wmsg, guienv, texture_src, dtime, percent,
4476 void Game::settingChangedCallback(const std::string &setting_name, void *data)
4478 ((Game *)data)->readSettings();
4481 void Game::readSettings()
4483 m_cache_doubletap_jump = g_settings->getBool("doubletap_jump");
4484 m_cache_enable_clouds = g_settings->getBool("enable_clouds");
4485 m_cache_enable_joysticks = g_settings->getBool("enable_joysticks");
4486 m_cache_enable_particles = g_settings->getBool("enable_particles");
4487 m_cache_enable_fog = g_settings->getBool("enable_fog");
4488 m_cache_mouse_sensitivity = g_settings->getFloat("mouse_sensitivity");
4489 m_cache_joystick_frustum_sensitivity = g_settings->getFloat("joystick_frustum_sensitivity");
4490 m_repeat_right_click_time = g_settings->getFloat("repeat_rightclick_time");
4492 m_cache_enable_noclip = g_settings->getBool("noclip");
4493 m_cache_enable_free_move = g_settings->getBool("free_move");
4495 m_cache_fog_start = g_settings->getFloat("fog_start");
4497 m_cache_cam_smoothing = 0;
4498 if (g_settings->getBool("cinematic"))
4499 m_cache_cam_smoothing = 1 - g_settings->getFloat("cinematic_camera_smoothing");
4501 m_cache_cam_smoothing = 1 - g_settings->getFloat("camera_smoothing");
4503 m_cache_fog_start = rangelim(m_cache_fog_start, 0.0f, 0.99f);
4504 m_cache_cam_smoothing = rangelim(m_cache_cam_smoothing, 0.01f, 1.0f);
4505 m_cache_mouse_sensitivity = rangelim(m_cache_mouse_sensitivity, 0.001, 100.0);
4509 /****************************************************************************/
4510 /****************************************************************************
4512 ****************************************************************************/
4513 /****************************************************************************/
4515 void Game::extendedResourceCleanup()
4517 // Extended resource accounting
4518 infostream << "Irrlicht resources after cleanup:" << std::endl;
4519 infostream << "\tRemaining meshes : "
4520 << RenderingEngine::get_mesh_cache()->getMeshCount() << std::endl;
4521 infostream << "\tRemaining textures : "
4522 << driver->getTextureCount() << std::endl;
4524 for (unsigned int i = 0; i < driver->getTextureCount(); i++) {
4525 irr::video::ITexture *texture = driver->getTextureByIndex(i);
4526 infostream << "\t\t" << i << ":" << texture->getName().getPath().c_str()
4530 clearTextureNameCache();
4531 infostream << "\tRemaining materials: "
4532 << driver-> getMaterialRendererCount()
4533 << " (note: irrlicht doesn't support removing renderers)" << std::endl;
4536 #define GET_KEY_NAME(KEY) gettext(getKeySetting(#KEY).name())
4537 void Game::showPauseMenu()
4540 static const std::string control_text = strgettext("Default Controls:\n"
4541 "No menu visible:\n"
4542 "- single tap: button activate\n"
4543 "- double tap: place/use\n"
4544 "- slide finger: look around\n"
4545 "Menu/Inventory visible:\n"
4546 "- double tap (outside):\n"
4548 "- touch stack, touch slot:\n"
4550 "- touch&drag, tap 2nd finger\n"
4551 " --> place single item to slot\n"
4554 static const std::string control_text_template = strgettext("Controls:\n"
4555 "- %s: move forwards\n"
4556 "- %s: move backwards\n"
4558 "- %s: move right\n"
4559 "- %s: jump/climb\n"
4560 "- %s: sneak/go down\n"
4563 "- Mouse: turn/look\n"
4564 "- Mouse left: dig/punch\n"
4565 "- Mouse right: place/use\n"
4566 "- Mouse wheel: select item\n"
4570 char control_text_buf[600];
4572 snprintf(control_text_buf, ARRLEN(control_text_buf), control_text_template.c_str(),
4573 GET_KEY_NAME(keymap_forward),
4574 GET_KEY_NAME(keymap_backward),
4575 GET_KEY_NAME(keymap_left),
4576 GET_KEY_NAME(keymap_right),
4577 GET_KEY_NAME(keymap_jump),
4578 GET_KEY_NAME(keymap_sneak),
4579 GET_KEY_NAME(keymap_drop),
4580 GET_KEY_NAME(keymap_inventory),
4581 GET_KEY_NAME(keymap_chat)
4584 std::string control_text = std::string(control_text_buf);
4585 str_formspec_escape(control_text);
4588 float ypos = simple_singleplayer_mode ? 0.7f : 0.1f;
4589 std::ostringstream os;
4591 os << FORMSPEC_VERSION_STRING << SIZE_TAG
4592 << "button_exit[4," << (ypos++) << ";3,0.5;btn_continue;"
4593 << strgettext("Continue") << "]";
4595 if (!simple_singleplayer_mode) {
4596 os << "button_exit[4," << (ypos++) << ";3,0.5;btn_change_password;"
4597 << strgettext("Change Password") << "]";
4599 os << "field[4.95,0;5,1.5;;" << strgettext("Game paused") << ";]";
4603 os << "button_exit[4," << (ypos++) << ";3,0.5;btn_sound;"
4604 << strgettext("Sound Volume") << "]";
4605 os << "button_exit[4," << (ypos++) << ";3,0.5;btn_key_config;"
4606 << strgettext("Change Keys") << "]";
4608 os << "button_exit[4," << (ypos++) << ";3,0.5;btn_exit_menu;"
4609 << strgettext("Exit to Menu") << "]";
4610 os << "button_exit[4," << (ypos++) << ";3,0.5;btn_exit_os;"
4611 << strgettext("Exit to OS") << "]"
4612 << "textarea[7.5,0.25;3.9,6.25;;" << control_text << ";]"
4613 << "textarea[0.4,0.25;3.9,6.25;;" << PROJECT_NAME_C " " VERSION_STRING "\n"
4615 << strgettext("Game info:") << "\n";
4616 const std::string &address = client->getAddressName();
4617 static const std::string mode = strgettext("- Mode: ");
4618 if (!simple_singleplayer_mode) {
4619 Address serverAddress = client->getServerAddress();
4620 if (address != "") {
4621 os << mode << strgettext("Remote server") << "\n"
4622 << strgettext("- Address: ") << address;
4624 os << mode << strgettext("Hosting server");
4626 os << "\n" << strgettext("- Port: ") << serverAddress.getPort() << "\n";
4628 os << mode << strgettext("Singleplayer") << "\n";
4630 if (simple_singleplayer_mode || address == "") {
4631 static const std::string on = strgettext("On");
4632 static const std::string off = strgettext("Off");
4633 const std::string &damage = g_settings->getBool("enable_damage") ? on : off;
4634 const std::string &creative = g_settings->getBool("creative_mode") ? on : off;
4635 const std::string &announced = g_settings->getBool("server_announce") ? on : off;
4636 os << strgettext("- Damage: ") << damage << "\n"
4637 << strgettext("- Creative Mode: ") << creative << "\n";
4638 if (!simple_singleplayer_mode) {
4639 const std::string &pvp = g_settings->getBool("enable_pvp") ? on : off;
4640 os << strgettext("- PvP: ") << pvp << "\n"
4641 << strgettext("- Public: ") << announced << "\n";
4642 std::string server_name = g_settings->get("server_name");
4643 str_formspec_escape(server_name);
4644 if (announced == on && server_name != "")
4645 os << strgettext("- Server Name: ") << server_name;
4652 /* Note: FormspecFormSource and LocalFormspecHandler *
4653 * are deleted by guiFormSpecMenu */
4654 FormspecFormSource *fs_src = new FormspecFormSource(os.str());
4655 LocalFormspecHandler *txt_dst = new LocalFormspecHandler("MT_PAUSE_MENU");
4657 create_formspec_menu(¤t_formspec, client, &input->joystick, fs_src, txt_dst);
4658 current_formspec->setFocus("btn_continue");
4659 current_formspec->doPause = true;
4662 /****************************************************************************/
4663 /****************************************************************************
4664 extern function for launching the game
4665 ****************************************************************************/
4666 /****************************************************************************/
4668 void the_game(bool *kill,
4670 InputHandler *input,
4671 const std::string &map_dir,
4672 const std::string &playername,
4673 const std::string &password,
4674 const std::string &address, // If empty local server is created
4677 std::string &error_message,
4678 ChatBackend &chat_backend,
4679 bool *reconnect_requested,
4680 const SubgameSpec &gamespec, // Used for local game
4681 bool simple_singleplayer_mode)
4685 /* Make a copy of the server address because if a local singleplayer server
4686 * is created then this is updated and we don't want to change the value
4687 * passed to us by the calling function
4689 std::string server_address = address;
4693 if (game.startup(kill, random_input, input, map_dir,
4694 playername, password, &server_address, port, error_message,
4695 reconnect_requested, &chat_backend, gamespec,
4696 simple_singleplayer_mode)) {
4701 } catch (SerializationError &e) {
4702 error_message = std::string("A serialization error occurred:\n")
4703 + e.what() + "\n\nThe server is probably "
4704 " running a different version of " PROJECT_NAME_C ".";
4705 errorstream << error_message << std::endl;
4706 } catch (ServerError &e) {
4707 error_message = e.what();
4708 errorstream << "ServerError: " << error_message << std::endl;
4709 } catch (ModError &e) {
4710 error_message = e.what() + strgettext("\nCheck debug.txt for details.");
4711 errorstream << "ModError: " << error_message << std::endl;