3 Copyright (C) 2010-2013 celeron55, Perttu Ahola <celeron55@gmail.com>
5 This program is free software; you can redistribute it and/or modify
6 it under the terms of the GNU Lesser General Public License as published by
7 the Free Software Foundation; either version 2.1 of the License, or
8 (at your option) any later version.
10 This program is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 GNU Lesser General Public License for more details.
15 You should have received a copy of the GNU Lesser General Public License along
16 with this program; if not, write to the Free Software Foundation, Inc.,
17 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
25 #include "client/tile.h" // For TextureSource
26 #include "client/keys.h"
27 #include "client/joystick_controller.h"
28 #include "clientmap.h"
31 #include "content_cao.h"
32 #include "drawscene.h"
33 #include "event_manager.h"
34 #include "fontengine.h"
39 #include "guiChatConsole.h"
40 #include "guiFormSpecMenu.h"
41 #include "guiKeyChangeMenu.h"
42 #include "guiPasswordChange.h"
43 #include "guiVolumeChange.h"
44 #include "mainmenumanager.h"
46 #include "nodedef.h" // Needed for determining pointing to nodes
47 #include "nodemetadata.h"
48 #include "particles.h"
50 #include "quicktune_shortcutter.h"
53 #include "shader.h" // For ShaderSource
57 #include "util/directiontables.h"
58 #include "util/pointedthing.h"
59 #include "irrlicht_changes/static_text.h"
62 #include "mapblock_mesh.h"
63 #include "script/scripting_client.h"
68 #include "sound_openal.h"
71 #ifdef HAVE_TOUCHSCREENGUI
72 #include "touchscreengui.h"
75 extern Settings *g_settings;
76 extern Profiler *g_profiler;
82 struct TextDestNodeMetadata : public TextDest
84 TextDestNodeMetadata(v3s16 p, Client *client)
89 // This is deprecated I guess? -celeron55
90 void gotText(const std::wstring &text)
92 std::string ntext = wide_to_utf8(text);
93 infostream << "Submitting 'text' field of node at (" << m_p.X << ","
94 << m_p.Y << "," << m_p.Z << "): " << ntext << std::endl;
96 fields["text"] = ntext;
97 m_client->sendNodemetaFields(m_p, "", fields);
99 void gotText(const StringMap &fields)
101 m_client->sendNodemetaFields(m_p, "", fields);
108 struct TextDestPlayerInventory : public TextDest
110 TextDestPlayerInventory(Client *client)
115 TextDestPlayerInventory(Client *client, const std::string &formname)
118 m_formname = formname;
120 void gotText(const StringMap &fields)
122 m_client->sendInventoryFields(m_formname, fields);
128 struct LocalFormspecHandler : public TextDest
130 LocalFormspecHandler(const std::string &formname):
133 m_formname = formname;
136 LocalFormspecHandler(const std::string &formname, Client *client):
139 m_formname = formname;
142 void gotText(const StringMap &fields)
144 if (m_formname == "MT_PAUSE_MENU") {
145 if (fields.find("btn_sound") != fields.end()) {
146 g_gamecallback->changeVolume();
150 if (fields.find("btn_key_config") != fields.end()) {
151 g_gamecallback->keyConfig();
155 if (fields.find("btn_exit_menu") != fields.end()) {
156 g_gamecallback->disconnect();
160 if (fields.find("btn_exit_os") != fields.end()) {
161 g_gamecallback->exitToOS();
165 if (fields.find("btn_change_password") != fields.end()) {
166 g_gamecallback->changePassword();
170 if (fields.find("quit") != fields.end()) {
174 if (fields.find("btn_continue") != fields.end()) {
179 // Don't disable this part when modding is disabled, it's used in builtin
180 m_client->getScript()->on_formspec_input(m_formname, fields);
186 /* Form update callback */
188 class NodeMetadataFormSource: public IFormSource
191 NodeMetadataFormSource(ClientMap *map, v3s16 p):
196 std::string getForm()
198 NodeMetadata *meta = m_map->getNodeMetadata(m_p);
203 return meta->getString("formspec");
206 virtual std::string resolveText(const std::string &str)
208 NodeMetadata *meta = m_map->getNodeMetadata(m_p);
213 return meta->resolveString(str);
220 class PlayerInventoryFormSource: public IFormSource
223 PlayerInventoryFormSource(Client *client):
227 std::string getForm()
229 LocalPlayer *player = m_client->getEnv().getLocalPlayer();
230 return player->inventory_formspec;
236 /* Profiler display */
238 void update_profiler_gui(gui::IGUIStaticText *guitext_profiler, FontEngine *fe,
239 u32 show_profiler, u32 show_profiler_max, s32 screen_height)
241 if (show_profiler == 0) {
242 guitext_profiler->setVisible(false);
245 std::ostringstream os(std::ios_base::binary);
246 g_profiler->printPage(os, show_profiler, show_profiler_max);
247 std::wstring text = utf8_to_wide(os.str());
248 setStaticText(guitext_profiler, text.c_str());
249 guitext_profiler->setVisible(true);
251 s32 w = fe->getTextWidth(text.c_str());
256 unsigned text_height = fe->getTextHeight();
258 core::position2di upper_left, lower_right;
261 upper_left.Y = (text_height + 5) * 2;
262 lower_right.X = 12 + w;
263 lower_right.Y = upper_left.Y + (text_height + 1) * MAX_PROFILER_TEXT_ROWS;
265 if (lower_right.Y > screen_height * 2 / 3)
266 lower_right.Y = screen_height * 2 / 3;
268 core::rect<s32> rect(upper_left, lower_right);
270 guitext_profiler->setRelativePosition(rect);
271 guitext_profiler->setVisible(true);
279 Profiler::GraphValues values;
285 Meta(float initial = 0,
286 video::SColor color = video::SColor(255, 255, 255, 255)):
292 std::deque<Piece> m_log;
300 void put(const Profiler::GraphValues &values)
303 piece.values = values;
304 m_log.push_back(piece);
306 while (m_log.size() > m_log_max_size)
307 m_log.erase(m_log.begin());
310 void draw(s32 x_left, s32 y_bottom, video::IVideoDriver *driver,
311 gui::IGUIFont *font) const
313 // Do *not* use UNORDERED_MAP here as the order needs
314 // to be the same for each call to prevent flickering
315 std::map<std::string, Meta> m_meta;
317 for (std::deque<Piece>::const_iterator k = m_log.begin();
318 k != m_log.end(); ++k) {
319 const Piece &piece = *k;
321 for (Profiler::GraphValues::const_iterator i = piece.values.begin();
322 i != piece.values.end(); ++i) {
323 const std::string &id = i->first;
324 const float &value = i->second;
325 std::map<std::string, Meta>::iterator j = m_meta.find(id);
327 if (j == m_meta.end()) {
328 m_meta[id] = Meta(value);
332 if (value < j->second.min)
333 j->second.min = value;
335 if (value > j->second.max)
336 j->second.max = value;
341 static const video::SColor usable_colors[] = {
342 video::SColor(255, 255, 100, 100),
343 video::SColor(255, 90, 225, 90),
344 video::SColor(255, 100, 100, 255),
345 video::SColor(255, 255, 150, 50),
346 video::SColor(255, 220, 220, 100)
348 static const u32 usable_colors_count =
349 sizeof(usable_colors) / sizeof(*usable_colors);
350 u32 next_color_i = 0;
352 for (std::map<std::string, Meta>::iterator i = m_meta.begin();
353 i != m_meta.end(); ++i) {
354 Meta &meta = i->second;
355 video::SColor color(255, 200, 200, 200);
357 if (next_color_i < usable_colors_count)
358 color = usable_colors[next_color_i++];
364 s32 textx = x_left + m_log_max_size + 15;
365 s32 textx2 = textx + 200 - 15;
368 for (std::map<std::string, Meta>::const_iterator i = m_meta.begin();
369 i != m_meta.end(); ++i) {
370 const std::string &id = i->first;
371 const Meta &meta = i->second;
373 s32 y = y_bottom - meta_i * 50;
374 float show_min = meta.min;
375 float show_max = meta.max;
377 if (show_min >= -0.0001 && show_max >= -0.0001) {
378 if (show_min <= show_max * 0.5)
384 snprintf(buf, 10, "%.3g", show_max);
385 font->draw(utf8_to_wide(buf).c_str(),
386 core::rect<s32>(textx, y - graphh,
387 textx2, y - graphh + texth),
389 snprintf(buf, 10, "%.3g", show_min);
390 font->draw(utf8_to_wide(buf).c_str(),
391 core::rect<s32>(textx, y - texth,
394 font->draw(utf8_to_wide(id).c_str(),
395 core::rect<s32>(textx, y - graphh / 2 - texth / 2,
396 textx2, y - graphh / 2 + texth / 2),
399 s32 graph1h = graphh;
400 bool relativegraph = (show_min != 0 && show_min != show_max);
401 float lastscaledvalue = 0.0;
402 bool lastscaledvalue_exists = false;
404 for (std::deque<Piece>::const_iterator j = m_log.begin();
405 j != m_log.end(); ++j) {
406 const Piece &piece = *j;
408 bool value_exists = false;
409 Profiler::GraphValues::const_iterator k =
410 piece.values.find(id);
412 if (k != piece.values.end()) {
419 lastscaledvalue_exists = false;
423 float scaledvalue = 1.0;
425 if (show_max != show_min)
426 scaledvalue = (value - show_min) / (show_max - show_min);
428 if (scaledvalue == 1.0 && value == 0) {
430 lastscaledvalue_exists = false;
435 if (lastscaledvalue_exists) {
436 s32 ivalue1 = lastscaledvalue * graph1h;
437 s32 ivalue2 = scaledvalue * graph1h;
438 driver->draw2DLine(v2s32(x - 1, graph1y - ivalue1),
439 v2s32(x, graph1y - ivalue2), meta.color);
442 lastscaledvalue = scaledvalue;
443 lastscaledvalue_exists = true;
445 s32 ivalue = scaledvalue * graph1h;
446 driver->draw2DLine(v2s32(x, graph1y),
447 v2s32(x, graph1y - ivalue), meta.color);
458 class NodeDugEvent: public MtEvent
464 NodeDugEvent(v3s16 p, MapNode n):
468 const char *getType() const
476 ISoundManager *m_sound;
477 INodeDefManager *m_ndef;
479 float m_player_step_timer;
481 SimpleSoundSpec m_player_step_sound;
482 SimpleSoundSpec m_player_leftpunch_sound;
483 SimpleSoundSpec m_player_rightpunch_sound;
485 SoundMaker(ISoundManager *sound, INodeDefManager *ndef):
488 m_player_step_timer(0)
492 void playPlayerStep()
494 if (m_player_step_timer <= 0 && m_player_step_sound.exists()) {
495 m_player_step_timer = 0.03;
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 float minimap_yaw_array[3];
723 v3f minimap_yaw = m_client->getMinimap()->getYawVec();
724 #if (IRRLICHT_VERSION_MAJOR == 1 && IRRLICHT_VERSION_MINOR < 8)
725 minimap_yaw_array[0] = minimap_yaw.X;
726 minimap_yaw_array[1] = minimap_yaw.Y;
727 minimap_yaw_array[2] = minimap_yaw.Z;
729 minimap_yaw.getAs3Values(minimap_yaw_array);
731 m_minimap_yaw.set(minimap_yaw_array, services);
733 SamplerLayer_t base_tex = 0,
736 m_base_texture.set(&base_tex, services);
737 m_normal_texture.set(&normal_tex, services);
738 m_texture_flags.set(&flags_tex, services);
743 class GameGlobalShaderConstantSetterFactory : public IShaderConstantSetterFactory
746 bool *m_force_fog_off;
749 std::vector<GameGlobalShaderConstantSetter *> created_nosky;
751 GameGlobalShaderConstantSetterFactory(bool *force_fog_off,
752 f32 *fog_range, Client *client) :
754 m_force_fog_off(force_fog_off),
755 m_fog_range(fog_range),
759 void setSky(Sky *sky) {
761 for (size_t i = 0; i < created_nosky.size(); ++i) {
762 created_nosky[i]->setSky(m_sky);
764 created_nosky.clear();
767 virtual IShaderConstantSetter* create()
769 GameGlobalShaderConstantSetter *scs = new GameGlobalShaderConstantSetter(
770 m_sky, m_force_fog_off, m_fog_range, m_client);
772 created_nosky.push_back(scs);
778 bool nodePlacementPrediction(Client &client,
779 const ItemDefinition &playeritem_def, v3s16 nodepos, v3s16 neighbourpos)
781 std::string prediction = playeritem_def.node_placement_prediction;
782 INodeDefManager *nodedef = client.ndef();
783 ClientMap &map = client.getEnv().getClientMap();
785 bool is_valid_position;
787 node = map.getNodeNoEx(nodepos, &is_valid_position);
788 if (!is_valid_position)
791 if (prediction != "" && !nodedef->get(node).rightclickable) {
792 verbosestream << "Node placement prediction for "
793 << playeritem_def.name << " is "
794 << prediction << std::endl;
795 v3s16 p = neighbourpos;
797 // Place inside node itself if buildable_to
798 MapNode n_under = map.getNodeNoEx(nodepos, &is_valid_position);
799 if (is_valid_position)
801 if (nodedef->get(n_under).buildable_to)
804 node = map.getNodeNoEx(p, &is_valid_position);
805 if (is_valid_position &&!nodedef->get(node).buildable_to)
810 // Find id of predicted node
812 bool found = nodedef->getId(prediction, id);
815 errorstream << "Node placement prediction failed for "
816 << playeritem_def.name << " (places "
818 << ") - Name not known" << std::endl;
822 // Predict param2 for facedir and wallmounted nodes
825 if (nodedef->get(id).param_type_2 == CPT2_WALLMOUNTED ||
826 nodedef->get(id).param_type_2 == CPT2_COLORED_WALLMOUNTED) {
827 v3s16 dir = nodepos - neighbourpos;
829 if (abs(dir.Y) > MYMAX(abs(dir.X), abs(dir.Z))) {
830 param2 = dir.Y < 0 ? 1 : 0;
831 } else if (abs(dir.X) > abs(dir.Z)) {
832 param2 = dir.X < 0 ? 3 : 2;
834 param2 = dir.Z < 0 ? 5 : 4;
838 if (nodedef->get(id).param_type_2 == CPT2_FACEDIR ||
839 nodedef->get(id).param_type_2 == CPT2_COLORED_FACEDIR) {
840 v3s16 dir = nodepos - floatToInt(client.getEnv().getLocalPlayer()->getPosition(), BS);
842 if (abs(dir.X) > abs(dir.Z)) {
843 param2 = dir.X < 0 ? 3 : 1;
845 param2 = dir.Z < 0 ? 2 : 0;
851 //Check attachment if node is in group attached_node
852 if (((ItemGroupList) nodedef->get(id).groups)["attached_node"] != 0) {
853 static v3s16 wallmounted_dirs[8] = {
863 if (nodedef->get(id).param_type_2 == CPT2_WALLMOUNTED ||
864 nodedef->get(id).param_type_2 == CPT2_COLORED_WALLMOUNTED)
865 pp = p + wallmounted_dirs[param2];
867 pp = p + v3s16(0, -1, 0);
869 if (!nodedef->get(map.getNodeNoEx(pp)).walkable)
873 // Add node to client map
874 MapNode n(id, 0, param2);
877 LocalPlayer *player = client.getEnv().getLocalPlayer();
879 // Dont place node when player would be inside new node
880 // NOTE: This is to be eventually implemented by a mod as client-side Lua
881 if (!nodedef->get(n).walkable ||
882 g_settings->getBool("enable_build_where_you_stand") ||
883 (client.checkPrivilege("noclip") && g_settings->getBool("noclip")) ||
884 (nodedef->get(n).walkable &&
885 neighbourpos != player->getStandingNodePos() + v3s16(0, 1, 0) &&
886 neighbourpos != player->getStandingNodePos() + v3s16(0, 2, 0))) {
888 // This triggers the required mesh update too
889 client.addNode(p, n);
892 } catch (InvalidPositionException &e) {
893 errorstream << "Node placement prediction failed for "
894 << playeritem_def.name << " (places "
896 << ") - Position not loaded" << std::endl;
903 static inline void create_formspec_menu(GUIFormSpecMenu **cur_formspec,
904 Client *client, IrrlichtDevice *device, JoystickController *joystick,
905 IFormSource *fs_src, TextDest *txt_dest)
908 if (*cur_formspec == 0) {
909 *cur_formspec = new GUIFormSpecMenu(device, joystick,
910 guiroot, -1, &g_menumgr, client, client->getTextureSource(),
912 (*cur_formspec)->doPause = false;
915 Caution: do not call (*cur_formspec)->drop() here --
916 the reference might outlive the menu, so we will
917 periodically check if *cur_formspec is the only
918 remaining reference (i.e. the menu was removed)
919 and delete it in that case.
923 (*cur_formspec)->setFormSource(fs_src);
924 (*cur_formspec)->setTextDest(txt_dest);
930 #define SIZE_TAG "size[11,5.5]"
932 #define SIZE_TAG "size[11,5.5,true]" // Fixed size on desktop
935 /******************************************************************************/
936 static void updateChat(Client &client, f32 dtime, bool show_debug,
937 const v2u32 &screensize, bool show_chat, u32 show_profiler,
938 ChatBackend &chat_backend, gui::IGUIStaticText *guitext_chat)
940 // Add chat log output for errors to be shown in chat
941 static LogOutputBuffer chat_log_error_buf(g_logger, LL_ERROR);
943 // Get new messages from error log buffer
944 while (!chat_log_error_buf.empty()) {
945 std::wstring error_message = utf8_to_wide(chat_log_error_buf.get());
946 if (!g_settings->getBool("disable_escape_sequences")) {
947 error_message = L"\x1b(c@red)" + error_message + L"\x1b(c@white)";
949 chat_backend.addMessage(L"", error_message);
952 // Get new messages from client
953 std::wstring message;
955 while (client.getChatMessage(message)) {
956 chat_backend.addUnparsedMessage(message);
959 // Remove old messages
960 chat_backend.step(dtime);
962 // Display all messages in a static text element
963 unsigned int recent_chat_count = chat_backend.getRecentBuffer().getLineCount();
964 EnrichedString recent_chat = chat_backend.getRecentChat();
965 unsigned int line_height = g_fontengine->getLineHeight();
967 setStaticText(guitext_chat, recent_chat);
969 // Update gui element size and position
973 chat_y += 2 * line_height;
975 // first pass to calculate height of text to be set
976 s32 width = std::min(g_fontengine->getTextWidth(recent_chat.c_str()) + 10,
977 porting::getWindowSize().X - 20);
978 core::rect<s32> rect(10, chat_y, width, chat_y + porting::getWindowSize().Y);
979 guitext_chat->setRelativePosition(rect);
981 //now use real height of text and adjust rect according to this size
982 rect = core::rect<s32>(10, chat_y, width,
983 chat_y + guitext_chat->getTextHeight());
986 guitext_chat->setRelativePosition(rect);
987 // Don't show chat if disabled or empty or profiler is enabled
988 guitext_chat->setVisible(
989 show_chat && recent_chat_count != 0 && !show_profiler);
993 /****************************************************************************
994 Fast key cache for main game loop
995 ****************************************************************************/
997 /* This is faster than using getKeySetting with the tradeoff that functions
998 * using it must make sure that it's initialised before using it and there is
999 * no error handling (for example bounds checking). This is really intended for
1000 * use only in the main running loop of the client (the_game()) where the faster
1001 * (up to 10x faster) key lookup is an asset. Other parts of the codebase
1002 * (e.g. formspecs) should continue using getKeySetting().
1010 populate_nonchanging();
1015 // Keys that are not settings dependent
1016 void populate_nonchanging();
1018 KeyPress key[KeyType::INTERNAL_ENUM_COUNT];
1019 InputHandler *handler;
1022 void KeyCache::populate_nonchanging()
1024 key[KeyType::ESC] = EscapeKey;
1027 void KeyCache::populate()
1029 key[KeyType::FORWARD] = getKeySetting("keymap_forward");
1030 key[KeyType::BACKWARD] = getKeySetting("keymap_backward");
1031 key[KeyType::LEFT] = getKeySetting("keymap_left");
1032 key[KeyType::RIGHT] = getKeySetting("keymap_right");
1033 key[KeyType::JUMP] = getKeySetting("keymap_jump");
1034 key[KeyType::SPECIAL1] = getKeySetting("keymap_special1");
1035 key[KeyType::SNEAK] = getKeySetting("keymap_sneak");
1037 key[KeyType::AUTORUN] = getKeySetting("keymap_autorun");
1039 key[KeyType::DROP] = getKeySetting("keymap_drop");
1040 key[KeyType::INVENTORY] = getKeySetting("keymap_inventory");
1041 key[KeyType::CHAT] = getKeySetting("keymap_chat");
1042 key[KeyType::CMD] = getKeySetting("keymap_cmd");
1043 key[KeyType::CMD_LOCAL] = getKeySetting("keymap_cmd_local");
1044 key[KeyType::CONSOLE] = getKeySetting("keymap_console");
1045 key[KeyType::MINIMAP] = getKeySetting("keymap_minimap");
1046 key[KeyType::FREEMOVE] = getKeySetting("keymap_freemove");
1047 key[KeyType::FASTMOVE] = getKeySetting("keymap_fastmove");
1048 key[KeyType::NOCLIP] = getKeySetting("keymap_noclip");
1049 key[KeyType::CINEMATIC] = getKeySetting("keymap_cinematic");
1050 key[KeyType::SCREENSHOT] = getKeySetting("keymap_screenshot");
1051 key[KeyType::TOGGLE_HUD] = getKeySetting("keymap_toggle_hud");
1052 key[KeyType::TOGGLE_CHAT] = getKeySetting("keymap_toggle_chat");
1053 key[KeyType::TOGGLE_FORCE_FOG_OFF]
1054 = getKeySetting("keymap_toggle_force_fog_off");
1055 key[KeyType::TOGGLE_UPDATE_CAMERA]
1056 = getKeySetting("keymap_toggle_update_camera");
1057 key[KeyType::TOGGLE_DEBUG]
1058 = getKeySetting("keymap_toggle_debug");
1059 key[KeyType::TOGGLE_PROFILER]
1060 = getKeySetting("keymap_toggle_profiler");
1061 key[KeyType::CAMERA_MODE]
1062 = getKeySetting("keymap_camera_mode");
1063 key[KeyType::INCREASE_VIEWING_RANGE]
1064 = getKeySetting("keymap_increase_viewing_range_min");
1065 key[KeyType::DECREASE_VIEWING_RANGE]
1066 = getKeySetting("keymap_decrease_viewing_range_min");
1067 key[KeyType::RANGESELECT]
1068 = getKeySetting("keymap_rangeselect");
1069 key[KeyType::ZOOM] = getKeySetting("keymap_zoom");
1071 key[KeyType::QUICKTUNE_NEXT] = getKeySetting("keymap_quicktune_next");
1072 key[KeyType::QUICKTUNE_PREV] = getKeySetting("keymap_quicktune_prev");
1073 key[KeyType::QUICKTUNE_INC] = getKeySetting("keymap_quicktune_inc");
1074 key[KeyType::QUICKTUNE_DEC] = getKeySetting("keymap_quicktune_dec");
1076 key[KeyType::DEBUG_STACKS] = getKeySetting("keymap_print_debug_stacks");
1079 // First clear all keys, then re-add the ones we listen for
1080 handler->dontListenForKeys();
1081 for (size_t i = 0; i < KeyType::INTERNAL_ENUM_COUNT; i++) {
1082 handler->listenForKey(key[i]);
1084 handler->listenForKey(EscapeKey);
1085 handler->listenForKey(CancelKey);
1086 for (size_t i = 0; i < 10; i++) {
1087 handler->listenForKey(NumberKey[i]);
1093 /****************************************************************************
1095 ****************************************************************************/
1097 const float object_hit_delay = 0.2;
1100 u32 last_time, busy_time, sleep_time;
1104 /* The reason the following structs are not anonymous structs within the
1105 * class is that they are not used by the majority of member functions and
1106 * many functions that do require objects of thse types do not modify them
1107 * (so they can be passed as a const qualified parameter)
1109 struct CameraOrientation {
1110 f32 camera_yaw; // "right/left"
1111 f32 camera_pitch; // "up/down"
1114 struct GameRunData {
1117 PointedThing pointed_old;
1121 bool update_wielded_item_trigger;
1122 bool reset_jump_timer;
1123 float nodig_delay_timer;
1125 float dig_time_complete;
1126 float repeat_rightclick_timer;
1127 float object_hit_delay_timer;
1128 float time_from_last_punch;
1129 ClientActiveObject *selected_object;
1133 float update_draw_list_timer;
1134 float statustext_time;
1138 v3f update_draw_list_last_cam_dir;
1140 u32 profiler_current_page;
1141 u32 profiler_max_page; // Number of pages
1144 float time_of_day_smooth;
1148 f32 max, min, avg, counter, max_sample, min_sample, max_fraction;
1154 Jitter dtime_jitter, busy_time_jitter;
1157 /****************************************************************************
1159 ****************************************************************************/
1161 /* This is not intended to be a public class. If a public class becomes
1162 * desirable then it may be better to create another 'wrapper' class that
1163 * hides most of the stuff in this class (nothing in this class is required
1164 * by any other file) but exposes the public methods/data only.
1171 bool startup(bool *kill,
1173 InputHandler *input,
1174 IrrlichtDevice *device,
1175 const std::string &map_dir,
1176 const std::string &playername,
1177 const std::string &password,
1178 // If address is "", local server is used and address is updated
1179 std::string *address,
1181 std::string &error_message,
1183 ChatBackend *chat_backend,
1184 const SubgameSpec &gamespec, // Used for local game
1185 bool simple_singleplayer_mode);
1192 void extendedResourceCleanup();
1194 // Basic initialisation
1195 bool init(const std::string &map_dir, std::string *address,
1197 const SubgameSpec &gamespec);
1199 bool createSingleplayerServer(const std::string &map_dir,
1200 const SubgameSpec &gamespec, u16 port, std::string *address);
1203 bool createClient(const std::string &playername,
1204 const std::string &password, std::string *address, u16 port);
1207 // Client connection
1208 bool connectToServer(const std::string &playername,
1209 const std::string &password, std::string *address, u16 port,
1210 bool *connect_ok, bool *aborted);
1211 bool getServerContent(bool *aborted);
1215 void updateInteractTimers(f32 dtime);
1216 bool checkConnection();
1217 bool handleCallbacks();
1218 void processQueues();
1219 void updateProfilers(const RunStats &stats, const FpsControl &draw_times, f32 dtime);
1220 void addProfilerGraphs(const RunStats &stats, const FpsControl &draw_times, f32 dtime);
1221 void updateStats(RunStats *stats, const FpsControl &draw_times, f32 dtime);
1224 void processUserInput(f32 dtime);
1225 void processKeyInput();
1226 void processItemSelection(u16 *new_playeritem);
1228 void dropSelectedItem();
1229 void openInventory();
1230 void openConsole(float scale, const wchar_t *line=NULL);
1231 void toggleFreeMove();
1232 void toggleFreeMoveAlt();
1234 void toggleNoClip();
1235 void toggleCinematic();
1236 void toggleAutorun();
1240 void toggleMinimap(bool shift_pressed);
1243 void toggleUpdateCamera();
1244 void toggleProfiler();
1246 void increaseViewRange();
1247 void decreaseViewRange();
1248 void toggleFullViewRange();
1250 void updateCameraDirection(CameraOrientation *cam, float dtime);
1251 void updateCameraOrientation(CameraOrientation *cam, float dtime);
1252 void updatePlayerControl(const CameraOrientation &cam);
1253 void step(f32 *dtime);
1254 void processClientEvents(CameraOrientation *cam);
1255 void updateCamera(u32 busy_time, f32 dtime);
1256 void updateSound(f32 dtime);
1257 void processPlayerInteraction(f32 dtime, bool show_hud, bool show_debug);
1259 * Returns the object or node the player is pointing at.
1260 * Also updates the selected thing in the Hud.
1262 * @param[in] shootline the shootline, starting from
1263 * the camera position. This also gives the maximal distance
1265 * @param[in] liquids_pointable if false, liquids are ignored
1266 * @param[in] look_for_object if false, objects are ignored
1267 * @param[in] camera_offset offset of the camera
1268 * @param[out] selected_object the selected object or
1271 PointedThing updatePointedThing(
1272 const core::line3d<f32> &shootline, bool liquids_pointable,
1273 bool look_for_object, const v3s16 &camera_offset);
1274 void handlePointingAtNothing(const ItemStack &playerItem);
1275 void handlePointingAtNode(const PointedThing &pointed, const ItemDefinition &playeritem_def,
1276 const ToolCapabilities &playeritem_toolcap, f32 dtime);
1277 void handlePointingAtObject(const PointedThing &pointed, const ItemStack &playeritem,
1278 const v3f &player_position, bool show_debug);
1279 void handleDigging(const PointedThing &pointed, const v3s16 &nodepos,
1280 const ToolCapabilities &playeritem_toolcap, f32 dtime);
1281 void updateFrame(ProfilerGraph *graph, RunStats *stats, f32 dtime,
1282 const CameraOrientation &cam);
1283 void updateGui(const RunStats &stats, f32 dtime, const CameraOrientation &cam);
1284 void updateProfilerGraphs(ProfilerGraph *graph);
1287 void limitFps(FpsControl *fps_timings, f32 *dtime);
1289 void showOverlayMessage(const wchar_t *msg, float dtime, int percent,
1290 bool draw_clouds = true);
1292 static void settingChangedCallback(const std::string &setting_name, void *data);
1293 void readSettings();
1295 inline bool getLeftClicked()
1297 return input->getLeftClicked() ||
1298 input->joystick.getWasKeyDown(KeyType::MOUSE_L);
1300 inline bool getRightClicked()
1302 return input->getRightClicked() ||
1303 input->joystick.getWasKeyDown(KeyType::MOUSE_R);
1305 inline bool isLeftPressed()
1307 return input->getLeftState() ||
1308 input->joystick.isKeyDown(KeyType::MOUSE_L);
1310 inline bool isRightPressed()
1312 return input->getRightState() ||
1313 input->joystick.isKeyDown(KeyType::MOUSE_R);
1315 inline bool getLeftReleased()
1317 return input->getLeftReleased() ||
1318 input->joystick.wasKeyReleased(KeyType::MOUSE_L);
1321 inline bool isKeyDown(GameKeyType k)
1323 return input->isKeyDown(keycache.key[k]) || input->joystick.isKeyDown(k);
1325 inline bool wasKeyDown(GameKeyType k)
1327 return input->wasKeyDown(keycache.key[k]) || input->joystick.wasKeyDown(k);
1331 void handleAndroidChatInput();
1335 void showPauseMenu();
1337 InputHandler *input;
1342 IWritableTextureSource *texture_src;
1343 IWritableShaderSource *shader_src;
1345 // When created, these will be filled with data received from the server
1346 IWritableItemDefManager *itemdef_manager;
1347 IWritableNodeDefManager *nodedef_manager;
1349 GameOnDemandSoundFetcher soundfetcher; // useful when testing
1350 ISoundManager *sound;
1351 bool sound_is_dummy;
1352 SoundMaker *soundmaker;
1354 ChatBackend *chat_backend;
1356 GUIFormSpecMenu *current_formspec;
1357 //default: "". If other than "", empty show_formspec packets will only close the formspec when the formname matches
1358 std::string cur_formname;
1360 EventManager *eventmgr;
1361 QuicktuneShortcutter *quicktune;
1363 GUIChatConsole *gui_chat_console; // Free using ->Drop()
1364 MapDrawControl *draw_control;
1366 Clouds *clouds; // Free using ->Drop()
1367 Sky *sky; // Free using ->Drop()
1368 Inventory *local_inventory;
1372 GameRunData runData;
1376 This class does take ownership/responsibily for cleaning up etc of any of
1377 these items (e.g. device)
1379 IrrlichtDevice *device;
1380 video::IVideoDriver *driver;
1381 scene::ISceneManager *smgr;
1383 std::string *error_message;
1384 bool *reconnect_requested;
1385 scene::ISceneNode *skybox;
1388 bool simple_singleplayer_mode;
1391 /* Pre-calculated values
1393 int crack_animation_length;
1397 gui::IGUIStaticText *guitext; // First line of debug text
1398 gui::IGUIStaticText *guitext2; // Second line of debug text
1399 gui::IGUIStaticText *guitext_info; // At the middle of the screen
1400 gui::IGUIStaticText *guitext_status;
1401 gui::IGUIStaticText *guitext_chat; // Chat text
1402 gui::IGUIStaticText *guitext_profiler; // Profiler text
1404 std::wstring infotext;
1405 std::wstring m_statustext;
1409 IntervalLimiter profiler_interval;
1412 * TODO: Local caching of settings is not optimal and should at some stage
1413 * be updated to use a global settings object for getting thse values
1414 * (as opposed to the this local caching). This can be addressed in
1417 bool m_cache_doubletap_jump;
1418 bool m_cache_enable_clouds;
1419 bool m_cache_enable_joysticks;
1420 bool m_cache_enable_particles;
1421 bool m_cache_enable_fog;
1422 bool m_cache_enable_noclip;
1423 bool m_cache_enable_free_move;
1424 f32 m_cache_mouse_sensitivity;
1425 f32 m_cache_joystick_frustum_sensitivity;
1426 f32 m_repeat_right_click_time;
1427 f32 m_cache_cam_smoothing;
1428 f32 m_cache_fog_start;
1430 bool m_invert_mouse;
1431 bool m_first_loop_after_window_activation;
1432 bool m_camera_offset_changed;
1435 bool m_cache_hold_aux1;
1436 bool m_android_chat_open;
1445 itemdef_manager(NULL),
1446 nodedef_manager(NULL),
1448 sound_is_dummy(false),
1451 current_formspec(NULL),
1455 gui_chat_console(NULL),
1460 local_inventory(NULL),
1463 m_invert_mouse(false),
1464 m_first_loop_after_window_activation(false),
1465 m_camera_offset_changed(false)
1467 g_settings->registerChangedCallback("doubletap_jump",
1468 &settingChangedCallback, this);
1469 g_settings->registerChangedCallback("enable_clouds",
1470 &settingChangedCallback, this);
1471 g_settings->registerChangedCallback("doubletap_joysticks",
1472 &settingChangedCallback, this);
1473 g_settings->registerChangedCallback("enable_particles",
1474 &settingChangedCallback, this);
1475 g_settings->registerChangedCallback("enable_fog",
1476 &settingChangedCallback, this);
1477 g_settings->registerChangedCallback("mouse_sensitivity",
1478 &settingChangedCallback, this);
1479 g_settings->registerChangedCallback("joystick_frustum_sensitivity",
1480 &settingChangedCallback, this);
1481 g_settings->registerChangedCallback("repeat_rightclick_time",
1482 &settingChangedCallback, this);
1483 g_settings->registerChangedCallback("noclip",
1484 &settingChangedCallback, this);
1485 g_settings->registerChangedCallback("free_move",
1486 &settingChangedCallback, this);
1487 g_settings->registerChangedCallback("cinematic",
1488 &settingChangedCallback, this);
1489 g_settings->registerChangedCallback("cinematic_camera_smoothing",
1490 &settingChangedCallback, this);
1491 g_settings->registerChangedCallback("camera_smoothing",
1492 &settingChangedCallback, this);
1497 m_cache_hold_aux1 = false; // This is initialised properly later
1504 /****************************************************************************
1506 ****************************************************************************/
1512 if (!sound_is_dummy)
1515 delete server; // deleted first to stop all server threads
1518 delete local_inventory;
1524 delete nodedef_manager;
1525 delete itemdef_manager;
1526 delete draw_control;
1528 extendedResourceCleanup();
1530 g_settings->deregisterChangedCallback("doubletap_jump",
1531 &settingChangedCallback, this);
1532 g_settings->deregisterChangedCallback("enable_clouds",
1533 &settingChangedCallback, this);
1534 g_settings->deregisterChangedCallback("enable_particles",
1535 &settingChangedCallback, this);
1536 g_settings->deregisterChangedCallback("enable_fog",
1537 &settingChangedCallback, this);
1538 g_settings->deregisterChangedCallback("mouse_sensitivity",
1539 &settingChangedCallback, this);
1540 g_settings->deregisterChangedCallback("repeat_rightclick_time",
1541 &settingChangedCallback, this);
1542 g_settings->deregisterChangedCallback("noclip",
1543 &settingChangedCallback, this);
1544 g_settings->deregisterChangedCallback("free_move",
1545 &settingChangedCallback, this);
1546 g_settings->deregisterChangedCallback("cinematic",
1547 &settingChangedCallback, this);
1548 g_settings->deregisterChangedCallback("cinematic_camera_smoothing",
1549 &settingChangedCallback, this);
1550 g_settings->deregisterChangedCallback("camera_smoothing",
1551 &settingChangedCallback, this);
1554 bool Game::startup(bool *kill,
1556 InputHandler *input,
1557 IrrlichtDevice *device,
1558 const std::string &map_dir,
1559 const std::string &playername,
1560 const std::string &password,
1561 std::string *address, // can change if simple_singleplayer_mode
1563 std::string &error_message,
1565 ChatBackend *chat_backend,
1566 const SubgameSpec &gamespec,
1567 bool simple_singleplayer_mode)
1570 this->device = device;
1572 this->error_message = &error_message;
1573 this->reconnect_requested = reconnect;
1574 this->random_input = random_input;
1575 this->input = input;
1576 this->chat_backend = chat_backend;
1577 this->simple_singleplayer_mode = simple_singleplayer_mode;
1579 keycache.handler = input;
1580 keycache.populate();
1582 driver = device->getVideoDriver();
1583 smgr = device->getSceneManager();
1585 smgr->getParameters()->setAttribute(scene::OBJ_LOADER_IGNORE_MATERIAL_FILES, true);
1587 memset(&runData, 0, sizeof(runData));
1588 runData.time_from_last_punch = 10.0;
1589 runData.profiler_max_page = 3;
1590 runData.update_wielded_item_trigger = true;
1592 memset(&flags, 0, sizeof(flags));
1593 flags.show_chat = true;
1594 flags.show_hud = true;
1595 flags.show_debug = g_settings->getBool("show_debug");
1596 m_invert_mouse = g_settings->getBool("invert_mouse");
1597 m_first_loop_after_window_activation = true;
1599 if (!init(map_dir, address, port, gamespec))
1602 if (!createClient(playername, password, address, port))
1611 ProfilerGraph graph;
1612 RunStats stats = { 0 };
1613 CameraOrientation cam_view_target = { 0 };
1614 CameraOrientation cam_view = { 0 };
1615 FpsControl draw_times = { 0 };
1616 f32 dtime; // in seconds
1618 /* Clear the profiler */
1619 Profiler::GraphValues dummyvalues;
1620 g_profiler->graphGet(dummyvalues);
1622 draw_times.last_time = device->getTimer()->getTime();
1624 set_light_table(g_settings->getFloat("display_gamma"));
1627 m_cache_hold_aux1 = g_settings->getBool("fast_move")
1628 && client->checkPrivilege("fast");
1631 while (device->run()
1632 && !(*kill || g_gamecallback->shutdown_requested
1633 || (server && server->getShutdownRequested()))) {
1635 /* Must be called immediately after a device->run() call because it
1636 * uses device->getTimer()->getTime()
1638 limitFps(&draw_times, &dtime);
1640 updateStats(&stats, draw_times, dtime);
1641 updateInteractTimers(dtime);
1643 if (!checkConnection())
1645 if (!handleCallbacks())
1651 hud->resizeHotbar();
1653 updateProfilers(stats, draw_times, dtime);
1654 processUserInput(dtime);
1655 // Update camera before player movement to avoid camera lag of one frame
1656 updateCameraDirection(&cam_view_target, dtime);
1657 cam_view.camera_yaw += (cam_view_target.camera_yaw -
1658 cam_view.camera_yaw) * m_cache_cam_smoothing;
1659 cam_view.camera_pitch += (cam_view_target.camera_pitch -
1660 cam_view.camera_pitch) * m_cache_cam_smoothing;
1661 updatePlayerControl(cam_view);
1663 processClientEvents(&cam_view_target);
1664 updateCamera(draw_times.busy_time, dtime);
1666 processPlayerInteraction(dtime, flags.show_hud, flags.show_debug);
1667 updateFrame(&graph, &stats, dtime, cam_view);
1668 updateProfilerGraphs(&graph);
1670 // Update if minimap has been disabled by the server
1671 flags.show_minimap &= client->shouldShowMinimap();
1676 void Game::shutdown()
1678 #if IRRLICHT_VERSION_MAJOR == 1 && IRRLICHT_VERSION_MINOR <= 8
1679 if (g_settings->get("3d_mode") == "pageflip") {
1680 driver->setRenderTarget(irr::video::ERT_STEREO_BOTH_BUFFERS);
1684 showOverlayMessage(wgettext("Shutting down..."), 0, 0, false);
1689 if (gui_chat_console)
1690 gui_chat_console->drop();
1696 while (g_menumgr.menuCount() > 0) {
1697 g_menumgr.m_stack.front()->setVisible(false);
1698 g_menumgr.deletingMenu(g_menumgr.m_stack.front());
1701 if (current_formspec) {
1702 current_formspec->drop();
1703 current_formspec = NULL;
1706 chat_backend->addMessage(L"", L"# Disconnected.");
1707 chat_backend->addMessage(L"", L"");
1711 while (!client->isShutdown()) {
1712 assert(texture_src != NULL);
1713 assert(shader_src != NULL);
1714 texture_src->processQueue();
1715 shader_src->processQueue();
1722 /****************************************************************************/
1723 /****************************************************************************
1725 ****************************************************************************/
1726 /****************************************************************************/
1729 const std::string &map_dir,
1730 std::string *address,
1732 const SubgameSpec &gamespec)
1734 texture_src = createTextureSource(device);
1736 showOverlayMessage(wgettext("Loading..."), 0, 0);
1738 shader_src = createShaderSource(device);
1740 itemdef_manager = createItemDefManager();
1741 nodedef_manager = createNodeDefManager();
1743 eventmgr = new EventManager();
1744 quicktune = new QuicktuneShortcutter();
1746 if (!(texture_src && shader_src && itemdef_manager && nodedef_manager
1747 && eventmgr && quicktune))
1753 // Create a server if not connecting to an existing one
1754 if (*address == "") {
1755 if (!createSingleplayerServer(map_dir, gamespec, port, address))
1762 bool Game::initSound()
1765 if (g_settings->getBool("enable_sound")) {
1766 infostream << "Attempting to use OpenAL audio" << std::endl;
1767 sound = createOpenALSoundManager(&soundfetcher);
1769 infostream << "Failed to initialize OpenAL audio" << std::endl;
1771 infostream << "Sound disabled." << std::endl;
1775 infostream << "Using dummy audio." << std::endl;
1776 sound = &dummySoundManager;
1777 sound_is_dummy = true;
1780 soundmaker = new SoundMaker(sound, nodedef_manager);
1784 soundmaker->registerReceiver(eventmgr);
1789 bool Game::createSingleplayerServer(const std::string &map_dir,
1790 const SubgameSpec &gamespec, u16 port, std::string *address)
1792 showOverlayMessage(wgettext("Creating server..."), 0, 5);
1794 std::string bind_str = g_settings->get("bind_address");
1795 Address bind_addr(0, 0, 0, 0, port);
1797 if (g_settings->getBool("ipv6_server")) {
1798 bind_addr.setAddress((IPv6AddressBytes *) NULL);
1802 bind_addr.Resolve(bind_str.c_str());
1803 } catch (ResolveError &e) {
1804 infostream << "Resolving bind address \"" << bind_str
1805 << "\" failed: " << e.what()
1806 << " -- Listening on all addresses." << std::endl;
1809 if (bind_addr.isIPv6() && !g_settings->getBool("enable_ipv6")) {
1810 *error_message = "Unable to listen on " +
1811 bind_addr.serializeString() +
1812 " because IPv6 is disabled";
1813 errorstream << *error_message << std::endl;
1817 server = new Server(map_dir, gamespec, simple_singleplayer_mode,
1818 bind_addr.isIPv6(), false);
1820 server->start(bind_addr);
1825 bool Game::createClient(const std::string &playername,
1826 const std::string &password, std::string *address, u16 port)
1828 showOverlayMessage(wgettext("Creating client..."), 0, 10);
1830 draw_control = new MapDrawControl;
1834 bool could_connect, connect_aborted;
1836 if (!connectToServer(playername, password, address, port,
1837 &could_connect, &connect_aborted))
1840 if (!could_connect) {
1841 if (error_message->empty() && !connect_aborted) {
1842 // Should not happen if error messages are set properly
1843 *error_message = "Connection failed for unknown reason";
1844 errorstream << *error_message << std::endl;
1849 if (!getServerContent(&connect_aborted)) {
1850 if (error_message->empty() && !connect_aborted) {
1851 // Should not happen if error messages are set properly
1852 *error_message = "Connection failed for unknown reason";
1853 errorstream << *error_message << std::endl;
1858 GameGlobalShaderConstantSetterFactory *scsf = new GameGlobalShaderConstantSetterFactory(
1859 &flags.force_fog_off, &runData.fog_range, client);
1860 shader_src->addShaderConstantSetterFactory(scsf);
1862 // Update cached textures, meshes and materials
1863 client->afterContentReceived(device);
1867 camera = new Camera(smgr, *draw_control, client);
1868 if (!camera || !camera->successfullyCreated(*error_message))
1870 client->setCamera(camera);
1874 if (m_cache_enable_clouds) {
1875 clouds = new Clouds(smgr->getRootSceneNode(), smgr, -1, time(0));
1877 *error_message = "Memory allocation error (clouds)";
1878 errorstream << *error_message << std::endl;
1885 sky = new Sky(smgr->getRootSceneNode(), smgr, -1, texture_src);
1887 skybox = NULL; // This is used/set later on in the main run loop
1889 local_inventory = new Inventory(itemdef_manager);
1891 if (!(sky && local_inventory)) {
1892 *error_message = "Memory allocation error (sky or local inventory)";
1893 errorstream << *error_message << std::endl;
1897 /* Pre-calculated values
1899 video::ITexture *t = texture_src->getTexture("crack_anylength.png");
1901 v2u32 size = t->getOriginalSize();
1902 crack_animation_length = size.Y / size.X;
1904 crack_animation_length = 5;
1910 /* Set window caption
1912 std::wstring str = utf8_to_wide(PROJECT_NAME_C);
1914 str += utf8_to_wide(g_version_hash);
1916 str += driver->getName();
1918 device->setWindowCaption(str.c_str());
1920 LocalPlayer *player = client->getEnv().getLocalPlayer();
1921 player->hurt_tilt_timer = 0;
1922 player->hurt_tilt_strength = 0;
1924 hud = new Hud(driver, smgr, guienv, client, player, local_inventory);
1927 *error_message = "Memory error: could not create HUD";
1928 errorstream << *error_message << std::endl;
1932 mapper = client->getMinimap();
1933 mapper->setMinimapMode(MINIMAP_MODE_OFF);
1938 bool Game::initGui()
1940 // First line of debug text
1941 guitext = addStaticText(guienv,
1942 utf8_to_wide(PROJECT_NAME_C).c_str(),
1943 core::rect<s32>(0, 0, 0, 0),
1944 false, false, guiroot);
1946 // Second line of debug text
1947 guitext2 = addStaticText(guienv,
1949 core::rect<s32>(0, 0, 0, 0),
1950 false, false, guiroot);
1952 // At the middle of the screen
1953 // Object infos are shown in this
1954 guitext_info = addStaticText(guienv,
1956 core::rect<s32>(0, 0, 400, g_fontengine->getTextHeight() * 5 + 5) + v2s32(100, 200),
1957 false, true, guiroot);
1959 // Status text (displays info when showing and hiding GUI stuff, etc.)
1960 guitext_status = addStaticText(guienv,
1962 core::rect<s32>(0, 0, 0, 0),
1963 false, false, guiroot);
1964 guitext_status->setVisible(false);
1967 guitext_chat = addStaticText(
1970 core::rect<s32>(0, 0, 0, 0),
1971 //false, false); // Disable word wrap as of now
1972 false, true, guiroot);
1974 // Remove stale "recent" chat messages from previous connections
1975 chat_backend->clearRecentChat();
1977 // Chat backend and console
1978 gui_chat_console = new GUIChatConsole(guienv, guienv->getRootGUIElement(),
1979 -1, chat_backend, client, &g_menumgr);
1980 if (!gui_chat_console) {
1981 *error_message = "Could not allocate memory for chat console";
1982 errorstream << *error_message << std::endl;
1986 // Profiler text (size is updated when text is updated)
1987 guitext_profiler = addStaticText(guienv,
1989 core::rect<s32>(0, 0, 0, 0),
1990 false, false, guiroot);
1991 guitext_profiler->setBackgroundColor(video::SColor(120, 0, 0, 0));
1992 guitext_profiler->setVisible(false);
1993 guitext_profiler->setWordWrap(true);
1995 #ifdef HAVE_TOUCHSCREENGUI
1997 if (g_touchscreengui)
1998 g_touchscreengui->init(texture_src);
2005 bool Game::connectToServer(const std::string &playername,
2006 const std::string &password, std::string *address, u16 port,
2007 bool *connect_ok, bool *aborted)
2009 *connect_ok = false; // Let's not be overly optimistic
2011 bool local_server_mode = false;
2013 showOverlayMessage(wgettext("Resolving address..."), 0, 15);
2015 Address connect_address(0, 0, 0, 0, port);
2018 connect_address.Resolve(address->c_str());
2020 if (connect_address.isZero()) { // i.e. INADDR_ANY, IN6ADDR_ANY
2021 //connect_address.Resolve("localhost");
2022 if (connect_address.isIPv6()) {
2023 IPv6AddressBytes addr_bytes;
2024 addr_bytes.bytes[15] = 1;
2025 connect_address.setAddress(&addr_bytes);
2027 connect_address.setAddress(127, 0, 0, 1);
2029 local_server_mode = true;
2031 } catch (ResolveError &e) {
2032 *error_message = std::string("Couldn't resolve address: ") + e.what();
2033 errorstream << *error_message << std::endl;
2037 if (connect_address.isIPv6() && !g_settings->getBool("enable_ipv6")) {
2038 *error_message = "Unable to connect to " +
2039 connect_address.serializeString() +
2040 " because IPv6 is disabled";
2041 errorstream << *error_message << std::endl;
2045 client = new Client(device,
2046 playername.c_str(), password,
2047 *draw_control, texture_src, shader_src,
2048 itemdef_manager, nodedef_manager, sound, eventmgr,
2049 connect_address.isIPv6(), &flags);
2054 infostream << "Connecting to server at ";
2055 connect_address.print(&infostream);
2056 infostream << std::endl;
2058 client->connect(connect_address, *address,
2059 simple_singleplayer_mode || local_server_mode);
2062 Wait for server to accept connection
2068 FpsControl fps_control = { 0 };
2070 f32 wait_time = 0; // in seconds
2072 fps_control.last_time = device->getTimer()->getTime();
2076 while (device->run()) {
2078 limitFps(&fps_control, &dtime);
2080 // Update client and server
2081 client->step(dtime);
2084 server->step(dtime);
2087 if (client->getState() == LC_Init) {
2093 if (client->accessDenied()) {
2094 *error_message = "Access denied. Reason: "
2095 + client->accessDeniedReason();
2096 *reconnect_requested = client->reconnectRequested();
2097 errorstream << *error_message << std::endl;
2101 if (wasKeyDown(KeyType::ESC) || input->wasKeyDown(CancelKey)) {
2103 infostream << "Connect aborted [Escape]" << std::endl;
2108 // Only time out if we aren't waiting for the server we started
2109 if ((*address != "") && (wait_time > 10)) {
2110 bool sent_old_init = g_settings->getFlag("send_pre_v25_init");
2111 // If no pre v25 init was sent, and no answer was received,
2112 // but the low level connection could be established
2113 // (meaning that we have a peer id), then we probably wanted
2114 // to connect to a legacy server. In this case, tell the user
2115 // to enable the option to be able to connect.
2116 if (!sent_old_init &&
2117 (client->getProtoVersion() == 0) &&
2118 client->connectedToServer()) {
2119 *error_message = "Connection failure: init packet not "
2120 "recognized by server.\n"
2121 "Most likely the server uses an old protocol version (<v25).\n"
2122 "Please ask the server owner to update to 0.4.13 or later.\n"
2123 "To still connect to the server in the meantime,\n"
2124 "you can enable the 'send_pre_v25_init' setting by editing minetest.conf,\n"
2125 "or by enabling the 'Client -> Network -> Support older Servers'\n"
2126 "entry in the advanced settings menu.";
2128 *error_message = "Connection timed out.";
2130 errorstream << *error_message << std::endl;
2135 showOverlayMessage(wgettext("Connecting to server..."), dtime, 20);
2137 } catch (con::PeerNotFoundException &e) {
2138 // TODO: Should something be done here? At least an info/error
2146 bool Game::getServerContent(bool *aborted)
2150 FpsControl fps_control = { 0 };
2151 f32 dtime; // in seconds
2153 fps_control.last_time = device->getTimer()->getTime();
2155 while (device->run()) {
2157 limitFps(&fps_control, &dtime);
2159 // Update client and server
2160 client->step(dtime);
2163 server->step(dtime);
2166 if (client->mediaReceived() && client->itemdefReceived() &&
2167 client->nodedefReceived()) {
2172 if (!checkConnection())
2175 if (client->getState() < LC_Init) {
2176 *error_message = "Client disconnected";
2177 errorstream << *error_message << std::endl;
2181 if (wasKeyDown(KeyType::ESC) || input->wasKeyDown(CancelKey)) {
2183 infostream << "Connect aborted [Escape]" << std::endl;
2190 if (!client->itemdefReceived()) {
2191 const wchar_t *text = wgettext("Item definitions...");
2193 draw_load_screen(text, device, guienv, texture_src,
2196 } else if (!client->nodedefReceived()) {
2197 const wchar_t *text = wgettext("Node definitions...");
2199 draw_load_screen(text, device, guienv, texture_src,
2203 std::stringstream message;
2204 std::fixed(message);
2205 message.precision(0);
2206 message << gettext("Media...") << " " << (client->mediaReceiveProgress()*100) << "%";
2207 message.precision(2);
2209 if ((USE_CURL == 0) ||
2210 (!g_settings->getBool("enable_remote_media_server"))) {
2211 float cur = client->getCurRate();
2212 std::string cur_unit = gettext("KiB/s");
2216 cur_unit = gettext("MiB/s");
2219 message << " (" << cur << ' ' << cur_unit << ")";
2222 progress = 30 + client->mediaReceiveProgress() * 35 + 0.5;
2223 draw_load_screen(utf8_to_wide(message.str()), device,
2224 guienv, texture_src, dtime, progress);
2232 /****************************************************************************/
2233 /****************************************************************************
2235 ****************************************************************************/
2236 /****************************************************************************/
2238 inline void Game::updateInteractTimers(f32 dtime)
2240 if (runData.nodig_delay_timer >= 0)
2241 runData.nodig_delay_timer -= dtime;
2243 if (runData.object_hit_delay_timer >= 0)
2244 runData.object_hit_delay_timer -= dtime;
2246 runData.time_from_last_punch += dtime;
2250 /* returns false if game should exit, otherwise true
2252 inline bool Game::checkConnection()
2254 if (client->accessDenied()) {
2255 *error_message = "Access denied. Reason: "
2256 + client->accessDeniedReason();
2257 *reconnect_requested = client->reconnectRequested();
2258 errorstream << *error_message << std::endl;
2266 /* returns false if game should exit, otherwise true
2268 inline bool Game::handleCallbacks()
2270 if (g_gamecallback->disconnect_requested) {
2271 g_gamecallback->disconnect_requested = false;
2275 if (g_gamecallback->changepassword_requested) {
2276 (new GUIPasswordChange(guienv, guiroot, -1,
2277 &g_menumgr, client))->drop();
2278 g_gamecallback->changepassword_requested = false;
2281 if (g_gamecallback->changevolume_requested) {
2282 (new GUIVolumeChange(guienv, guiroot, -1,
2283 &g_menumgr))->drop();
2284 g_gamecallback->changevolume_requested = false;
2287 if (g_gamecallback->keyconfig_requested) {
2288 (new GUIKeyChangeMenu(guienv, guiroot, -1,
2289 &g_menumgr))->drop();
2290 g_gamecallback->keyconfig_requested = false;
2293 if (g_gamecallback->keyconfig_changed) {
2294 keycache.populate(); // update the cache with new settings
2295 g_gamecallback->keyconfig_changed = false;
2302 void Game::processQueues()
2304 texture_src->processQueue();
2305 itemdef_manager->processQueue(client);
2306 shader_src->processQueue();
2310 void Game::updateProfilers(const RunStats &stats, const FpsControl &draw_times, f32 dtime)
2312 float profiler_print_interval =
2313 g_settings->getFloat("profiler_print_interval");
2314 bool print_to_log = true;
2316 if (profiler_print_interval == 0) {
2317 print_to_log = false;
2318 profiler_print_interval = 5;
2321 if (profiler_interval.step(dtime, profiler_print_interval)) {
2323 infostream << "Profiler:" << std::endl;
2324 g_profiler->print(infostream);
2327 update_profiler_gui(guitext_profiler, g_fontengine,
2328 runData.profiler_current_page, runData.profiler_max_page,
2329 driver->getScreenSize().Height);
2331 g_profiler->clear();
2334 addProfilerGraphs(stats, draw_times, dtime);
2338 void Game::addProfilerGraphs(const RunStats &stats,
2339 const FpsControl &draw_times, f32 dtime)
2341 g_profiler->graphAdd("mainloop_other",
2342 draw_times.busy_time / 1000.0f - stats.drawtime / 1000.0f);
2344 if (draw_times.sleep_time != 0)
2345 g_profiler->graphAdd("mainloop_sleep", draw_times.sleep_time / 1000.0f);
2346 g_profiler->graphAdd("mainloop_dtime", dtime);
2348 g_profiler->add("Elapsed time", dtime);
2349 g_profiler->avg("FPS", 1. / dtime);
2353 void Game::updateStats(RunStats *stats, const FpsControl &draw_times,
2360 /* Time average and jitter calculation
2362 jp = &stats->dtime_jitter;
2363 jp->avg = jp->avg * 0.96 + dtime * 0.04;
2365 jitter = dtime - jp->avg;
2367 if (jitter > jp->max)
2370 jp->counter += dtime;
2372 if (jp->counter > 0.0) {
2374 jp->max_sample = jp->max;
2375 jp->max_fraction = jp->max_sample / (jp->avg + 0.001);
2379 /* Busytime average and jitter calculation
2381 jp = &stats->busy_time_jitter;
2382 jp->avg = jp->avg + draw_times.busy_time * 0.02;
2384 jitter = draw_times.busy_time - jp->avg;
2386 if (jitter > jp->max)
2388 if (jitter < jp->min)
2391 jp->counter += dtime;
2393 if (jp->counter > 0.0) {
2395 jp->max_sample = jp->max;
2396 jp->min_sample = jp->min;
2404 /****************************************************************************
2406 ****************************************************************************/
2408 void Game::processUserInput(f32 dtime)
2410 // Reset input if window not active or some menu is active
2411 if (!device->isWindowActive() || !noMenuActive() || guienv->hasFocus(gui_chat_console)) {
2413 #ifdef HAVE_TOUCHSCREENGUI
2414 g_touchscreengui->hide();
2417 #ifdef HAVE_TOUCHSCREENGUI
2418 else if (g_touchscreengui) {
2419 /* on touchscreengui step may generate own input events which ain't
2420 * what we want in case we just did clear them */
2421 g_touchscreengui->step(dtime);
2425 if (!guienv->hasFocus(gui_chat_console) && gui_chat_console->isOpen()) {
2426 gui_chat_console->closeConsoleAtOnce();
2429 // Input handler step() (used by the random input generator)
2433 if (current_formspec != NULL)
2434 current_formspec->getAndroidUIInput();
2436 handleAndroidChatInput();
2439 // Increase timer for double tap of "keymap_jump"
2440 if (m_cache_doubletap_jump && runData.jump_timer <= 0.2f)
2441 runData.jump_timer += dtime;
2444 processItemSelection(&runData.new_playeritem);
2448 void Game::processKeyInput()
2450 if (wasKeyDown(KeyType::DROP)) {
2452 } else if (wasKeyDown(KeyType::AUTORUN)) {
2454 } else if (wasKeyDown(KeyType::INVENTORY)) {
2456 } else if (wasKeyDown(KeyType::ESC) || input->wasKeyDown(CancelKey)) {
2457 if (!gui_chat_console->isOpenInhibited()) {
2460 } else if (wasKeyDown(KeyType::CHAT)) {
2461 openConsole(0.2, L"");
2462 } else if (wasKeyDown(KeyType::CMD)) {
2463 openConsole(0.2, L"/");
2464 } else if (wasKeyDown(KeyType::CMD_LOCAL)) {
2465 openConsole(0.2, L".");
2466 } else if (wasKeyDown(KeyType::CONSOLE)) {
2467 openConsole(core::clamp(g_settings->getFloat("console_height"), 0.1f, 1.0f));
2468 } else if (wasKeyDown(KeyType::FREEMOVE)) {
2470 } else if (wasKeyDown(KeyType::JUMP)) {
2471 toggleFreeMoveAlt();
2472 } else if (wasKeyDown(KeyType::FASTMOVE)) {
2474 } else if (wasKeyDown(KeyType::NOCLIP)) {
2476 } else if (wasKeyDown(KeyType::CINEMATIC)) {
2478 } else if (wasKeyDown(KeyType::SCREENSHOT)) {
2479 client->makeScreenshot(device);
2480 } else if (wasKeyDown(KeyType::TOGGLE_HUD)) {
2482 } else if (wasKeyDown(KeyType::MINIMAP)) {
2483 toggleMinimap(isKeyDown(KeyType::SNEAK));
2484 } else if (wasKeyDown(KeyType::TOGGLE_CHAT)) {
2486 } else if (wasKeyDown(KeyType::TOGGLE_FORCE_FOG_OFF)) {
2488 } else if (wasKeyDown(KeyType::TOGGLE_UPDATE_CAMERA)) {
2489 toggleUpdateCamera();
2490 } else if (wasKeyDown(KeyType::TOGGLE_DEBUG)) {
2492 } else if (wasKeyDown(KeyType::TOGGLE_PROFILER)) {
2494 } else if (wasKeyDown(KeyType::INCREASE_VIEWING_RANGE)) {
2495 increaseViewRange();
2496 } else if (wasKeyDown(KeyType::DECREASE_VIEWING_RANGE)) {
2497 decreaseViewRange();
2498 } else if (wasKeyDown(KeyType::RANGESELECT)) {
2499 toggleFullViewRange();
2500 } else if (wasKeyDown(KeyType::QUICKTUNE_NEXT)) {
2502 } else if (wasKeyDown(KeyType::QUICKTUNE_PREV)) {
2504 } else if (wasKeyDown(KeyType::QUICKTUNE_INC)) {
2506 } else if (wasKeyDown(KeyType::QUICKTUNE_DEC)) {
2508 } else if (wasKeyDown(KeyType::DEBUG_STACKS)) {
2509 // Print debug stacks
2510 dstream << "-----------------------------------------"
2512 dstream << "Printing debug stacks:" << std::endl;
2513 dstream << "-----------------------------------------"
2515 debug_stacks_print();
2518 if (!isKeyDown(KeyType::JUMP) && runData.reset_jump_timer) {
2519 runData.reset_jump_timer = false;
2520 runData.jump_timer = 0.0f;
2523 if (quicktune->hasMessage()) {
2524 m_statustext = utf8_to_wide(quicktune->getMessage());
2525 runData.statustext_time = 0.0f;
2529 void Game::processItemSelection(u16 *new_playeritem)
2531 LocalPlayer *player = client->getEnv().getLocalPlayer();
2533 /* Item selection using mouse wheel
2535 *new_playeritem = client->getPlayerItem();
2537 s32 wheel = input->getMouseWheel();
2538 u16 max_item = MYMIN(PLAYER_INVENTORY_SIZE - 1,
2539 player->hud_hotbar_itemcount - 1);
2543 if (input->joystick.wasKeyDown(KeyType::SCROLL_DOWN)) {
2547 if (input->joystick.wasKeyDown(KeyType::SCROLL_UP)) {
2552 *new_playeritem = *new_playeritem < max_item ? *new_playeritem + 1 : 0;
2554 *new_playeritem = *new_playeritem > 0 ? *new_playeritem - 1 : max_item;
2557 /* Item selection using keyboard
2559 for (u16 i = 0; i < 10; i++) {
2560 static const KeyPress *item_keys[10] = {
2561 NumberKey + 1, NumberKey + 2, NumberKey + 3, NumberKey + 4,
2562 NumberKey + 5, NumberKey + 6, NumberKey + 7, NumberKey + 8,
2563 NumberKey + 9, NumberKey + 0,
2566 if (input->wasKeyDown(*item_keys[i])) {
2567 if (i < PLAYER_INVENTORY_SIZE && i < player->hud_hotbar_itemcount) {
2568 *new_playeritem = i;
2569 infostream << "Selected item: " << new_playeritem << std::endl;
2577 void Game::dropSelectedItem()
2579 IDropAction *a = new IDropAction();
2581 a->from_inv.setCurrentPlayer();
2582 a->from_list = "main";
2583 a->from_i = client->getPlayerItem();
2584 client->inventoryAction(a);
2588 void Game::openInventory()
2591 * Don't permit to open inventory is CAO or player doesn't exists.
2592 * This prevent showing an empty inventory at player load
2595 LocalPlayer *player = client->getEnv().getLocalPlayer();
2596 if (player == NULL || player->getCAO() == NULL)
2599 infostream << "the_game: " << "Launching inventory" << std::endl;
2601 PlayerInventoryFormSource *fs_src = new PlayerInventoryFormSource(client);
2602 TextDest *txt_dst = new TextDestPlayerInventory(client);
2604 create_formspec_menu(¤t_formspec, client, device, &input->joystick, fs_src, txt_dst);
2607 InventoryLocation inventoryloc;
2608 inventoryloc.setCurrentPlayer();
2609 current_formspec->setFormSpec(fs_src->getForm(), inventoryloc);
2613 void Game::openConsole(float scale, const wchar_t *line)
2615 assert(scale > 0.0f && scale <= 1.0f);
2618 porting::showInputDialog(gettext("ok"), "", "", 2);
2619 m_android_chat_open = true;
2621 if (gui_chat_console->isOpenInhibited())
2623 gui_chat_console->openConsole(scale);
2625 gui_chat_console->setCloseOnEnter(true);
2626 gui_chat_console->replaceAndAddToHistory(line);
2632 void Game::handleAndroidChatInput()
2634 if (m_android_chat_open && porting::getInputDialogState() == 0) {
2635 std::string text = porting::getInputDialogValue();
2636 client->typeChatMessage(utf8_to_wide(text));
2642 void Game::toggleFreeMove()
2644 static const wchar_t *msg[] = { L"free_move disabled", L"free_move enabled" };
2646 bool free_move = !g_settings->getBool("free_move");
2647 g_settings->set("free_move", bool_to_cstr(free_move));
2649 runData.statustext_time = 0;
2650 m_statustext = msg[free_move];
2651 if (free_move && !client->checkPrivilege("fly"))
2652 m_statustext += L" (note: no 'fly' privilege)";
2656 void Game::toggleFreeMoveAlt()
2658 if (m_cache_doubletap_jump && runData.jump_timer < 0.2f)
2661 runData.reset_jump_timer = true;
2665 void Game::toggleFast()
2667 static const wchar_t *msg[] = { L"fast_move disabled", L"fast_move enabled" };
2668 bool fast_move = !g_settings->getBool("fast_move");
2669 g_settings->set("fast_move", bool_to_cstr(fast_move));
2671 runData.statustext_time = 0;
2672 m_statustext = msg[fast_move];
2674 bool has_fast_privs = client->checkPrivilege("fast");
2676 if (fast_move && !has_fast_privs)
2677 m_statustext += L" (note: no 'fast' privilege)";
2680 m_cache_hold_aux1 = fast_move && has_fast_privs;
2685 void Game::toggleNoClip()
2687 static const wchar_t *msg[] = { L"noclip disabled", L"noclip enabled" };
2688 bool noclip = !g_settings->getBool("noclip");
2689 g_settings->set("noclip", bool_to_cstr(noclip));
2691 runData.statustext_time = 0;
2692 m_statustext = msg[noclip];
2694 if (noclip && !client->checkPrivilege("noclip"))
2695 m_statustext += L" (note: no 'noclip' privilege)";
2698 void Game::toggleCinematic()
2700 static const wchar_t *msg[] = { L"cinematic disabled", L"cinematic enabled" };
2701 bool cinematic = !g_settings->getBool("cinematic");
2702 g_settings->set("cinematic", bool_to_cstr(cinematic));
2704 runData.statustext_time = 0;
2705 m_statustext = msg[cinematic];
2708 // Add WoW-style autorun by toggling continuous forward.
2709 void Game::toggleAutorun()
2711 static const wchar_t *msg[] = { L"autorun disabled", L"autorun enabled" };
2712 bool autorun_enabled = !g_settings->getBool("continuous_forward");
2713 g_settings->set("continuous_forward", bool_to_cstr(autorun_enabled));
2715 runData.statustext_time = 0;
2716 m_statustext = msg[autorun_enabled ? 1 : 0];
2719 void Game::toggleChat()
2721 static const wchar_t *msg[] = { L"Chat hidden", L"Chat shown" };
2723 flags.show_chat = !flags.show_chat;
2724 runData.statustext_time = 0;
2725 m_statustext = msg[flags.show_chat];
2729 void Game::toggleHud()
2731 static const wchar_t *msg[] = { L"HUD hidden", L"HUD shown" };
2733 flags.show_hud = !flags.show_hud;
2734 runData.statustext_time = 0;
2735 m_statustext = msg[flags.show_hud];
2738 void Game::toggleMinimap(bool shift_pressed)
2740 if (!flags.show_hud || !g_settings->getBool("enable_minimap"))
2743 if (shift_pressed) {
2744 mapper->toggleMinimapShape();
2748 u32 hud_flags = client->getEnv().getLocalPlayer()->hud_flags;
2750 MinimapMode mode = MINIMAP_MODE_OFF;
2751 if (hud_flags & HUD_FLAG_MINIMAP_VISIBLE) {
2752 mode = mapper->getMinimapMode();
2753 mode = (MinimapMode)((int)mode + 1);
2756 flags.show_minimap = true;
2758 case MINIMAP_MODE_SURFACEx1:
2759 m_statustext = L"Minimap in surface mode, Zoom x1";
2761 case MINIMAP_MODE_SURFACEx2:
2762 m_statustext = L"Minimap in surface mode, Zoom x2";
2764 case MINIMAP_MODE_SURFACEx4:
2765 m_statustext = L"Minimap in surface mode, Zoom x4";
2767 case MINIMAP_MODE_RADARx1:
2768 m_statustext = L"Minimap in radar mode, Zoom x1";
2770 case MINIMAP_MODE_RADARx2:
2771 m_statustext = L"Minimap in radar mode, Zoom x2";
2773 case MINIMAP_MODE_RADARx4:
2774 m_statustext = L"Minimap in radar mode, Zoom x4";
2777 mode = MINIMAP_MODE_OFF;
2778 flags.show_minimap = false;
2779 m_statustext = (hud_flags & HUD_FLAG_MINIMAP_VISIBLE) ?
2780 L"Minimap hidden" : L"Minimap disabled by server";
2783 runData.statustext_time = 0;
2784 mapper->setMinimapMode(mode);
2787 void Game::toggleFog()
2789 static const wchar_t *msg[] = { L"Fog enabled", L"Fog disabled" };
2791 flags.force_fog_off = !flags.force_fog_off;
2792 runData.statustext_time = 0;
2793 m_statustext = msg[flags.force_fog_off];
2797 void Game::toggleDebug()
2799 // Initial / 4x toggle: Chat only
2800 // 1x toggle: Debug text with chat
2801 // 2x toggle: Debug text with profiler graph
2802 // 3x toggle: Debug text and wireframe
2803 if (!flags.show_debug) {
2804 flags.show_debug = true;
2805 flags.show_profiler_graph = false;
2806 draw_control->show_wireframe = false;
2807 m_statustext = L"Debug info shown";
2808 } else if (!flags.show_profiler_graph && !draw_control->show_wireframe) {
2809 flags.show_profiler_graph = true;
2810 m_statustext = L"Profiler graph shown";
2811 } else if (!draw_control->show_wireframe && client->checkPrivilege("debug")) {
2812 flags.show_profiler_graph = false;
2813 draw_control->show_wireframe = true;
2814 m_statustext = L"Wireframe shown";
2816 flags.show_debug = false;
2817 flags.show_profiler_graph = false;
2818 draw_control->show_wireframe = false;
2819 if (client->checkPrivilege("debug")) {
2820 m_statustext = L"Debug info, profiler graph, and wireframe hidden";
2822 m_statustext = L"Debug info and profiler graph hidden";
2825 runData.statustext_time = 0;
2829 void Game::toggleUpdateCamera()
2831 static const wchar_t *msg[] = {
2832 L"Camera update enabled",
2833 L"Camera update disabled"
2836 flags.disable_camera_update = !flags.disable_camera_update;
2837 runData.statustext_time = 0;
2838 m_statustext = msg[flags.disable_camera_update];
2842 void Game::toggleProfiler()
2844 runData.profiler_current_page =
2845 (runData.profiler_current_page + 1) % (runData.profiler_max_page + 1);
2847 // FIXME: This updates the profiler with incomplete values
2848 update_profiler_gui(guitext_profiler, g_fontengine, runData.profiler_current_page,
2849 runData.profiler_max_page, driver->getScreenSize().Height);
2851 if (runData.profiler_current_page != 0) {
2852 std::wstringstream sstr;
2853 sstr << "Profiler shown (page " << runData.profiler_current_page
2854 << " of " << runData.profiler_max_page << ")";
2855 m_statustext = sstr.str();
2857 m_statustext = L"Profiler hidden";
2859 runData.statustext_time = 0;
2863 void Game::increaseViewRange()
2865 s16 range = g_settings->getS16("viewing_range");
2866 s16 range_new = range + 10;
2868 if (range_new > 4000) {
2870 m_statustext = utf8_to_wide("Viewing range is at maximum: "
2873 m_statustext = utf8_to_wide("Viewing range changed to "
2876 g_settings->set("viewing_range", itos(range_new));
2877 runData.statustext_time = 0;
2881 void Game::decreaseViewRange()
2883 s16 range = g_settings->getS16("viewing_range");
2884 s16 range_new = range - 10;
2886 if (range_new < 20) {
2888 m_statustext = utf8_to_wide("Viewing range is at minimum: "
2891 m_statustext = utf8_to_wide("Viewing range changed to "
2894 g_settings->set("viewing_range", itos(range_new));
2895 runData.statustext_time = 0;
2899 void Game::toggleFullViewRange()
2901 static const wchar_t *msg[] = {
2902 L"Disabled full viewing range",
2903 L"Enabled full viewing range"
2906 draw_control->range_all = !draw_control->range_all;
2907 infostream << msg[draw_control->range_all] << std::endl;
2908 m_statustext = msg[draw_control->range_all];
2909 runData.statustext_time = 0;
2913 void Game::updateCameraDirection(CameraOrientation *cam, float dtime)
2915 if ((device->isWindowActive() && noMenuActive()) || random_input) {
2918 if (!random_input) {
2919 // Mac OSX gets upset if this is set every frame
2920 if (device->getCursorControl()->isVisible())
2921 device->getCursorControl()->setVisible(false);
2925 if (m_first_loop_after_window_activation)
2926 m_first_loop_after_window_activation = false;
2928 updateCameraOrientation(cam, dtime);
2930 input->setMousePos((driver->getScreenSize().Width / 2),
2931 (driver->getScreenSize().Height / 2));
2935 // Mac OSX gets upset if this is set every frame
2936 if (!device->getCursorControl()->isVisible())
2937 device->getCursorControl()->setVisible(true);
2940 if (!m_first_loop_after_window_activation)
2941 m_first_loop_after_window_activation = true;
2946 void Game::updateCameraOrientation(CameraOrientation *cam, float dtime)
2948 #ifdef HAVE_TOUCHSCREENGUI
2949 if (g_touchscreengui) {
2950 cam->camera_yaw += g_touchscreengui->getYawChange();
2951 cam->camera_pitch = g_touchscreengui->getPitch();
2955 s32 dx = input->getMousePos().X - (driver->getScreenSize().Width / 2);
2956 s32 dy = input->getMousePos().Y - (driver->getScreenSize().Height / 2);
2958 if (m_invert_mouse || camera->getCameraMode() == CAMERA_MODE_THIRD_FRONT) {
2962 cam->camera_yaw -= dx * m_cache_mouse_sensitivity;
2963 cam->camera_pitch += dy * m_cache_mouse_sensitivity;
2965 #ifdef HAVE_TOUCHSCREENGUI
2969 if (m_cache_enable_joysticks) {
2970 f32 c = m_cache_joystick_frustum_sensitivity * (1.f / 32767.f) * dtime;
2971 cam->camera_yaw -= input->joystick.getAxisWithoutDead(JA_FRUSTUM_HORIZONTAL) * c;
2972 cam->camera_pitch += input->joystick.getAxisWithoutDead(JA_FRUSTUM_VERTICAL) * c;
2975 cam->camera_pitch = rangelim(cam->camera_pitch, -89.5, 89.5);
2979 void Game::updatePlayerControl(const CameraOrientation &cam)
2981 //TimeTaker tt("update player control", NULL, PRECISION_NANO);
2983 // DO NOT use the isKeyDown method for the forward, backward, left, right
2984 // buttons, as the code that uses the controls needs to be able to
2985 // distinguish between the two in order to know when to use joysticks.
2987 PlayerControl control(
2988 input->isKeyDown(keycache.key[KeyType::FORWARD]),
2989 input->isKeyDown(keycache.key[KeyType::BACKWARD]),
2990 input->isKeyDown(keycache.key[KeyType::LEFT]),
2991 input->isKeyDown(keycache.key[KeyType::RIGHT]),
2992 isKeyDown(KeyType::JUMP),
2993 isKeyDown(KeyType::SPECIAL1),
2994 isKeyDown(KeyType::SNEAK),
2995 isKeyDown(KeyType::ZOOM),
3000 input->joystick.getAxisWithoutDead(JA_SIDEWARD_MOVE),
3001 input->joystick.getAxisWithoutDead(JA_FORWARD_MOVE)
3005 ( (u32)(isKeyDown(KeyType::FORWARD) & 0x1) << 0) |
3006 ( (u32)(isKeyDown(KeyType::BACKWARD) & 0x1) << 1) |
3007 ( (u32)(isKeyDown(KeyType::LEFT) & 0x1) << 2) |
3008 ( (u32)(isKeyDown(KeyType::RIGHT) & 0x1) << 3) |
3009 ( (u32)(isKeyDown(KeyType::JUMP) & 0x1) << 4) |
3010 ( (u32)(isKeyDown(KeyType::SPECIAL1) & 0x1) << 5) |
3011 ( (u32)(isKeyDown(KeyType::SNEAK) & 0x1) << 6) |
3012 ( (u32)(isLeftPressed() & 0x1) << 7) |
3013 ( (u32)(isRightPressed() & 0x1) << 8
3017 /* For Android, simulate holding down AUX1 (fast move) if the user has
3018 * the fast_move setting toggled on. If there is an aux1 key defined for
3019 * Android then its meaning is inverted (i.e. holding aux1 means walk and
3022 if (m_cache_hold_aux1) {
3023 control.aux1 = control.aux1 ^ true;
3024 keypress_bits ^= ((u32)(1U << 5));
3028 client->setPlayerControl(control);
3029 LocalPlayer *player = client->getEnv().getLocalPlayer();
3030 player->keyPressed = keypress_bits;
3036 inline void Game::step(f32 *dtime)
3038 bool can_be_and_is_paused =
3039 (simple_singleplayer_mode && g_menumgr.pausesGame());
3041 if (can_be_and_is_paused) { // This is for a singleplayer server
3042 *dtime = 0; // No time passes
3044 if (server != NULL) {
3045 //TimeTaker timer("server->step(dtime)");
3046 server->step(*dtime);
3049 //TimeTaker timer("client.step(dtime)");
3050 client->step(*dtime);
3055 void Game::processClientEvents(CameraOrientation *cam)
3057 ClientEvent event = client->getClientEvent();
3059 LocalPlayer *player = client->getEnv().getLocalPlayer();
3061 for ( ; event.type != CE_NONE; event = client->getClientEvent()) {
3063 switch (event.type) {
3064 case CE_PLAYER_DAMAGE:
3065 if (client->getHP() == 0)
3067 if (client->moddingEnabled()) {
3068 client->getScript()->on_damage_taken(event.player_damage.amount);
3071 runData.damage_flash += 95.0 + 3.2 * event.player_damage.amount;
3072 runData.damage_flash = MYMIN(runData.damage_flash, 127.0);
3074 player->hurt_tilt_timer = 1.5;
3075 player->hurt_tilt_strength =
3076 rangelim(event.player_damage.amount / 4, 1.0, 4.0);
3078 client->event()->put(new SimpleTriggerEvent("PlayerDamage"));
3081 case CE_PLAYER_FORCE_MOVE:
3082 cam->camera_yaw = event.player_force_move.yaw;
3083 cam->camera_pitch = event.player_force_move.pitch;
3086 case CE_DEATHSCREEN:
3087 // This should be enabled for death formspec in builtin
3088 client->getScript()->on_death();
3090 /* Handle visualization */
3091 runData.damage_flash = 0;
3092 player->hurt_tilt_timer = 0;
3093 player->hurt_tilt_strength = 0;
3096 case CE_SHOW_FORMSPEC:
3097 if (*(event.show_formspec.formspec) == "") {
3098 if (current_formspec && ( *(event.show_formspec.formname) == "" || *(event.show_formspec.formname) == cur_formname) ){
3099 current_formspec->quitMenu();
3102 FormspecFormSource *fs_src =
3103 new FormspecFormSource(*(event.show_formspec.formspec));
3104 TextDestPlayerInventory *txt_dst =
3105 new TextDestPlayerInventory(client, *(event.show_formspec.formname));
3107 create_formspec_menu(¤t_formspec, client, device, &input->joystick,
3109 cur_formname = *(event.show_formspec.formname);
3112 delete event.show_formspec.formspec;
3113 delete event.show_formspec.formname;
3116 case CE_SHOW_LOCAL_FORMSPEC:
3118 FormspecFormSource *fs_src = new FormspecFormSource(*event.show_formspec.formspec);
3119 LocalFormspecHandler *txt_dst = new LocalFormspecHandler(*event.show_formspec.formname, client);
3120 create_formspec_menu(¤t_formspec, client, device, &input->joystick,
3123 delete event.show_formspec.formspec;
3124 delete event.show_formspec.formname;
3127 case CE_SPAWN_PARTICLE:
3128 case CE_ADD_PARTICLESPAWNER:
3129 case CE_DELETE_PARTICLESPAWNER:
3130 client->getParticleManager()->handleParticleEvent(&event, client,
3136 u32 id = event.hudadd.id;
3138 HudElement *e = player->getHud(id);
3141 delete event.hudadd.pos;
3142 delete event.hudadd.name;
3143 delete event.hudadd.scale;
3144 delete event.hudadd.text;
3145 delete event.hudadd.align;
3146 delete event.hudadd.offset;
3147 delete event.hudadd.world_pos;
3148 delete event.hudadd.size;
3153 e->type = (HudElementType)event.hudadd.type;
3154 e->pos = *event.hudadd.pos;
3155 e->name = *event.hudadd.name;
3156 e->scale = *event.hudadd.scale;
3157 e->text = *event.hudadd.text;
3158 e->number = event.hudadd.number;
3159 e->item = event.hudadd.item;
3160 e->dir = event.hudadd.dir;
3161 e->align = *event.hudadd.align;
3162 e->offset = *event.hudadd.offset;
3163 e->world_pos = *event.hudadd.world_pos;
3164 e->size = *event.hudadd.size;
3166 u32 new_id = player->addHud(e);
3167 //if this isn't true our huds aren't consistent
3168 sanity_check(new_id == id);
3171 delete event.hudadd.pos;
3172 delete event.hudadd.name;
3173 delete event.hudadd.scale;
3174 delete event.hudadd.text;
3175 delete event.hudadd.align;
3176 delete event.hudadd.offset;
3177 delete event.hudadd.world_pos;
3178 delete event.hudadd.size;
3183 HudElement *e = player->removeHud(event.hudrm.id);
3192 u32 id = event.hudchange.id;
3193 HudElement *e = player->getHud(id);
3196 delete event.hudchange.v3fdata;
3197 delete event.hudchange.v2fdata;
3198 delete event.hudchange.sdata;
3199 delete event.hudchange.v2s32data;
3203 switch (event.hudchange.stat) {
3205 e->pos = *event.hudchange.v2fdata;
3209 e->name = *event.hudchange.sdata;
3212 case HUD_STAT_SCALE:
3213 e->scale = *event.hudchange.v2fdata;
3217 e->text = *event.hudchange.sdata;
3220 case HUD_STAT_NUMBER:
3221 e->number = event.hudchange.data;
3225 e->item = event.hudchange.data;
3229 e->dir = event.hudchange.data;
3232 case HUD_STAT_ALIGN:
3233 e->align = *event.hudchange.v2fdata;
3236 case HUD_STAT_OFFSET:
3237 e->offset = *event.hudchange.v2fdata;
3240 case HUD_STAT_WORLD_POS:
3241 e->world_pos = *event.hudchange.v3fdata;
3245 e->size = *event.hudchange.v2s32data;
3250 delete event.hudchange.v3fdata;
3251 delete event.hudchange.v2fdata;
3252 delete event.hudchange.sdata;
3253 delete event.hudchange.v2s32data;
3257 sky->setVisible(false);
3264 // Handle according to type
3265 if (*event.set_sky.type == "regular") {
3266 sky->setVisible(true);
3267 } else if (*event.set_sky.type == "skybox" &&
3268 event.set_sky.params->size() == 6) {
3269 sky->setFallbackBgColor(*event.set_sky.bgcolor);
3270 skybox = smgr->addSkyBoxSceneNode(
3271 texture_src->getTextureForMesh((*event.set_sky.params)[0]),
3272 texture_src->getTextureForMesh((*event.set_sky.params)[1]),
3273 texture_src->getTextureForMesh((*event.set_sky.params)[2]),
3274 texture_src->getTextureForMesh((*event.set_sky.params)[3]),
3275 texture_src->getTextureForMesh((*event.set_sky.params)[4]),
3276 texture_src->getTextureForMesh((*event.set_sky.params)[5]));
3278 // Handle everything else as plain color
3280 if (*event.set_sky.type != "plain")
3281 infostream << "Unknown sky type: "
3282 << (*event.set_sky.type) << std::endl;
3284 sky->setFallbackBgColor(*event.set_sky.bgcolor);
3287 delete event.set_sky.bgcolor;
3288 delete event.set_sky.type;
3289 delete event.set_sky.params;
3292 case CE_OVERRIDE_DAY_NIGHT_RATIO:
3293 client->getEnv().setDayNightRatioOverride(
3294 event.override_day_night_ratio.do_override,
3295 event.override_day_night_ratio.ratio_f * 1000);
3299 // unknown or unhandled type
3307 void Game::updateCamera(u32 busy_time, f32 dtime)
3309 LocalPlayer *player = client->getEnv().getLocalPlayer();
3312 For interaction purposes, get info about the held item
3314 - Is it a usable item?
3315 - Can it point to liquids?
3317 ItemStack playeritem;
3319 InventoryList *mlist = local_inventory->getList("main");
3321 if (mlist && client->getPlayerItem() < mlist->getSize())
3322 playeritem = mlist->getItem(client->getPlayerItem());
3325 if (playeritem.getDefinition(itemdef_manager).name.empty()) { // override the hand
3326 InventoryList *hlist = local_inventory->getList("hand");
3328 playeritem = hlist->getItem(0);
3332 ToolCapabilities playeritem_toolcap =
3333 playeritem.getToolCapabilities(itemdef_manager);
3335 v3s16 old_camera_offset = camera->getOffset();
3337 if (wasKeyDown(KeyType::CAMERA_MODE)) {
3338 GenericCAO *playercao = player->getCAO();
3340 // If playercao not loaded, don't change camera
3341 if (playercao == NULL)
3344 camera->toggleCameraMode();
3346 playercao->setVisible(camera->getCameraMode() > CAMERA_MODE_FIRST);
3347 playercao->setChildrenVisible(camera->getCameraMode() > CAMERA_MODE_FIRST);
3350 float full_punch_interval = playeritem_toolcap.full_punch_interval;
3351 float tool_reload_ratio = runData.time_from_last_punch / full_punch_interval;
3353 tool_reload_ratio = MYMIN(tool_reload_ratio, 1.0);
3354 camera->update(player, dtime, busy_time / 1000.0f, tool_reload_ratio,
3356 camera->step(dtime);
3358 v3f camera_position = camera->getPosition();
3359 v3f camera_direction = camera->getDirection();
3360 f32 camera_fov = camera->getFovMax();
3361 v3s16 camera_offset = camera->getOffset();
3363 m_camera_offset_changed = (camera_offset != old_camera_offset);
3365 if (!flags.disable_camera_update) {
3366 client->getEnv().getClientMap().updateCamera(camera_position,
3367 camera_direction, camera_fov, camera_offset);
3369 if (m_camera_offset_changed) {
3370 client->updateCameraOffset(camera_offset);
3371 client->getEnv().updateCameraOffset(camera_offset);
3374 clouds->updateCameraOffset(camera_offset);
3380 void Game::updateSound(f32 dtime)
3382 // Update sound listener
3383 v3s16 camera_offset = camera->getOffset();
3384 sound->updateListener(camera->getCameraNode()->getPosition() + intToFloat(camera_offset, BS),
3385 v3f(0, 0, 0), // velocity
3386 camera->getDirection(),
3387 camera->getCameraNode()->getUpVector());
3388 sound->setListenerGain(g_settings->getFloat("sound_volume"));
3391 // Update sound maker
3392 soundmaker->step(dtime);
3394 LocalPlayer *player = client->getEnv().getLocalPlayer();
3396 ClientMap &map = client->getEnv().getClientMap();
3397 MapNode n = map.getNodeNoEx(player->getFootstepNodePos());
3398 soundmaker->m_player_step_sound = nodedef_manager->get(n).sound_footstep;
3402 void Game::processPlayerInteraction(f32 dtime, bool show_hud, bool show_debug)
3404 LocalPlayer *player = client->getEnv().getLocalPlayer();
3406 ItemStack playeritem;
3408 InventoryList *mlist = local_inventory->getList("main");
3410 if (mlist && client->getPlayerItem() < mlist->getSize())
3411 playeritem = mlist->getItem(client->getPlayerItem());
3414 const ItemDefinition &playeritem_def =
3415 playeritem.getDefinition(itemdef_manager);
3416 InventoryList *hlist = local_inventory->getList("hand");
3417 const ItemDefinition &hand_def =
3418 hlist ? hlist->getItem(0).getDefinition(itemdef_manager) : itemdef_manager->get("");
3420 v3f player_position = player->getPosition();
3421 v3f camera_position = camera->getPosition();
3422 v3f camera_direction = camera->getDirection();
3423 v3s16 camera_offset = camera->getOffset();
3427 Calculate what block is the crosshair pointing to
3430 f32 d = playeritem_def.range; // max. distance
3431 f32 d_hand = hand_def.range;
3433 if (d < 0 && d_hand >= 0)
3438 core::line3d<f32> shootline;
3440 if (camera->getCameraMode() != CAMERA_MODE_THIRD_FRONT) {
3441 shootline = core::line3d<f32>(camera_position,
3442 camera_position + camera_direction * BS * d);
3444 // prevent player pointing anything in front-view
3445 shootline = core::line3d<f32>(camera_position,camera_position);
3448 #ifdef HAVE_TOUCHSCREENGUI
3450 if ((g_settings->getBool("touchtarget")) && (g_touchscreengui)) {
3451 shootline = g_touchscreengui->getShootline();
3452 shootline.start += intToFloat(camera_offset, BS);
3453 shootline.end += intToFloat(camera_offset, BS);
3458 PointedThing pointed = updatePointedThing(shootline,
3459 playeritem_def.liquids_pointable,
3460 !runData.ldown_for_dig,
3463 if (pointed != runData.pointed_old) {
3464 infostream << "Pointing at " << pointed.dump() << std::endl;
3465 hud->updateSelectionMesh(camera_offset);
3470 - releasing left mouse button
3471 - pointing away from node
3473 if (runData.digging) {
3474 if (getLeftReleased()) {
3475 infostream << "Left button released"
3476 << " (stopped digging)" << std::endl;
3477 runData.digging = false;
3478 } else if (pointed != runData.pointed_old) {
3479 if (pointed.type == POINTEDTHING_NODE
3480 && runData.pointed_old.type == POINTEDTHING_NODE
3481 && pointed.node_undersurface
3482 == runData.pointed_old.node_undersurface) {
3483 // Still pointing to the same node, but a different face.
3486 infostream << "Pointing away from node"
3487 << " (stopped digging)" << std::endl;
3488 runData.digging = false;
3489 hud->updateSelectionMesh(camera_offset);
3493 if (!runData.digging) {
3494 client->interact(1, runData.pointed_old);
3495 client->setCrack(-1, v3s16(0, 0, 0));
3496 runData.dig_time = 0.0;
3500 if (!runData.digging && runData.ldown_for_dig && !isLeftPressed()) {
3501 runData.ldown_for_dig = false;
3504 runData.left_punch = false;
3506 soundmaker->m_player_leftpunch_sound.name = "";
3508 if (isRightPressed())
3509 runData.repeat_rightclick_timer += dtime;
3511 runData.repeat_rightclick_timer = 0;
3513 if (playeritem_def.usable && isLeftPressed()) {
3514 if (getLeftClicked())
3515 client->interact(4, pointed);
3516 } else if (pointed.type == POINTEDTHING_NODE) {
3517 ToolCapabilities playeritem_toolcap =
3518 playeritem.getToolCapabilities(itemdef_manager);
3519 if (playeritem.name.empty()) {
3520 playeritem_toolcap = *hand_def.tool_capabilities;
3522 handlePointingAtNode(pointed, playeritem_def, playeritem_toolcap, dtime);
3523 } else if (pointed.type == POINTEDTHING_OBJECT) {
3524 handlePointingAtObject(pointed, playeritem, player_position, show_debug);
3525 } else if (isLeftPressed()) {
3526 // When button is held down in air, show continuous animation
3527 runData.left_punch = true;
3528 } else if (getRightClicked()) {
3529 handlePointingAtNothing(playeritem);
3532 runData.pointed_old = pointed;
3534 if (runData.left_punch || getLeftClicked())
3535 camera->setDigging(0); // left click animation
3537 input->resetLeftClicked();
3538 input->resetRightClicked();
3540 input->joystick.clearWasKeyDown(KeyType::MOUSE_L);
3541 input->joystick.clearWasKeyDown(KeyType::MOUSE_R);
3543 input->resetLeftReleased();
3544 input->resetRightReleased();
3546 input->joystick.clearWasKeyReleased(KeyType::MOUSE_L);
3547 input->joystick.clearWasKeyReleased(KeyType::MOUSE_R);
3551 PointedThing Game::updatePointedThing(
3552 const core::line3d<f32> &shootline,
3553 bool liquids_pointable,
3554 bool look_for_object,
3555 const v3s16 &camera_offset)
3557 std::vector<aabb3f> *selectionboxes = hud->getSelectionBoxes();
3558 selectionboxes->clear();
3559 hud->setSelectedFaceNormal(v3f(0.0, 0.0, 0.0));
3560 static const bool show_entity_selectionbox = g_settings->getBool(
3561 "show_entity_selectionbox");
3563 ClientMap &map = client->getEnv().getClientMap();
3564 INodeDefManager *nodedef=client->getNodeDefManager();
3566 runData.selected_object = NULL;
3568 PointedThing result=client->getEnv().getPointedThing(
3569 shootline, liquids_pointable, look_for_object);
3570 if (result.type == POINTEDTHING_OBJECT) {
3571 runData.selected_object = client->getEnv().getActiveObject(result.object_id);
3572 if (show_entity_selectionbox && runData.selected_object->doShowSelectionBox()) {
3573 aabb3f *selection_box = runData.selected_object->getSelectionBox();
3575 // Box should exist because object was
3576 // returned in the first place
3578 assert(selection_box);
3580 v3f pos = runData.selected_object->getPosition();
3581 selectionboxes->push_back(aabb3f(
3582 selection_box->MinEdge, selection_box->MaxEdge));
3583 selectionboxes->push_back(
3584 aabb3f(selection_box->MinEdge, selection_box->MaxEdge));
3585 hud->setSelectionPos(pos, camera_offset);
3587 } else if (result.type == POINTEDTHING_NODE) {
3588 // Update selection boxes
3589 MapNode n = map.getNodeNoEx(result.node_undersurface);
3590 std::vector<aabb3f> boxes;
3591 n.getSelectionBoxes(nodedef, &boxes,
3592 n.getNeighbors(result.node_undersurface, &map));
3595 for (std::vector<aabb3f>::const_iterator i = boxes.begin();
3596 i != boxes.end(); ++i) {
3598 box.MinEdge -= v3f(d, d, d);
3599 box.MaxEdge += v3f(d, d, d);
3600 selectionboxes->push_back(box);
3602 hud->setSelectionPos(intToFloat(result.node_undersurface, BS),
3604 hud->setSelectedFaceNormal(v3f(
3605 result.intersection_normal.X,
3606 result.intersection_normal.Y,
3607 result.intersection_normal.Z));
3610 // Update selection mesh light level and vertex colors
3611 if (selectionboxes->size() > 0) {
3612 v3f pf = hud->getSelectionPos();
3613 v3s16 p = floatToInt(pf, BS);
3615 // Get selection mesh light level
3616 MapNode n = map.getNodeNoEx(p);
3617 u16 node_light = getInteriorLight(n, -1, nodedef);
3618 u16 light_level = node_light;
3620 for (u8 i = 0; i < 6; i++) {
3621 n = map.getNodeNoEx(p + g_6dirs[i]);
3622 node_light = getInteriorLight(n, -1, nodedef);
3623 if (node_light > light_level)
3624 light_level = node_light;
3627 u32 daynight_ratio = client->getEnv().getDayNightRatio();
3629 final_color_blend(&c, light_level, daynight_ratio);
3631 // Modify final color a bit with time
3632 u32 timer = porting::getTimeMs() % 5000;
3633 float timerf = (float) (irr::core::PI * ((timer / 2500.0) - 0.5));
3634 float sin_r = 0.08 * sin(timerf);
3635 float sin_g = 0.08 * sin(timerf + irr::core::PI * 0.5);
3636 float sin_b = 0.08 * sin(timerf + irr::core::PI);
3638 core::clamp(core::round32(c.getRed() * (0.8 + sin_r)), 0, 255));
3640 core::clamp(core::round32(c.getGreen() * (0.8 + sin_g)), 0, 255));
3642 core::clamp(core::round32(c.getBlue() * (0.8 + sin_b)), 0, 255));
3644 // Set mesh final color
3645 hud->setSelectionMeshColor(c);
3651 void Game::handlePointingAtNothing(const ItemStack &playerItem)
3653 infostream << "Right Clicked in Air" << std::endl;
3654 PointedThing fauxPointed;
3655 fauxPointed.type = POINTEDTHING_NOTHING;
3656 client->interact(5, fauxPointed);
3660 void Game::handlePointingAtNode(const PointedThing &pointed, const ItemDefinition &playeritem_def,
3661 const ToolCapabilities &playeritem_toolcap, f32 dtime)
3663 v3s16 nodepos = pointed.node_undersurface;
3664 v3s16 neighbourpos = pointed.node_abovesurface;
3667 Check information text of node
3670 ClientMap &map = client->getEnv().getClientMap();
3671 NodeMetadata *meta = map.getNodeMetadata(nodepos);
3674 infotext = unescape_enriched(utf8_to_wide(meta->getString("infotext")));
3676 MapNode n = map.getNodeNoEx(nodepos);
3678 if (nodedef_manager->get(n).tiledef[0].name == "unknown_node.png") {
3679 infotext = L"Unknown node: ";
3680 infotext += utf8_to_wide(nodedef_manager->get(n).name);
3684 if (runData.nodig_delay_timer <= 0.0 && isLeftPressed()
3685 && client->checkPrivilege("interact")) {
3686 handleDigging(pointed, nodepos, playeritem_toolcap, dtime);
3689 if ((getRightClicked() ||
3690 runData.repeat_rightclick_timer >= m_repeat_right_click_time) &&
3691 client->checkPrivilege("interact")) {
3692 runData.repeat_rightclick_timer = 0;
3693 infostream << "Ground right-clicked" << std::endl;
3695 if (meta && meta->getString("formspec") != "" && !random_input
3696 && !isKeyDown(KeyType::SNEAK)) {
3697 infostream << "Launching custom inventory view" << std::endl;
3699 InventoryLocation inventoryloc;
3700 inventoryloc.setNodeMeta(nodepos);
3702 NodeMetadataFormSource *fs_src = new NodeMetadataFormSource(
3703 &client->getEnv().getClientMap(), nodepos);
3704 TextDest *txt_dst = new TextDestNodeMetadata(nodepos, client);
3706 create_formspec_menu(¤t_formspec, client,
3707 device, &input->joystick, fs_src, txt_dst);
3710 current_formspec->setFormSpec(meta->getString("formspec"), inventoryloc);
3712 // Report right click to server
3714 camera->setDigging(1); // right click animation (always shown for feedback)
3716 // If the wielded item has node placement prediction,
3718 bool placed = nodePlacementPrediction(*client,
3720 nodepos, neighbourpos);
3724 client->interact(3, pointed);
3726 soundmaker->m_player_rightpunch_sound =
3727 playeritem_def.sound_place;
3729 soundmaker->m_player_rightpunch_sound =
3732 if (playeritem_def.node_placement_prediction == "" ||
3733 nodedef_manager->get(map.getNodeNoEx(nodepos)).rightclickable) {
3734 client->interact(3, pointed); // Report to server
3736 soundmaker->m_player_rightpunch_sound =
3737 playeritem_def.sound_place_failed;
3745 void Game::handlePointingAtObject(const PointedThing &pointed, const ItemStack &playeritem,
3746 const v3f &player_position, bool show_debug)
3748 infotext = unescape_enriched(
3749 utf8_to_wide(runData.selected_object->infoText()));
3752 if (infotext != L"") {
3755 infotext += unescape_enriched(utf8_to_wide(
3756 runData.selected_object->debugInfoText()));
3759 if (isLeftPressed()) {
3760 bool do_punch = false;
3761 bool do_punch_damage = false;
3763 if (runData.object_hit_delay_timer <= 0.0) {
3765 do_punch_damage = true;
3766 runData.object_hit_delay_timer = object_hit_delay;
3769 if (getLeftClicked())
3773 infostream << "Left-clicked object" << std::endl;
3774 runData.left_punch = true;
3777 if (do_punch_damage) {
3778 // Report direct punch
3779 v3f objpos = runData.selected_object->getPosition();
3780 v3f dir = (objpos - player_position).normalize();
3781 ItemStack item = playeritem;
3782 if (playeritem.name.empty()) {
3783 InventoryList *hlist = local_inventory->getList("hand");
3785 item = hlist->getItem(0);
3789 bool disable_send = runData.selected_object->directReportPunch(
3790 dir, &item, runData.time_from_last_punch);
3791 runData.time_from_last_punch = 0;
3794 client->interact(0, pointed);
3796 } else if (getRightClicked()) {
3797 infostream << "Right-clicked object" << std::endl;
3798 client->interact(3, pointed); // place
3803 void Game::handleDigging(const PointedThing &pointed, const v3s16 &nodepos,
3804 const ToolCapabilities &playeritem_toolcap, f32 dtime)
3806 LocalPlayer *player = client->getEnv().getLocalPlayer();
3807 ClientMap &map = client->getEnv().getClientMap();
3808 MapNode n = client->getEnv().getClientMap().getNodeNoEx(nodepos);
3810 if (!runData.digging) {
3811 infostream << "Started digging" << std::endl;
3812 if (client->moddingEnabled() && client->getScript()->on_punchnode(nodepos, n))
3814 client->interact(0, pointed);
3815 runData.digging = true;
3816 runData.ldown_for_dig = true;
3819 // NOTE: Similar piece of code exists on the server side for
3821 // Get digging parameters
3822 DigParams params = getDigParams(nodedef_manager->get(n).groups,
3823 &playeritem_toolcap);
3825 // If can't dig, try hand
3826 if (!params.diggable) {
3827 InventoryList *hlist = local_inventory->getList("hand");
3828 const ItemDefinition &hand =
3829 hlist ? hlist->getItem(0).getDefinition(itemdef_manager) : itemdef_manager->get("");
3830 const ToolCapabilities *tp = hand.tool_capabilities;
3833 params = getDigParams(nodedef_manager->get(n).groups, tp);
3836 if (!params.diggable) {
3837 // I guess nobody will wait for this long
3838 runData.dig_time_complete = 10000000.0;
3840 runData.dig_time_complete = params.time;
3842 if (m_cache_enable_particles) {
3843 const ContentFeatures &features =
3844 client->getNodeDefManager()->get(n);
3845 client->getParticleManager()->addPunchingParticles(client, smgr,
3846 player, nodepos, n, features);
3850 if (runData.dig_time_complete >= 0.001) {
3851 runData.dig_index = (float)crack_animation_length
3853 / runData.dig_time_complete;
3855 // This is for torches
3856 runData.dig_index = crack_animation_length;
3859 SimpleSoundSpec sound_dig = nodedef_manager->get(n).sound_dig;
3861 if (sound_dig.exists() && params.diggable) {
3862 if (sound_dig.name == "__group") {
3863 if (params.main_group != "") {
3864 soundmaker->m_player_leftpunch_sound.gain = 0.5;
3865 soundmaker->m_player_leftpunch_sound.name =
3866 std::string("default_dig_") +
3870 soundmaker->m_player_leftpunch_sound = sound_dig;
3874 // Don't show cracks if not diggable
3875 if (runData.dig_time_complete >= 100000.0) {
3876 } else if (runData.dig_index < crack_animation_length) {
3877 //TimeTaker timer("client.setTempMod");
3878 //infostream<<"dig_index="<<dig_index<<std::endl;
3879 client->setCrack(runData.dig_index, nodepos);
3881 infostream << "Digging completed" << std::endl;
3882 client->setCrack(-1, v3s16(0, 0, 0));
3884 runData.dig_time = 0;
3885 runData.digging = false;
3887 runData.nodig_delay_timer =
3888 runData.dig_time_complete / (float)crack_animation_length;
3890 // We don't want a corresponding delay to
3891 // very time consuming nodes
3892 if (runData.nodig_delay_timer > 0.3)
3893 runData.nodig_delay_timer = 0.3;
3895 bool is_valid_position;
3896 MapNode wasnode = map.getNodeNoEx(nodepos, &is_valid_position);
3897 if (is_valid_position) {
3898 if (client->moddingEnabled()) {
3899 if (client->getScript()->on_dignode(nodepos, wasnode)) {
3903 client->removeNode(nodepos);
3906 client->interact(2, pointed);
3908 if (m_cache_enable_particles) {
3909 const ContentFeatures &features =
3910 client->getNodeDefManager()->get(wasnode);
3911 client->getParticleManager()->addDiggingParticles(client, smgr,
3912 player, nodepos, wasnode, features);
3916 // Send event to trigger sound
3917 MtEvent *e = new NodeDugEvent(nodepos, wasnode);
3918 client->event()->put(e);
3921 if (runData.dig_time_complete < 100000.0) {
3922 runData.dig_time += dtime;
3924 runData.dig_time = 0;
3925 client->setCrack(-1, nodepos);
3928 camera->setDigging(0); // left click animation
3932 void Game::updateFrame(ProfilerGraph *graph, RunStats *stats, f32 dtime,
3933 const CameraOrientation &cam)
3935 LocalPlayer *player = client->getEnv().getLocalPlayer();
3941 if (draw_control->range_all) {
3942 runData.fog_range = 100000 * BS;
3944 runData.fog_range = draw_control->wanted_range * BS;
3948 Calculate general brightness
3950 u32 daynight_ratio = client->getEnv().getDayNightRatio();
3951 float time_brightness = decode_light_f((float)daynight_ratio / 1000.0);
3952 float direct_brightness;
3955 if (m_cache_enable_noclip && m_cache_enable_free_move) {
3956 direct_brightness = time_brightness;
3957 sunlight_seen = true;
3959 ScopeProfiler sp(g_profiler, "Detecting background light", SPT_AVG);
3960 float old_brightness = sky->getBrightness();
3961 direct_brightness = client->getEnv().getClientMap()
3962 .getBackgroundBrightness(MYMIN(runData.fog_range * 1.2, 60 * BS),
3963 daynight_ratio, (int)(old_brightness * 255.5), &sunlight_seen)
3967 float time_of_day_smooth = runData.time_of_day_smooth;
3968 float time_of_day = client->getEnv().getTimeOfDayF();
3970 static const float maxsm = 0.05;
3971 static const float todsm = 0.05;
3973 if (fabs(time_of_day - time_of_day_smooth) > maxsm &&
3974 fabs(time_of_day - time_of_day_smooth + 1.0) > maxsm &&
3975 fabs(time_of_day - time_of_day_smooth - 1.0) > maxsm)
3976 time_of_day_smooth = time_of_day;
3978 if (time_of_day_smooth > 0.8 && time_of_day < 0.2)
3979 time_of_day_smooth = time_of_day_smooth * (1.0 - todsm)
3980 + (time_of_day + 1.0) * todsm;
3982 time_of_day_smooth = time_of_day_smooth * (1.0 - todsm)
3983 + time_of_day * todsm;
3985 runData.time_of_day = time_of_day;
3986 runData.time_of_day_smooth = time_of_day_smooth;
3988 sky->update(time_of_day_smooth, time_brightness, direct_brightness,
3989 sunlight_seen, camera->getCameraMode(), player->getYaw(),
3990 player->getPitch());
3996 v3f player_position = player->getPosition();
3997 if (sky->getCloudsVisible()) {
3998 clouds->setVisible(true);
3999 clouds->step(dtime);
4000 clouds->update(v2f(player_position.X, player_position.Z),
4001 sky->getCloudColor());
4003 clouds->setVisible(false);
4010 client->getParticleManager()->step(dtime);
4016 if (m_cache_enable_fog && !flags.force_fog_off) {
4019 video::EFT_FOG_LINEAR,
4020 runData.fog_range * m_cache_fog_start,
4021 runData.fog_range * 1.0,
4029 video::EFT_FOG_LINEAR,
4039 Get chat messages from client
4042 v2u32 screensize = driver->getScreenSize();
4044 updateChat(*client, dtime, flags.show_debug, screensize,
4045 flags.show_chat, runData.profiler_current_page,
4046 *chat_backend, guitext_chat);
4052 if (client->getPlayerItem() != runData.new_playeritem)
4053 client->selectPlayerItem(runData.new_playeritem);
4055 // Update local inventory if it has changed
4056 if (client->getLocalInventoryUpdated()) {
4057 //infostream<<"Updating local inventory"<<std::endl;
4058 client->getLocalInventory(*local_inventory);
4059 runData.update_wielded_item_trigger = true;
4062 if (runData.update_wielded_item_trigger) {
4063 // Update wielded tool
4064 InventoryList *mlist = local_inventory->getList("main");
4066 if (mlist && (client->getPlayerItem() < mlist->getSize())) {
4067 ItemStack item = mlist->getItem(client->getPlayerItem());
4068 if (item.getDefinition(itemdef_manager).name.empty()) { // override the hand
4069 InventoryList *hlist = local_inventory->getList("hand");
4071 item = hlist->getItem(0);
4073 camera->wield(item);
4076 runData.update_wielded_item_trigger = false;
4080 Update block draw list every 200ms or when camera direction has
4083 runData.update_draw_list_timer += dtime;
4085 v3f camera_direction = camera->getDirection();
4086 if (runData.update_draw_list_timer >= 0.2
4087 || runData.update_draw_list_last_cam_dir.getDistanceFrom(camera_direction) > 0.2
4088 || m_camera_offset_changed) {
4089 runData.update_draw_list_timer = 0;
4090 client->getEnv().getClientMap().updateDrawList(driver);
4091 runData.update_draw_list_last_cam_dir = camera_direction;
4094 updateGui(*stats, dtime, cam);
4097 make sure menu is on top
4098 1. Delete formspec menu reference if menu was removed
4099 2. Else, make sure formspec menu is on top
4101 if (current_formspec) {
4102 if (current_formspec->getReferenceCount() == 1) {
4103 current_formspec->drop();
4104 current_formspec = NULL;
4105 } else if (!noMenuActive()) {
4106 guiroot->bringToFront(current_formspec);
4114 const video::SColor &skycolor = sky->getSkyColor();
4116 TimeTaker tt_draw("mainloop: draw");
4117 driver->beginScene(true, true, skycolor);
4119 draw_scene(driver, smgr, *camera, *client, player, *hud, *mapper,
4120 guienv, screensize, skycolor, flags.show_hud,
4121 flags.show_minimap);
4126 if (flags.show_profiler_graph)
4127 graph->draw(10, screensize.Y - 10, driver, g_fontengine->getFont());
4132 if (runData.damage_flash > 0.0) {
4133 video::SColor color(runData.damage_flash, 180, 0, 0);
4134 driver->draw2DRectangle(color,
4135 core::rect<s32>(0, 0, screensize.X, screensize.Y),
4138 runData.damage_flash -= 100.0 * dtime;
4144 if (player->hurt_tilt_timer > 0.0) {
4145 player->hurt_tilt_timer -= dtime * 5;
4147 if (player->hurt_tilt_timer < 0)
4148 player->hurt_tilt_strength = 0;
4152 Update minimap pos and rotation
4154 if (flags.show_minimap && flags.show_hud) {
4155 mapper->setPos(floatToInt(player->getPosition(), BS));
4156 mapper->setAngle(player->getYaw());
4164 stats->drawtime = tt_draw.stop(true);
4165 g_profiler->graphAdd("mainloop_draw", stats->drawtime / 1000.0f);
4169 inline static const char *yawToDirectionString(int yaw)
4171 static const char *direction[4] = {"North [+Z]", "West [-X]", "South [-Z]", "East [+X]"};
4173 yaw = wrapDegrees_0_360(yaw);
4174 yaw = (yaw + 45) % 360 / 90;
4176 return direction[yaw];
4180 void Game::updateGui(const RunStats &stats, f32 dtime, const CameraOrientation &cam)
4182 v2u32 screensize = driver->getScreenSize();
4183 LocalPlayer *player = client->getEnv().getLocalPlayer();
4184 v3f player_position = player->getPosition();
4186 if (flags.show_debug) {
4187 static float drawtime_avg = 0;
4188 drawtime_avg = drawtime_avg * 0.95 + stats.drawtime * 0.05;
4190 u16 fps = 1.0 / stats.dtime_jitter.avg;
4192 std::ostringstream os(std::ios_base::binary);
4194 << PROJECT_NAME_C " " << g_version_hash
4196 << " (R: range_all=" << draw_control->range_all << ")"
4197 << std::setprecision(0)
4198 << " drawtime = " << drawtime_avg
4199 << std::setprecision(1)
4200 << ", dtime_jitter = "
4201 << (stats.dtime_jitter.max_fraction * 100.0) << " %"
4202 << std::setprecision(1)
4203 << ", v_range = " << draw_control->wanted_range
4204 << std::setprecision(3)
4205 << ", RTT = " << client->getRTT();
4206 setStaticText(guitext, utf8_to_wide(os.str()).c_str());
4207 guitext->setVisible(true);
4209 guitext->setVisible(false);
4212 if (guitext->isVisible()) {
4213 core::rect<s32> rect(
4215 screensize.X, 5 + g_fontengine->getTextHeight()
4217 guitext->setRelativePosition(rect);
4220 if (flags.show_debug) {
4221 std::ostringstream os(std::ios_base::binary);
4222 os << std::setprecision(1) << std::fixed
4223 << "(" << (player_position.X / BS)
4224 << ", " << (player_position.Y / BS)
4225 << ", " << (player_position.Z / BS)
4226 << ") (yaw=" << (wrapDegrees_0_360(cam.camera_yaw))
4227 << " " << yawToDirectionString(cam.camera_yaw)
4228 << ") (seed = " << ((u64)client->getMapSeed())
4231 if (runData.pointed_old.type == POINTEDTHING_NODE) {
4232 ClientMap &map = client->getEnv().getClientMap();
4233 const INodeDefManager *nodedef = client->getNodeDefManager();
4234 MapNode n = map.getNodeNoEx(runData.pointed_old.node_undersurface);
4235 if (n.getContent() != CONTENT_IGNORE && nodedef->get(n).name != "unknown") {
4236 const ContentFeatures &features = nodedef->get(n);
4237 os << " (pointing_at = " << nodedef->get(n).name
4238 << " - " << features.tiledef[0].name.c_str()
4243 setStaticText(guitext2, utf8_to_wide(os.str()).c_str());
4244 guitext2->setVisible(true);
4246 core::rect<s32> rect(
4247 5, 5 + g_fontengine->getTextHeight(),
4248 screensize.X, 5 + g_fontengine->getTextHeight() * 2
4250 guitext2->setRelativePosition(rect);
4252 guitext2->setVisible(false);
4255 setStaticText(guitext_info, infotext.c_str());
4256 guitext_info->setVisible(flags.show_hud && g_menumgr.menuCount() == 0);
4258 float statustext_time_max = 1.5;
4260 if (!m_statustext.empty()) {
4261 runData.statustext_time += dtime;
4263 if (runData.statustext_time >= statustext_time_max) {
4265 runData.statustext_time = 0;
4269 setStaticText(guitext_status, m_statustext.c_str());
4270 guitext_status->setVisible(!m_statustext.empty());
4272 if (!m_statustext.empty()) {
4273 s32 status_width = guitext_status->getTextWidth();
4274 s32 status_height = guitext_status->getTextHeight();
4275 s32 status_y = screensize.Y - 150;
4276 s32 status_x = (screensize.X - status_width) / 2;
4277 core::rect<s32> rect(
4278 status_x , status_y - status_height,
4279 status_x + status_width, status_y
4281 guitext_status->setRelativePosition(rect);
4284 video::SColor initial_color(255, 0, 0, 0);
4286 if (guienv->getSkin())
4287 initial_color = guienv->getSkin()->getColor(gui::EGDC_BUTTON_TEXT);
4289 video::SColor final_color = initial_color;
4290 final_color.setAlpha(0);
4291 video::SColor fade_color = initial_color.getInterpolated_quadratic(
4292 initial_color, final_color,
4293 pow(runData.statustext_time / statustext_time_max, 2.0f));
4294 guitext_status->setOverrideColor(fade_color);
4295 guitext_status->enableOverrideColor(true);
4300 /* Log times and stuff for visualization */
4301 inline void Game::updateProfilerGraphs(ProfilerGraph *graph)
4303 Profiler::GraphValues values;
4304 g_profiler->graphGet(values);
4310 /****************************************************************************
4312 ****************************************************************************/
4314 /* On some computers framerate doesn't seem to be automatically limited
4316 inline void Game::limitFps(FpsControl *fps_timings, f32 *dtime)
4318 // not using getRealTime is necessary for wine
4319 device->getTimer()->tick(); // Maker sure device time is up-to-date
4320 u32 time = device->getTimer()->getTime();
4321 u32 last_time = fps_timings->last_time;
4323 if (time > last_time) // Make sure time hasn't overflowed
4324 fps_timings->busy_time = time - last_time;
4326 fps_timings->busy_time = 0;
4328 u32 frametime_min = 1000 / (g_menumgr.pausesGame()
4329 ? g_settings->getFloat("pause_fps_max")
4330 : g_settings->getFloat("fps_max"));
4332 if (fps_timings->busy_time < frametime_min) {
4333 fps_timings->sleep_time = frametime_min - fps_timings->busy_time;
4334 device->sleep(fps_timings->sleep_time);
4336 fps_timings->sleep_time = 0;
4339 /* Get the new value of the device timer. Note that device->sleep() may
4340 * not sleep for the entire requested time as sleep may be interrupted and
4341 * therefore it is arguably more accurate to get the new time from the
4342 * device rather than calculating it by adding sleep_time to time.
4345 device->getTimer()->tick(); // Update device timer
4346 time = device->getTimer()->getTime();
4348 if (time > last_time) // Make sure last_time hasn't overflowed
4349 *dtime = (time - last_time) / 1000.0;
4353 fps_timings->last_time = time;
4356 // Note: This will free (using delete[])! \p msg. If you want to use it later,
4357 // pass a copy of it to this function
4358 // Note: \p msg must be allocated using new (not malloc())
4359 void Game::showOverlayMessage(const wchar_t *msg, float dtime,
4360 int percent, bool draw_clouds)
4362 draw_load_screen(msg, device, guienv, texture_src, dtime, percent,
4367 void Game::settingChangedCallback(const std::string &setting_name, void *data)
4369 ((Game *)data)->readSettings();
4372 void Game::readSettings()
4374 m_cache_doubletap_jump = g_settings->getBool("doubletap_jump");
4375 m_cache_enable_clouds = g_settings->getBool("enable_clouds");
4376 m_cache_enable_joysticks = g_settings->getBool("enable_joysticks");
4377 m_cache_enable_particles = g_settings->getBool("enable_particles");
4378 m_cache_enable_fog = g_settings->getBool("enable_fog");
4379 m_cache_mouse_sensitivity = g_settings->getFloat("mouse_sensitivity");
4380 m_cache_joystick_frustum_sensitivity = g_settings->getFloat("joystick_frustum_sensitivity");
4381 m_repeat_right_click_time = g_settings->getFloat("repeat_rightclick_time");
4383 m_cache_enable_noclip = g_settings->getBool("noclip");
4384 m_cache_enable_free_move = g_settings->getBool("free_move");
4386 m_cache_fog_start = g_settings->getFloat("fog_start");
4388 m_cache_cam_smoothing = 0;
4389 if (g_settings->getBool("cinematic"))
4390 m_cache_cam_smoothing = 1 - g_settings->getFloat("cinematic_camera_smoothing");
4392 m_cache_cam_smoothing = 1 - g_settings->getFloat("camera_smoothing");
4394 m_cache_fog_start = rangelim(m_cache_fog_start, 0.0f, 0.99f);
4395 m_cache_cam_smoothing = rangelim(m_cache_cam_smoothing, 0.01f, 1.0f);
4396 m_cache_mouse_sensitivity = rangelim(m_cache_mouse_sensitivity, 0.001, 100.0);
4400 /****************************************************************************/
4401 /****************************************************************************
4403 ****************************************************************************/
4404 /****************************************************************************/
4406 void Game::extendedResourceCleanup()
4408 // Extended resource accounting
4409 infostream << "Irrlicht resources after cleanup:" << std::endl;
4410 infostream << "\tRemaining meshes : "
4411 << device->getSceneManager()->getMeshCache()->getMeshCount() << std::endl;
4412 infostream << "\tRemaining textures : "
4413 << driver->getTextureCount() << std::endl;
4415 for (unsigned int i = 0; i < driver->getTextureCount(); i++) {
4416 irr::video::ITexture *texture = driver->getTextureByIndex(i);
4417 infostream << "\t\t" << i << ":" << texture->getName().getPath().c_str()
4421 clearTextureNameCache();
4422 infostream << "\tRemaining materials: "
4423 << driver-> getMaterialRendererCount()
4424 << " (note: irrlicht doesn't support removing renderers)" << std::endl;
4427 void Game::showPauseMenu()
4430 static const std::string control_text = strgettext("Default Controls:\n"
4431 "No menu visible:\n"
4432 "- single tap: button activate\n"
4433 "- double tap: place/use\n"
4434 "- slide finger: look around\n"
4435 "Menu/Inventory visible:\n"
4436 "- double tap (outside):\n"
4438 "- touch stack, touch slot:\n"
4440 "- touch&drag, tap 2nd finger\n"
4441 " --> place single item to slot\n"
4444 static const std::string control_text = strgettext("Default Controls:\n"
4446 "- Space: jump/climb\n"
4447 "- Shift: sneak/go down\n"
4450 "- Mouse: turn/look\n"
4451 "- Mouse left: dig/punch\n"
4452 "- Mouse right: place/use\n"
4453 "- Mouse wheel: select item\n"
4458 float ypos = simple_singleplayer_mode ? 0.5 : 0.1;
4459 std::ostringstream os;
4461 os << FORMSPEC_VERSION_STRING << SIZE_TAG
4462 << "button_exit[4," << (ypos++) << ";3,0.5;btn_continue;"
4463 << strgettext("Continue") << "]";
4465 if (!simple_singleplayer_mode) {
4466 os << "button_exit[4," << (ypos++) << ";3,0.5;btn_change_password;"
4467 << strgettext("Change Password") << "]";
4471 os << "button_exit[4," << (ypos++) << ";3,0.5;btn_sound;"
4472 << strgettext("Sound Volume") << "]";
4473 os << "button_exit[4," << (ypos++) << ";3,0.5;btn_key_config;"
4474 << strgettext("Change Keys") << "]";
4476 os << "button_exit[4," << (ypos++) << ";3,0.5;btn_exit_menu;"
4477 << strgettext("Exit to Menu") << "]";
4478 os << "button_exit[4," << (ypos++) << ";3,0.5;btn_exit_os;"
4479 << strgettext("Exit to OS") << "]"
4480 << "textarea[7.5,0.25;3.9,6.25;;" << control_text << ";]"
4481 << "textarea[0.4,0.25;3.5,6;;" << PROJECT_NAME_C "\n"
4482 << g_build_info << "\n"
4483 << "path_user = " << wrap_rows(porting::path_user, 20)
4487 /* Note: FormspecFormSource and LocalFormspecHandler *
4488 * are deleted by guiFormSpecMenu */
4489 FormspecFormSource *fs_src = new FormspecFormSource(os.str());
4490 LocalFormspecHandler *txt_dst = new LocalFormspecHandler("MT_PAUSE_MENU");
4492 create_formspec_menu(¤t_formspec, client, device, &input->joystick, fs_src, txt_dst);
4493 current_formspec->setFocus("btn_continue");
4494 current_formspec->doPause = true;
4497 /****************************************************************************/
4498 /****************************************************************************
4499 extern function for launching the game
4500 ****************************************************************************/
4501 /****************************************************************************/
4503 void the_game(bool *kill,
4505 InputHandler *input,
4506 IrrlichtDevice *device,
4508 const std::string &map_dir,
4509 const std::string &playername,
4510 const std::string &password,
4511 const std::string &address, // If empty local server is created
4514 std::string &error_message,
4515 ChatBackend &chat_backend,
4516 bool *reconnect_requested,
4517 const SubgameSpec &gamespec, // Used for local game
4518 bool simple_singleplayer_mode)
4522 /* Make a copy of the server address because if a local singleplayer server
4523 * is created then this is updated and we don't want to change the value
4524 * passed to us by the calling function
4526 std::string server_address = address;
4530 if (game.startup(kill, random_input, input, device, map_dir,
4531 playername, password, &server_address, port, error_message,
4532 reconnect_requested, &chat_backend, gamespec,
4533 simple_singleplayer_mode)) {
4538 } catch (SerializationError &e) {
4539 error_message = std::string("A serialization error occurred:\n")
4540 + e.what() + "\n\nThe server is probably "
4541 " running a different version of " PROJECT_NAME_C ".";
4542 errorstream << error_message << std::endl;
4543 } catch (ServerError &e) {
4544 error_message = e.what();
4545 errorstream << "ServerError: " << error_message << std::endl;
4546 } catch (ModError &e) {
4547 error_message = e.what() + strgettext("\nCheck debug.txt for details.");
4548 errorstream << "ModError: " << error_message << std::endl;