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/basic_macros.h"
58 #include "util/directiontables.h"
59 #include "util/pointedthing.h"
60 #include "irrlicht_changes/static_text.h"
63 #include "mapblock_mesh.h"
64 #include "script/scripting_client.h"
69 #include "sound_openal.h"
72 #ifdef HAVE_TOUCHSCREENGUI
73 #include "touchscreengui.h"
76 extern Settings *g_settings;
77 extern Profiler *g_profiler;
83 struct TextDestNodeMetadata : public TextDest
85 TextDestNodeMetadata(v3s16 p, Client *client)
90 // This is deprecated I guess? -celeron55
91 void gotText(const std::wstring &text)
93 std::string ntext = wide_to_utf8(text);
94 infostream << "Submitting 'text' field of node at (" << m_p.X << ","
95 << m_p.Y << "," << m_p.Z << "): " << ntext << std::endl;
97 fields["text"] = ntext;
98 m_client->sendNodemetaFields(m_p, "", fields);
100 void gotText(const StringMap &fields)
102 m_client->sendNodemetaFields(m_p, "", fields);
109 struct TextDestPlayerInventory : public TextDest
111 TextDestPlayerInventory(Client *client)
116 TextDestPlayerInventory(Client *client, const std::string &formname)
119 m_formname = formname;
121 void gotText(const StringMap &fields)
123 m_client->sendInventoryFields(m_formname, fields);
129 struct LocalFormspecHandler : public TextDest
131 LocalFormspecHandler(const std::string &formname):
134 m_formname = formname;
137 LocalFormspecHandler(const std::string &formname, Client *client):
140 m_formname = formname;
143 void gotText(const StringMap &fields)
145 if (m_formname == "MT_PAUSE_MENU") {
146 if (fields.find("btn_sound") != fields.end()) {
147 g_gamecallback->changeVolume();
151 if (fields.find("btn_key_config") != fields.end()) {
152 g_gamecallback->keyConfig();
156 if (fields.find("btn_exit_menu") != fields.end()) {
157 g_gamecallback->disconnect();
161 if (fields.find("btn_exit_os") != fields.end()) {
162 g_gamecallback->exitToOS();
166 if (fields.find("btn_change_password") != fields.end()) {
167 g_gamecallback->changePassword();
171 if (fields.find("quit") != fields.end()) {
175 if (fields.find("btn_continue") != fields.end()) {
180 // Don't disable this part when modding is disabled, it's used in builtin
181 m_client->getScript()->on_formspec_input(m_formname, fields);
187 /* Form update callback */
189 class NodeMetadataFormSource: public IFormSource
192 NodeMetadataFormSource(ClientMap *map, v3s16 p):
197 std::string getForm()
199 NodeMetadata *meta = m_map->getNodeMetadata(m_p);
204 return meta->getString("formspec");
207 virtual std::string resolveText(const std::string &str)
209 NodeMetadata *meta = m_map->getNodeMetadata(m_p);
214 return meta->resolveString(str);
221 class PlayerInventoryFormSource: public IFormSource
224 PlayerInventoryFormSource(Client *client):
228 std::string getForm()
230 LocalPlayer *player = m_client->getEnv().getLocalPlayer();
231 return player->inventory_formspec;
237 /* Profiler display */
239 void update_profiler_gui(gui::IGUIStaticText *guitext_profiler, FontEngine *fe,
240 u32 show_profiler, u32 show_profiler_max, s32 screen_height)
242 if (show_profiler == 0) {
243 guitext_profiler->setVisible(false);
246 std::ostringstream os(std::ios_base::binary);
247 g_profiler->printPage(os, show_profiler, show_profiler_max);
248 std::wstring text = utf8_to_wide(os.str());
249 setStaticText(guitext_profiler, text.c_str());
250 guitext_profiler->setVisible(true);
252 s32 w = fe->getTextWidth(text.c_str());
257 unsigned text_height = fe->getTextHeight();
259 core::position2di upper_left, lower_right;
262 upper_left.Y = (text_height + 5) * 2;
263 lower_right.X = 12 + w;
264 lower_right.Y = upper_left.Y + (text_height + 1) * MAX_PROFILER_TEXT_ROWS;
266 if (lower_right.Y > screen_height * 2 / 3)
267 lower_right.Y = screen_height * 2 / 3;
269 core::rect<s32> rect(upper_left, lower_right);
271 guitext_profiler->setRelativePosition(rect);
272 guitext_profiler->setVisible(true);
280 Profiler::GraphValues values;
286 Meta(float initial = 0,
287 video::SColor color = video::SColor(255, 255, 255, 255)):
293 std::deque<Piece> m_log;
301 void put(const Profiler::GraphValues &values)
304 piece.values = values;
305 m_log.push_back(piece);
307 while (m_log.size() > m_log_max_size)
308 m_log.erase(m_log.begin());
311 void draw(s32 x_left, s32 y_bottom, video::IVideoDriver *driver,
312 gui::IGUIFont *font) const
314 // Do *not* use UNORDERED_MAP here as the order needs
315 // to be the same for each call to prevent flickering
316 std::map<std::string, Meta> m_meta;
318 for (std::deque<Piece>::const_iterator k = m_log.begin();
319 k != m_log.end(); ++k) {
320 const Piece &piece = *k;
322 for (Profiler::GraphValues::const_iterator i = piece.values.begin();
323 i != piece.values.end(); ++i) {
324 const std::string &id = i->first;
325 const float &value = i->second;
326 std::map<std::string, Meta>::iterator j = m_meta.find(id);
328 if (j == m_meta.end()) {
329 m_meta[id] = Meta(value);
333 if (value < j->second.min)
334 j->second.min = value;
336 if (value > j->second.max)
337 j->second.max = value;
342 static const video::SColor usable_colors[] = {
343 video::SColor(255, 255, 100, 100),
344 video::SColor(255, 90, 225, 90),
345 video::SColor(255, 100, 100, 255),
346 video::SColor(255, 255, 150, 50),
347 video::SColor(255, 220, 220, 100)
349 static const u32 usable_colors_count =
350 sizeof(usable_colors) / sizeof(*usable_colors);
351 u32 next_color_i = 0;
353 for (std::map<std::string, Meta>::iterator i = m_meta.begin();
354 i != m_meta.end(); ++i) {
355 Meta &meta = i->second;
356 video::SColor color(255, 200, 200, 200);
358 if (next_color_i < usable_colors_count)
359 color = usable_colors[next_color_i++];
365 s32 textx = x_left + m_log_max_size + 15;
366 s32 textx2 = textx + 200 - 15;
369 for (std::map<std::string, Meta>::const_iterator i = m_meta.begin();
370 i != m_meta.end(); ++i) {
371 const std::string &id = i->first;
372 const Meta &meta = i->second;
374 s32 y = y_bottom - meta_i * 50;
375 float show_min = meta.min;
376 float show_max = meta.max;
378 if (show_min >= -0.0001 && show_max >= -0.0001) {
379 if (show_min <= show_max * 0.5)
385 snprintf(buf, 10, "%.3g", show_max);
386 font->draw(utf8_to_wide(buf).c_str(),
387 core::rect<s32>(textx, y - graphh,
388 textx2, y - graphh + texth),
390 snprintf(buf, 10, "%.3g", show_min);
391 font->draw(utf8_to_wide(buf).c_str(),
392 core::rect<s32>(textx, y - texth,
395 font->draw(utf8_to_wide(id).c_str(),
396 core::rect<s32>(textx, y - graphh / 2 - texth / 2,
397 textx2, y - graphh / 2 + texth / 2),
400 s32 graph1h = graphh;
401 bool relativegraph = (show_min != 0 && show_min != show_max);
402 float lastscaledvalue = 0.0;
403 bool lastscaledvalue_exists = false;
405 for (std::deque<Piece>::const_iterator j = m_log.begin();
406 j != m_log.end(); ++j) {
407 const Piece &piece = *j;
409 bool value_exists = false;
410 Profiler::GraphValues::const_iterator k =
411 piece.values.find(id);
413 if (k != piece.values.end()) {
420 lastscaledvalue_exists = false;
424 float scaledvalue = 1.0;
426 if (show_max != show_min)
427 scaledvalue = (value - show_min) / (show_max - show_min);
429 if (scaledvalue == 1.0 && value == 0) {
431 lastscaledvalue_exists = false;
436 if (lastscaledvalue_exists) {
437 s32 ivalue1 = lastscaledvalue * graph1h;
438 s32 ivalue2 = scaledvalue * graph1h;
439 driver->draw2DLine(v2s32(x - 1, graph1y - ivalue1),
440 v2s32(x, graph1y - ivalue2), meta.color);
443 lastscaledvalue = scaledvalue;
444 lastscaledvalue_exists = true;
446 s32 ivalue = scaledvalue * graph1h;
447 driver->draw2DLine(v2s32(x, graph1y),
448 v2s32(x, graph1y - ivalue), meta.color);
459 class NodeDugEvent: public MtEvent
465 NodeDugEvent(v3s16 p, MapNode n):
469 const char *getType() const
477 ISoundManager *m_sound;
478 INodeDefManager *m_ndef;
480 bool makes_footstep_sound;
481 float m_player_step_timer;
483 SimpleSoundSpec m_player_step_sound;
484 SimpleSoundSpec m_player_leftpunch_sound;
485 SimpleSoundSpec m_player_rightpunch_sound;
487 SoundMaker(ISoundManager *sound, INodeDefManager *ndef):
490 makes_footstep_sound(true),
491 m_player_step_timer(0)
495 void playPlayerStep()
497 if (m_player_step_timer <= 0 && m_player_step_sound.exists()) {
498 m_player_step_timer = 0.03;
499 if (makes_footstep_sound)
500 m_sound->playSound(m_player_step_sound, false);
504 static void viewBobbingStep(MtEvent *e, void *data)
506 SoundMaker *sm = (SoundMaker *)data;
507 sm->playPlayerStep();
510 static void playerRegainGround(MtEvent *e, void *data)
512 SoundMaker *sm = (SoundMaker *)data;
513 sm->playPlayerStep();
516 static void playerJump(MtEvent *e, void *data)
518 //SoundMaker *sm = (SoundMaker*)data;
521 static void cameraPunchLeft(MtEvent *e, void *data)
523 SoundMaker *sm = (SoundMaker *)data;
524 sm->m_sound->playSound(sm->m_player_leftpunch_sound, false);
527 static void cameraPunchRight(MtEvent *e, void *data)
529 SoundMaker *sm = (SoundMaker *)data;
530 sm->m_sound->playSound(sm->m_player_rightpunch_sound, false);
533 static void nodeDug(MtEvent *e, void *data)
535 SoundMaker *sm = (SoundMaker *)data;
536 NodeDugEvent *nde = (NodeDugEvent *)e;
537 sm->m_sound->playSound(sm->m_ndef->get(nde->n).sound_dug, false);
540 static void playerDamage(MtEvent *e, void *data)
542 SoundMaker *sm = (SoundMaker *)data;
543 sm->m_sound->playSound(SimpleSoundSpec("player_damage", 0.5), false);
546 static void playerFallingDamage(MtEvent *e, void *data)
548 SoundMaker *sm = (SoundMaker *)data;
549 sm->m_sound->playSound(SimpleSoundSpec("player_falling_damage", 0.5), false);
552 void registerReceiver(MtEventManager *mgr)
554 mgr->reg("ViewBobbingStep", SoundMaker::viewBobbingStep, this);
555 mgr->reg("PlayerRegainGround", SoundMaker::playerRegainGround, this);
556 mgr->reg("PlayerJump", SoundMaker::playerJump, this);
557 mgr->reg("CameraPunchLeft", SoundMaker::cameraPunchLeft, this);
558 mgr->reg("CameraPunchRight", SoundMaker::cameraPunchRight, this);
559 mgr->reg("NodeDug", SoundMaker::nodeDug, this);
560 mgr->reg("PlayerDamage", SoundMaker::playerDamage, this);
561 mgr->reg("PlayerFallingDamage", SoundMaker::playerFallingDamage, this);
564 void step(float dtime)
566 m_player_step_timer -= dtime;
570 // Locally stored sounds don't need to be preloaded because of this
571 class GameOnDemandSoundFetcher: public OnDemandSoundFetcher
573 std::set<std::string> m_fetched;
575 void paths_insert(std::set<std::string> &dst_paths,
576 const std::string &base,
577 const std::string &name)
579 dst_paths.insert(base + DIR_DELIM + "sounds" + DIR_DELIM + name + ".ogg");
580 dst_paths.insert(base + DIR_DELIM + "sounds" + DIR_DELIM + name + ".0.ogg");
581 dst_paths.insert(base + DIR_DELIM + "sounds" + DIR_DELIM + name + ".1.ogg");
582 dst_paths.insert(base + DIR_DELIM + "sounds" + DIR_DELIM + name + ".2.ogg");
583 dst_paths.insert(base + DIR_DELIM + "sounds" + DIR_DELIM + name + ".3.ogg");
584 dst_paths.insert(base + DIR_DELIM + "sounds" + DIR_DELIM + name + ".4.ogg");
585 dst_paths.insert(base + DIR_DELIM + "sounds" + DIR_DELIM + name + ".5.ogg");
586 dst_paths.insert(base + DIR_DELIM + "sounds" + DIR_DELIM + name + ".6.ogg");
587 dst_paths.insert(base + DIR_DELIM + "sounds" + DIR_DELIM + name + ".7.ogg");
588 dst_paths.insert(base + DIR_DELIM + "sounds" + DIR_DELIM + name + ".8.ogg");
589 dst_paths.insert(base + DIR_DELIM + "sounds" + DIR_DELIM + name + ".9.ogg");
592 void fetchSounds(const std::string &name,
593 std::set<std::string> &dst_paths,
594 std::set<std::string> &dst_datas)
596 if (m_fetched.count(name))
599 m_fetched.insert(name);
601 paths_insert(dst_paths, porting::path_share, name);
602 paths_insert(dst_paths, porting::path_user, name);
607 // before 1.8 there isn't a "integer interface", only float
608 #if (IRRLICHT_VERSION_MAJOR == 1 && IRRLICHT_VERSION_MINOR < 8)
609 typedef f32 SamplerLayer_t;
611 typedef s32 SamplerLayer_t;
615 class GameGlobalShaderConstantSetter : public IShaderConstantSetter
618 bool *m_force_fog_off;
621 CachedPixelShaderSetting<float, 4> m_sky_bg_color;
622 CachedPixelShaderSetting<float> m_fog_distance;
623 CachedVertexShaderSetting<float> m_animation_timer_vertex;
624 CachedPixelShaderSetting<float> m_animation_timer_pixel;
625 CachedPixelShaderSetting<float, 3> m_day_light;
626 CachedPixelShaderSetting<float, 3> m_eye_position_pixel;
627 CachedVertexShaderSetting<float, 3> m_eye_position_vertex;
628 CachedPixelShaderSetting<float, 3> m_minimap_yaw;
629 CachedPixelShaderSetting<SamplerLayer_t> m_base_texture;
630 CachedPixelShaderSetting<SamplerLayer_t> m_normal_texture;
631 CachedPixelShaderSetting<SamplerLayer_t> m_texture_flags;
635 void onSettingsChange(const std::string &name)
637 if (name == "enable_fog")
638 m_fog_enabled = g_settings->getBool("enable_fog");
641 static void settingsCallback(const std::string &name, void *userdata)
643 reinterpret_cast<GameGlobalShaderConstantSetter*>(userdata)->onSettingsChange(name);
646 void setSky(Sky *sky) { m_sky = sky; }
648 GameGlobalShaderConstantSetter(Sky *sky, bool *force_fog_off,
649 f32 *fog_range, Client *client) :
651 m_force_fog_off(force_fog_off),
652 m_fog_range(fog_range),
653 m_sky_bg_color("skyBgColor"),
654 m_fog_distance("fogDistance"),
655 m_animation_timer_vertex("animationTimer"),
656 m_animation_timer_pixel("animationTimer"),
657 m_day_light("dayLight"),
658 m_eye_position_pixel("eyePosition"),
659 m_eye_position_vertex("eyePosition"),
660 m_minimap_yaw("yawVec"),
661 m_base_texture("baseTexture"),
662 m_normal_texture("normalTexture"),
663 m_texture_flags("textureFlags"),
666 g_settings->registerChangedCallback("enable_fog", settingsCallback, this);
667 m_fog_enabled = g_settings->getBool("enable_fog");
670 ~GameGlobalShaderConstantSetter()
672 g_settings->deregisterChangedCallback("enable_fog", settingsCallback, this);
675 virtual void onSetConstants(video::IMaterialRendererServices *services,
682 video::SColor bgcolor = m_sky->getBgColor();
683 video::SColorf bgcolorf(bgcolor);
684 float bgcolorfa[4] = {
690 m_sky_bg_color.set(bgcolorfa, services);
693 float fog_distance = 10000 * BS;
695 if (m_fog_enabled && !*m_force_fog_off)
696 fog_distance = *m_fog_range;
698 m_fog_distance.set(&fog_distance, services);
700 u32 daynight_ratio = (float)m_client->getEnv().getDayNightRatio();
701 video::SColorf sunlight;
702 get_sunlight_color(&sunlight, daynight_ratio);
707 m_day_light.set(dnc, services);
709 u32 animation_timer = porting::getTimeMs() % 100000;
710 float animation_timer_f = (float)animation_timer / 100000.f;
711 m_animation_timer_vertex.set(&animation_timer_f, services);
712 m_animation_timer_pixel.set(&animation_timer_f, services);
714 float eye_position_array[3];
715 v3f epos = m_client->getEnv().getLocalPlayer()->getEyePosition();
716 #if (IRRLICHT_VERSION_MAJOR == 1 && IRRLICHT_VERSION_MINOR < 8)
717 eye_position_array[0] = epos.X;
718 eye_position_array[1] = epos.Y;
719 eye_position_array[2] = epos.Z;
721 epos.getAs3Values(eye_position_array);
723 m_eye_position_pixel.set(eye_position_array, services);
724 m_eye_position_vertex.set(eye_position_array, services);
726 float minimap_yaw_array[3];
727 v3f minimap_yaw = m_client->getMinimap()->getYawVec();
728 #if (IRRLICHT_VERSION_MAJOR == 1 && IRRLICHT_VERSION_MINOR < 8)
729 minimap_yaw_array[0] = minimap_yaw.X;
730 minimap_yaw_array[1] = minimap_yaw.Y;
731 minimap_yaw_array[2] = minimap_yaw.Z;
733 minimap_yaw.getAs3Values(minimap_yaw_array);
735 m_minimap_yaw.set(minimap_yaw_array, services);
737 SamplerLayer_t base_tex = 0,
740 m_base_texture.set(&base_tex, services);
741 m_normal_texture.set(&normal_tex, services);
742 m_texture_flags.set(&flags_tex, services);
747 class GameGlobalShaderConstantSetterFactory : public IShaderConstantSetterFactory
750 bool *m_force_fog_off;
753 std::vector<GameGlobalShaderConstantSetter *> created_nosky;
755 GameGlobalShaderConstantSetterFactory(bool *force_fog_off,
756 f32 *fog_range, Client *client) :
758 m_force_fog_off(force_fog_off),
759 m_fog_range(fog_range),
763 void setSky(Sky *sky) {
765 for (size_t i = 0; i < created_nosky.size(); ++i) {
766 created_nosky[i]->setSky(m_sky);
768 created_nosky.clear();
771 virtual IShaderConstantSetter* create()
773 GameGlobalShaderConstantSetter *scs = new GameGlobalShaderConstantSetter(
774 m_sky, m_force_fog_off, m_fog_range, m_client);
776 created_nosky.push_back(scs);
782 bool nodePlacementPrediction(Client &client,
783 const ItemDefinition &playeritem_def, v3s16 nodepos, v3s16 neighbourpos)
785 std::string prediction = playeritem_def.node_placement_prediction;
786 INodeDefManager *nodedef = client.ndef();
787 ClientMap &map = client.getEnv().getClientMap();
789 bool is_valid_position;
791 node = map.getNodeNoEx(nodepos, &is_valid_position);
792 if (!is_valid_position)
795 if (prediction != "" && !nodedef->get(node).rightclickable) {
796 verbosestream << "Node placement prediction for "
797 << playeritem_def.name << " is "
798 << prediction << std::endl;
799 v3s16 p = neighbourpos;
801 // Place inside node itself if buildable_to
802 MapNode n_under = map.getNodeNoEx(nodepos, &is_valid_position);
803 if (is_valid_position)
805 if (nodedef->get(n_under).buildable_to)
808 node = map.getNodeNoEx(p, &is_valid_position);
809 if (is_valid_position &&!nodedef->get(node).buildable_to)
814 // Find id of predicted node
816 bool found = nodedef->getId(prediction, id);
819 errorstream << "Node placement prediction failed for "
820 << playeritem_def.name << " (places "
822 << ") - Name not known" << std::endl;
826 // Predict param2 for facedir and wallmounted nodes
829 if (nodedef->get(id).param_type_2 == CPT2_WALLMOUNTED ||
830 nodedef->get(id).param_type_2 == CPT2_COLORED_WALLMOUNTED) {
831 v3s16 dir = nodepos - neighbourpos;
833 if (abs(dir.Y) > MYMAX(abs(dir.X), abs(dir.Z))) {
834 param2 = dir.Y < 0 ? 1 : 0;
835 } else if (abs(dir.X) > abs(dir.Z)) {
836 param2 = dir.X < 0 ? 3 : 2;
838 param2 = dir.Z < 0 ? 5 : 4;
842 if (nodedef->get(id).param_type_2 == CPT2_FACEDIR ||
843 nodedef->get(id).param_type_2 == CPT2_COLORED_FACEDIR) {
844 v3s16 dir = nodepos - floatToInt(client.getEnv().getLocalPlayer()->getPosition(), BS);
846 if (abs(dir.X) > abs(dir.Z)) {
847 param2 = dir.X < 0 ? 3 : 1;
849 param2 = dir.Z < 0 ? 2 : 0;
855 //Check attachment if node is in group attached_node
856 if (((ItemGroupList) nodedef->get(id).groups)["attached_node"] != 0) {
857 static v3s16 wallmounted_dirs[8] = {
867 if (nodedef->get(id).param_type_2 == CPT2_WALLMOUNTED ||
868 nodedef->get(id).param_type_2 == CPT2_COLORED_WALLMOUNTED)
869 pp = p + wallmounted_dirs[param2];
871 pp = p + v3s16(0, -1, 0);
873 if (!nodedef->get(map.getNodeNoEx(pp)).walkable)
877 // Add node to client map
878 MapNode n(id, 0, param2);
881 LocalPlayer *player = client.getEnv().getLocalPlayer();
883 // Dont place node when player would be inside new node
884 // NOTE: This is to be eventually implemented by a mod as client-side Lua
885 if (!nodedef->get(n).walkable ||
886 g_settings->getBool("enable_build_where_you_stand") ||
887 (client.checkPrivilege("noclip") && g_settings->getBool("noclip")) ||
888 (nodedef->get(n).walkable &&
889 neighbourpos != player->getStandingNodePos() + v3s16(0, 1, 0) &&
890 neighbourpos != player->getStandingNodePos() + v3s16(0, 2, 0))) {
892 // This triggers the required mesh update too
893 client.addNode(p, n);
896 } catch (InvalidPositionException &e) {
897 errorstream << "Node placement prediction failed for "
898 << playeritem_def.name << " (places "
900 << ") - Position not loaded" << std::endl;
907 static inline void create_formspec_menu(GUIFormSpecMenu **cur_formspec,
908 Client *client, IrrlichtDevice *device, JoystickController *joystick,
909 IFormSource *fs_src, TextDest *txt_dest)
912 if (*cur_formspec == 0) {
913 *cur_formspec = new GUIFormSpecMenu(device, joystick,
914 guiroot, -1, &g_menumgr, client, client->getTextureSource(),
916 (*cur_formspec)->doPause = false;
919 Caution: do not call (*cur_formspec)->drop() here --
920 the reference might outlive the menu, so we will
921 periodically check if *cur_formspec is the only
922 remaining reference (i.e. the menu was removed)
923 and delete it in that case.
927 (*cur_formspec)->setFormSource(fs_src);
928 (*cur_formspec)->setTextDest(txt_dest);
934 #define SIZE_TAG "size[11,5.5]"
936 #define SIZE_TAG "size[11,5.5,true]" // Fixed size on desktop
939 /******************************************************************************/
940 static void updateChat(Client &client, f32 dtime, bool show_debug,
941 const v2u32 &screensize, bool show_chat, u32 show_profiler,
942 ChatBackend &chat_backend, gui::IGUIStaticText *guitext_chat)
944 // Add chat log output for errors to be shown in chat
945 static LogOutputBuffer chat_log_error_buf(g_logger, LL_ERROR);
947 // Get new messages from error log buffer
948 while (!chat_log_error_buf.empty()) {
949 std::wstring error_message = utf8_to_wide(chat_log_error_buf.get());
950 if (!g_settings->getBool("disable_escape_sequences")) {
951 error_message = L"\x1b(c@red)" + error_message + L"\x1b(c@white)";
953 chat_backend.addMessage(L"", error_message);
956 // Get new messages from client
957 std::wstring message;
959 while (client.getChatMessage(message)) {
960 chat_backend.addUnparsedMessage(message);
963 // Remove old messages
964 chat_backend.step(dtime);
966 // Display all messages in a static text element
967 unsigned int recent_chat_count = chat_backend.getRecentBuffer().getLineCount();
968 EnrichedString recent_chat = chat_backend.getRecentChat();
969 unsigned int line_height = g_fontengine->getLineHeight();
971 setStaticText(guitext_chat, recent_chat);
973 // Update gui element size and position
977 chat_y += 2 * line_height;
979 // first pass to calculate height of text to be set
980 s32 width = std::min(g_fontengine->getTextWidth(recent_chat.c_str()) + 10,
981 porting::getWindowSize().X - 20);
982 core::rect<s32> rect(10, chat_y, width, chat_y + porting::getWindowSize().Y);
983 guitext_chat->setRelativePosition(rect);
985 //now use real height of text and adjust rect according to this size
986 rect = core::rect<s32>(10, chat_y, width,
987 chat_y + guitext_chat->getTextHeight());
990 guitext_chat->setRelativePosition(rect);
991 // Don't show chat if disabled or empty or profiler is enabled
992 guitext_chat->setVisible(
993 show_chat && recent_chat_count != 0 && !show_profiler);
997 /****************************************************************************
998 Fast key cache for main game loop
999 ****************************************************************************/
1001 /* This is faster than using getKeySetting with the tradeoff that functions
1002 * using it must make sure that it's initialised before using it and there is
1003 * no error handling (for example bounds checking). This is really intended for
1004 * use only in the main running loop of the client (the_game()) where the faster
1005 * (up to 10x faster) key lookup is an asset. Other parts of the codebase
1006 * (e.g. formspecs) should continue using getKeySetting().
1014 populate_nonchanging();
1019 // Keys that are not settings dependent
1020 void populate_nonchanging();
1022 KeyPress key[KeyType::INTERNAL_ENUM_COUNT];
1023 InputHandler *handler;
1026 void KeyCache::populate_nonchanging()
1028 key[KeyType::ESC] = EscapeKey;
1031 void KeyCache::populate()
1033 key[KeyType::FORWARD] = getKeySetting("keymap_forward");
1034 key[KeyType::BACKWARD] = getKeySetting("keymap_backward");
1035 key[KeyType::LEFT] = getKeySetting("keymap_left");
1036 key[KeyType::RIGHT] = getKeySetting("keymap_right");
1037 key[KeyType::JUMP] = getKeySetting("keymap_jump");
1038 key[KeyType::SPECIAL1] = getKeySetting("keymap_special1");
1039 key[KeyType::SNEAK] = getKeySetting("keymap_sneak");
1041 key[KeyType::AUTORUN] = getKeySetting("keymap_autorun");
1043 key[KeyType::DROP] = getKeySetting("keymap_drop");
1044 key[KeyType::INVENTORY] = getKeySetting("keymap_inventory");
1045 key[KeyType::CHAT] = getKeySetting("keymap_chat");
1046 key[KeyType::CMD] = getKeySetting("keymap_cmd");
1047 key[KeyType::CMD_LOCAL] = getKeySetting("keymap_cmd_local");
1048 key[KeyType::CONSOLE] = getKeySetting("keymap_console");
1049 key[KeyType::MINIMAP] = getKeySetting("keymap_minimap");
1050 key[KeyType::FREEMOVE] = getKeySetting("keymap_freemove");
1051 key[KeyType::FASTMOVE] = getKeySetting("keymap_fastmove");
1052 key[KeyType::NOCLIP] = getKeySetting("keymap_noclip");
1053 key[KeyType::HOTBAR_PREV] = getKeySetting("keymap_hotbar_previous");
1054 key[KeyType::HOTBAR_NEXT] = getKeySetting("keymap_hotbar_next");
1055 key[KeyType::MUTE] = getKeySetting("keymap_mute");
1056 key[KeyType::INC_VOLUME] = getKeySetting("keymap_increase_volume");
1057 key[KeyType::DEC_VOLUME] = getKeySetting("keymap_decrease_volume");
1058 key[KeyType::CINEMATIC] = getKeySetting("keymap_cinematic");
1059 key[KeyType::SCREENSHOT] = getKeySetting("keymap_screenshot");
1060 key[KeyType::TOGGLE_HUD] = getKeySetting("keymap_toggle_hud");
1061 key[KeyType::TOGGLE_CHAT] = getKeySetting("keymap_toggle_chat");
1062 key[KeyType::TOGGLE_FORCE_FOG_OFF]
1063 = getKeySetting("keymap_toggle_force_fog_off");
1064 key[KeyType::TOGGLE_UPDATE_CAMERA]
1065 = getKeySetting("keymap_toggle_update_camera");
1066 key[KeyType::TOGGLE_DEBUG]
1067 = getKeySetting("keymap_toggle_debug");
1068 key[KeyType::TOGGLE_PROFILER]
1069 = getKeySetting("keymap_toggle_profiler");
1070 key[KeyType::CAMERA_MODE]
1071 = getKeySetting("keymap_camera_mode");
1072 key[KeyType::INCREASE_VIEWING_RANGE]
1073 = getKeySetting("keymap_increase_viewing_range_min");
1074 key[KeyType::DECREASE_VIEWING_RANGE]
1075 = getKeySetting("keymap_decrease_viewing_range_min");
1076 key[KeyType::RANGESELECT]
1077 = getKeySetting("keymap_rangeselect");
1078 key[KeyType::ZOOM] = getKeySetting("keymap_zoom");
1080 key[KeyType::QUICKTUNE_NEXT] = getKeySetting("keymap_quicktune_next");
1081 key[KeyType::QUICKTUNE_PREV] = getKeySetting("keymap_quicktune_prev");
1082 key[KeyType::QUICKTUNE_INC] = getKeySetting("keymap_quicktune_inc");
1083 key[KeyType::QUICKTUNE_DEC] = getKeySetting("keymap_quicktune_dec");
1085 key[KeyType::DEBUG_STACKS] = getKeySetting("keymap_print_debug_stacks");
1088 // First clear all keys, then re-add the ones we listen for
1089 handler->dontListenForKeys();
1090 for (size_t i = 0; i < KeyType::INTERNAL_ENUM_COUNT; i++) {
1091 handler->listenForKey(key[i]);
1093 handler->listenForKey(EscapeKey);
1094 handler->listenForKey(CancelKey);
1095 for (size_t i = 0; i < 10; i++) {
1096 handler->listenForKey(NumberKey[i]);
1102 /****************************************************************************
1104 ****************************************************************************/
1106 const float object_hit_delay = 0.2;
1109 u32 last_time, busy_time, sleep_time;
1113 /* The reason the following structs are not anonymous structs within the
1114 * class is that they are not used by the majority of member functions and
1115 * many functions that do require objects of thse types do not modify them
1116 * (so they can be passed as a const qualified parameter)
1118 struct CameraOrientation {
1119 f32 camera_yaw; // "right/left"
1120 f32 camera_pitch; // "up/down"
1123 struct GameRunData {
1126 PointedThing pointed_old;
1131 bool update_wielded_item_trigger;
1132 bool reset_jump_timer;
1133 float nodig_delay_timer;
1135 float dig_time_complete;
1136 float repeat_rightclick_timer;
1137 float object_hit_delay_timer;
1138 float time_from_last_punch;
1139 ClientActiveObject *selected_object;
1143 float update_draw_list_timer;
1144 float statustext_time;
1148 v3f update_draw_list_last_cam_dir;
1150 u32 profiler_current_page;
1151 u32 profiler_max_page; // Number of pages
1154 float time_of_day_smooth;
1158 f32 max, min, avg, counter, max_sample, min_sample, max_fraction;
1164 Jitter dtime_jitter, busy_time_jitter;
1167 /****************************************************************************
1169 ****************************************************************************/
1171 /* This is not intended to be a public class. If a public class becomes
1172 * desirable then it may be better to create another 'wrapper' class that
1173 * hides most of the stuff in this class (nothing in this class is required
1174 * by any other file) but exposes the public methods/data only.
1181 bool startup(bool *kill,
1183 InputHandler *input,
1184 IrrlichtDevice *device,
1185 const std::string &map_dir,
1186 const std::string &playername,
1187 const std::string &password,
1188 // If address is "", local server is used and address is updated
1189 std::string *address,
1191 std::string &error_message,
1193 ChatBackend *chat_backend,
1194 const SubgameSpec &gamespec, // Used for local game
1195 bool simple_singleplayer_mode);
1202 void extendedResourceCleanup();
1204 // Basic initialisation
1205 bool init(const std::string &map_dir, std::string *address,
1207 const SubgameSpec &gamespec);
1209 bool createSingleplayerServer(const std::string &map_dir,
1210 const SubgameSpec &gamespec, u16 port, std::string *address);
1213 bool createClient(const std::string &playername,
1214 const std::string &password, std::string *address, u16 port);
1217 // Client connection
1218 bool connectToServer(const std::string &playername,
1219 const std::string &password, std::string *address, u16 port,
1220 bool *connect_ok, bool *aborted);
1221 bool getServerContent(bool *aborted);
1225 void updateInteractTimers(f32 dtime);
1226 bool checkConnection();
1227 bool handleCallbacks();
1228 void processQueues();
1229 void updateProfilers(const RunStats &stats, const FpsControl &draw_times, f32 dtime);
1230 void addProfilerGraphs(const RunStats &stats, const FpsControl &draw_times, f32 dtime);
1231 void updateStats(RunStats *stats, const FpsControl &draw_times, f32 dtime);
1234 void processUserInput(f32 dtime);
1235 void processKeyInput();
1236 void processItemSelection(u16 *new_playeritem);
1238 void dropSelectedItem();
1239 void openInventory();
1240 void openConsole(float scale, const wchar_t *line=NULL);
1241 void toggleFreeMove();
1242 void toggleFreeMoveAlt();
1244 void toggleNoClip();
1245 void toggleCinematic();
1246 void toggleAutorun();
1250 void toggleMinimap(bool shift_pressed);
1253 void toggleUpdateCamera();
1254 void toggleProfiler();
1256 void increaseViewRange();
1257 void decreaseViewRange();
1258 void toggleFullViewRange();
1260 void updateCameraDirection(CameraOrientation *cam, float dtime);
1261 void updateCameraOrientation(CameraOrientation *cam, float dtime);
1262 void updatePlayerControl(const CameraOrientation &cam);
1263 void step(f32 *dtime);
1264 void processClientEvents(CameraOrientation *cam);
1265 void updateCamera(u32 busy_time, f32 dtime);
1266 void updateSound(f32 dtime);
1267 void processPlayerInteraction(f32 dtime, bool show_hud, bool show_debug);
1269 * Returns the object or node the player is pointing at.
1270 * Also updates the selected thing in the Hud.
1272 * @param[in] shootline the shootline, starting from
1273 * the camera position. This also gives the maximal distance
1275 * @param[in] liquids_pointable if false, liquids are ignored
1276 * @param[in] look_for_object if false, objects are ignored
1277 * @param[in] camera_offset offset of the camera
1278 * @param[out] selected_object the selected object or
1281 PointedThing updatePointedThing(
1282 const core::line3d<f32> &shootline, bool liquids_pointable,
1283 bool look_for_object, const v3s16 &camera_offset);
1284 void handlePointingAtNothing(const ItemStack &playerItem);
1285 void handlePointingAtNode(const PointedThing &pointed, const ItemDefinition &playeritem_def,
1286 const ToolCapabilities &playeritem_toolcap, f32 dtime);
1287 void handlePointingAtObject(const PointedThing &pointed, const ItemStack &playeritem,
1288 const v3f &player_position, bool show_debug);
1289 void handleDigging(const PointedThing &pointed, const v3s16 &nodepos,
1290 const ToolCapabilities &playeritem_toolcap, f32 dtime);
1291 void updateFrame(ProfilerGraph *graph, RunStats *stats, f32 dtime,
1292 const CameraOrientation &cam);
1293 void updateGui(const RunStats &stats, f32 dtime, const CameraOrientation &cam);
1294 void updateProfilerGraphs(ProfilerGraph *graph);
1297 void limitFps(FpsControl *fps_timings, f32 *dtime);
1299 void showOverlayMessage(const wchar_t *msg, float dtime, int percent,
1300 bool draw_clouds = true);
1302 static void settingChangedCallback(const std::string &setting_name, void *data);
1303 void readSettings();
1305 inline bool getLeftClicked()
1307 return input->getLeftClicked() ||
1308 input->joystick.getWasKeyDown(KeyType::MOUSE_L);
1310 inline bool getRightClicked()
1312 return input->getRightClicked() ||
1313 input->joystick.getWasKeyDown(KeyType::MOUSE_R);
1315 inline bool isLeftPressed()
1317 return input->getLeftState() ||
1318 input->joystick.isKeyDown(KeyType::MOUSE_L);
1320 inline bool isRightPressed()
1322 return input->getRightState() ||
1323 input->joystick.isKeyDown(KeyType::MOUSE_R);
1325 inline bool getLeftReleased()
1327 return input->getLeftReleased() ||
1328 input->joystick.wasKeyReleased(KeyType::MOUSE_L);
1331 inline bool isKeyDown(GameKeyType k)
1333 return input->isKeyDown(keycache.key[k]) || input->joystick.isKeyDown(k);
1335 inline bool wasKeyDown(GameKeyType k)
1337 return input->wasKeyDown(keycache.key[k]) || input->joystick.wasKeyDown(k);
1341 void handleAndroidChatInput();
1345 void showPauseMenu();
1347 InputHandler *input;
1352 IWritableTextureSource *texture_src;
1353 IWritableShaderSource *shader_src;
1355 // When created, these will be filled with data received from the server
1356 IWritableItemDefManager *itemdef_manager;
1357 IWritableNodeDefManager *nodedef_manager;
1359 GameOnDemandSoundFetcher soundfetcher; // useful when testing
1360 ISoundManager *sound;
1361 bool sound_is_dummy;
1362 SoundMaker *soundmaker;
1364 ChatBackend *chat_backend;
1366 GUIFormSpecMenu *current_formspec;
1367 //default: "". If other than "", empty show_formspec packets will only close the formspec when the formname matches
1368 std::string cur_formname;
1370 EventManager *eventmgr;
1371 QuicktuneShortcutter *quicktune;
1373 GUIChatConsole *gui_chat_console; // Free using ->Drop()
1374 MapDrawControl *draw_control;
1376 Clouds *clouds; // Free using ->Drop()
1377 Sky *sky; // Free using ->Drop()
1378 Inventory *local_inventory;
1382 GameRunData runData;
1386 This class does take ownership/responsibily for cleaning up etc of any of
1387 these items (e.g. device)
1389 IrrlichtDevice *device;
1390 video::IVideoDriver *driver;
1391 scene::ISceneManager *smgr;
1393 std::string *error_message;
1394 bool *reconnect_requested;
1395 scene::ISceneNode *skybox;
1398 bool simple_singleplayer_mode;
1401 /* Pre-calculated values
1403 int crack_animation_length;
1407 gui::IGUIStaticText *guitext; // First line of debug text
1408 gui::IGUIStaticText *guitext2; // Second line of debug text
1409 gui::IGUIStaticText *guitext_info; // At the middle of the screen
1410 gui::IGUIStaticText *guitext_status;
1411 gui::IGUIStaticText *guitext_chat; // Chat text
1412 gui::IGUIStaticText *guitext_profiler; // Profiler text
1414 std::wstring infotext;
1415 std::wstring m_statustext;
1419 IntervalLimiter profiler_interval;
1422 * TODO: Local caching of settings is not optimal and should at some stage
1423 * be updated to use a global settings object for getting thse values
1424 * (as opposed to the this local caching). This can be addressed in
1427 bool m_cache_doubletap_jump;
1428 bool m_cache_enable_clouds;
1429 bool m_cache_enable_joysticks;
1430 bool m_cache_enable_particles;
1431 bool m_cache_enable_fog;
1432 bool m_cache_enable_noclip;
1433 bool m_cache_enable_free_move;
1434 f32 m_cache_mouse_sensitivity;
1435 f32 m_cache_joystick_frustum_sensitivity;
1436 f32 m_repeat_right_click_time;
1437 f32 m_cache_cam_smoothing;
1438 f32 m_cache_fog_start;
1440 bool m_invert_mouse;
1441 bool m_first_loop_after_window_activation;
1442 bool m_camera_offset_changed;
1445 bool m_cache_hold_aux1;
1446 bool m_android_chat_open;
1455 itemdef_manager(NULL),
1456 nodedef_manager(NULL),
1458 sound_is_dummy(false),
1461 current_formspec(NULL),
1465 gui_chat_console(NULL),
1470 local_inventory(NULL),
1473 m_invert_mouse(false),
1474 m_first_loop_after_window_activation(false),
1475 m_camera_offset_changed(false)
1477 g_settings->registerChangedCallback("doubletap_jump",
1478 &settingChangedCallback, this);
1479 g_settings->registerChangedCallback("enable_clouds",
1480 &settingChangedCallback, this);
1481 g_settings->registerChangedCallback("doubletap_joysticks",
1482 &settingChangedCallback, this);
1483 g_settings->registerChangedCallback("enable_particles",
1484 &settingChangedCallback, this);
1485 g_settings->registerChangedCallback("enable_fog",
1486 &settingChangedCallback, this);
1487 g_settings->registerChangedCallback("mouse_sensitivity",
1488 &settingChangedCallback, this);
1489 g_settings->registerChangedCallback("joystick_frustum_sensitivity",
1490 &settingChangedCallback, this);
1491 g_settings->registerChangedCallback("repeat_rightclick_time",
1492 &settingChangedCallback, this);
1493 g_settings->registerChangedCallback("noclip",
1494 &settingChangedCallback, this);
1495 g_settings->registerChangedCallback("free_move",
1496 &settingChangedCallback, this);
1497 g_settings->registerChangedCallback("cinematic",
1498 &settingChangedCallback, this);
1499 g_settings->registerChangedCallback("cinematic_camera_smoothing",
1500 &settingChangedCallback, this);
1501 g_settings->registerChangedCallback("camera_smoothing",
1502 &settingChangedCallback, this);
1507 m_cache_hold_aux1 = false; // This is initialised properly later
1514 /****************************************************************************
1516 ****************************************************************************/
1522 if (!sound_is_dummy)
1525 delete server; // deleted first to stop all server threads
1528 delete local_inventory;
1534 delete nodedef_manager;
1535 delete itemdef_manager;
1536 delete draw_control;
1538 extendedResourceCleanup();
1540 g_settings->deregisterChangedCallback("doubletap_jump",
1541 &settingChangedCallback, this);
1542 g_settings->deregisterChangedCallback("enable_clouds",
1543 &settingChangedCallback, this);
1544 g_settings->deregisterChangedCallback("enable_particles",
1545 &settingChangedCallback, this);
1546 g_settings->deregisterChangedCallback("enable_fog",
1547 &settingChangedCallback, this);
1548 g_settings->deregisterChangedCallback("mouse_sensitivity",
1549 &settingChangedCallback, this);
1550 g_settings->deregisterChangedCallback("repeat_rightclick_time",
1551 &settingChangedCallback, this);
1552 g_settings->deregisterChangedCallback("noclip",
1553 &settingChangedCallback, this);
1554 g_settings->deregisterChangedCallback("free_move",
1555 &settingChangedCallback, this);
1556 g_settings->deregisterChangedCallback("cinematic",
1557 &settingChangedCallback, this);
1558 g_settings->deregisterChangedCallback("cinematic_camera_smoothing",
1559 &settingChangedCallback, this);
1560 g_settings->deregisterChangedCallback("camera_smoothing",
1561 &settingChangedCallback, this);
1564 bool Game::startup(bool *kill,
1566 InputHandler *input,
1567 IrrlichtDevice *device,
1568 const std::string &map_dir,
1569 const std::string &playername,
1570 const std::string &password,
1571 std::string *address, // can change if simple_singleplayer_mode
1573 std::string &error_message,
1575 ChatBackend *chat_backend,
1576 const SubgameSpec &gamespec,
1577 bool simple_singleplayer_mode)
1580 this->device = device;
1582 this->error_message = &error_message;
1583 this->reconnect_requested = reconnect;
1584 this->random_input = random_input;
1585 this->input = input;
1586 this->chat_backend = chat_backend;
1587 this->simple_singleplayer_mode = simple_singleplayer_mode;
1589 keycache.handler = input;
1590 keycache.populate();
1592 driver = device->getVideoDriver();
1593 smgr = device->getSceneManager();
1595 smgr->getParameters()->setAttribute(scene::OBJ_LOADER_IGNORE_MATERIAL_FILES, true);
1597 memset(&runData, 0, sizeof(runData));
1598 runData.time_from_last_punch = 10.0;
1599 runData.profiler_max_page = 3;
1600 runData.update_wielded_item_trigger = true;
1602 memset(&flags, 0, sizeof(flags));
1603 flags.show_chat = true;
1604 flags.show_hud = true;
1605 flags.show_debug = g_settings->getBool("show_debug");
1606 m_invert_mouse = g_settings->getBool("invert_mouse");
1607 m_first_loop_after_window_activation = true;
1609 if (!init(map_dir, address, port, gamespec))
1612 if (!createClient(playername, password, address, port))
1621 ProfilerGraph graph;
1622 RunStats stats = { 0 };
1623 CameraOrientation cam_view_target = { 0 };
1624 CameraOrientation cam_view = { 0 };
1625 FpsControl draw_times = { 0 };
1626 f32 dtime; // in seconds
1628 /* Clear the profiler */
1629 Profiler::GraphValues dummyvalues;
1630 g_profiler->graphGet(dummyvalues);
1632 draw_times.last_time = device->getTimer()->getTime();
1634 set_light_table(g_settings->getFloat("display_gamma"));
1637 m_cache_hold_aux1 = g_settings->getBool("fast_move")
1638 && client->checkPrivilege("fast");
1641 irr::core::dimension2d<u32> previous_screen_size(g_settings->getU16("screenW"),
1642 g_settings->getU16("screenH"));
1644 while (device->run()
1645 && !(*kill || g_gamecallback->shutdown_requested
1646 || (server && server->getShutdownRequested()))) {
1648 const irr::core::dimension2d<u32> ¤t_screen_size =
1649 device->getVideoDriver()->getScreenSize();
1650 // Verify if window size has changed and save it if it's the case
1651 // Ensure evaluating settings->getBool after verifying screensize
1652 // First condition is cheaper
1653 if (previous_screen_size != current_screen_size &&
1654 current_screen_size != irr::core::dimension2d<u32>(0,0) &&
1655 g_settings->getBool("autosave_screensize")) {
1656 g_settings->setU16("screenW", current_screen_size.Width);
1657 g_settings->setU16("screenH", current_screen_size.Height);
1658 previous_screen_size = current_screen_size;
1661 /* Must be called immediately after a device->run() call because it
1662 * uses device->getTimer()->getTime()
1664 limitFps(&draw_times, &dtime);
1666 updateStats(&stats, draw_times, dtime);
1667 updateInteractTimers(dtime);
1669 if (!checkConnection())
1671 if (!handleCallbacks())
1677 hud->resizeHotbar();
1679 updateProfilers(stats, draw_times, dtime);
1680 processUserInput(dtime);
1681 // Update camera before player movement to avoid camera lag of one frame
1682 updateCameraDirection(&cam_view_target, dtime);
1683 cam_view.camera_yaw += (cam_view_target.camera_yaw -
1684 cam_view.camera_yaw) * m_cache_cam_smoothing;
1685 cam_view.camera_pitch += (cam_view_target.camera_pitch -
1686 cam_view.camera_pitch) * m_cache_cam_smoothing;
1687 updatePlayerControl(cam_view);
1689 processClientEvents(&cam_view_target);
1690 updateCamera(draw_times.busy_time, dtime);
1692 processPlayerInteraction(dtime, flags.show_hud, flags.show_debug);
1693 updateFrame(&graph, &stats, dtime, cam_view);
1694 updateProfilerGraphs(&graph);
1696 // Update if minimap has been disabled by the server
1697 flags.show_minimap &= client->shouldShowMinimap();
1702 void Game::shutdown()
1704 #if IRRLICHT_VERSION_MAJOR == 1 && IRRLICHT_VERSION_MINOR <= 8
1705 if (g_settings->get("3d_mode") == "pageflip") {
1706 driver->setRenderTarget(irr::video::ERT_STEREO_BOTH_BUFFERS);
1710 showOverlayMessage(wgettext("Shutting down..."), 0, 0, false);
1715 if (gui_chat_console)
1716 gui_chat_console->drop();
1722 while (g_menumgr.menuCount() > 0) {
1723 g_menumgr.m_stack.front()->setVisible(false);
1724 g_menumgr.deletingMenu(g_menumgr.m_stack.front());
1727 if (current_formspec) {
1728 current_formspec->drop();
1729 current_formspec = NULL;
1732 chat_backend->addMessage(L"", L"# Disconnected.");
1733 chat_backend->addMessage(L"", L"");
1737 while (!client->isShutdown()) {
1738 assert(texture_src != NULL);
1739 assert(shader_src != NULL);
1740 texture_src->processQueue();
1741 shader_src->processQueue();
1748 /****************************************************************************/
1749 /****************************************************************************
1751 ****************************************************************************/
1752 /****************************************************************************/
1755 const std::string &map_dir,
1756 std::string *address,
1758 const SubgameSpec &gamespec)
1760 texture_src = createTextureSource(device);
1762 showOverlayMessage(wgettext("Loading..."), 0, 0);
1764 shader_src = createShaderSource(device);
1766 itemdef_manager = createItemDefManager();
1767 nodedef_manager = createNodeDefManager();
1769 eventmgr = new EventManager();
1770 quicktune = new QuicktuneShortcutter();
1772 if (!(texture_src && shader_src && itemdef_manager && nodedef_manager
1773 && eventmgr && quicktune))
1779 // Create a server if not connecting to an existing one
1780 if (*address == "") {
1781 if (!createSingleplayerServer(map_dir, gamespec, port, address))
1788 bool Game::initSound()
1791 if (g_settings->getBool("enable_sound")) {
1792 infostream << "Attempting to use OpenAL audio" << std::endl;
1793 sound = createOpenALSoundManager(&soundfetcher);
1795 infostream << "Failed to initialize OpenAL audio" << std::endl;
1797 infostream << "Sound disabled." << std::endl;
1801 infostream << "Using dummy audio." << std::endl;
1802 sound = &dummySoundManager;
1803 sound_is_dummy = true;
1806 soundmaker = new SoundMaker(sound, nodedef_manager);
1810 soundmaker->registerReceiver(eventmgr);
1815 bool Game::createSingleplayerServer(const std::string &map_dir,
1816 const SubgameSpec &gamespec, u16 port, std::string *address)
1818 showOverlayMessage(wgettext("Creating server..."), 0, 5);
1820 std::string bind_str = g_settings->get("bind_address");
1821 Address bind_addr(0, 0, 0, 0, port);
1823 if (g_settings->getBool("ipv6_server")) {
1824 bind_addr.setAddress((IPv6AddressBytes *) NULL);
1828 bind_addr.Resolve(bind_str.c_str());
1829 } catch (ResolveError &e) {
1830 infostream << "Resolving bind address \"" << bind_str
1831 << "\" failed: " << e.what()
1832 << " -- Listening on all addresses." << std::endl;
1835 if (bind_addr.isIPv6() && !g_settings->getBool("enable_ipv6")) {
1836 *error_message = "Unable to listen on " +
1837 bind_addr.serializeString() +
1838 " because IPv6 is disabled";
1839 errorstream << *error_message << std::endl;
1843 server = new Server(map_dir, gamespec, simple_singleplayer_mode,
1844 bind_addr.isIPv6(), false);
1846 server->start(bind_addr);
1851 bool Game::createClient(const std::string &playername,
1852 const std::string &password, std::string *address, u16 port)
1854 showOverlayMessage(wgettext("Creating client..."), 0, 10);
1856 draw_control = new MapDrawControl;
1860 bool could_connect, connect_aborted;
1862 if (!connectToServer(playername, password, address, port,
1863 &could_connect, &connect_aborted))
1866 if (!could_connect) {
1867 if (error_message->empty() && !connect_aborted) {
1868 // Should not happen if error messages are set properly
1869 *error_message = "Connection failed for unknown reason";
1870 errorstream << *error_message << std::endl;
1875 if (!getServerContent(&connect_aborted)) {
1876 if (error_message->empty() && !connect_aborted) {
1877 // Should not happen if error messages are set properly
1878 *error_message = "Connection failed for unknown reason";
1879 errorstream << *error_message << std::endl;
1884 GameGlobalShaderConstantSetterFactory *scsf = new GameGlobalShaderConstantSetterFactory(
1885 &flags.force_fog_off, &runData.fog_range, client);
1886 shader_src->addShaderConstantSetterFactory(scsf);
1888 // Update cached textures, meshes and materials
1889 client->afterContentReceived(device);
1893 camera = new Camera(smgr, *draw_control, client);
1894 if (!camera || !camera->successfullyCreated(*error_message))
1896 client->setCamera(camera);
1900 if (m_cache_enable_clouds) {
1901 clouds = new Clouds(smgr->getRootSceneNode(), smgr, -1, time(0));
1903 *error_message = "Memory allocation error (clouds)";
1904 errorstream << *error_message << std::endl;
1911 sky = new Sky(smgr->getRootSceneNode(), smgr, -1, texture_src);
1913 skybox = NULL; // This is used/set later on in the main run loop
1915 local_inventory = new Inventory(itemdef_manager);
1917 if (!(sky && local_inventory)) {
1918 *error_message = "Memory allocation error (sky or local inventory)";
1919 errorstream << *error_message << std::endl;
1923 /* Pre-calculated values
1925 video::ITexture *t = texture_src->getTexture("crack_anylength.png");
1927 v2u32 size = t->getOriginalSize();
1928 crack_animation_length = size.Y / size.X;
1930 crack_animation_length = 5;
1936 /* Set window caption
1938 std::wstring str = utf8_to_wide(PROJECT_NAME_C);
1940 str += utf8_to_wide(g_version_hash);
1942 str += driver->getName();
1944 device->setWindowCaption(str.c_str());
1946 LocalPlayer *player = client->getEnv().getLocalPlayer();
1947 player->hurt_tilt_timer = 0;
1948 player->hurt_tilt_strength = 0;
1950 hud = new Hud(driver, smgr, guienv, client, player, local_inventory);
1953 *error_message = "Memory error: could not create HUD";
1954 errorstream << *error_message << std::endl;
1958 mapper = client->getMinimap();
1959 mapper->setMinimapMode(MINIMAP_MODE_OFF);
1964 bool Game::initGui()
1966 // First line of debug text
1967 guitext = addStaticText(guienv,
1968 utf8_to_wide(PROJECT_NAME_C).c_str(),
1969 core::rect<s32>(0, 0, 0, 0),
1970 false, false, guiroot);
1972 // Second line of debug text
1973 guitext2 = addStaticText(guienv,
1975 core::rect<s32>(0, 0, 0, 0),
1976 false, false, guiroot);
1978 // At the middle of the screen
1979 // Object infos are shown in this
1980 guitext_info = addStaticText(guienv,
1982 core::rect<s32>(0, 0, 400, g_fontengine->getTextHeight() * 5 + 5) + v2s32(100, 200),
1983 false, true, guiroot);
1985 // Status text (displays info when showing and hiding GUI stuff, etc.)
1986 guitext_status = addStaticText(guienv,
1988 core::rect<s32>(0, 0, 0, 0),
1989 false, false, guiroot);
1990 guitext_status->setVisible(false);
1993 guitext_chat = addStaticText(
1996 core::rect<s32>(0, 0, 0, 0),
1997 //false, false); // Disable word wrap as of now
1998 false, true, guiroot);
2000 // Remove stale "recent" chat messages from previous connections
2001 chat_backend->clearRecentChat();
2003 // Chat backend and console
2004 gui_chat_console = new GUIChatConsole(guienv, guienv->getRootGUIElement(),
2005 -1, chat_backend, client, &g_menumgr);
2006 if (!gui_chat_console) {
2007 *error_message = "Could not allocate memory for chat console";
2008 errorstream << *error_message << std::endl;
2012 // Profiler text (size is updated when text is updated)
2013 guitext_profiler = addStaticText(guienv,
2015 core::rect<s32>(0, 0, 0, 0),
2016 false, false, guiroot);
2017 guitext_profiler->setBackgroundColor(video::SColor(120, 0, 0, 0));
2018 guitext_profiler->setVisible(false);
2019 guitext_profiler->setWordWrap(true);
2021 #ifdef HAVE_TOUCHSCREENGUI
2023 if (g_touchscreengui)
2024 g_touchscreengui->init(texture_src);
2031 bool Game::connectToServer(const std::string &playername,
2032 const std::string &password, std::string *address, u16 port,
2033 bool *connect_ok, bool *aborted)
2035 *connect_ok = false; // Let's not be overly optimistic
2037 bool local_server_mode = false;
2039 showOverlayMessage(wgettext("Resolving address..."), 0, 15);
2041 Address connect_address(0, 0, 0, 0, port);
2044 connect_address.Resolve(address->c_str());
2046 if (connect_address.isZero()) { // i.e. INADDR_ANY, IN6ADDR_ANY
2047 //connect_address.Resolve("localhost");
2048 if (connect_address.isIPv6()) {
2049 IPv6AddressBytes addr_bytes;
2050 addr_bytes.bytes[15] = 1;
2051 connect_address.setAddress(&addr_bytes);
2053 connect_address.setAddress(127, 0, 0, 1);
2055 local_server_mode = true;
2057 } catch (ResolveError &e) {
2058 *error_message = std::string("Couldn't resolve address: ") + e.what();
2059 errorstream << *error_message << std::endl;
2063 if (connect_address.isIPv6() && !g_settings->getBool("enable_ipv6")) {
2064 *error_message = "Unable to connect to " +
2065 connect_address.serializeString() +
2066 " because IPv6 is disabled";
2067 errorstream << *error_message << std::endl;
2071 client = new Client(device,
2072 playername.c_str(), password, *address,
2073 *draw_control, texture_src, shader_src,
2074 itemdef_manager, nodedef_manager, sound, eventmgr,
2075 connect_address.isIPv6(), &flags);
2080 infostream << "Connecting to server at ";
2081 connect_address.print(&infostream);
2082 infostream << std::endl;
2084 client->connect(connect_address,
2085 simple_singleplayer_mode || local_server_mode);
2088 Wait for server to accept connection
2094 FpsControl fps_control = { 0 };
2096 f32 wait_time = 0; // in seconds
2098 fps_control.last_time = device->getTimer()->getTime();
2102 while (device->run()) {
2104 limitFps(&fps_control, &dtime);
2106 // Update client and server
2107 client->step(dtime);
2110 server->step(dtime);
2113 if (client->getState() == LC_Init) {
2119 if (client->accessDenied()) {
2120 *error_message = "Access denied. Reason: "
2121 + client->accessDeniedReason();
2122 *reconnect_requested = client->reconnectRequested();
2123 errorstream << *error_message << std::endl;
2127 if (wasKeyDown(KeyType::ESC) || input->wasKeyDown(CancelKey)) {
2129 infostream << "Connect aborted [Escape]" << std::endl;
2134 // Only time out if we aren't waiting for the server we started
2135 if ((*address != "") && (wait_time > 10)) {
2136 bool sent_old_init = g_settings->getFlag("send_pre_v25_init");
2137 // If no pre v25 init was sent, and no answer was received,
2138 // but the low level connection could be established
2139 // (meaning that we have a peer id), then we probably wanted
2140 // to connect to a legacy server. In this case, tell the user
2141 // to enable the option to be able to connect.
2142 if (!sent_old_init &&
2143 (client->getProtoVersion() == 0) &&
2144 client->connectedToServer()) {
2145 *error_message = "Connection failure: init packet not "
2146 "recognized by server.\n"
2147 "Most likely the server uses an old protocol version (<v25).\n"
2148 "Please ask the server owner to update to 0.4.13 or later.\n"
2149 "To still connect to the server in the meantime,\n"
2150 "you can enable the 'send_pre_v25_init' setting by editing minetest.conf,\n"
2151 "or by enabling the 'Client -> Network -> Support older Servers'\n"
2152 "entry in the advanced settings menu.";
2154 *error_message = "Connection timed out.";
2156 errorstream << *error_message << std::endl;
2161 showOverlayMessage(wgettext("Connecting to server..."), dtime, 20);
2163 } catch (con::PeerNotFoundException &e) {
2164 // TODO: Should something be done here? At least an info/error
2172 bool Game::getServerContent(bool *aborted)
2176 FpsControl fps_control = { 0 };
2177 f32 dtime; // in seconds
2179 fps_control.last_time = device->getTimer()->getTime();
2181 while (device->run()) {
2183 limitFps(&fps_control, &dtime);
2185 // Update client and server
2186 client->step(dtime);
2189 server->step(dtime);
2192 if (client->mediaReceived() && client->itemdefReceived() &&
2193 client->nodedefReceived()) {
2198 if (!checkConnection())
2201 if (client->getState() < LC_Init) {
2202 *error_message = "Client disconnected";
2203 errorstream << *error_message << std::endl;
2207 if (wasKeyDown(KeyType::ESC) || input->wasKeyDown(CancelKey)) {
2209 infostream << "Connect aborted [Escape]" << std::endl;
2216 if (!client->itemdefReceived()) {
2217 const wchar_t *text = wgettext("Item definitions...");
2219 draw_load_screen(text, device, guienv, texture_src,
2222 } else if (!client->nodedefReceived()) {
2223 const wchar_t *text = wgettext("Node definitions...");
2225 draw_load_screen(text, device, guienv, texture_src,
2229 std::stringstream message;
2230 std::fixed(message);
2231 message.precision(0);
2232 message << gettext("Media...") << " " << (client->mediaReceiveProgress()*100) << "%";
2233 message.precision(2);
2235 if ((USE_CURL == 0) ||
2236 (!g_settings->getBool("enable_remote_media_server"))) {
2237 float cur = client->getCurRate();
2238 std::string cur_unit = gettext("KiB/s");
2242 cur_unit = gettext("MiB/s");
2245 message << " (" << cur << ' ' << cur_unit << ")";
2248 progress = 30 + client->mediaReceiveProgress() * 35 + 0.5;
2249 draw_load_screen(utf8_to_wide(message.str()), device,
2250 guienv, texture_src, dtime, progress);
2258 /****************************************************************************/
2259 /****************************************************************************
2261 ****************************************************************************/
2262 /****************************************************************************/
2264 inline void Game::updateInteractTimers(f32 dtime)
2266 if (runData.nodig_delay_timer >= 0)
2267 runData.nodig_delay_timer -= dtime;
2269 if (runData.object_hit_delay_timer >= 0)
2270 runData.object_hit_delay_timer -= dtime;
2272 runData.time_from_last_punch += dtime;
2276 /* returns false if game should exit, otherwise true
2278 inline bool Game::checkConnection()
2280 if (client->accessDenied()) {
2281 *error_message = "Access denied. Reason: "
2282 + client->accessDeniedReason();
2283 *reconnect_requested = client->reconnectRequested();
2284 errorstream << *error_message << std::endl;
2292 /* returns false if game should exit, otherwise true
2294 inline bool Game::handleCallbacks()
2296 if (g_gamecallback->disconnect_requested) {
2297 g_gamecallback->disconnect_requested = false;
2301 if (g_gamecallback->changepassword_requested) {
2302 (new GUIPasswordChange(guienv, guiroot, -1,
2303 &g_menumgr, client))->drop();
2304 g_gamecallback->changepassword_requested = false;
2307 if (g_gamecallback->changevolume_requested) {
2308 (new GUIVolumeChange(guienv, guiroot, -1,
2309 &g_menumgr))->drop();
2310 g_gamecallback->changevolume_requested = false;
2313 if (g_gamecallback->keyconfig_requested) {
2314 (new GUIKeyChangeMenu(guienv, guiroot, -1,
2315 &g_menumgr))->drop();
2316 g_gamecallback->keyconfig_requested = false;
2319 if (g_gamecallback->keyconfig_changed) {
2320 keycache.populate(); // update the cache with new settings
2321 g_gamecallback->keyconfig_changed = false;
2328 void Game::processQueues()
2330 texture_src->processQueue();
2331 itemdef_manager->processQueue(client);
2332 shader_src->processQueue();
2336 void Game::updateProfilers(const RunStats &stats, const FpsControl &draw_times, f32 dtime)
2338 float profiler_print_interval =
2339 g_settings->getFloat("profiler_print_interval");
2340 bool print_to_log = true;
2342 if (profiler_print_interval == 0) {
2343 print_to_log = false;
2344 profiler_print_interval = 5;
2347 if (profiler_interval.step(dtime, profiler_print_interval)) {
2349 infostream << "Profiler:" << std::endl;
2350 g_profiler->print(infostream);
2353 update_profiler_gui(guitext_profiler, g_fontengine,
2354 runData.profiler_current_page, runData.profiler_max_page,
2355 driver->getScreenSize().Height);
2357 g_profiler->clear();
2360 addProfilerGraphs(stats, draw_times, dtime);
2364 void Game::addProfilerGraphs(const RunStats &stats,
2365 const FpsControl &draw_times, f32 dtime)
2367 g_profiler->graphAdd("mainloop_other",
2368 draw_times.busy_time / 1000.0f - stats.drawtime / 1000.0f);
2370 if (draw_times.sleep_time != 0)
2371 g_profiler->graphAdd("mainloop_sleep", draw_times.sleep_time / 1000.0f);
2372 g_profiler->graphAdd("mainloop_dtime", dtime);
2374 g_profiler->add("Elapsed time", dtime);
2375 g_profiler->avg("FPS", 1. / dtime);
2379 void Game::updateStats(RunStats *stats, const FpsControl &draw_times,
2386 /* Time average and jitter calculation
2388 jp = &stats->dtime_jitter;
2389 jp->avg = jp->avg * 0.96 + dtime * 0.04;
2391 jitter = dtime - jp->avg;
2393 if (jitter > jp->max)
2396 jp->counter += dtime;
2398 if (jp->counter > 0.0) {
2400 jp->max_sample = jp->max;
2401 jp->max_fraction = jp->max_sample / (jp->avg + 0.001);
2405 /* Busytime average and jitter calculation
2407 jp = &stats->busy_time_jitter;
2408 jp->avg = jp->avg + draw_times.busy_time * 0.02;
2410 jitter = draw_times.busy_time - jp->avg;
2412 if (jitter > jp->max)
2414 if (jitter < jp->min)
2417 jp->counter += dtime;
2419 if (jp->counter > 0.0) {
2421 jp->max_sample = jp->max;
2422 jp->min_sample = jp->min;
2430 /****************************************************************************
2432 ****************************************************************************/
2434 void Game::processUserInput(f32 dtime)
2436 // Reset input if window not active or some menu is active
2437 if (!device->isWindowActive() || !noMenuActive() || guienv->hasFocus(gui_chat_console)) {
2439 #ifdef HAVE_TOUCHSCREENGUI
2440 g_touchscreengui->hide();
2443 #ifdef HAVE_TOUCHSCREENGUI
2444 else if (g_touchscreengui) {
2445 /* on touchscreengui step may generate own input events which ain't
2446 * what we want in case we just did clear them */
2447 g_touchscreengui->step(dtime);
2451 if (!guienv->hasFocus(gui_chat_console) && gui_chat_console->isOpen()) {
2452 gui_chat_console->closeConsoleAtOnce();
2455 // Input handler step() (used by the random input generator)
2459 if (current_formspec != NULL)
2460 current_formspec->getAndroidUIInput();
2462 handleAndroidChatInput();
2465 // Increase timer for double tap of "keymap_jump"
2466 if (m_cache_doubletap_jump && runData.jump_timer <= 0.2f)
2467 runData.jump_timer += dtime;
2470 processItemSelection(&runData.new_playeritem);
2474 void Game::processKeyInput()
2476 if (wasKeyDown(KeyType::DROP)) {
2478 } else if (wasKeyDown(KeyType::AUTORUN)) {
2480 } else if (wasKeyDown(KeyType::INVENTORY)) {
2482 } else if (wasKeyDown(KeyType::ESC) || input->wasKeyDown(CancelKey)) {
2483 if (!gui_chat_console->isOpenInhibited()) {
2486 } else if (wasKeyDown(KeyType::CHAT)) {
2487 openConsole(0.2, L"");
2488 } else if (wasKeyDown(KeyType::CMD)) {
2489 openConsole(0.2, L"/");
2490 } else if (wasKeyDown(KeyType::CMD_LOCAL)) {
2491 openConsole(0.2, L".");
2492 } else if (wasKeyDown(KeyType::CONSOLE)) {
2493 openConsole(core::clamp(g_settings->getFloat("console_height"), 0.1f, 1.0f));
2494 } else if (wasKeyDown(KeyType::FREEMOVE)) {
2496 } else if (wasKeyDown(KeyType::JUMP)) {
2497 toggleFreeMoveAlt();
2498 } else if (wasKeyDown(KeyType::FASTMOVE)) {
2500 } else if (wasKeyDown(KeyType::NOCLIP)) {
2502 } else if (wasKeyDown(KeyType::MUTE)) {
2503 float volume = g_settings->getFloat("sound_volume");
2504 if (volume < 0.001f) {
2505 g_settings->setFloat("sound_volume", 1.0f);
2506 m_statustext = narrow_to_wide(gettext("Volume changed to 100%"));
2508 g_settings->setFloat("sound_volume", 0.0f);
2509 m_statustext = narrow_to_wide(gettext("Volume changed to 0%"));
2511 runData.statustext_time = 0;
2512 } else if (wasKeyDown(KeyType::INC_VOLUME)) {
2513 float new_volume = rangelim(g_settings->getFloat("sound_volume") + 0.1f, 0.0f, 1.0f);
2515 g_settings->setFloat("sound_volume", new_volume);
2516 snprintf(buf, sizeof(buf), gettext("Volume changed to %d%%"), myround(new_volume * 100));
2517 m_statustext = narrow_to_wide(buf);
2518 runData.statustext_time = 0;
2519 } else if (wasKeyDown(KeyType::DEC_VOLUME)) {
2520 float new_volume = rangelim(g_settings->getFloat("sound_volume") - 0.1f, 0.0f, 1.0f);
2522 g_settings->setFloat("sound_volume", new_volume);
2523 snprintf(buf, sizeof(buf), gettext("Volume changed to %d%%"), myround(new_volume * 100));
2524 m_statustext = narrow_to_wide(buf);
2525 runData.statustext_time = 0;
2526 } else if (wasKeyDown(KeyType::CINEMATIC)) {
2528 } else if (wasKeyDown(KeyType::SCREENSHOT)) {
2529 client->makeScreenshot(device);
2530 } else if (wasKeyDown(KeyType::TOGGLE_HUD)) {
2532 } else if (wasKeyDown(KeyType::MINIMAP)) {
2533 toggleMinimap(isKeyDown(KeyType::SNEAK));
2534 } else if (wasKeyDown(KeyType::TOGGLE_CHAT)) {
2536 } else if (wasKeyDown(KeyType::TOGGLE_FORCE_FOG_OFF)) {
2538 } else if (wasKeyDown(KeyType::TOGGLE_UPDATE_CAMERA)) {
2539 toggleUpdateCamera();
2540 } else if (wasKeyDown(KeyType::TOGGLE_DEBUG)) {
2542 } else if (wasKeyDown(KeyType::TOGGLE_PROFILER)) {
2544 } else if (wasKeyDown(KeyType::INCREASE_VIEWING_RANGE)) {
2545 increaseViewRange();
2546 } else if (wasKeyDown(KeyType::DECREASE_VIEWING_RANGE)) {
2547 decreaseViewRange();
2548 } else if (wasKeyDown(KeyType::RANGESELECT)) {
2549 toggleFullViewRange();
2550 } else if (wasKeyDown(KeyType::QUICKTUNE_NEXT)) {
2552 } else if (wasKeyDown(KeyType::QUICKTUNE_PREV)) {
2554 } else if (wasKeyDown(KeyType::QUICKTUNE_INC)) {
2556 } else if (wasKeyDown(KeyType::QUICKTUNE_DEC)) {
2558 } else if (wasKeyDown(KeyType::DEBUG_STACKS)) {
2559 // Print debug stacks
2560 dstream << "-----------------------------------------"
2562 dstream << "Printing debug stacks:" << std::endl;
2563 dstream << "-----------------------------------------"
2565 debug_stacks_print();
2568 if (!isKeyDown(KeyType::JUMP) && runData.reset_jump_timer) {
2569 runData.reset_jump_timer = false;
2570 runData.jump_timer = 0.0f;
2573 if (quicktune->hasMessage()) {
2574 m_statustext = utf8_to_wide(quicktune->getMessage());
2575 runData.statustext_time = 0.0f;
2579 void Game::processItemSelection(u16 *new_playeritem)
2581 LocalPlayer *player = client->getEnv().getLocalPlayer();
2583 /* Item selection using mouse wheel
2585 *new_playeritem = client->getPlayerItem();
2587 s32 wheel = input->getMouseWheel();
2588 u16 max_item = MYMIN(PLAYER_INVENTORY_SIZE - 1,
2589 player->hud_hotbar_itemcount - 1);
2593 if (input->joystick.wasKeyDown(KeyType::SCROLL_DOWN) ||
2594 wasKeyDown(KeyType::HOTBAR_NEXT)) {
2598 if (input->joystick.wasKeyDown(KeyType::SCROLL_UP) ||
2599 wasKeyDown(KeyType::HOTBAR_PREV)) {
2604 *new_playeritem = *new_playeritem < max_item ? *new_playeritem + 1 : 0;
2606 *new_playeritem = *new_playeritem > 0 ? *new_playeritem - 1 : max_item;
2609 /* Item selection using keyboard
2611 for (u16 i = 0; i < 10; i++) {
2612 static const KeyPress *item_keys[10] = {
2613 NumberKey + 1, NumberKey + 2, NumberKey + 3, NumberKey + 4,
2614 NumberKey + 5, NumberKey + 6, NumberKey + 7, NumberKey + 8,
2615 NumberKey + 9, NumberKey + 0,
2618 if (input->wasKeyDown(*item_keys[i])) {
2619 if (i < PLAYER_INVENTORY_SIZE && i < player->hud_hotbar_itemcount) {
2620 *new_playeritem = i;
2621 infostream << "Selected item: " << new_playeritem << std::endl;
2629 void Game::dropSelectedItem()
2631 IDropAction *a = new IDropAction();
2633 a->from_inv.setCurrentPlayer();
2634 a->from_list = "main";
2635 a->from_i = client->getPlayerItem();
2636 client->inventoryAction(a);
2640 void Game::openInventory()
2643 * Don't permit to open inventory is CAO or player doesn't exists.
2644 * This prevent showing an empty inventory at player load
2647 LocalPlayer *player = client->getEnv().getLocalPlayer();
2648 if (player == NULL || player->getCAO() == NULL)
2651 infostream << "the_game: " << "Launching inventory" << std::endl;
2653 PlayerInventoryFormSource *fs_src = new PlayerInventoryFormSource(client);
2654 TextDest *txt_dst = new TextDestPlayerInventory(client);
2656 create_formspec_menu(¤t_formspec, client, device, &input->joystick, fs_src, txt_dst);
2659 InventoryLocation inventoryloc;
2660 inventoryloc.setCurrentPlayer();
2661 current_formspec->setFormSpec(fs_src->getForm(), inventoryloc);
2665 void Game::openConsole(float scale, const wchar_t *line)
2667 assert(scale > 0.0f && scale <= 1.0f);
2670 porting::showInputDialog(gettext("ok"), "", "", 2);
2671 m_android_chat_open = true;
2673 if (gui_chat_console->isOpenInhibited())
2675 gui_chat_console->openConsole(scale);
2677 gui_chat_console->setCloseOnEnter(true);
2678 gui_chat_console->replaceAndAddToHistory(line);
2684 void Game::handleAndroidChatInput()
2686 if (m_android_chat_open && porting::getInputDialogState() == 0) {
2687 std::string text = porting::getInputDialogValue();
2688 client->typeChatMessage(utf8_to_wide(text));
2694 void Game::toggleFreeMove()
2696 static const wchar_t *msg[] = { L"free_move disabled", L"free_move enabled" };
2698 bool free_move = !g_settings->getBool("free_move");
2699 g_settings->set("free_move", bool_to_cstr(free_move));
2701 runData.statustext_time = 0;
2702 m_statustext = msg[free_move];
2703 if (free_move && !client->checkPrivilege("fly"))
2704 m_statustext += L" (note: no 'fly' privilege)";
2708 void Game::toggleFreeMoveAlt()
2710 if (m_cache_doubletap_jump && runData.jump_timer < 0.2f)
2713 runData.reset_jump_timer = true;
2717 void Game::toggleFast()
2719 static const wchar_t *msg[] = { L"fast_move disabled", L"fast_move enabled" };
2720 bool fast_move = !g_settings->getBool("fast_move");
2721 g_settings->set("fast_move", bool_to_cstr(fast_move));
2723 runData.statustext_time = 0;
2724 m_statustext = msg[fast_move];
2726 bool has_fast_privs = client->checkPrivilege("fast");
2728 if (fast_move && !has_fast_privs)
2729 m_statustext += L" (note: no 'fast' privilege)";
2732 m_cache_hold_aux1 = fast_move && has_fast_privs;
2737 void Game::toggleNoClip()
2739 static const wchar_t *msg[] = { L"noclip disabled", L"noclip enabled" };
2740 bool noclip = !g_settings->getBool("noclip");
2741 g_settings->set("noclip", bool_to_cstr(noclip));
2743 runData.statustext_time = 0;
2744 m_statustext = msg[noclip];
2746 if (noclip && !client->checkPrivilege("noclip"))
2747 m_statustext += L" (note: no 'noclip' privilege)";
2750 void Game::toggleCinematic()
2752 static const wchar_t *msg[] = { L"cinematic disabled", L"cinematic enabled" };
2753 bool cinematic = !g_settings->getBool("cinematic");
2754 g_settings->set("cinematic", bool_to_cstr(cinematic));
2756 runData.statustext_time = 0;
2757 m_statustext = msg[cinematic];
2760 // Add WoW-style autorun by toggling continuous forward.
2761 void Game::toggleAutorun()
2763 static const wchar_t *msg[] = { L"autorun disabled", L"autorun enabled" };
2764 bool autorun_enabled = !g_settings->getBool("continuous_forward");
2765 g_settings->set("continuous_forward", bool_to_cstr(autorun_enabled));
2767 runData.statustext_time = 0;
2768 m_statustext = msg[autorun_enabled ? 1 : 0];
2771 void Game::toggleChat()
2773 static const wchar_t *msg[] = { L"Chat hidden", L"Chat shown" };
2775 flags.show_chat = !flags.show_chat;
2776 runData.statustext_time = 0;
2777 m_statustext = msg[flags.show_chat];
2781 void Game::toggleHud()
2783 static const wchar_t *msg[] = { L"HUD hidden", L"HUD shown" };
2785 flags.show_hud = !flags.show_hud;
2786 runData.statustext_time = 0;
2787 m_statustext = msg[flags.show_hud];
2790 void Game::toggleMinimap(bool shift_pressed)
2792 if (!flags.show_hud || !g_settings->getBool("enable_minimap"))
2795 if (shift_pressed) {
2796 mapper->toggleMinimapShape();
2800 u32 hud_flags = client->getEnv().getLocalPlayer()->hud_flags;
2802 MinimapMode mode = MINIMAP_MODE_OFF;
2803 if (hud_flags & HUD_FLAG_MINIMAP_VISIBLE) {
2804 mode = mapper->getMinimapMode();
2805 mode = (MinimapMode)((int)mode + 1);
2808 flags.show_minimap = true;
2810 case MINIMAP_MODE_SURFACEx1:
2811 m_statustext = L"Minimap in surface mode, Zoom x1";
2813 case MINIMAP_MODE_SURFACEx2:
2814 m_statustext = L"Minimap in surface mode, Zoom x2";
2816 case MINIMAP_MODE_SURFACEx4:
2817 m_statustext = L"Minimap in surface mode, Zoom x4";
2819 case MINIMAP_MODE_RADARx1:
2820 m_statustext = L"Minimap in radar mode, Zoom x1";
2822 case MINIMAP_MODE_RADARx2:
2823 m_statustext = L"Minimap in radar mode, Zoom x2";
2825 case MINIMAP_MODE_RADARx4:
2826 m_statustext = L"Minimap in radar mode, Zoom x4";
2829 mode = MINIMAP_MODE_OFF;
2830 flags.show_minimap = false;
2831 m_statustext = (hud_flags & HUD_FLAG_MINIMAP_VISIBLE) ?
2832 L"Minimap hidden" : L"Minimap disabled by server";
2835 runData.statustext_time = 0;
2836 mapper->setMinimapMode(mode);
2839 void Game::toggleFog()
2841 static const wchar_t *msg[] = { L"Fog enabled", L"Fog disabled" };
2843 flags.force_fog_off = !flags.force_fog_off;
2844 runData.statustext_time = 0;
2845 m_statustext = msg[flags.force_fog_off];
2849 void Game::toggleDebug()
2851 // Initial / 4x toggle: Chat only
2852 // 1x toggle: Debug text with chat
2853 // 2x toggle: Debug text with profiler graph
2854 // 3x toggle: Debug text and wireframe
2855 if (!flags.show_debug) {
2856 flags.show_debug = true;
2857 flags.show_profiler_graph = false;
2858 draw_control->show_wireframe = false;
2859 m_statustext = L"Debug info shown";
2860 } else if (!flags.show_profiler_graph && !draw_control->show_wireframe) {
2861 flags.show_profiler_graph = true;
2862 m_statustext = L"Profiler graph shown";
2863 } else if (!draw_control->show_wireframe && client->checkPrivilege("debug")) {
2864 flags.show_profiler_graph = false;
2865 draw_control->show_wireframe = true;
2866 m_statustext = L"Wireframe shown";
2868 flags.show_debug = false;
2869 flags.show_profiler_graph = false;
2870 draw_control->show_wireframe = false;
2871 if (client->checkPrivilege("debug")) {
2872 m_statustext = L"Debug info, profiler graph, and wireframe hidden";
2874 m_statustext = L"Debug info and profiler graph hidden";
2877 runData.statustext_time = 0;
2881 void Game::toggleUpdateCamera()
2883 static const wchar_t *msg[] = {
2884 L"Camera update enabled",
2885 L"Camera update disabled"
2888 flags.disable_camera_update = !flags.disable_camera_update;
2889 runData.statustext_time = 0;
2890 m_statustext = msg[flags.disable_camera_update];
2894 void Game::toggleProfiler()
2896 runData.profiler_current_page =
2897 (runData.profiler_current_page + 1) % (runData.profiler_max_page + 1);
2899 // FIXME: This updates the profiler with incomplete values
2900 update_profiler_gui(guitext_profiler, g_fontengine, runData.profiler_current_page,
2901 runData.profiler_max_page, driver->getScreenSize().Height);
2903 if (runData.profiler_current_page != 0) {
2904 std::wstringstream sstr;
2905 sstr << "Profiler shown (page " << runData.profiler_current_page
2906 << " of " << runData.profiler_max_page << ")";
2907 m_statustext = sstr.str();
2909 m_statustext = L"Profiler hidden";
2911 runData.statustext_time = 0;
2915 void Game::increaseViewRange()
2917 s16 range = g_settings->getS16("viewing_range");
2918 s16 range_new = range + 10;
2920 if (range_new > 4000) {
2922 m_statustext = utf8_to_wide("Viewing range is at maximum: "
2925 m_statustext = utf8_to_wide("Viewing range changed to "
2928 g_settings->set("viewing_range", itos(range_new));
2929 runData.statustext_time = 0;
2933 void Game::decreaseViewRange()
2935 s16 range = g_settings->getS16("viewing_range");
2936 s16 range_new = range - 10;
2938 if (range_new < 20) {
2940 m_statustext = utf8_to_wide("Viewing range is at minimum: "
2943 m_statustext = utf8_to_wide("Viewing range changed to "
2946 g_settings->set("viewing_range", itos(range_new));
2947 runData.statustext_time = 0;
2951 void Game::toggleFullViewRange()
2953 static const wchar_t *msg[] = {
2954 L"Disabled full viewing range",
2955 L"Enabled full viewing range"
2958 draw_control->range_all = !draw_control->range_all;
2959 infostream << msg[draw_control->range_all] << std::endl;
2960 m_statustext = msg[draw_control->range_all];
2961 runData.statustext_time = 0;
2965 void Game::updateCameraDirection(CameraOrientation *cam, float dtime)
2967 if ((device->isWindowActive() && noMenuActive()) || random_input) {
2970 if (!random_input) {
2971 // Mac OSX gets upset if this is set every frame
2972 if (device->getCursorControl()->isVisible())
2973 device->getCursorControl()->setVisible(false);
2977 if (m_first_loop_after_window_activation)
2978 m_first_loop_after_window_activation = false;
2980 updateCameraOrientation(cam, dtime);
2982 input->setMousePos((driver->getScreenSize().Width / 2),
2983 (driver->getScreenSize().Height / 2));
2987 // Mac OSX gets upset if this is set every frame
2988 if (!device->getCursorControl()->isVisible())
2989 device->getCursorControl()->setVisible(true);
2992 if (!m_first_loop_after_window_activation)
2993 m_first_loop_after_window_activation = true;
2998 void Game::updateCameraOrientation(CameraOrientation *cam, float dtime)
3000 #ifdef HAVE_TOUCHSCREENGUI
3001 if (g_touchscreengui) {
3002 cam->camera_yaw += g_touchscreengui->getYawChange();
3003 cam->camera_pitch = g_touchscreengui->getPitch();
3007 s32 dx = input->getMousePos().X - (driver->getScreenSize().Width / 2);
3008 s32 dy = input->getMousePos().Y - (driver->getScreenSize().Height / 2);
3010 if (m_invert_mouse || camera->getCameraMode() == CAMERA_MODE_THIRD_FRONT) {
3014 cam->camera_yaw -= dx * m_cache_mouse_sensitivity;
3015 cam->camera_pitch += dy * m_cache_mouse_sensitivity;
3017 #ifdef HAVE_TOUCHSCREENGUI
3021 if (m_cache_enable_joysticks) {
3022 f32 c = m_cache_joystick_frustum_sensitivity * (1.f / 32767.f) * dtime;
3023 cam->camera_yaw -= input->joystick.getAxisWithoutDead(JA_FRUSTUM_HORIZONTAL) * c;
3024 cam->camera_pitch += input->joystick.getAxisWithoutDead(JA_FRUSTUM_VERTICAL) * c;
3027 cam->camera_pitch = rangelim(cam->camera_pitch, -89.5, 89.5);
3031 void Game::updatePlayerControl(const CameraOrientation &cam)
3033 //TimeTaker tt("update player control", NULL, PRECISION_NANO);
3035 // DO NOT use the isKeyDown method for the forward, backward, left, right
3036 // buttons, as the code that uses the controls needs to be able to
3037 // distinguish between the two in order to know when to use joysticks.
3039 PlayerControl control(
3040 input->isKeyDown(keycache.key[KeyType::FORWARD]),
3041 input->isKeyDown(keycache.key[KeyType::BACKWARD]),
3042 input->isKeyDown(keycache.key[KeyType::LEFT]),
3043 input->isKeyDown(keycache.key[KeyType::RIGHT]),
3044 isKeyDown(KeyType::JUMP),
3045 isKeyDown(KeyType::SPECIAL1),
3046 isKeyDown(KeyType::SNEAK),
3047 isKeyDown(KeyType::ZOOM),
3052 input->joystick.getAxisWithoutDead(JA_SIDEWARD_MOVE),
3053 input->joystick.getAxisWithoutDead(JA_FORWARD_MOVE)
3057 ( (u32)(isKeyDown(KeyType::FORWARD) & 0x1) << 0) |
3058 ( (u32)(isKeyDown(KeyType::BACKWARD) & 0x1) << 1) |
3059 ( (u32)(isKeyDown(KeyType::LEFT) & 0x1) << 2) |
3060 ( (u32)(isKeyDown(KeyType::RIGHT) & 0x1) << 3) |
3061 ( (u32)(isKeyDown(KeyType::JUMP) & 0x1) << 4) |
3062 ( (u32)(isKeyDown(KeyType::SPECIAL1) & 0x1) << 5) |
3063 ( (u32)(isKeyDown(KeyType::SNEAK) & 0x1) << 6) |
3064 ( (u32)(isLeftPressed() & 0x1) << 7) |
3065 ( (u32)(isRightPressed() & 0x1) << 8
3069 /* For Android, simulate holding down AUX1 (fast move) if the user has
3070 * the fast_move setting toggled on. If there is an aux1 key defined for
3071 * Android then its meaning is inverted (i.e. holding aux1 means walk and
3074 if (m_cache_hold_aux1) {
3075 control.aux1 = control.aux1 ^ true;
3076 keypress_bits ^= ((u32)(1U << 5));
3080 client->setPlayerControl(control);
3081 LocalPlayer *player = client->getEnv().getLocalPlayer();
3082 player->keyPressed = keypress_bits;
3088 inline void Game::step(f32 *dtime)
3090 bool can_be_and_is_paused =
3091 (simple_singleplayer_mode && g_menumgr.pausesGame());
3093 if (can_be_and_is_paused) { // This is for a singleplayer server
3094 *dtime = 0; // No time passes
3096 if (server != NULL) {
3097 //TimeTaker timer("server->step(dtime)");
3098 server->step(*dtime);
3101 //TimeTaker timer("client.step(dtime)");
3102 client->step(*dtime);
3107 void Game::processClientEvents(CameraOrientation *cam)
3109 LocalPlayer *player = client->getEnv().getLocalPlayer();
3111 while (client->hasClientEvents()) {
3112 ClientEvent event = client->getClientEvent();
3114 switch (event.type) {
3115 case CE_PLAYER_DAMAGE:
3116 if (client->getHP() == 0)
3118 if (client->moddingEnabled()) {
3119 client->getScript()->on_damage_taken(event.player_damage.amount);
3122 runData.damage_flash += 95.0 + 3.2 * event.player_damage.amount;
3123 runData.damage_flash = MYMIN(runData.damage_flash, 127.0);
3125 player->hurt_tilt_timer = 1.5;
3126 player->hurt_tilt_strength =
3127 rangelim(event.player_damage.amount / 4, 1.0, 4.0);
3129 client->event()->put(new SimpleTriggerEvent("PlayerDamage"));
3132 case CE_PLAYER_FORCE_MOVE:
3133 cam->camera_yaw = event.player_force_move.yaw;
3134 cam->camera_pitch = event.player_force_move.pitch;
3137 case CE_DEATHSCREEN:
3138 // This should be enabled for death formspec in builtin
3139 client->getScript()->on_death();
3141 /* Handle visualization */
3142 runData.damage_flash = 0;
3143 player->hurt_tilt_timer = 0;
3144 player->hurt_tilt_strength = 0;
3147 case CE_SHOW_FORMSPEC:
3148 if (*(event.show_formspec.formspec) == "") {
3149 if (current_formspec && ( *(event.show_formspec.formname) == "" || *(event.show_formspec.formname) == cur_formname) ){
3150 current_formspec->quitMenu();
3153 FormspecFormSource *fs_src =
3154 new FormspecFormSource(*(event.show_formspec.formspec));
3155 TextDestPlayerInventory *txt_dst =
3156 new TextDestPlayerInventory(client, *(event.show_formspec.formname));
3158 create_formspec_menu(¤t_formspec, client, device, &input->joystick,
3160 cur_formname = *(event.show_formspec.formname);
3163 delete event.show_formspec.formspec;
3164 delete event.show_formspec.formname;
3167 case CE_SHOW_LOCAL_FORMSPEC:
3169 FormspecFormSource *fs_src = new FormspecFormSource(*event.show_formspec.formspec);
3170 LocalFormspecHandler *txt_dst = new LocalFormspecHandler(*event.show_formspec.formname, client);
3171 create_formspec_menu(¤t_formspec, client, device, &input->joystick,
3174 delete event.show_formspec.formspec;
3175 delete event.show_formspec.formname;
3178 case CE_SPAWN_PARTICLE:
3179 case CE_ADD_PARTICLESPAWNER:
3180 case CE_DELETE_PARTICLESPAWNER:
3181 client->getParticleManager()->handleParticleEvent(&event, client,
3187 u32 id = event.hudadd.id;
3189 HudElement *e = player->getHud(id);
3192 delete event.hudadd.pos;
3193 delete event.hudadd.name;
3194 delete event.hudadd.scale;
3195 delete event.hudadd.text;
3196 delete event.hudadd.align;
3197 delete event.hudadd.offset;
3198 delete event.hudadd.world_pos;
3199 delete event.hudadd.size;
3204 e->type = (HudElementType)event.hudadd.type;
3205 e->pos = *event.hudadd.pos;
3206 e->name = *event.hudadd.name;
3207 e->scale = *event.hudadd.scale;
3208 e->text = *event.hudadd.text;
3209 e->number = event.hudadd.number;
3210 e->item = event.hudadd.item;
3211 e->dir = event.hudadd.dir;
3212 e->align = *event.hudadd.align;
3213 e->offset = *event.hudadd.offset;
3214 e->world_pos = *event.hudadd.world_pos;
3215 e->size = *event.hudadd.size;
3217 u32 new_id = player->addHud(e);
3218 //if this isn't true our huds aren't consistent
3219 sanity_check(new_id == id);
3222 delete event.hudadd.pos;
3223 delete event.hudadd.name;
3224 delete event.hudadd.scale;
3225 delete event.hudadd.text;
3226 delete event.hudadd.align;
3227 delete event.hudadd.offset;
3228 delete event.hudadd.world_pos;
3229 delete event.hudadd.size;
3234 HudElement *e = player->removeHud(event.hudrm.id);
3243 u32 id = event.hudchange.id;
3244 HudElement *e = player->getHud(id);
3247 delete event.hudchange.v3fdata;
3248 delete event.hudchange.v2fdata;
3249 delete event.hudchange.sdata;
3250 delete event.hudchange.v2s32data;
3254 switch (event.hudchange.stat) {
3256 e->pos = *event.hudchange.v2fdata;
3260 e->name = *event.hudchange.sdata;
3263 case HUD_STAT_SCALE:
3264 e->scale = *event.hudchange.v2fdata;
3268 e->text = *event.hudchange.sdata;
3271 case HUD_STAT_NUMBER:
3272 e->number = event.hudchange.data;
3276 e->item = event.hudchange.data;
3280 e->dir = event.hudchange.data;
3283 case HUD_STAT_ALIGN:
3284 e->align = *event.hudchange.v2fdata;
3287 case HUD_STAT_OFFSET:
3288 e->offset = *event.hudchange.v2fdata;
3291 case HUD_STAT_WORLD_POS:
3292 e->world_pos = *event.hudchange.v3fdata;
3296 e->size = *event.hudchange.v2s32data;
3301 delete event.hudchange.v3fdata;
3302 delete event.hudchange.v2fdata;
3303 delete event.hudchange.sdata;
3304 delete event.hudchange.v2s32data;
3308 sky->setVisible(false);
3309 // Whether clouds are visible in front of a custom skybox
3310 sky->setCloudsEnabled(event.set_sky.clouds);
3317 // Handle according to type
3318 if (*event.set_sky.type == "regular") {
3319 sky->setVisible(true);
3320 sky->setCloudsEnabled(true);
3321 } else if (*event.set_sky.type == "skybox" &&
3322 event.set_sky.params->size() == 6) {
3323 sky->setFallbackBgColor(*event.set_sky.bgcolor);
3324 skybox = smgr->addSkyBoxSceneNode(
3325 texture_src->getTextureForMesh((*event.set_sky.params)[0]),
3326 texture_src->getTextureForMesh((*event.set_sky.params)[1]),
3327 texture_src->getTextureForMesh((*event.set_sky.params)[2]),
3328 texture_src->getTextureForMesh((*event.set_sky.params)[3]),
3329 texture_src->getTextureForMesh((*event.set_sky.params)[4]),
3330 texture_src->getTextureForMesh((*event.set_sky.params)[5]));
3332 // Handle everything else as plain color
3334 if (*event.set_sky.type != "plain")
3335 infostream << "Unknown sky type: "
3336 << (*event.set_sky.type) << std::endl;
3338 sky->setFallbackBgColor(*event.set_sky.bgcolor);
3341 delete event.set_sky.bgcolor;
3342 delete event.set_sky.type;
3343 delete event.set_sky.params;
3346 case CE_OVERRIDE_DAY_NIGHT_RATIO:
3347 client->getEnv().setDayNightRatioOverride(
3348 event.override_day_night_ratio.do_override,
3349 event.override_day_night_ratio.ratio_f * 1000);
3352 case CE_CLOUD_PARAMS:
3354 clouds->setDensity(event.cloud_params.density);
3355 clouds->setColorBright(video::SColor(event.cloud_params.color_bright));
3356 clouds->setColorAmbient(video::SColor(event.cloud_params.color_ambient));
3357 clouds->setHeight(event.cloud_params.height);
3358 clouds->setThickness(event.cloud_params.thickness);
3359 clouds->setSpeed(v2f(
3360 event.cloud_params.speed_x,
3361 event.cloud_params.speed_y));
3366 // unknown or unhandled type
3374 void Game::updateCamera(u32 busy_time, f32 dtime)
3376 LocalPlayer *player = client->getEnv().getLocalPlayer();
3379 For interaction purposes, get info about the held item
3381 - Is it a usable item?
3382 - Can it point to liquids?
3384 ItemStack playeritem;
3386 InventoryList *mlist = local_inventory->getList("main");
3388 if (mlist && client->getPlayerItem() < mlist->getSize())
3389 playeritem = mlist->getItem(client->getPlayerItem());
3392 if (playeritem.getDefinition(itemdef_manager).name.empty()) { // override the hand
3393 InventoryList *hlist = local_inventory->getList("hand");
3395 playeritem = hlist->getItem(0);
3399 ToolCapabilities playeritem_toolcap =
3400 playeritem.getToolCapabilities(itemdef_manager);
3402 v3s16 old_camera_offset = camera->getOffset();
3404 if (wasKeyDown(KeyType::CAMERA_MODE)) {
3405 GenericCAO *playercao = player->getCAO();
3407 // If playercao not loaded, don't change camera
3408 if (playercao == NULL)
3411 camera->toggleCameraMode();
3413 playercao->setVisible(camera->getCameraMode() > CAMERA_MODE_FIRST);
3414 playercao->setChildrenVisible(camera->getCameraMode() > CAMERA_MODE_FIRST);
3417 float full_punch_interval = playeritem_toolcap.full_punch_interval;
3418 float tool_reload_ratio = runData.time_from_last_punch / full_punch_interval;
3420 tool_reload_ratio = MYMIN(tool_reload_ratio, 1.0);
3421 camera->update(player, dtime, busy_time / 1000.0f, tool_reload_ratio,
3423 camera->step(dtime);
3425 v3f camera_position = camera->getPosition();
3426 v3f camera_direction = camera->getDirection();
3427 f32 camera_fov = camera->getFovMax();
3428 v3s16 camera_offset = camera->getOffset();
3430 m_camera_offset_changed = (camera_offset != old_camera_offset);
3432 if (!flags.disable_camera_update) {
3433 client->getEnv().getClientMap().updateCamera(camera_position,
3434 camera_direction, camera_fov, camera_offset);
3436 if (m_camera_offset_changed) {
3437 client->updateCameraOffset(camera_offset);
3438 client->getEnv().updateCameraOffset(camera_offset);
3441 clouds->updateCameraOffset(camera_offset);
3447 void Game::updateSound(f32 dtime)
3449 // Update sound listener
3450 v3s16 camera_offset = camera->getOffset();
3451 sound->updateListener(camera->getCameraNode()->getPosition() + intToFloat(camera_offset, BS),
3452 v3f(0, 0, 0), // velocity
3453 camera->getDirection(),
3454 camera->getCameraNode()->getUpVector());
3455 sound->setListenerGain(g_settings->getFloat("sound_volume"));
3457 LocalPlayer *player = client->getEnv().getLocalPlayer();
3459 // Tell the sound maker whether to make footstep sounds
3460 soundmaker->makes_footstep_sound = player->makes_footstep_sound;
3462 // Update sound maker
3463 if (player->makes_footstep_sound)
3464 soundmaker->step(dtime);
3466 ClientMap &map = client->getEnv().getClientMap();
3467 MapNode n = map.getNodeNoEx(player->getFootstepNodePos());
3468 soundmaker->m_player_step_sound = nodedef_manager->get(n).sound_footstep;
3472 void Game::processPlayerInteraction(f32 dtime, bool show_hud, bool show_debug)
3474 LocalPlayer *player = client->getEnv().getLocalPlayer();
3476 ItemStack playeritem;
3478 InventoryList *mlist = local_inventory->getList("main");
3480 if (mlist && client->getPlayerItem() < mlist->getSize())
3481 playeritem = mlist->getItem(client->getPlayerItem());
3484 const ItemDefinition &playeritem_def =
3485 playeritem.getDefinition(itemdef_manager);
3486 InventoryList *hlist = local_inventory->getList("hand");
3487 const ItemDefinition &hand_def =
3488 hlist ? hlist->getItem(0).getDefinition(itemdef_manager) : itemdef_manager->get("");
3490 v3f player_position = player->getPosition();
3491 v3f camera_position = camera->getPosition();
3492 v3f camera_direction = camera->getDirection();
3493 v3s16 camera_offset = camera->getOffset();
3497 Calculate what block is the crosshair pointing to
3500 f32 d = playeritem_def.range; // max. distance
3501 f32 d_hand = hand_def.range;
3503 if (d < 0 && d_hand >= 0)
3508 core::line3d<f32> shootline;
3510 if (camera->getCameraMode() != CAMERA_MODE_THIRD_FRONT) {
3511 shootline = core::line3d<f32>(camera_position,
3512 camera_position + camera_direction * BS * d);
3514 // prevent player pointing anything in front-view
3515 shootline = core::line3d<f32>(camera_position,camera_position);
3518 #ifdef HAVE_TOUCHSCREENGUI
3520 if ((g_settings->getBool("touchtarget")) && (g_touchscreengui)) {
3521 shootline = g_touchscreengui->getShootline();
3522 shootline.start += intToFloat(camera_offset, BS);
3523 shootline.end += intToFloat(camera_offset, BS);
3528 PointedThing pointed = updatePointedThing(shootline,
3529 playeritem_def.liquids_pointable,
3530 !runData.ldown_for_dig,
3533 if (pointed != runData.pointed_old) {
3534 infostream << "Pointing at " << pointed.dump() << std::endl;
3535 hud->updateSelectionMesh(camera_offset);
3540 - releasing left mouse button
3541 - pointing away from node
3543 if (runData.digging) {
3544 if (getLeftReleased()) {
3545 infostream << "Left button released"
3546 << " (stopped digging)" << std::endl;
3547 runData.digging = false;
3548 } else if (pointed != runData.pointed_old) {
3549 if (pointed.type == POINTEDTHING_NODE
3550 && runData.pointed_old.type == POINTEDTHING_NODE
3551 && pointed.node_undersurface
3552 == runData.pointed_old.node_undersurface) {
3553 // Still pointing to the same node, but a different face.
3556 infostream << "Pointing away from node"
3557 << " (stopped digging)" << std::endl;
3558 runData.digging = false;
3559 hud->updateSelectionMesh(camera_offset);
3563 if (!runData.digging) {
3564 client->interact(1, runData.pointed_old);
3565 client->setCrack(-1, v3s16(0, 0, 0));
3566 runData.dig_time = 0.0;
3568 } else if (runData.dig_instantly && getLeftReleased()) {
3569 // Remove e.g. torches faster when clicking instead of holding LMB
3570 runData.nodig_delay_timer = 0;
3571 runData.dig_instantly = false;
3574 if (!runData.digging && runData.ldown_for_dig && !isLeftPressed()) {
3575 runData.ldown_for_dig = false;
3578 runData.left_punch = false;
3580 soundmaker->m_player_leftpunch_sound.name = "";
3582 if (isRightPressed())
3583 runData.repeat_rightclick_timer += dtime;
3585 runData.repeat_rightclick_timer = 0;
3587 if (playeritem_def.usable && isLeftPressed()) {
3588 if (getLeftClicked() && (!client->moddingEnabled()
3589 || !client->getScript()->on_item_use(playeritem, pointed)))
3590 client->interact(4, pointed);
3591 } else if (pointed.type == POINTEDTHING_NODE) {
3592 ToolCapabilities playeritem_toolcap =
3593 playeritem.getToolCapabilities(itemdef_manager);
3594 if (playeritem.name.empty()) {
3595 playeritem_toolcap = *hand_def.tool_capabilities;
3597 handlePointingAtNode(pointed, playeritem_def, playeritem_toolcap, dtime);
3598 } else if (pointed.type == POINTEDTHING_OBJECT) {
3599 handlePointingAtObject(pointed, playeritem, player_position, show_debug);
3600 } else if (isLeftPressed()) {
3601 // When button is held down in air, show continuous animation
3602 runData.left_punch = true;
3603 } else if (getRightClicked()) {
3604 handlePointingAtNothing(playeritem);
3607 runData.pointed_old = pointed;
3609 if (runData.left_punch || getLeftClicked())
3610 camera->setDigging(0); // left click animation
3612 input->resetLeftClicked();
3613 input->resetRightClicked();
3615 input->joystick.clearWasKeyDown(KeyType::MOUSE_L);
3616 input->joystick.clearWasKeyDown(KeyType::MOUSE_R);
3618 input->resetLeftReleased();
3619 input->resetRightReleased();
3621 input->joystick.clearWasKeyReleased(KeyType::MOUSE_L);
3622 input->joystick.clearWasKeyReleased(KeyType::MOUSE_R);
3626 PointedThing Game::updatePointedThing(
3627 const core::line3d<f32> &shootline,
3628 bool liquids_pointable,
3629 bool look_for_object,
3630 const v3s16 &camera_offset)
3632 std::vector<aabb3f> *selectionboxes = hud->getSelectionBoxes();
3633 selectionboxes->clear();
3634 hud->setSelectedFaceNormal(v3f(0.0, 0.0, 0.0));
3635 static const bool show_entity_selectionbox = g_settings->getBool(
3636 "show_entity_selectionbox");
3638 ClientMap &map = client->getEnv().getClientMap();
3639 INodeDefManager *nodedef=client->getNodeDefManager();
3641 runData.selected_object = NULL;
3643 PointedThing result=client->getEnv().getPointedThing(
3644 shootline, liquids_pointable, look_for_object);
3645 if (result.type == POINTEDTHING_OBJECT) {
3646 runData.selected_object = client->getEnv().getActiveObject(result.object_id);
3647 if (show_entity_selectionbox && runData.selected_object->doShowSelectionBox()) {
3648 aabb3f *selection_box = runData.selected_object->getSelectionBox();
3650 // Box should exist because object was
3651 // returned in the first place
3653 assert(selection_box);
3655 v3f pos = runData.selected_object->getPosition();
3656 selectionboxes->push_back(aabb3f(
3657 selection_box->MinEdge, selection_box->MaxEdge));
3658 selectionboxes->push_back(
3659 aabb3f(selection_box->MinEdge, selection_box->MaxEdge));
3660 hud->setSelectionPos(pos, camera_offset);
3662 } else if (result.type == POINTEDTHING_NODE) {
3663 // Update selection boxes
3664 MapNode n = map.getNodeNoEx(result.node_undersurface);
3665 std::vector<aabb3f> boxes;
3666 n.getSelectionBoxes(nodedef, &boxes,
3667 n.getNeighbors(result.node_undersurface, &map));
3670 for (std::vector<aabb3f>::const_iterator i = boxes.begin();
3671 i != boxes.end(); ++i) {
3673 box.MinEdge -= v3f(d, d, d);
3674 box.MaxEdge += v3f(d, d, d);
3675 selectionboxes->push_back(box);
3677 hud->setSelectionPos(intToFloat(result.node_undersurface, BS),
3679 hud->setSelectedFaceNormal(v3f(
3680 result.intersection_normal.X,
3681 result.intersection_normal.Y,
3682 result.intersection_normal.Z));
3685 // Update selection mesh light level and vertex colors
3686 if (selectionboxes->size() > 0) {
3687 v3f pf = hud->getSelectionPos();
3688 v3s16 p = floatToInt(pf, BS);
3690 // Get selection mesh light level
3691 MapNode n = map.getNodeNoEx(p);
3692 u16 node_light = getInteriorLight(n, -1, nodedef);
3693 u16 light_level = node_light;
3695 for (u8 i = 0; i < 6; i++) {
3696 n = map.getNodeNoEx(p + g_6dirs[i]);
3697 node_light = getInteriorLight(n, -1, nodedef);
3698 if (node_light > light_level)
3699 light_level = node_light;
3702 u32 daynight_ratio = client->getEnv().getDayNightRatio();
3704 final_color_blend(&c, light_level, daynight_ratio);
3706 // Modify final color a bit with time
3707 u32 timer = porting::getTimeMs() % 5000;
3708 float timerf = (float) (irr::core::PI * ((timer / 2500.0) - 0.5));
3709 float sin_r = 0.08 * sin(timerf);
3710 float sin_g = 0.08 * sin(timerf + irr::core::PI * 0.5);
3711 float sin_b = 0.08 * sin(timerf + irr::core::PI);
3713 core::clamp(core::round32(c.getRed() * (0.8 + sin_r)), 0, 255));
3715 core::clamp(core::round32(c.getGreen() * (0.8 + sin_g)), 0, 255));
3717 core::clamp(core::round32(c.getBlue() * (0.8 + sin_b)), 0, 255));
3719 // Set mesh final color
3720 hud->setSelectionMeshColor(c);
3726 void Game::handlePointingAtNothing(const ItemStack &playerItem)
3728 infostream << "Right Clicked in Air" << std::endl;
3729 PointedThing fauxPointed;
3730 fauxPointed.type = POINTEDTHING_NOTHING;
3731 client->interact(5, fauxPointed);
3735 void Game::handlePointingAtNode(const PointedThing &pointed, const ItemDefinition &playeritem_def,
3736 const ToolCapabilities &playeritem_toolcap, f32 dtime)
3738 v3s16 nodepos = pointed.node_undersurface;
3739 v3s16 neighbourpos = pointed.node_abovesurface;
3742 Check information text of node
3745 ClientMap &map = client->getEnv().getClientMap();
3746 NodeMetadata *meta = map.getNodeMetadata(nodepos);
3749 infotext = unescape_enriched(utf8_to_wide(meta->getString("infotext")));
3751 MapNode n = map.getNodeNoEx(nodepos);
3753 if (nodedef_manager->get(n).tiledef[0].name == "unknown_node.png") {
3754 infotext = L"Unknown node: ";
3755 infotext += utf8_to_wide(nodedef_manager->get(n).name);
3759 if (runData.nodig_delay_timer <= 0.0 && isLeftPressed()
3760 && client->checkPrivilege("interact")) {
3761 handleDigging(pointed, nodepos, playeritem_toolcap, dtime);
3764 if ((getRightClicked() ||
3765 runData.repeat_rightclick_timer >= m_repeat_right_click_time) &&
3766 client->checkPrivilege("interact")) {
3767 runData.repeat_rightclick_timer = 0;
3768 infostream << "Ground right-clicked" << std::endl;
3770 if (meta && meta->getString("formspec") != "" && !random_input
3771 && !isKeyDown(KeyType::SNEAK)) {
3772 infostream << "Launching custom inventory view" << std::endl;
3774 InventoryLocation inventoryloc;
3775 inventoryloc.setNodeMeta(nodepos);
3777 NodeMetadataFormSource *fs_src = new NodeMetadataFormSource(
3778 &client->getEnv().getClientMap(), nodepos);
3779 TextDest *txt_dst = new TextDestNodeMetadata(nodepos, client);
3781 create_formspec_menu(¤t_formspec, client,
3782 device, &input->joystick, fs_src, txt_dst);
3785 current_formspec->setFormSpec(meta->getString("formspec"), inventoryloc);
3787 // Report right click to server
3789 camera->setDigging(1); // right click animation (always shown for feedback)
3791 // If the wielded item has node placement prediction,
3793 bool placed = nodePlacementPrediction(*client,
3795 nodepos, neighbourpos);
3799 client->interact(3, pointed);
3801 soundmaker->m_player_rightpunch_sound =
3802 playeritem_def.sound_place;
3804 if (client->moddingEnabled())
3805 client->getScript()->on_placenode(pointed, playeritem_def);
3807 soundmaker->m_player_rightpunch_sound =
3810 if (playeritem_def.node_placement_prediction == "" ||
3811 nodedef_manager->get(map.getNodeNoEx(nodepos)).rightclickable) {
3812 client->interact(3, pointed); // Report to server
3814 soundmaker->m_player_rightpunch_sound =
3815 playeritem_def.sound_place_failed;
3823 void Game::handlePointingAtObject(const PointedThing &pointed, const ItemStack &playeritem,
3824 const v3f &player_position, bool show_debug)
3826 infotext = unescape_enriched(
3827 utf8_to_wide(runData.selected_object->infoText()));
3830 if (infotext != L"") {
3833 infotext += unescape_enriched(utf8_to_wide(
3834 runData.selected_object->debugInfoText()));
3837 if (isLeftPressed()) {
3838 bool do_punch = false;
3839 bool do_punch_damage = false;
3841 if (runData.object_hit_delay_timer <= 0.0) {
3843 do_punch_damage = true;
3844 runData.object_hit_delay_timer = object_hit_delay;
3847 if (getLeftClicked())
3851 infostream << "Left-clicked object" << std::endl;
3852 runData.left_punch = true;
3855 if (do_punch_damage) {
3856 // Report direct punch
3857 v3f objpos = runData.selected_object->getPosition();
3858 v3f dir = (objpos - player_position).normalize();
3859 ItemStack item = playeritem;
3860 if (playeritem.name.empty()) {
3861 InventoryList *hlist = local_inventory->getList("hand");
3863 item = hlist->getItem(0);
3867 bool disable_send = runData.selected_object->directReportPunch(
3868 dir, &item, runData.time_from_last_punch);
3869 runData.time_from_last_punch = 0;
3872 client->interact(0, pointed);
3874 } else if (getRightClicked()) {
3875 infostream << "Right-clicked object" << std::endl;
3876 client->interact(3, pointed); // place
3881 void Game::handleDigging(const PointedThing &pointed, const v3s16 &nodepos,
3882 const ToolCapabilities &playeritem_toolcap, f32 dtime)
3884 LocalPlayer *player = client->getEnv().getLocalPlayer();
3885 ClientMap &map = client->getEnv().getClientMap();
3886 MapNode n = client->getEnv().getClientMap().getNodeNoEx(nodepos);
3888 // NOTE: Similar piece of code exists on the server side for
3890 // Get digging parameters
3891 DigParams params = getDigParams(nodedef_manager->get(n).groups,
3892 &playeritem_toolcap);
3894 // If can't dig, try hand
3895 if (!params.diggable) {
3896 InventoryList *hlist = local_inventory->getList("hand");
3897 const ItemDefinition &hand =
3898 hlist ? hlist->getItem(0).getDefinition(itemdef_manager) : itemdef_manager->get("");
3899 const ToolCapabilities *tp = hand.tool_capabilities;
3902 params = getDigParams(nodedef_manager->get(n).groups, tp);
3905 if (!runData.digging) {
3906 infostream << "Started digging" << std::endl;
3907 runData.dig_instantly = params.time == 0;
3908 if (client->moddingEnabled() && client->getScript()->on_punchnode(nodepos, n))
3910 client->interact(0, pointed);
3911 runData.digging = true;
3912 runData.ldown_for_dig = true;
3915 if (!params.diggable) {
3916 // I guess nobody will wait for this long
3917 runData.dig_time_complete = 10000000.0;
3919 runData.dig_time_complete = params.time;
3921 if (m_cache_enable_particles) {
3922 const ContentFeatures &features =
3923 client->getNodeDefManager()->get(n);
3924 client->getParticleManager()->addPunchingParticles(client, smgr,
3925 player, nodepos, n, features);
3929 if (!runData.dig_instantly) {
3930 runData.dig_index = (float)crack_animation_length
3932 / runData.dig_time_complete;
3934 // This is for e.g. torches
3935 runData.dig_index = crack_animation_length;
3938 SimpleSoundSpec sound_dig = nodedef_manager->get(n).sound_dig;
3940 if (sound_dig.exists() && params.diggable) {
3941 if (sound_dig.name == "__group") {
3942 if (params.main_group != "") {
3943 soundmaker->m_player_leftpunch_sound.gain = 0.5;
3944 soundmaker->m_player_leftpunch_sound.name =
3945 std::string("default_dig_") +
3949 soundmaker->m_player_leftpunch_sound = sound_dig;
3953 // Don't show cracks if not diggable
3954 if (runData.dig_time_complete >= 100000.0) {
3955 } else if (runData.dig_index < crack_animation_length) {
3956 //TimeTaker timer("client.setTempMod");
3957 //infostream<<"dig_index="<<dig_index<<std::endl;
3958 client->setCrack(runData.dig_index, nodepos);
3960 infostream << "Digging completed" << std::endl;
3961 client->setCrack(-1, v3s16(0, 0, 0));
3963 runData.dig_time = 0;
3964 runData.digging = false;
3966 runData.nodig_delay_timer =
3967 runData.dig_time_complete / (float)crack_animation_length;
3969 // We don't want a corresponding delay to very time consuming nodes
3970 // and nodes without digging time (e.g. torches) get a fixed delay.
3971 if (runData.nodig_delay_timer > 0.3)
3972 runData.nodig_delay_timer = 0.3;
3973 else if (runData.dig_instantly)
3974 runData.nodig_delay_timer = 0.15;
3976 bool is_valid_position;
3977 MapNode wasnode = map.getNodeNoEx(nodepos, &is_valid_position);
3978 if (is_valid_position) {
3979 if (client->moddingEnabled()) {
3980 if (client->getScript()->on_dignode(nodepos, wasnode)) {
3984 client->removeNode(nodepos);
3987 client->interact(2, pointed);
3989 if (m_cache_enable_particles) {
3990 const ContentFeatures &features =
3991 client->getNodeDefManager()->get(wasnode);
3992 client->getParticleManager()->addDiggingParticles(client, smgr,
3993 player, nodepos, wasnode, features);
3997 // Send event to trigger sound
3998 MtEvent *e = new NodeDugEvent(nodepos, wasnode);
3999 client->event()->put(e);
4002 if (runData.dig_time_complete < 100000.0) {
4003 runData.dig_time += dtime;
4005 runData.dig_time = 0;
4006 client->setCrack(-1, nodepos);
4009 camera->setDigging(0); // left click animation
4013 void Game::updateFrame(ProfilerGraph *graph, RunStats *stats, f32 dtime,
4014 const CameraOrientation &cam)
4016 LocalPlayer *player = client->getEnv().getLocalPlayer();
4022 if (draw_control->range_all) {
4023 runData.fog_range = 100000 * BS;
4025 runData.fog_range = draw_control->wanted_range * BS;
4029 Calculate general brightness
4031 u32 daynight_ratio = client->getEnv().getDayNightRatio();
4032 float time_brightness = decode_light_f((float)daynight_ratio / 1000.0);
4033 float direct_brightness;
4036 if (m_cache_enable_noclip && m_cache_enable_free_move) {
4037 direct_brightness = time_brightness;
4038 sunlight_seen = true;
4040 ScopeProfiler sp(g_profiler, "Detecting background light", SPT_AVG);
4041 float old_brightness = sky->getBrightness();
4042 direct_brightness = client->getEnv().getClientMap()
4043 .getBackgroundBrightness(MYMIN(runData.fog_range * 1.2, 60 * BS),
4044 daynight_ratio, (int)(old_brightness * 255.5), &sunlight_seen)
4048 float time_of_day_smooth = runData.time_of_day_smooth;
4049 float time_of_day = client->getEnv().getTimeOfDayF();
4051 static const float maxsm = 0.05;
4052 static const float todsm = 0.05;
4054 if (fabs(time_of_day - time_of_day_smooth) > maxsm &&
4055 fabs(time_of_day - time_of_day_smooth + 1.0) > maxsm &&
4056 fabs(time_of_day - time_of_day_smooth - 1.0) > maxsm)
4057 time_of_day_smooth = time_of_day;
4059 if (time_of_day_smooth > 0.8 && time_of_day < 0.2)
4060 time_of_day_smooth = time_of_day_smooth * (1.0 - todsm)
4061 + (time_of_day + 1.0) * todsm;
4063 time_of_day_smooth = time_of_day_smooth * (1.0 - todsm)
4064 + time_of_day * todsm;
4066 runData.time_of_day = time_of_day;
4067 runData.time_of_day_smooth = time_of_day_smooth;
4069 sky->update(time_of_day_smooth, time_brightness, direct_brightness,
4070 sunlight_seen, camera->getCameraMode(), player->getYaw(),
4071 player->getPitch());
4077 v3f player_position = player->getPosition();
4078 if (sky->getCloudsVisible()) {
4079 clouds->setVisible(true);
4080 clouds->step(dtime);
4081 clouds->update(v2f(player_position.X, player_position.Z),
4082 sky->getCloudColor());
4084 clouds->setVisible(false);
4091 client->getParticleManager()->step(dtime);
4097 if (m_cache_enable_fog && !flags.force_fog_off) {
4100 video::EFT_FOG_LINEAR,
4101 runData.fog_range * m_cache_fog_start,
4102 runData.fog_range * 1.0,
4110 video::EFT_FOG_LINEAR,
4120 Get chat messages from client
4123 v2u32 screensize = driver->getScreenSize();
4125 updateChat(*client, dtime, flags.show_debug, screensize,
4126 flags.show_chat, runData.profiler_current_page,
4127 *chat_backend, guitext_chat);
4133 if (client->getPlayerItem() != runData.new_playeritem)
4134 client->selectPlayerItem(runData.new_playeritem);
4136 // Update local inventory if it has changed
4137 if (client->getLocalInventoryUpdated()) {
4138 //infostream<<"Updating local inventory"<<std::endl;
4139 client->getLocalInventory(*local_inventory);
4140 runData.update_wielded_item_trigger = true;
4143 if (runData.update_wielded_item_trigger) {
4144 // Update wielded tool
4145 InventoryList *mlist = local_inventory->getList("main");
4147 if (mlist && (client->getPlayerItem() < mlist->getSize())) {
4148 ItemStack item = mlist->getItem(client->getPlayerItem());
4149 if (item.getDefinition(itemdef_manager).name.empty()) { // override the hand
4150 InventoryList *hlist = local_inventory->getList("hand");
4152 item = hlist->getItem(0);
4154 camera->wield(item);
4157 runData.update_wielded_item_trigger = false;
4161 Update block draw list every 200ms or when camera direction has
4164 runData.update_draw_list_timer += dtime;
4166 v3f camera_direction = camera->getDirection();
4167 if (runData.update_draw_list_timer >= 0.2
4168 || runData.update_draw_list_last_cam_dir.getDistanceFrom(camera_direction) > 0.2
4169 || m_camera_offset_changed) {
4170 runData.update_draw_list_timer = 0;
4171 client->getEnv().getClientMap().updateDrawList(driver);
4172 runData.update_draw_list_last_cam_dir = camera_direction;
4175 updateGui(*stats, dtime, cam);
4178 make sure menu is on top
4179 1. Delete formspec menu reference if menu was removed
4180 2. Else, make sure formspec menu is on top
4182 if (current_formspec) {
4183 if (current_formspec->getReferenceCount() == 1) {
4184 current_formspec->drop();
4185 current_formspec = NULL;
4186 } else if (!noMenuActive()) {
4187 guiroot->bringToFront(current_formspec);
4195 const video::SColor &skycolor = sky->getSkyColor();
4197 TimeTaker tt_draw("mainloop: draw");
4198 driver->beginScene(true, true, skycolor);
4200 draw_scene(driver, smgr, *camera, *client, player, *hud, *mapper,
4201 guienv, screensize, skycolor, flags.show_hud,
4202 flags.show_minimap);
4207 if (flags.show_profiler_graph)
4208 graph->draw(10, screensize.Y - 10, driver, g_fontengine->getFont());
4213 if (runData.damage_flash > 0.0) {
4214 video::SColor color(runData.damage_flash, 180, 0, 0);
4215 driver->draw2DRectangle(color,
4216 core::rect<s32>(0, 0, screensize.X, screensize.Y),
4219 runData.damage_flash -= 100.0 * dtime;
4225 if (player->hurt_tilt_timer > 0.0) {
4226 player->hurt_tilt_timer -= dtime * 5;
4228 if (player->hurt_tilt_timer < 0)
4229 player->hurt_tilt_strength = 0;
4233 Update minimap pos and rotation
4235 if (flags.show_minimap && flags.show_hud) {
4236 mapper->setPos(floatToInt(player->getPosition(), BS));
4237 mapper->setAngle(player->getYaw());
4245 stats->drawtime = tt_draw.stop(true);
4246 g_profiler->graphAdd("mainloop_draw", stats->drawtime / 1000.0f);
4250 inline static const char *yawToDirectionString(int yaw)
4252 static const char *direction[4] = {"North [+Z]", "West [-X]", "South [-Z]", "East [+X]"};
4254 yaw = wrapDegrees_0_360(yaw);
4255 yaw = (yaw + 45) % 360 / 90;
4257 return direction[yaw];
4261 void Game::updateGui(const RunStats &stats, f32 dtime, const CameraOrientation &cam)
4263 v2u32 screensize = driver->getScreenSize();
4264 LocalPlayer *player = client->getEnv().getLocalPlayer();
4265 v3f player_position = player->getPosition();
4267 if (flags.show_debug) {
4268 static float drawtime_avg = 0;
4269 drawtime_avg = drawtime_avg * 0.95 + stats.drawtime * 0.05;
4271 u16 fps = 1.0 / stats.dtime_jitter.avg;
4273 std::ostringstream os(std::ios_base::binary);
4275 << PROJECT_NAME_C " " << g_version_hash
4277 << " (R: range_all=" << draw_control->range_all << ")"
4278 << std::setprecision(0)
4279 << " drawtime = " << drawtime_avg
4280 << std::setprecision(1)
4281 << ", dtime_jitter = "
4282 << (stats.dtime_jitter.max_fraction * 100.0) << " %"
4283 << std::setprecision(1)
4284 << ", v_range = " << draw_control->wanted_range
4285 << std::setprecision(3)
4286 << ", RTT = " << client->getRTT();
4287 setStaticText(guitext, utf8_to_wide(os.str()).c_str());
4288 guitext->setVisible(true);
4290 guitext->setVisible(false);
4293 if (guitext->isVisible()) {
4294 core::rect<s32> rect(
4296 screensize.X, 5 + g_fontengine->getTextHeight()
4298 guitext->setRelativePosition(rect);
4301 if (flags.show_debug) {
4302 std::ostringstream os(std::ios_base::binary);
4303 os << std::setprecision(1) << std::fixed
4304 << "(" << (player_position.X / BS)
4305 << ", " << (player_position.Y / BS)
4306 << ", " << (player_position.Z / BS)
4307 << ") (yaw=" << (wrapDegrees_0_360(cam.camera_yaw))
4308 << " " << yawToDirectionString(cam.camera_yaw)
4309 << ") (seed = " << ((u64)client->getMapSeed())
4312 if (runData.pointed_old.type == POINTEDTHING_NODE) {
4313 ClientMap &map = client->getEnv().getClientMap();
4314 const INodeDefManager *nodedef = client->getNodeDefManager();
4315 MapNode n = map.getNodeNoEx(runData.pointed_old.node_undersurface);
4316 if (n.getContent() != CONTENT_IGNORE && nodedef->get(n).name != "unknown") {
4317 const ContentFeatures &features = nodedef->get(n);
4318 os << " (pointing_at = " << nodedef->get(n).name
4319 << " - " << features.tiledef[0].name.c_str()
4324 setStaticText(guitext2, utf8_to_wide(os.str()).c_str());
4325 guitext2->setVisible(true);
4327 core::rect<s32> rect(
4328 5, 5 + g_fontengine->getTextHeight(),
4329 screensize.X, 5 + g_fontengine->getTextHeight() * 2
4331 guitext2->setRelativePosition(rect);
4333 guitext2->setVisible(false);
4336 setStaticText(guitext_info, infotext.c_str());
4337 guitext_info->setVisible(flags.show_hud && g_menumgr.menuCount() == 0);
4339 float statustext_time_max = 1.5;
4341 if (!m_statustext.empty()) {
4342 runData.statustext_time += dtime;
4344 if (runData.statustext_time >= statustext_time_max) {
4346 runData.statustext_time = 0;
4350 setStaticText(guitext_status, m_statustext.c_str());
4351 guitext_status->setVisible(!m_statustext.empty());
4353 if (!m_statustext.empty()) {
4354 s32 status_width = guitext_status->getTextWidth();
4355 s32 status_height = guitext_status->getTextHeight();
4356 s32 status_y = screensize.Y - 150;
4357 s32 status_x = (screensize.X - status_width) / 2;
4358 core::rect<s32> rect(
4359 status_x , status_y - status_height,
4360 status_x + status_width, status_y
4362 guitext_status->setRelativePosition(rect);
4365 video::SColor initial_color(255, 0, 0, 0);
4367 if (guienv->getSkin())
4368 initial_color = guienv->getSkin()->getColor(gui::EGDC_BUTTON_TEXT);
4370 video::SColor final_color = initial_color;
4371 final_color.setAlpha(0);
4372 video::SColor fade_color = initial_color.getInterpolated_quadratic(
4373 initial_color, final_color,
4374 pow(runData.statustext_time / statustext_time_max, 2.0f));
4375 guitext_status->setOverrideColor(fade_color);
4376 guitext_status->enableOverrideColor(true);
4381 /* Log times and stuff for visualization */
4382 inline void Game::updateProfilerGraphs(ProfilerGraph *graph)
4384 Profiler::GraphValues values;
4385 g_profiler->graphGet(values);
4391 /****************************************************************************
4393 ****************************************************************************/
4395 /* On some computers framerate doesn't seem to be automatically limited
4397 inline void Game::limitFps(FpsControl *fps_timings, f32 *dtime)
4399 // not using getRealTime is necessary for wine
4400 device->getTimer()->tick(); // Maker sure device time is up-to-date
4401 u32 time = device->getTimer()->getTime();
4402 u32 last_time = fps_timings->last_time;
4404 if (time > last_time) // Make sure time hasn't overflowed
4405 fps_timings->busy_time = time - last_time;
4407 fps_timings->busy_time = 0;
4409 u32 frametime_min = 1000 / (g_menumgr.pausesGame()
4410 ? g_settings->getFloat("pause_fps_max")
4411 : g_settings->getFloat("fps_max"));
4413 if (fps_timings->busy_time < frametime_min) {
4414 fps_timings->sleep_time = frametime_min - fps_timings->busy_time;
4415 device->sleep(fps_timings->sleep_time);
4417 fps_timings->sleep_time = 0;
4420 /* Get the new value of the device timer. Note that device->sleep() may
4421 * not sleep for the entire requested time as sleep may be interrupted and
4422 * therefore it is arguably more accurate to get the new time from the
4423 * device rather than calculating it by adding sleep_time to time.
4426 device->getTimer()->tick(); // Update device timer
4427 time = device->getTimer()->getTime();
4429 if (time > last_time) // Make sure last_time hasn't overflowed
4430 *dtime = (time - last_time) / 1000.0;
4434 fps_timings->last_time = time;
4437 // Note: This will free (using delete[])! \p msg. If you want to use it later,
4438 // pass a copy of it to this function
4439 // Note: \p msg must be allocated using new (not malloc())
4440 void Game::showOverlayMessage(const wchar_t *msg, float dtime,
4441 int percent, bool draw_clouds)
4443 draw_load_screen(msg, device, guienv, texture_src, dtime, percent,
4448 void Game::settingChangedCallback(const std::string &setting_name, void *data)
4450 ((Game *)data)->readSettings();
4453 void Game::readSettings()
4455 m_cache_doubletap_jump = g_settings->getBool("doubletap_jump");
4456 m_cache_enable_clouds = g_settings->getBool("enable_clouds");
4457 m_cache_enable_joysticks = g_settings->getBool("enable_joysticks");
4458 m_cache_enable_particles = g_settings->getBool("enable_particles");
4459 m_cache_enable_fog = g_settings->getBool("enable_fog");
4460 m_cache_mouse_sensitivity = g_settings->getFloat("mouse_sensitivity");
4461 m_cache_joystick_frustum_sensitivity = g_settings->getFloat("joystick_frustum_sensitivity");
4462 m_repeat_right_click_time = g_settings->getFloat("repeat_rightclick_time");
4464 m_cache_enable_noclip = g_settings->getBool("noclip");
4465 m_cache_enable_free_move = g_settings->getBool("free_move");
4467 m_cache_fog_start = g_settings->getFloat("fog_start");
4469 m_cache_cam_smoothing = 0;
4470 if (g_settings->getBool("cinematic"))
4471 m_cache_cam_smoothing = 1 - g_settings->getFloat("cinematic_camera_smoothing");
4473 m_cache_cam_smoothing = 1 - g_settings->getFloat("camera_smoothing");
4475 m_cache_fog_start = rangelim(m_cache_fog_start, 0.0f, 0.99f);
4476 m_cache_cam_smoothing = rangelim(m_cache_cam_smoothing, 0.01f, 1.0f);
4477 m_cache_mouse_sensitivity = rangelim(m_cache_mouse_sensitivity, 0.001, 100.0);
4481 /****************************************************************************/
4482 /****************************************************************************
4484 ****************************************************************************/
4485 /****************************************************************************/
4487 void Game::extendedResourceCleanup()
4489 // Extended resource accounting
4490 infostream << "Irrlicht resources after cleanup:" << std::endl;
4491 infostream << "\tRemaining meshes : "
4492 << device->getSceneManager()->getMeshCache()->getMeshCount() << std::endl;
4493 infostream << "\tRemaining textures : "
4494 << driver->getTextureCount() << std::endl;
4496 for (unsigned int i = 0; i < driver->getTextureCount(); i++) {
4497 irr::video::ITexture *texture = driver->getTextureByIndex(i);
4498 infostream << "\t\t" << i << ":" << texture->getName().getPath().c_str()
4502 clearTextureNameCache();
4503 infostream << "\tRemaining materials: "
4504 << driver-> getMaterialRendererCount()
4505 << " (note: irrlicht doesn't support removing renderers)" << std::endl;
4508 #define GET_KEY_NAME(KEY) gettext(getKeySetting(#KEY).name())
4509 void Game::showPauseMenu()
4512 static const std::string control_text = strgettext("Default Controls:\n"
4513 "No menu visible:\n"
4514 "- single tap: button activate\n"
4515 "- double tap: place/use\n"
4516 "- slide finger: look around\n"
4517 "Menu/Inventory visible:\n"
4518 "- double tap (outside):\n"
4520 "- touch stack, touch slot:\n"
4522 "- touch&drag, tap 2nd finger\n"
4523 " --> place single item to slot\n"
4526 static const std::string control_text_template = strgettext("Controls:\n"
4527 "- %s: move forwards\n"
4528 "- %s: move backwards\n"
4530 "- %s: move right\n"
4531 "- %s: jump/climb\n"
4532 "- %s: sneak/go down\n"
4535 "- Mouse: turn/look\n"
4536 "- Mouse left: dig/punch\n"
4537 "- Mouse right: place/use\n"
4538 "- Mouse wheel: select item\n"
4542 char control_text_buf[600];
4544 snprintf(control_text_buf, ARRLEN(control_text_buf), control_text_template.c_str(),
4545 GET_KEY_NAME(keymap_forward),
4546 GET_KEY_NAME(keymap_backward),
4547 GET_KEY_NAME(keymap_left),
4548 GET_KEY_NAME(keymap_right),
4549 GET_KEY_NAME(keymap_jump),
4550 GET_KEY_NAME(keymap_sneak),
4551 GET_KEY_NAME(keymap_drop),
4552 GET_KEY_NAME(keymap_inventory),
4553 GET_KEY_NAME(keymap_chat)
4556 std::string control_text = std::string(control_text_buf);
4557 str_formspec_escape(control_text);
4560 float ypos = simple_singleplayer_mode ? 0.7f : 0.1f;
4561 std::ostringstream os;
4563 os << FORMSPEC_VERSION_STRING << SIZE_TAG
4564 << "button_exit[4," << (ypos++) << ";3,0.5;btn_continue;"
4565 << strgettext("Continue") << "]";
4567 if (!simple_singleplayer_mode) {
4568 os << "button_exit[4," << (ypos++) << ";3,0.5;btn_change_password;"
4569 << strgettext("Change Password") << "]";
4571 os << "field[4.95,0;5,1.5;;" << strgettext("Game paused") << ";]";
4575 os << "button_exit[4," << (ypos++) << ";3,0.5;btn_sound;"
4576 << strgettext("Sound Volume") << "]";
4577 os << "button_exit[4," << (ypos++) << ";3,0.5;btn_key_config;"
4578 << strgettext("Change Keys") << "]";
4580 os << "button_exit[4," << (ypos++) << ";3,0.5;btn_exit_menu;"
4581 << strgettext("Exit to Menu") << "]";
4582 os << "button_exit[4," << (ypos++) << ";3,0.5;btn_exit_os;"
4583 << strgettext("Exit to OS") << "]"
4584 << "textarea[7.5,0.25;3.9,6.25;;" << control_text << ";]"
4585 << "textarea[0.4,0.25;3.9,6.25;;" << PROJECT_NAME_C " " VERSION_STRING "\n"
4587 << strgettext("Game info:") << "\n";
4588 const std::string &address = client->getAddressName();
4589 static const std::string mode = strgettext("- Mode: ");
4590 if (!simple_singleplayer_mode) {
4591 Address serverAddress = client->getServerAddress();
4592 if (address != "") {
4593 os << mode << strgettext("Remote server") << "\n"
4594 << strgettext("- Address: ") << address;
4596 os << mode << strgettext("Hosting server");
4598 os << "\n" << strgettext("- Port: ") << serverAddress.getPort() << "\n";
4600 os << mode << strgettext("Singleplayer") << "\n";
4602 if (simple_singleplayer_mode || address == "") {
4603 static const std::string on = strgettext("On");
4604 static const std::string off = strgettext("Off");
4605 const std::string &damage = g_settings->getBool("enable_damage") ? on : off;
4606 const std::string &creative = g_settings->getBool("creative_mode") ? on : off;
4607 const std::string &announced = g_settings->getBool("server_announce") ? on : off;
4608 os << strgettext("- Damage: ") << damage << "\n"
4609 << strgettext("- Creative Mode: ") << creative << "\n";
4610 if (!simple_singleplayer_mode) {
4611 const std::string &pvp = g_settings->getBool("enable_pvp") ? on : off;
4612 os << strgettext("- PvP: ") << pvp << "\n"
4613 << strgettext("- Public: ") << announced << "\n";
4614 std::string server_name = g_settings->get("server_name");
4615 str_formspec_escape(server_name);
4616 if (announced == on && server_name != "")
4617 os << strgettext("- Server Name: ") << server_name;
4624 /* Note: FormspecFormSource and LocalFormspecHandler *
4625 * are deleted by guiFormSpecMenu */
4626 FormspecFormSource *fs_src = new FormspecFormSource(os.str());
4627 LocalFormspecHandler *txt_dst = new LocalFormspecHandler("MT_PAUSE_MENU");
4629 create_formspec_menu(¤t_formspec, client, device, &input->joystick, fs_src, txt_dst);
4630 current_formspec->setFocus("btn_continue");
4631 current_formspec->doPause = true;
4634 /****************************************************************************/
4635 /****************************************************************************
4636 extern function for launching the game
4637 ****************************************************************************/
4638 /****************************************************************************/
4640 void the_game(bool *kill,
4642 InputHandler *input,
4643 IrrlichtDevice *device,
4645 const std::string &map_dir,
4646 const std::string &playername,
4647 const std::string &password,
4648 const std::string &address, // If empty local server is created
4651 std::string &error_message,
4652 ChatBackend &chat_backend,
4653 bool *reconnect_requested,
4654 const SubgameSpec &gamespec, // Used for local game
4655 bool simple_singleplayer_mode)
4659 /* Make a copy of the server address because if a local singleplayer server
4660 * is created then this is updated and we don't want to change the value
4661 * passed to us by the calling function
4663 std::string server_address = address;
4667 if (game.startup(kill, random_input, input, device, map_dir,
4668 playername, password, &server_address, port, error_message,
4669 reconnect_requested, &chat_backend, gamespec,
4670 simple_singleplayer_mode)) {
4675 } catch (SerializationError &e) {
4676 error_message = std::string("A serialization error occurred:\n")
4677 + e.what() + "\n\nThe server is probably "
4678 " running a different version of " PROJECT_NAME_C ".";
4679 errorstream << error_message << std::endl;
4680 } catch (ServerError &e) {
4681 error_message = e.what();
4682 errorstream << "ServerError: " << error_message << std::endl;
4683 } catch (ModError &e) {
4684 error_message = e.what() + strgettext("\nCheck debug.txt for details.");
4685 errorstream << "ModError: " << error_message << std::endl;