3 Copyright (C) 2010-2013 celeron55, Perttu Ahola <celeron55@gmail.com>
5 This program is free software; you can redistribute it and/or modify
6 it under the terms of the GNU Lesser General Public License as published by
7 the Free Software Foundation; either version 2.1 of the License, or
8 (at your option) any later version.
10 This program is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 GNU Lesser General Public License for more details.
15 You should have received a copy of the GNU Lesser General Public License along
16 with this program; if not, write to the Free Software Foundation, Inc.,
17 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
25 #include "client/tile.h" // For TextureSource
26 #include "client/keys.h"
27 #include "client/joystick_controller.h"
28 #include "clientmap.h"
31 #include "content_cao.h"
32 #include "drawscene.h"
33 #include "event_manager.h"
34 #include "fontengine.h"
39 #include "guiChatConsole.h"
40 #include "guiFormSpecMenu.h"
41 #include "guiKeyChangeMenu.h"
42 #include "guiPasswordChange.h"
43 #include "guiVolumeChange.h"
44 #include "mainmenumanager.h"
46 #include "nodedef.h" // Needed for determining pointing to nodes
47 #include "nodemetadata.h"
48 #include "particles.h"
50 #include "quicktune_shortcutter.h"
53 #include "shader.h" // For ShaderSource
57 #include "util/directiontables.h"
58 #include "util/pointedthing.h"
59 #include "irrlicht_changes/static_text.h"
62 #include "mapblock_mesh.h"
63 #include "script/clientscripting.h"
68 #include "sound_openal.h"
71 #ifdef HAVE_TOUCHSCREENGUI
72 #include "touchscreengui.h"
75 extern Settings *g_settings;
76 extern Profiler *g_profiler;
82 struct TextDestNodeMetadata : public TextDest {
83 TextDestNodeMetadata(v3s16 p, Client *client)
88 // This is deprecated I guess? -celeron55
89 void gotText(std::wstring text)
91 std::string ntext = wide_to_utf8(text);
92 infostream << "Submitting 'text' field of node at (" << m_p.X << ","
93 << m_p.Y << "," << m_p.Z << "): " << ntext << std::endl;
95 fields["text"] = ntext;
96 m_client->sendNodemetaFields(m_p, "", fields);
98 void gotText(const StringMap &fields)
100 m_client->sendNodemetaFields(m_p, "", fields);
107 struct TextDestPlayerInventory : public TextDest {
108 TextDestPlayerInventory(Client *client)
113 TextDestPlayerInventory(Client *client, std::string formname)
116 m_formname = formname;
118 void gotText(const StringMap &fields)
120 m_client->sendInventoryFields(m_formname, fields);
126 struct LocalFormspecHandler : public TextDest {
127 LocalFormspecHandler();
129 LocalFormspecHandler(std::string formname) :
132 m_formname = formname;
135 LocalFormspecHandler(std::string formname, Client *client) :
138 m_formname = formname;
141 void gotText(std::wstring message)
143 errorstream << "LocalFormspecHandler::gotText old style message received" << std::endl;
146 void gotText(const StringMap &fields)
148 if (m_formname == "MT_PAUSE_MENU") {
149 if (fields.find("btn_sound") != fields.end()) {
150 g_gamecallback->changeVolume();
154 if (fields.find("btn_key_config") != fields.end()) {
155 g_gamecallback->keyConfig();
159 if (fields.find("btn_exit_menu") != fields.end()) {
160 g_gamecallback->disconnect();
164 if (fields.find("btn_exit_os") != fields.end()) {
165 g_gamecallback->exitToOS();
169 if (fields.find("btn_change_password") != fields.end()) {
170 g_gamecallback->changePassword();
174 if (fields.find("quit") != fields.end()) {
178 if (fields.find("btn_continue") != fields.end()) {
183 // Don't disable this part when modding is disabled, it's used in builtin
184 m_client->getScript()->on_formspec_input(m_formname, fields);
190 /* Form update callback */
192 class NodeMetadataFormSource: public IFormSource
195 NodeMetadataFormSource(ClientMap *map, v3s16 p):
200 std::string getForm()
202 NodeMetadata *meta = m_map->getNodeMetadata(m_p);
207 return meta->getString("formspec");
209 std::string resolveText(std::string str)
211 NodeMetadata *meta = m_map->getNodeMetadata(m_p);
216 return meta->resolveString(str);
223 class PlayerInventoryFormSource: public IFormSource
226 PlayerInventoryFormSource(Client *client):
230 std::string getForm()
232 LocalPlayer *player = m_client->getEnv().getLocalPlayer();
233 return player->inventory_formspec;
239 /* Profiler display */
241 void update_profiler_gui(gui::IGUIStaticText *guitext_profiler, FontEngine *fe,
242 u32 show_profiler, u32 show_profiler_max, s32 screen_height)
244 if (show_profiler == 0) {
245 guitext_profiler->setVisible(false);
248 std::ostringstream os(std::ios_base::binary);
249 g_profiler->printPage(os, show_profiler, show_profiler_max);
250 std::wstring text = utf8_to_wide(os.str());
251 setStaticText(guitext_profiler, text.c_str());
252 guitext_profiler->setVisible(true);
254 s32 w = fe->getTextWidth(text.c_str());
259 unsigned text_height = fe->getTextHeight();
261 core::position2di upper_left, lower_right;
264 upper_left.Y = (text_height + 5) * 2;
265 lower_right.X = 12 + w;
266 lower_right.Y = upper_left.Y + (text_height + 1) * MAX_PROFILER_TEXT_ROWS;
268 if (lower_right.Y > screen_height * 2 / 3)
269 lower_right.Y = screen_height * 2 / 3;
271 core::rect<s32> rect(upper_left, lower_right);
273 guitext_profiler->setRelativePosition(rect);
274 guitext_profiler->setVisible(true);
282 Profiler::GraphValues values;
288 Meta(float initial = 0,
289 video::SColor color = video::SColor(255, 255, 255, 255)):
295 std::deque<Piece> m_log;
303 void put(const Profiler::GraphValues &values)
306 piece.values = values;
307 m_log.push_back(piece);
309 while (m_log.size() > m_log_max_size)
310 m_log.erase(m_log.begin());
313 void draw(s32 x_left, s32 y_bottom, video::IVideoDriver *driver,
314 gui::IGUIFont *font) const
316 // Do *not* use UNORDERED_MAP here as the order needs
317 // to be the same for each call to prevent flickering
318 std::map<std::string, Meta> m_meta;
320 for (std::deque<Piece>::const_iterator k = m_log.begin();
321 k != m_log.end(); ++k) {
322 const Piece &piece = *k;
324 for (Profiler::GraphValues::const_iterator i = piece.values.begin();
325 i != piece.values.end(); ++i) {
326 const std::string &id = i->first;
327 const float &value = i->second;
328 std::map<std::string, Meta>::iterator j = m_meta.find(id);
330 if (j == m_meta.end()) {
331 m_meta[id] = Meta(value);
335 if (value < j->second.min)
336 j->second.min = value;
338 if (value > j->second.max)
339 j->second.max = value;
344 static const video::SColor usable_colors[] = {
345 video::SColor(255, 255, 100, 100),
346 video::SColor(255, 90, 225, 90),
347 video::SColor(255, 100, 100, 255),
348 video::SColor(255, 255, 150, 50),
349 video::SColor(255, 220, 220, 100)
351 static const u32 usable_colors_count =
352 sizeof(usable_colors) / sizeof(*usable_colors);
353 u32 next_color_i = 0;
355 for (std::map<std::string, Meta>::iterator i = m_meta.begin();
356 i != m_meta.end(); ++i) {
357 Meta &meta = i->second;
358 video::SColor color(255, 200, 200, 200);
360 if (next_color_i < usable_colors_count)
361 color = usable_colors[next_color_i++];
367 s32 textx = x_left + m_log_max_size + 15;
368 s32 textx2 = textx + 200 - 15;
371 for (std::map<std::string, Meta>::const_iterator i = m_meta.begin();
372 i != m_meta.end(); ++i) {
373 const std::string &id = i->first;
374 const Meta &meta = i->second;
376 s32 y = y_bottom - meta_i * 50;
377 float show_min = meta.min;
378 float show_max = meta.max;
380 if (show_min >= -0.0001 && show_max >= -0.0001) {
381 if (show_min <= show_max * 0.5)
387 snprintf(buf, 10, "%.3g", show_max);
388 font->draw(utf8_to_wide(buf).c_str(),
389 core::rect<s32>(textx, y - graphh,
390 textx2, y - graphh + texth),
392 snprintf(buf, 10, "%.3g", show_min);
393 font->draw(utf8_to_wide(buf).c_str(),
394 core::rect<s32>(textx, y - texth,
397 font->draw(utf8_to_wide(id).c_str(),
398 core::rect<s32>(textx, y - graphh / 2 - texth / 2,
399 textx2, y - graphh / 2 + texth / 2),
402 s32 graph1h = graphh;
403 bool relativegraph = (show_min != 0 && show_min != show_max);
404 float lastscaledvalue = 0.0;
405 bool lastscaledvalue_exists = false;
407 for (std::deque<Piece>::const_iterator j = m_log.begin();
408 j != m_log.end(); ++j) {
409 const Piece &piece = *j;
411 bool value_exists = false;
412 Profiler::GraphValues::const_iterator k =
413 piece.values.find(id);
415 if (k != piece.values.end()) {
422 lastscaledvalue_exists = false;
426 float scaledvalue = 1.0;
428 if (show_max != show_min)
429 scaledvalue = (value - show_min) / (show_max - show_min);
431 if (scaledvalue == 1.0 && value == 0) {
433 lastscaledvalue_exists = false;
438 if (lastscaledvalue_exists) {
439 s32 ivalue1 = lastscaledvalue * graph1h;
440 s32 ivalue2 = scaledvalue * graph1h;
441 driver->draw2DLine(v2s32(x - 1, graph1y - ivalue1),
442 v2s32(x, graph1y - ivalue2), meta.color);
445 lastscaledvalue = scaledvalue;
446 lastscaledvalue_exists = true;
448 s32 ivalue = scaledvalue * graph1h;
449 driver->draw2DLine(v2s32(x, graph1y),
450 v2s32(x, graph1y - ivalue), meta.color);
461 class NodeDugEvent: public MtEvent
467 NodeDugEvent(v3s16 p, MapNode n):
471 const char *getType() const
479 ISoundManager *m_sound;
480 INodeDefManager *m_ndef;
482 float m_player_step_timer;
484 SimpleSoundSpec m_player_step_sound;
485 SimpleSoundSpec m_player_leftpunch_sound;
486 SimpleSoundSpec m_player_rightpunch_sound;
488 SoundMaker(ISoundManager *sound, INodeDefManager *ndef):
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 m_sound->playSound(m_player_step_sound, false);
503 static void viewBobbingStep(MtEvent *e, void *data)
505 SoundMaker *sm = (SoundMaker *)data;
506 sm->playPlayerStep();
509 static void playerRegainGround(MtEvent *e, void *data)
511 SoundMaker *sm = (SoundMaker *)data;
512 sm->playPlayerStep();
515 static void playerJump(MtEvent *e, void *data)
517 //SoundMaker *sm = (SoundMaker*)data;
520 static void cameraPunchLeft(MtEvent *e, void *data)
522 SoundMaker *sm = (SoundMaker *)data;
523 sm->m_sound->playSound(sm->m_player_leftpunch_sound, false);
526 static void cameraPunchRight(MtEvent *e, void *data)
528 SoundMaker *sm = (SoundMaker *)data;
529 sm->m_sound->playSound(sm->m_player_rightpunch_sound, false);
532 static void nodeDug(MtEvent *e, void *data)
534 SoundMaker *sm = (SoundMaker *)data;
535 NodeDugEvent *nde = (NodeDugEvent *)e;
536 sm->m_sound->playSound(sm->m_ndef->get(nde->n).sound_dug, false);
539 static void playerDamage(MtEvent *e, void *data)
541 SoundMaker *sm = (SoundMaker *)data;
542 sm->m_sound->playSound(SimpleSoundSpec("player_damage", 0.5), false);
545 static void playerFallingDamage(MtEvent *e, void *data)
547 SoundMaker *sm = (SoundMaker *)data;
548 sm->m_sound->playSound(SimpleSoundSpec("player_falling_damage", 0.5), false);
551 void registerReceiver(MtEventManager *mgr)
553 mgr->reg("ViewBobbingStep", SoundMaker::viewBobbingStep, this);
554 mgr->reg("PlayerRegainGround", SoundMaker::playerRegainGround, this);
555 mgr->reg("PlayerJump", SoundMaker::playerJump, this);
556 mgr->reg("CameraPunchLeft", SoundMaker::cameraPunchLeft, this);
557 mgr->reg("CameraPunchRight", SoundMaker::cameraPunchRight, this);
558 mgr->reg("NodeDug", SoundMaker::nodeDug, this);
559 mgr->reg("PlayerDamage", SoundMaker::playerDamage, this);
560 mgr->reg("PlayerFallingDamage", SoundMaker::playerFallingDamage, this);
563 void step(float dtime)
565 m_player_step_timer -= dtime;
569 // Locally stored sounds don't need to be preloaded because of this
570 class GameOnDemandSoundFetcher: public OnDemandSoundFetcher
572 std::set<std::string> m_fetched;
574 void fetchSounds(const std::string &name,
575 std::set<std::string> &dst_paths,
576 std::set<std::string> &dst_datas)
578 if (m_fetched.count(name))
581 m_fetched.insert(name);
582 std::string base = porting::path_share + DIR_DELIM + "sounds";
583 dst_paths.insert(base + DIR_DELIM + name + ".ogg");
584 dst_paths.insert(base + DIR_DELIM + name + ".0.ogg");
585 dst_paths.insert(base + DIR_DELIM + name + ".1.ogg");
586 dst_paths.insert(base + DIR_DELIM + name + ".2.ogg");
587 dst_paths.insert(base + DIR_DELIM + name + ".3.ogg");
588 dst_paths.insert(base + DIR_DELIM + name + ".4.ogg");
589 dst_paths.insert(base + DIR_DELIM + name + ".5.ogg");
590 dst_paths.insert(base + DIR_DELIM + name + ".6.ogg");
591 dst_paths.insert(base + DIR_DELIM + name + ".7.ogg");
592 dst_paths.insert(base + DIR_DELIM + name + ".8.ogg");
593 dst_paths.insert(base + DIR_DELIM + name + ".9.ogg");
598 // before 1.8 there isn't a "integer interface", only float
599 #if (IRRLICHT_VERSION_MAJOR == 1 && IRRLICHT_VERSION_MINOR < 8)
600 typedef f32 SamplerLayer_t;
602 typedef s32 SamplerLayer_t;
606 class GameGlobalShaderConstantSetter : public IShaderConstantSetter
609 bool *m_force_fog_off;
612 CachedPixelShaderSetting<float, 4> m_sky_bg_color;
613 CachedPixelShaderSetting<float> m_fog_distance;
614 CachedVertexShaderSetting<float> m_animation_timer_vertex;
615 CachedPixelShaderSetting<float> m_animation_timer_pixel;
616 CachedPixelShaderSetting<float, 3> m_day_light;
617 CachedPixelShaderSetting<float, 3> m_eye_position_pixel;
618 CachedVertexShaderSetting<float, 3> m_eye_position_vertex;
619 CachedPixelShaderSetting<float, 3> m_minimap_yaw;
620 CachedPixelShaderSetting<SamplerLayer_t> m_base_texture;
621 CachedPixelShaderSetting<SamplerLayer_t> m_normal_texture;
622 CachedPixelShaderSetting<SamplerLayer_t> m_texture_flags;
626 void onSettingsChange(const std::string &name)
628 if (name == "enable_fog")
629 m_fog_enabled = g_settings->getBool("enable_fog");
632 static void settingsCallback(const std::string &name, void *userdata)
634 reinterpret_cast<GameGlobalShaderConstantSetter*>(userdata)->onSettingsChange(name);
637 void setSky(Sky *sky) { m_sky = sky; }
639 GameGlobalShaderConstantSetter(Sky *sky, bool *force_fog_off,
640 f32 *fog_range, Client *client) :
642 m_force_fog_off(force_fog_off),
643 m_fog_range(fog_range),
644 m_sky_bg_color("skyBgColor"),
645 m_fog_distance("fogDistance"),
646 m_animation_timer_vertex("animationTimer"),
647 m_animation_timer_pixel("animationTimer"),
648 m_day_light("dayLight"),
649 m_eye_position_pixel("eyePosition"),
650 m_eye_position_vertex("eyePosition"),
651 m_minimap_yaw("yawVec"),
652 m_base_texture("baseTexture"),
653 m_normal_texture("normalTexture"),
654 m_texture_flags("textureFlags"),
657 g_settings->registerChangedCallback("enable_fog", settingsCallback, this);
658 m_fog_enabled = g_settings->getBool("enable_fog");
661 ~GameGlobalShaderConstantSetter()
663 g_settings->deregisterChangedCallback("enable_fog", settingsCallback, this);
666 virtual void onSetConstants(video::IMaterialRendererServices *services,
673 video::SColor bgcolor = m_sky->getBgColor();
674 video::SColorf bgcolorf(bgcolor);
675 float bgcolorfa[4] = {
681 m_sky_bg_color.set(bgcolorfa, services);
684 float fog_distance = 10000 * BS;
686 if (m_fog_enabled && !*m_force_fog_off)
687 fog_distance = *m_fog_range;
689 m_fog_distance.set(&fog_distance, services);
691 u32 daynight_ratio = (float)m_client->getEnv().getDayNightRatio();
692 video::SColorf sunlight;
693 get_sunlight_color(&sunlight, daynight_ratio);
698 m_day_light.set(dnc, services);
700 u32 animation_timer = porting::getTimeMs() % 100000;
701 float animation_timer_f = (float)animation_timer / 100000.f;
702 m_animation_timer_vertex.set(&animation_timer_f, services);
703 m_animation_timer_pixel.set(&animation_timer_f, services);
705 float eye_position_array[3];
706 v3f epos = m_client->getEnv().getLocalPlayer()->getEyePosition();
707 #if (IRRLICHT_VERSION_MAJOR == 1 && IRRLICHT_VERSION_MINOR < 8)
708 eye_position_array[0] = epos.X;
709 eye_position_array[1] = epos.Y;
710 eye_position_array[2] = epos.Z;
712 epos.getAs3Values(eye_position_array);
714 m_eye_position_pixel.set(eye_position_array, services);
715 m_eye_position_vertex.set(eye_position_array, services);
717 float minimap_yaw_array[3];
718 v3f minimap_yaw = m_client->getMapper()->getYawVec();
719 #if (IRRLICHT_VERSION_MAJOR == 1 && IRRLICHT_VERSION_MINOR < 8)
720 minimap_yaw_array[0] = minimap_yaw.X;
721 minimap_yaw_array[1] = minimap_yaw.Y;
722 minimap_yaw_array[2] = minimap_yaw.Z;
724 minimap_yaw.getAs3Values(minimap_yaw_array);
726 m_minimap_yaw.set(minimap_yaw_array, services);
728 SamplerLayer_t base_tex = 0,
731 m_base_texture.set(&base_tex, services);
732 m_normal_texture.set(&normal_tex, services);
733 m_texture_flags.set(&flags_tex, services);
738 class GameGlobalShaderConstantSetterFactory : public IShaderConstantSetterFactory
741 bool *m_force_fog_off;
744 std::vector<GameGlobalShaderConstantSetter *> created_nosky;
746 GameGlobalShaderConstantSetterFactory(bool *force_fog_off,
747 f32 *fog_range, Client *client) :
749 m_force_fog_off(force_fog_off),
750 m_fog_range(fog_range),
754 void setSky(Sky *sky) {
756 for (size_t i = 0; i < created_nosky.size(); ++i) {
757 created_nosky[i]->setSky(m_sky);
759 created_nosky.clear();
762 virtual IShaderConstantSetter* create()
764 GameGlobalShaderConstantSetter *scs = new GameGlobalShaderConstantSetter(
765 m_sky, m_force_fog_off, m_fog_range, m_client);
767 created_nosky.push_back(scs);
773 bool nodePlacementPrediction(Client &client,
774 const ItemDefinition &playeritem_def, v3s16 nodepos, v3s16 neighbourpos)
776 std::string prediction = playeritem_def.node_placement_prediction;
777 INodeDefManager *nodedef = client.ndef();
778 ClientMap &map = client.getEnv().getClientMap();
780 bool is_valid_position;
782 node = map.getNodeNoEx(nodepos, &is_valid_position);
783 if (!is_valid_position)
786 if (prediction != "" && !nodedef->get(node).rightclickable) {
787 verbosestream << "Node placement prediction for "
788 << playeritem_def.name << " is "
789 << prediction << std::endl;
790 v3s16 p = neighbourpos;
792 // Place inside node itself if buildable_to
793 MapNode n_under = map.getNodeNoEx(nodepos, &is_valid_position);
794 if (is_valid_position)
796 if (nodedef->get(n_under).buildable_to)
799 node = map.getNodeNoEx(p, &is_valid_position);
800 if (is_valid_position &&!nodedef->get(node).buildable_to)
805 // Find id of predicted node
807 bool found = nodedef->getId(prediction, id);
810 errorstream << "Node placement prediction failed for "
811 << playeritem_def.name << " (places "
813 << ") - Name not known" << std::endl;
817 // Predict param2 for facedir and wallmounted nodes
820 if (nodedef->get(id).param_type_2 == CPT2_WALLMOUNTED ||
821 nodedef->get(id).param_type_2 == CPT2_COLORED_WALLMOUNTED) {
822 v3s16 dir = nodepos - neighbourpos;
824 if (abs(dir.Y) > MYMAX(abs(dir.X), abs(dir.Z))) {
825 param2 = dir.Y < 0 ? 1 : 0;
826 } else if (abs(dir.X) > abs(dir.Z)) {
827 param2 = dir.X < 0 ? 3 : 2;
829 param2 = dir.Z < 0 ? 5 : 4;
833 if (nodedef->get(id).param_type_2 == CPT2_FACEDIR ||
834 nodedef->get(id).param_type_2 == CPT2_COLORED_FACEDIR) {
835 v3s16 dir = nodepos - floatToInt(client.getEnv().getLocalPlayer()->getPosition(), BS);
837 if (abs(dir.X) > abs(dir.Z)) {
838 param2 = dir.X < 0 ? 3 : 1;
840 param2 = dir.Z < 0 ? 2 : 0;
846 //Check attachment if node is in group attached_node
847 if (((ItemGroupList) nodedef->get(id).groups)["attached_node"] != 0) {
848 static v3s16 wallmounted_dirs[8] = {
858 if (nodedef->get(id).param_type_2 == CPT2_WALLMOUNTED ||
859 nodedef->get(id).param_type_2 == CPT2_COLORED_WALLMOUNTED)
860 pp = p + wallmounted_dirs[param2];
862 pp = p + v3s16(0, -1, 0);
864 if (!nodedef->get(map.getNodeNoEx(pp)).walkable)
868 // Add node to client map
869 MapNode n(id, 0, param2);
872 LocalPlayer *player = client.getEnv().getLocalPlayer();
874 // Dont place node when player would be inside new node
875 // NOTE: This is to be eventually implemented by a mod as client-side Lua
876 if (!nodedef->get(n).walkable ||
877 g_settings->getBool("enable_build_where_you_stand") ||
878 (client.checkPrivilege("noclip") && g_settings->getBool("noclip")) ||
879 (nodedef->get(n).walkable &&
880 neighbourpos != player->getStandingNodePos() + v3s16(0, 1, 0) &&
881 neighbourpos != player->getStandingNodePos() + v3s16(0, 2, 0))) {
883 // This triggers the required mesh update too
884 client.addNode(p, n);
887 } catch (InvalidPositionException &e) {
888 errorstream << "Node placement prediction failed for "
889 << playeritem_def.name << " (places "
891 << ") - Position not loaded" << std::endl;
898 static inline void create_formspec_menu(GUIFormSpecMenu **cur_formspec,
899 Client *client, IrrlichtDevice *device, JoystickController *joystick,
900 IFormSource *fs_src, TextDest *txt_dest)
903 if (*cur_formspec == 0) {
904 *cur_formspec = new GUIFormSpecMenu(device, joystick,
905 guiroot, -1, &g_menumgr, client, client->getTextureSource(),
907 (*cur_formspec)->doPause = false;
910 Caution: do not call (*cur_formspec)->drop() here --
911 the reference might outlive the menu, so we will
912 periodically check if *cur_formspec is the only
913 remaining reference (i.e. the menu was removed)
914 and delete it in that case.
918 (*cur_formspec)->setFormSource(fs_src);
919 (*cur_formspec)->setTextDest(txt_dest);
925 #define SIZE_TAG "size[11,5.5]"
927 #define SIZE_TAG "size[11,5.5,true]" // Fixed size on desktop
930 /******************************************************************************/
931 static void show_pause_menu(GUIFormSpecMenu **cur_formspec,
933 IWritableTextureSource *tsrc, IrrlichtDevice *device,
934 JoystickController *joystick, bool singleplayermode)
937 std::string control_text = strgettext("Default Controls:\n"
939 "- single tap: button activate\n"
940 "- double tap: place/use\n"
941 "- slide finger: look around\n"
942 "Menu/Inventory visible:\n"
943 "- double tap (outside):\n"
945 "- touch stack, touch slot:\n"
947 "- touch&drag, tap 2nd finger\n"
948 " --> place single item to slot\n"
951 std::string control_text = strgettext("Default Controls:\n"
953 "- Space: jump/climb\n"
954 "- Shift: sneak/go down\n"
957 "- Mouse: turn/look\n"
958 "- Mouse left: dig/punch\n"
959 "- Mouse right: place/use\n"
960 "- Mouse wheel: select item\n"
965 float ypos = singleplayermode ? 0.5 : 0.1;
966 std::ostringstream os;
968 os << FORMSPEC_VERSION_STRING << SIZE_TAG
969 << "button_exit[4," << (ypos++) << ";3,0.5;btn_continue;"
970 << strgettext("Continue") << "]";
972 if (!singleplayermode) {
973 os << "button_exit[4," << (ypos++) << ";3,0.5;btn_change_password;"
974 << strgettext("Change Password") << "]";
978 os << "button_exit[4," << (ypos++) << ";3,0.5;btn_sound;"
979 << strgettext("Sound Volume") << "]";
980 os << "button_exit[4," << (ypos++) << ";3,0.5;btn_key_config;"
981 << strgettext("Change Keys") << "]";
983 os << "button_exit[4," << (ypos++) << ";3,0.5;btn_exit_menu;"
984 << strgettext("Exit to Menu") << "]";
985 os << "button_exit[4," << (ypos++) << ";3,0.5;btn_exit_os;"
986 << strgettext("Exit to OS") << "]"
987 << "textarea[7.5,0.25;3.9,6.25;;" << control_text << ";]"
988 << "textarea[0.4,0.25;3.5,6;;" << PROJECT_NAME_C "\n"
989 << g_build_info << "\n"
990 << "path_user = " << wrap_rows(porting::path_user, 20)
994 /* Note: FormspecFormSource and LocalFormspecHandler *
995 * are deleted by guiFormSpecMenu */
996 FormspecFormSource *fs_src = new FormspecFormSource(os.str());
997 LocalFormspecHandler *txt_dst = new LocalFormspecHandler("MT_PAUSE_MENU");
999 create_formspec_menu(cur_formspec, client, device, joystick, fs_src, txt_dst);
1000 std::string con("btn_continue");
1001 (*cur_formspec)->setFocus(con);
1002 (*cur_formspec)->doPause = true;
1005 /******************************************************************************/
1006 static void updateChat(Client &client, f32 dtime, bool show_debug,
1007 const v2u32 &screensize, bool show_chat, u32 show_profiler,
1008 ChatBackend &chat_backend, gui::IGUIStaticText *guitext_chat)
1010 // Add chat log output for errors to be shown in chat
1011 static LogOutputBuffer chat_log_error_buf(g_logger, LL_ERROR);
1013 // Get new messages from error log buffer
1014 while (!chat_log_error_buf.empty()) {
1015 std::wstring error_message = utf8_to_wide(chat_log_error_buf.get());
1016 if (!g_settings->getBool("disable_escape_sequences")) {
1017 error_message = L"\x1b(c@red)" + error_message + L"\x1b(c@white)";
1019 chat_backend.addMessage(L"", error_message);
1022 // Get new messages from client
1023 std::wstring message;
1025 while (client.getChatMessage(message)) {
1026 chat_backend.addUnparsedMessage(message);
1029 // Remove old messages
1030 chat_backend.step(dtime);
1032 // Display all messages in a static text element
1033 unsigned int recent_chat_count = chat_backend.getRecentBuffer().getLineCount();
1034 EnrichedString recent_chat = chat_backend.getRecentChat();
1035 unsigned int line_height = g_fontengine->getLineHeight();
1037 setStaticText(guitext_chat, recent_chat);
1039 // Update gui element size and position
1043 chat_y += 2 * line_height;
1045 // first pass to calculate height of text to be set
1046 s32 width = std::min(g_fontengine->getTextWidth(recent_chat.c_str()) + 10,
1047 porting::getWindowSize().X - 20);
1048 core::rect<s32> rect(10, chat_y, width, chat_y + porting::getWindowSize().Y);
1049 guitext_chat->setRelativePosition(rect);
1051 //now use real height of text and adjust rect according to this size
1052 rect = core::rect<s32>(10, chat_y, width,
1053 chat_y + guitext_chat->getTextHeight());
1056 guitext_chat->setRelativePosition(rect);
1057 // Don't show chat if disabled or empty or profiler is enabled
1058 guitext_chat->setVisible(
1059 show_chat && recent_chat_count != 0 && !show_profiler);
1063 /****************************************************************************
1064 Fast key cache for main game loop
1065 ****************************************************************************/
1067 /* This is faster than using getKeySetting with the tradeoff that functions
1068 * using it must make sure that it's initialised before using it and there is
1069 * no error handling (for example bounds checking). This is really intended for
1070 * use only in the main running loop of the client (the_game()) where the faster
1071 * (up to 10x faster) key lookup is an asset. Other parts of the codebase
1072 * (e.g. formspecs) should continue using getKeySetting().
1080 populate_nonchanging();
1085 // Keys that are not settings dependent
1086 void populate_nonchanging();
1088 KeyPress key[KeyType::INTERNAL_ENUM_COUNT];
1089 InputHandler *handler;
1092 void KeyCache::populate_nonchanging()
1094 key[KeyType::ESC] = EscapeKey;
1097 void KeyCache::populate()
1099 key[KeyType::FORWARD] = getKeySetting("keymap_forward");
1100 key[KeyType::BACKWARD] = getKeySetting("keymap_backward");
1101 key[KeyType::LEFT] = getKeySetting("keymap_left");
1102 key[KeyType::RIGHT] = getKeySetting("keymap_right");
1103 key[KeyType::JUMP] = getKeySetting("keymap_jump");
1104 key[KeyType::SPECIAL1] = getKeySetting("keymap_special1");
1105 key[KeyType::SNEAK] = getKeySetting("keymap_sneak");
1107 key[KeyType::AUTORUN] = getKeySetting("keymap_autorun");
1109 key[KeyType::DROP] = getKeySetting("keymap_drop");
1110 key[KeyType::INVENTORY] = getKeySetting("keymap_inventory");
1111 key[KeyType::CHAT] = getKeySetting("keymap_chat");
1112 key[KeyType::CMD] = getKeySetting("keymap_cmd");
1113 key[KeyType::CONSOLE] = getKeySetting("keymap_console");
1114 key[KeyType::MINIMAP] = getKeySetting("keymap_minimap");
1115 key[KeyType::FREEMOVE] = getKeySetting("keymap_freemove");
1116 key[KeyType::FASTMOVE] = getKeySetting("keymap_fastmove");
1117 key[KeyType::NOCLIP] = getKeySetting("keymap_noclip");
1118 key[KeyType::CINEMATIC] = getKeySetting("keymap_cinematic");
1119 key[KeyType::SCREENSHOT] = getKeySetting("keymap_screenshot");
1120 key[KeyType::TOGGLE_HUD] = getKeySetting("keymap_toggle_hud");
1121 key[KeyType::TOGGLE_CHAT] = getKeySetting("keymap_toggle_chat");
1122 key[KeyType::TOGGLE_FORCE_FOG_OFF]
1123 = getKeySetting("keymap_toggle_force_fog_off");
1124 key[KeyType::TOGGLE_UPDATE_CAMERA]
1125 = getKeySetting("keymap_toggle_update_camera");
1126 key[KeyType::TOGGLE_DEBUG]
1127 = getKeySetting("keymap_toggle_debug");
1128 key[KeyType::TOGGLE_PROFILER]
1129 = getKeySetting("keymap_toggle_profiler");
1130 key[KeyType::CAMERA_MODE]
1131 = getKeySetting("keymap_camera_mode");
1132 key[KeyType::INCREASE_VIEWING_RANGE]
1133 = getKeySetting("keymap_increase_viewing_range_min");
1134 key[KeyType::DECREASE_VIEWING_RANGE]
1135 = getKeySetting("keymap_decrease_viewing_range_min");
1136 key[KeyType::RANGESELECT]
1137 = getKeySetting("keymap_rangeselect");
1138 key[KeyType::ZOOM] = getKeySetting("keymap_zoom");
1140 key[KeyType::QUICKTUNE_NEXT] = getKeySetting("keymap_quicktune_next");
1141 key[KeyType::QUICKTUNE_PREV] = getKeySetting("keymap_quicktune_prev");
1142 key[KeyType::QUICKTUNE_INC] = getKeySetting("keymap_quicktune_inc");
1143 key[KeyType::QUICKTUNE_DEC] = getKeySetting("keymap_quicktune_dec");
1145 key[KeyType::DEBUG_STACKS] = getKeySetting("keymap_print_debug_stacks");
1148 // First clear all keys, then re-add the ones we listen for
1149 handler->dontListenForKeys();
1150 for (size_t i = 0; i < KeyType::INTERNAL_ENUM_COUNT; i++) {
1151 handler->listenForKey(key[i]);
1153 handler->listenForKey(EscapeKey);
1154 handler->listenForKey(CancelKey);
1155 for (size_t i = 0; i < 10; i++) {
1156 handler->listenForKey(NumberKey[i]);
1162 /****************************************************************************
1164 ****************************************************************************/
1166 const float object_hit_delay = 0.2;
1169 u32 last_time, busy_time, sleep_time;
1173 /* The reason the following structs are not anonymous structs within the
1174 * class is that they are not used by the majority of member functions and
1175 * many functions that do require objects of thse types do not modify them
1176 * (so they can be passed as a const qualified parameter)
1178 struct CameraOrientation {
1179 f32 camera_yaw; // "right/left"
1180 f32 camera_pitch; // "up/down"
1183 struct GameRunData {
1186 PointedThing pointed_old;
1190 bool update_wielded_item_trigger;
1191 bool reset_jump_timer;
1192 float nodig_delay_timer;
1194 float dig_time_complete;
1195 float repeat_rightclick_timer;
1196 float object_hit_delay_timer;
1197 float time_from_last_punch;
1198 ClientActiveObject *selected_object;
1202 float update_draw_list_timer;
1203 float statustext_time;
1207 v3f update_draw_list_last_cam_dir;
1209 u32 profiler_current_page;
1210 u32 profiler_max_page; // Number of pages
1213 float time_of_day_smooth;
1217 f32 max, min, avg, counter, max_sample, min_sample, max_fraction;
1225 Jitter dtime_jitter, busy_time_jitter;
1228 /* Flags that can, or may, change during main game loop
1230 struct VolatileRunFlags {
1237 bool show_profiler_graph;
1238 bool disable_camera_update;
1239 bool first_loop_after_window_activation;
1240 bool camera_offset_changed;
1244 /****************************************************************************
1246 ****************************************************************************/
1248 /* This is not intended to be a public class. If a public class becomes
1249 * desirable then it may be better to create another 'wrapper' class that
1250 * hides most of the stuff in this class (nothing in this class is required
1251 * by any other file) but exposes the public methods/data only.
1258 bool startup(bool *kill,
1260 InputHandler *input,
1261 IrrlichtDevice *device,
1262 const std::string &map_dir,
1263 const std::string &playername,
1264 const std::string &password,
1265 // If address is "", local server is used and address is updated
1266 std::string *address,
1268 std::string &error_message,
1270 ChatBackend *chat_backend,
1271 const SubgameSpec &gamespec, // Used for local game
1272 bool simple_singleplayer_mode);
1279 void extendedResourceCleanup();
1281 // Basic initialisation
1282 bool init(const std::string &map_dir, std::string *address,
1284 const SubgameSpec &gamespec);
1286 bool createSingleplayerServer(const std::string map_dir,
1287 const SubgameSpec &gamespec, u16 port, std::string *address);
1290 bool createClient(const std::string &playername,
1291 const std::string &password, std::string *address, u16 port);
1294 // Client connection
1295 bool connectToServer(const std::string &playername,
1296 const std::string &password, std::string *address, u16 port,
1297 bool *connect_ok, bool *aborted);
1298 bool getServerContent(bool *aborted);
1302 void updateInteractTimers(GameRunData *runData, f32 dtime);
1303 bool checkConnection();
1304 bool handleCallbacks();
1305 void processQueues();
1306 void updateProfilers(const GameRunData &runData, const RunStats &stats,
1307 const FpsControl &draw_times, f32 dtime);
1308 void addProfilerGraphs(const RunStats &stats, const FpsControl &draw_times,
1310 void updateStats(RunStats *stats, const FpsControl &draw_times, f32 dtime);
1313 void processUserInput(VolatileRunFlags *flags, GameRunData *runData,
1315 void processKeyInput(VolatileRunFlags *flags,
1316 float *statustext_time,
1318 bool *reset_jump_timer,
1319 u32 *profiler_current_page,
1320 u32 profiler_max_page);
1321 void processItemSelection(u16 *new_playeritem);
1323 void dropSelectedItem();
1324 void openInventory();
1325 void openConsole(float scale, const wchar_t *line=NULL);
1326 void toggleFreeMove(float *statustext_time);
1327 void toggleFreeMoveAlt(float *statustext_time, float *jump_timer);
1328 void toggleFast(float *statustext_time);
1329 void toggleNoClip(float *statustext_time);
1330 void toggleCinematic(float *statustext_time);
1331 void toggleAutorun(float *statustext_time);
1333 void toggleChat(float *statustext_time, bool *flag);
1334 void toggleHud(float *statustext_time, bool *flag);
1335 void toggleMinimap(float *statustext_time, bool *flag, bool show_hud,
1336 bool shift_pressed);
1337 void toggleFog(float *statustext_time, bool *flag);
1338 void toggleDebug(float *statustext_time, bool *show_debug,
1339 bool *show_profiler_graph, bool *show_wireframe);
1340 void toggleUpdateCamera(float *statustext_time, bool *flag);
1341 void toggleProfiler(float *statustext_time, u32 *profiler_current_page,
1342 u32 profiler_max_page);
1344 void increaseViewRange(float *statustext_time);
1345 void decreaseViewRange(float *statustext_time);
1346 void toggleFullViewRange(float *statustext_time);
1348 void updateCameraDirection(CameraOrientation *cam, VolatileRunFlags *flags,
1350 void updateCameraOrientation(CameraOrientation *cam,
1351 const VolatileRunFlags &flags, float dtime);
1352 void updatePlayerControl(const CameraOrientation &cam);
1353 void step(f32 *dtime);
1354 void processClientEvents(CameraOrientation *cam, float *damage_flash);
1355 void updateCamera(VolatileRunFlags *flags, u32 busy_time, f32 dtime,
1356 float time_from_last_punch);
1357 void updateSound(f32 dtime);
1358 void processPlayerInteraction(GameRunData *runData, f32 dtime, bool show_hud,
1361 * Returns the object or node the player is pointing at.
1362 * Also updates the selected thing in the Hud.
1364 * @param[in] shootline the shootline, starting from
1365 * the camera position. This also gives the maximal distance
1367 * @param[in] liquids_pointable if false, liquids are ignored
1368 * @param[in] look_for_object if false, objects are ignored
1369 * @param[in] camera_offset offset of the camera
1370 * @param[out] selected_object the selected object or
1373 PointedThing updatePointedThing(
1374 const core::line3d<f32> &shootline, bool liquids_pointable,
1375 bool look_for_object, const v3s16 &camera_offset,
1376 ClientActiveObject *&selected_object);
1377 void handlePointingAtNothing(GameRunData *runData, const ItemStack &playerItem);
1378 void handlePointingAtNode(GameRunData *runData,
1379 const PointedThing &pointed, const ItemDefinition &playeritem_def,
1380 const ToolCapabilities &playeritem_toolcap, f32 dtime);
1381 void handlePointingAtObject(GameRunData *runData,
1382 const PointedThing &pointed, const ItemStack &playeritem,
1383 const v3f &player_position, bool show_debug);
1384 void handleDigging(GameRunData *runData, const PointedThing &pointed,
1385 const v3s16 &nodepos, const ToolCapabilities &playeritem_toolcap,
1387 void updateFrame(ProfilerGraph *graph, RunStats *stats, GameRunData *runData,
1388 f32 dtime, const VolatileRunFlags &flags, const CameraOrientation &cam);
1389 void updateGui(float *statustext_time, const RunStats &stats,
1390 const GameRunData& runData, f32 dtime, const VolatileRunFlags &flags,
1391 const CameraOrientation &cam);
1392 void updateProfilerGraphs(ProfilerGraph *graph);
1395 void limitFps(FpsControl *fps_timings, f32 *dtime);
1397 void showOverlayMessage(const wchar_t *msg, float dtime, int percent,
1398 bool draw_clouds = true);
1400 static void settingChangedCallback(const std::string &setting_name, void *data);
1401 void readSettings();
1403 inline bool getLeftClicked()
1405 return input->getLeftClicked() ||
1406 input->joystick.getWasKeyDown(KeyType::MOUSE_L);
1408 inline bool getRightClicked()
1410 return input->getRightClicked() ||
1411 input->joystick.getWasKeyDown(KeyType::MOUSE_R);
1413 inline bool isLeftPressed()
1415 return input->getLeftState() ||
1416 input->joystick.isKeyDown(KeyType::MOUSE_L);
1418 inline bool isRightPressed()
1420 return input->getRightState() ||
1421 input->joystick.isKeyDown(KeyType::MOUSE_R);
1423 inline bool getLeftReleased()
1425 return input->getLeftReleased() ||
1426 input->joystick.wasKeyReleased(KeyType::MOUSE_L);
1429 inline bool isKeyDown(GameKeyType k)
1431 return input->isKeyDown(keycache.key[k]) || input->joystick.isKeyDown(k);
1433 inline bool wasKeyDown(GameKeyType k)
1435 return input->wasKeyDown(keycache.key[k]) || input->joystick.wasKeyDown(k);
1439 void handleAndroidChatInput();
1443 InputHandler *input;
1448 IWritableTextureSource *texture_src;
1449 IWritableShaderSource *shader_src;
1451 // When created, these will be filled with data received from the server
1452 IWritableItemDefManager *itemdef_manager;
1453 IWritableNodeDefManager *nodedef_manager;
1455 GameOnDemandSoundFetcher soundfetcher; // useful when testing
1456 ISoundManager *sound;
1457 bool sound_is_dummy;
1458 SoundMaker *soundmaker;
1460 ChatBackend *chat_backend;
1462 GUIFormSpecMenu *current_formspec;
1463 //default: "". If other than "", empty show_formspec packets will only close the formspec when the formname matches
1464 std::string cur_formname;
1466 EventManager *eventmgr;
1467 QuicktuneShortcutter *quicktune;
1469 GUIChatConsole *gui_chat_console; // Free using ->Drop()
1470 MapDrawControl *draw_control;
1472 Clouds *clouds; // Free using ->Drop()
1473 Sky *sky; // Free using ->Drop()
1474 Inventory *local_inventory;
1478 GameRunData runData;
1479 VolatileRunFlags flags;
1482 This class does take ownership/responsibily for cleaning up etc of any of
1483 these items (e.g. device)
1485 IrrlichtDevice *device;
1486 video::IVideoDriver *driver;
1487 scene::ISceneManager *smgr;
1489 std::string *error_message;
1490 bool *reconnect_requested;
1491 scene::ISceneNode *skybox;
1494 bool simple_singleplayer_mode;
1497 /* Pre-calculated values
1499 int crack_animation_length;
1503 gui::IGUIStaticText *guitext; // First line of debug text
1504 gui::IGUIStaticText *guitext2; // Second line of debug text
1505 gui::IGUIStaticText *guitext_info; // At the middle of the screen
1506 gui::IGUIStaticText *guitext_status;
1507 gui::IGUIStaticText *guitext_chat; // Chat text
1508 gui::IGUIStaticText *guitext_profiler; // Profiler text
1510 std::wstring infotext;
1511 std::wstring statustext;
1515 IntervalLimiter profiler_interval;
1518 * TODO: Local caching of settings is not optimal and should at some stage
1519 * be updated to use a global settings object for getting thse values
1520 * (as opposed to the this local caching). This can be addressed in
1523 bool m_cache_doubletap_jump;
1524 bool m_cache_enable_clouds;
1525 bool m_cache_enable_joysticks;
1526 bool m_cache_enable_particles;
1527 bool m_cache_enable_fog;
1528 bool m_cache_enable_noclip;
1529 bool m_cache_enable_free_move;
1530 f32 m_cache_mouse_sensitivity;
1531 f32 m_cache_joystick_frustum_sensitivity;
1532 f32 m_repeat_right_click_time;
1533 f32 m_cache_cam_smoothing;
1534 f32 m_cache_fog_start;
1537 bool m_cache_hold_aux1;
1538 bool m_android_chat_open;
1547 itemdef_manager(NULL),
1548 nodedef_manager(NULL),
1550 sound_is_dummy(false),
1553 current_formspec(NULL),
1557 gui_chat_console(NULL),
1562 local_inventory(NULL),
1566 g_settings->registerChangedCallback("doubletap_jump",
1567 &settingChangedCallback, this);
1568 g_settings->registerChangedCallback("enable_clouds",
1569 &settingChangedCallback, this);
1570 g_settings->registerChangedCallback("doubletap_joysticks",
1571 &settingChangedCallback, this);
1572 g_settings->registerChangedCallback("enable_particles",
1573 &settingChangedCallback, this);
1574 g_settings->registerChangedCallback("enable_fog",
1575 &settingChangedCallback, this);
1576 g_settings->registerChangedCallback("mouse_sensitivity",
1577 &settingChangedCallback, this);
1578 g_settings->registerChangedCallback("joystick_frustum_sensitivity",
1579 &settingChangedCallback, this);
1580 g_settings->registerChangedCallback("repeat_rightclick_time",
1581 &settingChangedCallback, this);
1582 g_settings->registerChangedCallback("noclip",
1583 &settingChangedCallback, this);
1584 g_settings->registerChangedCallback("free_move",
1585 &settingChangedCallback, this);
1586 g_settings->registerChangedCallback("cinematic",
1587 &settingChangedCallback, this);
1588 g_settings->registerChangedCallback("cinematic_camera_smoothing",
1589 &settingChangedCallback, this);
1590 g_settings->registerChangedCallback("camera_smoothing",
1591 &settingChangedCallback, this);
1596 m_cache_hold_aux1 = false; // This is initialised properly later
1603 /****************************************************************************
1605 ****************************************************************************/
1611 if (!sound_is_dummy)
1614 delete server; // deleted first to stop all server threads
1617 delete local_inventory;
1623 delete nodedef_manager;
1624 delete itemdef_manager;
1625 delete draw_control;
1627 extendedResourceCleanup();
1629 g_settings->deregisterChangedCallback("doubletap_jump",
1630 &settingChangedCallback, this);
1631 g_settings->deregisterChangedCallback("enable_clouds",
1632 &settingChangedCallback, this);
1633 g_settings->deregisterChangedCallback("enable_particles",
1634 &settingChangedCallback, this);
1635 g_settings->deregisterChangedCallback("enable_fog",
1636 &settingChangedCallback, this);
1637 g_settings->deregisterChangedCallback("mouse_sensitivity",
1638 &settingChangedCallback, this);
1639 g_settings->deregisterChangedCallback("repeat_rightclick_time",
1640 &settingChangedCallback, this);
1641 g_settings->deregisterChangedCallback("noclip",
1642 &settingChangedCallback, this);
1643 g_settings->deregisterChangedCallback("free_move",
1644 &settingChangedCallback, this);
1645 g_settings->deregisterChangedCallback("cinematic",
1646 &settingChangedCallback, this);
1647 g_settings->deregisterChangedCallback("cinematic_camera_smoothing",
1648 &settingChangedCallback, this);
1649 g_settings->deregisterChangedCallback("camera_smoothing",
1650 &settingChangedCallback, this);
1653 bool Game::startup(bool *kill,
1655 InputHandler *input,
1656 IrrlichtDevice *device,
1657 const std::string &map_dir,
1658 const std::string &playername,
1659 const std::string &password,
1660 std::string *address, // can change if simple_singleplayer_mode
1662 std::string &error_message,
1664 ChatBackend *chat_backend,
1665 const SubgameSpec &gamespec,
1666 bool simple_singleplayer_mode)
1669 this->device = device;
1671 this->error_message = &error_message;
1672 this->reconnect_requested = reconnect;
1673 this->random_input = random_input;
1674 this->input = input;
1675 this->chat_backend = chat_backend;
1676 this->simple_singleplayer_mode = simple_singleplayer_mode;
1678 keycache.handler = input;
1679 keycache.populate();
1681 driver = device->getVideoDriver();
1682 smgr = device->getSceneManager();
1684 smgr->getParameters()->setAttribute(scene::OBJ_LOADER_IGNORE_MATERIAL_FILES, true);
1686 memset(&runData, 0, sizeof(runData));
1687 runData.time_from_last_punch = 10.0;
1688 runData.profiler_max_page = 3;
1689 runData.update_wielded_item_trigger = true;
1691 memset(&flags, 0, sizeof(flags));
1692 flags.show_chat = true;
1693 flags.show_hud = true;
1694 flags.show_debug = g_settings->getBool("show_debug");
1695 flags.invert_mouse = g_settings->getBool("invert_mouse");
1696 flags.first_loop_after_window_activation = true;
1698 if (!init(map_dir, address, port, gamespec))
1701 if (!createClient(playername, password, address, port))
1710 ProfilerGraph graph;
1711 RunStats stats = { 0 };
1712 CameraOrientation cam_view_target = { 0 };
1713 CameraOrientation cam_view = { 0 };
1714 FpsControl draw_times = { 0 };
1715 f32 dtime; // in seconds
1717 /* Clear the profiler */
1718 Profiler::GraphValues dummyvalues;
1719 g_profiler->graphGet(dummyvalues);
1721 draw_times.last_time = device->getTimer()->getTime();
1723 set_light_table(g_settings->getFloat("display_gamma"));
1726 m_cache_hold_aux1 = g_settings->getBool("fast_move")
1727 && client->checkPrivilege("fast");
1730 while (device->run()
1731 && !(*kill || g_gamecallback->shutdown_requested
1732 || (server && server->getShutdownRequested()))) {
1734 /* Must be called immediately after a device->run() call because it
1735 * uses device->getTimer()->getTime()
1737 limitFps(&draw_times, &dtime);
1739 updateStats(&stats, draw_times, dtime);
1740 updateInteractTimers(&runData, dtime);
1742 if (!checkConnection())
1744 if (!handleCallbacks())
1750 hud->resizeHotbar();
1752 updateProfilers(runData, stats, draw_times, dtime);
1753 processUserInput(&flags, &runData, dtime);
1754 // Update camera before player movement to avoid camera lag of one frame
1755 updateCameraDirection(&cam_view_target, &flags, dtime);
1756 cam_view.camera_yaw += (cam_view_target.camera_yaw -
1757 cam_view.camera_yaw) * m_cache_cam_smoothing;
1758 cam_view.camera_pitch += (cam_view_target.camera_pitch -
1759 cam_view.camera_pitch) * m_cache_cam_smoothing;
1760 updatePlayerControl(cam_view);
1762 processClientEvents(&cam_view_target, &runData.damage_flash);
1763 updateCamera(&flags, draw_times.busy_time, dtime,
1764 runData.time_from_last_punch);
1766 processPlayerInteraction(&runData, dtime, flags.show_hud,
1768 updateFrame(&graph, &stats, &runData, dtime, flags, cam_view);
1769 updateProfilerGraphs(&graph);
1771 // Update if minimap has been disabled by the server
1772 flags.show_minimap &= !client->isMinimapDisabledByServer();
1777 void Game::shutdown()
1779 #if IRRLICHT_VERSION_MAJOR == 1 && IRRLICHT_VERSION_MINOR <= 8
1780 if (g_settings->get("3d_mode") == "pageflip") {
1781 driver->setRenderTarget(irr::video::ERT_STEREO_BOTH_BUFFERS);
1785 showOverlayMessage(wgettext("Shutting down..."), 0, 0, false);
1790 if (gui_chat_console)
1791 gui_chat_console->drop();
1797 while (g_menumgr.menuCount() > 0) {
1798 g_menumgr.m_stack.front()->setVisible(false);
1799 g_menumgr.deletingMenu(g_menumgr.m_stack.front());
1802 if (current_formspec) {
1803 current_formspec->drop();
1804 current_formspec = NULL;
1807 chat_backend->addMessage(L"", L"# Disconnected.");
1808 chat_backend->addMessage(L"", L"");
1812 while (!client->isShutdown()) {
1813 assert(texture_src != NULL);
1814 assert(shader_src != NULL);
1815 texture_src->processQueue();
1816 shader_src->processQueue();
1823 /****************************************************************************/
1824 /****************************************************************************
1826 ****************************************************************************/
1827 /****************************************************************************/
1830 const std::string &map_dir,
1831 std::string *address,
1833 const SubgameSpec &gamespec)
1835 showOverlayMessage(wgettext("Loading..."), 0, 0);
1837 texture_src = createTextureSource(device);
1838 shader_src = createShaderSource(device);
1840 itemdef_manager = createItemDefManager();
1841 nodedef_manager = createNodeDefManager();
1843 eventmgr = new EventManager();
1844 quicktune = new QuicktuneShortcutter();
1846 if (!(texture_src && shader_src && itemdef_manager && nodedef_manager
1847 && eventmgr && quicktune))
1853 // Create a server if not connecting to an existing one
1854 if (*address == "") {
1855 if (!createSingleplayerServer(map_dir, gamespec, port, address))
1862 bool Game::initSound()
1865 if (g_settings->getBool("enable_sound")) {
1866 infostream << "Attempting to use OpenAL audio" << std::endl;
1867 sound = createOpenALSoundManager(&soundfetcher);
1869 infostream << "Failed to initialize OpenAL audio" << std::endl;
1871 infostream << "Sound disabled." << std::endl;
1875 infostream << "Using dummy audio." << std::endl;
1876 sound = &dummySoundManager;
1877 sound_is_dummy = true;
1880 soundmaker = new SoundMaker(sound, nodedef_manager);
1884 soundmaker->registerReceiver(eventmgr);
1889 bool Game::createSingleplayerServer(const std::string map_dir,
1890 const SubgameSpec &gamespec, u16 port, std::string *address)
1892 showOverlayMessage(wgettext("Creating server..."), 0, 5);
1894 std::string bind_str = g_settings->get("bind_address");
1895 Address bind_addr(0, 0, 0, 0, port);
1897 if (g_settings->getBool("ipv6_server")) {
1898 bind_addr.setAddress((IPv6AddressBytes *) NULL);
1902 bind_addr.Resolve(bind_str.c_str());
1903 } catch (ResolveError &e) {
1904 infostream << "Resolving bind address \"" << bind_str
1905 << "\" failed: " << e.what()
1906 << " -- Listening on all addresses." << std::endl;
1909 if (bind_addr.isIPv6() && !g_settings->getBool("enable_ipv6")) {
1910 *error_message = "Unable to listen on " +
1911 bind_addr.serializeString() +
1912 " because IPv6 is disabled";
1913 errorstream << *error_message << std::endl;
1917 server = new Server(map_dir, gamespec, simple_singleplayer_mode,
1918 bind_addr.isIPv6());
1920 server->start(bind_addr);
1925 bool Game::createClient(const std::string &playername,
1926 const std::string &password, std::string *address, u16 port)
1928 showOverlayMessage(wgettext("Creating client..."), 0, 10);
1930 draw_control = new MapDrawControl;
1934 bool could_connect, connect_aborted;
1936 if (!connectToServer(playername, password, address, port,
1937 &could_connect, &connect_aborted))
1940 if (!could_connect) {
1941 if (error_message->empty() && !connect_aborted) {
1942 // Should not happen if error messages are set properly
1943 *error_message = "Connection failed for unknown reason";
1944 errorstream << *error_message << std::endl;
1949 if (!getServerContent(&connect_aborted)) {
1950 if (error_message->empty() && !connect_aborted) {
1951 // Should not happen if error messages are set properly
1952 *error_message = "Connection failed for unknown reason";
1953 errorstream << *error_message << std::endl;
1958 GameGlobalShaderConstantSetterFactory *scsf = new GameGlobalShaderConstantSetterFactory(
1959 &flags.force_fog_off, &runData.fog_range, client);
1960 shader_src->addShaderConstantSetterFactory(scsf);
1962 // Update cached textures, meshes and materials
1963 client->afterContentReceived(device);
1967 camera = new Camera(smgr, *draw_control, client);
1968 if (!camera || !camera->successfullyCreated(*error_message))
1970 client->setCamera(camera);
1974 if (m_cache_enable_clouds) {
1975 clouds = new Clouds(smgr->getRootSceneNode(), smgr, -1, time(0));
1977 *error_message = "Memory allocation error (clouds)";
1978 errorstream << *error_message << std::endl;
1985 sky = new Sky(smgr->getRootSceneNode(), smgr, -1, texture_src);
1987 skybox = NULL; // This is used/set later on in the main run loop
1989 local_inventory = new Inventory(itemdef_manager);
1991 if (!(sky && local_inventory)) {
1992 *error_message = "Memory allocation error (sky or local inventory)";
1993 errorstream << *error_message << std::endl;
1997 /* Pre-calculated values
1999 video::ITexture *t = texture_src->getTexture("crack_anylength.png");
2001 v2u32 size = t->getOriginalSize();
2002 crack_animation_length = size.Y / size.X;
2004 crack_animation_length = 5;
2010 /* Set window caption
2012 std::wstring str = utf8_to_wide(PROJECT_NAME_C);
2014 str += utf8_to_wide(g_version_hash);
2016 str += driver->getName();
2018 device->setWindowCaption(str.c_str());
2020 LocalPlayer *player = client->getEnv().getLocalPlayer();
2021 player->hurt_tilt_timer = 0;
2022 player->hurt_tilt_strength = 0;
2024 hud = new Hud(driver, smgr, guienv, client, player, local_inventory);
2027 *error_message = "Memory error: could not create HUD";
2028 errorstream << *error_message << std::endl;
2032 mapper = client->getMapper();
2033 mapper->setMinimapMode(MINIMAP_MODE_OFF);
2038 bool Game::initGui()
2040 // First line of debug text
2041 guitext = addStaticText(guienv,
2042 utf8_to_wide(PROJECT_NAME_C).c_str(),
2043 core::rect<s32>(0, 0, 0, 0),
2044 false, false, guiroot);
2046 // Second line of debug text
2047 guitext2 = addStaticText(guienv,
2049 core::rect<s32>(0, 0, 0, 0),
2050 false, false, guiroot);
2052 // At the middle of the screen
2053 // Object infos are shown in this
2054 guitext_info = addStaticText(guienv,
2056 core::rect<s32>(0, 0, 400, g_fontengine->getTextHeight() * 5 + 5) + v2s32(100, 200),
2057 false, true, guiroot);
2059 // Status text (displays info when showing and hiding GUI stuff, etc.)
2060 guitext_status = addStaticText(guienv,
2062 core::rect<s32>(0, 0, 0, 0),
2063 false, false, guiroot);
2064 guitext_status->setVisible(false);
2067 guitext_chat = addStaticText(
2070 core::rect<s32>(0, 0, 0, 0),
2071 //false, false); // Disable word wrap as of now
2072 false, true, guiroot);
2074 // Remove stale "recent" chat messages from previous connections
2075 chat_backend->clearRecentChat();
2077 // Chat backend and console
2078 gui_chat_console = new GUIChatConsole(guienv, guienv->getRootGUIElement(),
2079 -1, chat_backend, client, &g_menumgr);
2080 if (!gui_chat_console) {
2081 *error_message = "Could not allocate memory for chat console";
2082 errorstream << *error_message << std::endl;
2086 // Profiler text (size is updated when text is updated)
2087 guitext_profiler = addStaticText(guienv,
2089 core::rect<s32>(0, 0, 0, 0),
2090 false, false, guiroot);
2091 guitext_profiler->setBackgroundColor(video::SColor(120, 0, 0, 0));
2092 guitext_profiler->setVisible(false);
2093 guitext_profiler->setWordWrap(true);
2095 #ifdef HAVE_TOUCHSCREENGUI
2097 if (g_touchscreengui)
2098 g_touchscreengui->init(texture_src);
2105 bool Game::connectToServer(const std::string &playername,
2106 const std::string &password, std::string *address, u16 port,
2107 bool *connect_ok, bool *aborted)
2109 *connect_ok = false; // Let's not be overly optimistic
2111 bool local_server_mode = false;
2113 showOverlayMessage(wgettext("Resolving address..."), 0, 15);
2115 Address connect_address(0, 0, 0, 0, port);
2118 connect_address.Resolve(address->c_str());
2120 if (connect_address.isZero()) { // i.e. INADDR_ANY, IN6ADDR_ANY
2121 //connect_address.Resolve("localhost");
2122 if (connect_address.isIPv6()) {
2123 IPv6AddressBytes addr_bytes;
2124 addr_bytes.bytes[15] = 1;
2125 connect_address.setAddress(&addr_bytes);
2127 connect_address.setAddress(127, 0, 0, 1);
2129 local_server_mode = true;
2131 } catch (ResolveError &e) {
2132 *error_message = std::string("Couldn't resolve address: ") + e.what();
2133 errorstream << *error_message << std::endl;
2137 if (connect_address.isIPv6() && !g_settings->getBool("enable_ipv6")) {
2138 *error_message = "Unable to connect to " +
2139 connect_address.serializeString() +
2140 " because IPv6 is disabled";
2141 errorstream << *error_message << std::endl;
2145 client = new Client(device,
2146 playername.c_str(), password,
2147 *draw_control, texture_src, shader_src,
2148 itemdef_manager, nodedef_manager, sound, eventmgr,
2149 connect_address.isIPv6());
2154 infostream << "Connecting to server at ";
2155 connect_address.print(&infostream);
2156 infostream << std::endl;
2158 client->connect(connect_address, *address,
2159 simple_singleplayer_mode || local_server_mode);
2162 Wait for server to accept connection
2168 FpsControl fps_control = { 0 };
2170 f32 wait_time = 0; // in seconds
2172 fps_control.last_time = device->getTimer()->getTime();
2176 while (device->run()) {
2178 limitFps(&fps_control, &dtime);
2180 // Update client and server
2181 client->step(dtime);
2184 server->step(dtime);
2187 if (client->getState() == LC_Init) {
2193 if (client->accessDenied()) {
2194 *error_message = "Access denied. Reason: "
2195 + client->accessDeniedReason();
2196 *reconnect_requested = client->reconnectRequested();
2197 errorstream << *error_message << std::endl;
2201 if (wasKeyDown(KeyType::ESC) || input->wasKeyDown(CancelKey)) {
2203 infostream << "Connect aborted [Escape]" << std::endl;
2208 // Only time out if we aren't waiting for the server we started
2209 if ((*address != "") && (wait_time > 10)) {
2210 bool sent_old_init = g_settings->getFlag("send_pre_v25_init");
2211 // If no pre v25 init was sent, and no answer was received,
2212 // but the low level connection could be established
2213 // (meaning that we have a peer id), then we probably wanted
2214 // to connect to a legacy server. In this case, tell the user
2215 // to enable the option to be able to connect.
2216 if (!sent_old_init &&
2217 (client->getProtoVersion() == 0) &&
2218 client->connectedToServer()) {
2219 *error_message = "Connection failure: init packet not "
2220 "recognized by server.\n"
2221 "Most likely the server uses an old protocol version (<v25).\n"
2222 "Please ask the server owner to update to 0.4.13 or later.\n"
2223 "To still connect to the server in the meantime,\n"
2224 "you can enable the 'send_pre_v25_init' setting by editing minetest.conf,\n"
2225 "or by enabling the 'Client -> Network -> Support older Servers'\n"
2226 "entry in the advanced settings menu.";
2228 *error_message = "Connection timed out.";
2230 errorstream << *error_message << std::endl;
2235 showOverlayMessage(wgettext("Connecting to server..."), dtime, 20);
2237 } catch (con::PeerNotFoundException &e) {
2238 // TODO: Should something be done here? At least an info/error
2246 bool Game::getServerContent(bool *aborted)
2250 FpsControl fps_control = { 0 };
2251 f32 dtime; // in seconds
2253 fps_control.last_time = device->getTimer()->getTime();
2255 while (device->run()) {
2257 limitFps(&fps_control, &dtime);
2259 // Update client and server
2260 client->step(dtime);
2263 server->step(dtime);
2266 if (client->mediaReceived() && client->itemdefReceived() &&
2267 client->nodedefReceived()) {
2272 if (!checkConnection())
2275 if (client->getState() < LC_Init) {
2276 *error_message = "Client disconnected";
2277 errorstream << *error_message << std::endl;
2281 if (wasKeyDown(KeyType::ESC) || input->wasKeyDown(CancelKey)) {
2283 infostream << "Connect aborted [Escape]" << std::endl;
2290 if (!client->itemdefReceived()) {
2291 const wchar_t *text = wgettext("Item definitions...");
2293 draw_load_screen(text, device, guienv, dtime, progress);
2295 } else if (!client->nodedefReceived()) {
2296 const wchar_t *text = wgettext("Node definitions...");
2298 draw_load_screen(text, device, guienv, dtime, progress);
2301 std::stringstream message;
2302 message.precision(3);
2303 message << gettext("Media...");
2305 if ((USE_CURL == 0) ||
2306 (!g_settings->getBool("enable_remote_media_server"))) {
2307 float cur = client->getCurRate();
2308 std::string cur_unit = gettext("KiB/s");
2312 cur_unit = gettext("MiB/s");
2315 message << " (" << cur << ' ' << cur_unit << ")";
2318 progress = 30 + client->mediaReceiveProgress() * 35 + 0.5;
2319 draw_load_screen(utf8_to_wide(message.str()), device,
2320 guienv, dtime, progress);
2328 /****************************************************************************/
2329 /****************************************************************************
2331 ****************************************************************************/
2332 /****************************************************************************/
2334 inline void Game::updateInteractTimers(GameRunData *runData, f32 dtime)
2336 if (runData->nodig_delay_timer >= 0)
2337 runData->nodig_delay_timer -= dtime;
2339 if (runData->object_hit_delay_timer >= 0)
2340 runData->object_hit_delay_timer -= dtime;
2342 runData->time_from_last_punch += dtime;
2346 /* returns false if game should exit, otherwise true
2348 inline bool Game::checkConnection()
2350 if (client->accessDenied()) {
2351 *error_message = "Access denied. Reason: "
2352 + client->accessDeniedReason();
2353 *reconnect_requested = client->reconnectRequested();
2354 errorstream << *error_message << std::endl;
2362 /* returns false if game should exit, otherwise true
2364 inline bool Game::handleCallbacks()
2366 if (g_gamecallback->disconnect_requested) {
2367 g_gamecallback->disconnect_requested = false;
2371 if (g_gamecallback->changepassword_requested) {
2372 (new GUIPasswordChange(guienv, guiroot, -1,
2373 &g_menumgr, client))->drop();
2374 g_gamecallback->changepassword_requested = false;
2377 if (g_gamecallback->changevolume_requested) {
2378 (new GUIVolumeChange(guienv, guiroot, -1,
2379 &g_menumgr))->drop();
2380 g_gamecallback->changevolume_requested = false;
2383 if (g_gamecallback->keyconfig_requested) {
2384 (new GUIKeyChangeMenu(guienv, guiroot, -1,
2385 &g_menumgr))->drop();
2386 g_gamecallback->keyconfig_requested = false;
2389 if (g_gamecallback->keyconfig_changed) {
2390 keycache.populate(); // update the cache with new settings
2391 g_gamecallback->keyconfig_changed = false;
2398 void Game::processQueues()
2400 texture_src->processQueue();
2401 itemdef_manager->processQueue(client);
2402 shader_src->processQueue();
2406 void Game::updateProfilers(const GameRunData &runData, const RunStats &stats,
2407 const FpsControl &draw_times, f32 dtime)
2409 float profiler_print_interval =
2410 g_settings->getFloat("profiler_print_interval");
2411 bool print_to_log = true;
2413 if (profiler_print_interval == 0) {
2414 print_to_log = false;
2415 profiler_print_interval = 5;
2418 if (profiler_interval.step(dtime, profiler_print_interval)) {
2420 infostream << "Profiler:" << std::endl;
2421 g_profiler->print(infostream);
2424 update_profiler_gui(guitext_profiler, g_fontengine,
2425 runData.profiler_current_page, runData.profiler_max_page,
2426 driver->getScreenSize().Height);
2428 g_profiler->clear();
2431 addProfilerGraphs(stats, draw_times, dtime);
2435 void Game::addProfilerGraphs(const RunStats &stats,
2436 const FpsControl &draw_times, f32 dtime)
2438 g_profiler->graphAdd("mainloop_other",
2439 draw_times.busy_time / 1000.0f - stats.drawtime / 1000.0f);
2441 if (draw_times.sleep_time != 0)
2442 g_profiler->graphAdd("mainloop_sleep", draw_times.sleep_time / 1000.0f);
2443 g_profiler->graphAdd("mainloop_dtime", dtime);
2445 g_profiler->add("Elapsed time", dtime);
2446 g_profiler->avg("FPS", 1. / dtime);
2450 void Game::updateStats(RunStats *stats, const FpsControl &draw_times,
2457 /* Time average and jitter calculation
2459 jp = &stats->dtime_jitter;
2460 jp->avg = jp->avg * 0.96 + dtime * 0.04;
2462 jitter = dtime - jp->avg;
2464 if (jitter > jp->max)
2467 jp->counter += dtime;
2469 if (jp->counter > 0.0) {
2471 jp->max_sample = jp->max;
2472 jp->max_fraction = jp->max_sample / (jp->avg + 0.001);
2476 /* Busytime average and jitter calculation
2478 jp = &stats->busy_time_jitter;
2479 jp->avg = jp->avg + draw_times.busy_time * 0.02;
2481 jitter = draw_times.busy_time - jp->avg;
2483 if (jitter > jp->max)
2485 if (jitter < jp->min)
2488 jp->counter += dtime;
2490 if (jp->counter > 0.0) {
2492 jp->max_sample = jp->max;
2493 jp->min_sample = jp->min;
2501 /****************************************************************************
2503 ****************************************************************************/
2505 void Game::processUserInput(VolatileRunFlags *flags,
2506 GameRunData *runData, f32 dtime)
2508 // Reset input if window not active or some menu is active
2509 if (device->isWindowActive() == false
2510 || noMenuActive() == false
2511 || guienv->hasFocus(gui_chat_console)) {
2513 #ifdef HAVE_TOUCHSCREENGUI
2514 g_touchscreengui->hide();
2517 #ifdef HAVE_TOUCHSCREENGUI
2518 else if (g_touchscreengui) {
2519 /* on touchscreengui step may generate own input events which ain't
2520 * what we want in case we just did clear them */
2521 g_touchscreengui->step(dtime);
2525 if (!guienv->hasFocus(gui_chat_console) && gui_chat_console->isOpen()) {
2526 gui_chat_console->closeConsoleAtOnce();
2529 // Input handler step() (used by the random input generator)
2533 if (current_formspec != NULL)
2534 current_formspec->getAndroidUIInput();
2536 handleAndroidChatInput();
2539 // Increase timer for double tap of "keymap_jump"
2540 if (m_cache_doubletap_jump && runData->jump_timer <= 0.2)
2541 runData->jump_timer += dtime;
2545 &runData->statustext_time,
2546 &runData->jump_timer,
2547 &runData->reset_jump_timer,
2548 &runData->profiler_current_page,
2549 runData->profiler_max_page);
2551 processItemSelection(&runData->new_playeritem);
2555 void Game::processKeyInput(VolatileRunFlags *flags,
2556 float *statustext_time,
2558 bool *reset_jump_timer,
2559 u32 *profiler_current_page,
2560 u32 profiler_max_page)
2563 //TimeTaker tt("process kybd input", NULL, PRECISION_NANO);
2565 if (wasKeyDown(KeyType::DROP)) {
2567 } else if (wasKeyDown(KeyType::AUTORUN)) {
2568 toggleAutorun(statustext_time);
2569 } else if (wasKeyDown(KeyType::INVENTORY)) {
2571 } else if (wasKeyDown(KeyType::ESC) || input->wasKeyDown(CancelKey)) {
2572 if (!gui_chat_console->isOpenInhibited()) {
2573 show_pause_menu(¤t_formspec, client,
2574 texture_src, device, &input->joystick,
2575 simple_singleplayer_mode);
2577 } else if (wasKeyDown(KeyType::CHAT)) {
2578 openConsole(0.2, L"");
2579 } else if (wasKeyDown(KeyType::CMD)) {
2580 openConsole(0.2, L"/");
2581 } else if (wasKeyDown(KeyType::CONSOLE)) {
2582 openConsole(core::clamp(
2583 g_settings->getFloat("console_height"), 0.1f, 1.0f));
2584 } else if (wasKeyDown(KeyType::FREEMOVE)) {
2585 toggleFreeMove(statustext_time);
2586 } else if (wasKeyDown(KeyType::JUMP)) {
2587 toggleFreeMoveAlt(statustext_time, jump_timer);
2588 *reset_jump_timer = true;
2589 } else if (wasKeyDown(KeyType::FASTMOVE)) {
2590 toggleFast(statustext_time);
2591 } else if (wasKeyDown(KeyType::NOCLIP)) {
2592 toggleNoClip(statustext_time);
2593 } else if (wasKeyDown(KeyType::CINEMATIC)) {
2594 toggleCinematic(statustext_time);
2595 } else if (wasKeyDown(KeyType::SCREENSHOT)) {
2596 client->makeScreenshot(device);
2597 } else if (wasKeyDown(KeyType::TOGGLE_HUD)) {
2598 toggleHud(statustext_time, &flags->show_hud);
2599 } else if (wasKeyDown(KeyType::MINIMAP)) {
2600 toggleMinimap(statustext_time, &flags->show_minimap, flags->show_hud,
2601 isKeyDown(KeyType::SNEAK));
2602 } else if (wasKeyDown(KeyType::TOGGLE_CHAT)) {
2603 toggleChat(statustext_time, &flags->show_chat);
2604 } else if (wasKeyDown(KeyType::TOGGLE_FORCE_FOG_OFF)) {
2605 toggleFog(statustext_time, &flags->force_fog_off);
2606 } else if (wasKeyDown(KeyType::TOGGLE_UPDATE_CAMERA)) {
2607 toggleUpdateCamera(statustext_time, &flags->disable_camera_update);
2608 } else if (wasKeyDown(KeyType::TOGGLE_DEBUG)) {
2609 toggleDebug(statustext_time, &flags->show_debug, &flags->show_profiler_graph,
2610 &draw_control->show_wireframe);
2611 } else if (wasKeyDown(KeyType::TOGGLE_PROFILER)) {
2612 toggleProfiler(statustext_time, profiler_current_page, profiler_max_page);
2613 } else if (wasKeyDown(KeyType::INCREASE_VIEWING_RANGE)) {
2614 increaseViewRange(statustext_time);
2615 } else if (wasKeyDown(KeyType::DECREASE_VIEWING_RANGE)) {
2616 decreaseViewRange(statustext_time);
2617 } else if (wasKeyDown(KeyType::RANGESELECT)) {
2618 toggleFullViewRange(statustext_time);
2619 } else if (wasKeyDown(KeyType::QUICKTUNE_NEXT)) {
2621 } else if (wasKeyDown(KeyType::QUICKTUNE_PREV)) {
2623 } else if (wasKeyDown(KeyType::QUICKTUNE_INC)) {
2625 } else if (wasKeyDown(KeyType::QUICKTUNE_DEC)) {
2627 } else if (wasKeyDown(KeyType::DEBUG_STACKS)) {
2628 // Print debug stacks
2629 dstream << "-----------------------------------------"
2631 dstream << "Printing debug stacks:" << std::endl;
2632 dstream << "-----------------------------------------"
2634 debug_stacks_print();
2637 if (!isKeyDown(KeyType::JUMP) && *reset_jump_timer) {
2638 *reset_jump_timer = false;
2644 if (quicktune->hasMessage()) {
2645 std::string msg = quicktune->getMessage();
2646 statustext = utf8_to_wide(msg);
2647 *statustext_time = 0;
2651 void Game::processItemSelection(u16 *new_playeritem)
2653 LocalPlayer *player = client->getEnv().getLocalPlayer();
2655 /* Item selection using mouse wheel
2657 *new_playeritem = client->getPlayerItem();
2659 s32 wheel = input->getMouseWheel();
2660 u16 max_item = MYMIN(PLAYER_INVENTORY_SIZE - 1,
2661 player->hud_hotbar_itemcount - 1);
2665 if (input->joystick.wasKeyDown(KeyType::SCROLL_DOWN)) {
2669 if (input->joystick.wasKeyDown(KeyType::SCROLL_UP)) {
2674 *new_playeritem = *new_playeritem < max_item ? *new_playeritem + 1 : 0;
2676 *new_playeritem = *new_playeritem > 0 ? *new_playeritem - 1 : max_item;
2679 /* Item selection using keyboard
2681 for (u16 i = 0; i < 10; i++) {
2682 static const KeyPress *item_keys[10] = {
2683 NumberKey + 1, NumberKey + 2, NumberKey + 3, NumberKey + 4,
2684 NumberKey + 5, NumberKey + 6, NumberKey + 7, NumberKey + 8,
2685 NumberKey + 9, NumberKey + 0,
2688 if (input->wasKeyDown(*item_keys[i])) {
2689 if (i < PLAYER_INVENTORY_SIZE && i < player->hud_hotbar_itemcount) {
2690 *new_playeritem = i;
2691 infostream << "Selected item: " << new_playeritem << std::endl;
2699 void Game::dropSelectedItem()
2701 IDropAction *a = new IDropAction();
2703 a->from_inv.setCurrentPlayer();
2704 a->from_list = "main";
2705 a->from_i = client->getPlayerItem();
2706 client->inventoryAction(a);
2710 void Game::openInventory()
2713 * Don't permit to open inventory is CAO or player doesn't exists.
2714 * This prevent showing an empty inventory at player load
2717 LocalPlayer *player = client->getEnv().getLocalPlayer();
2718 if (player == NULL || player->getCAO() == NULL)
2721 infostream << "the_game: " << "Launching inventory" << std::endl;
2723 PlayerInventoryFormSource *fs_src = new PlayerInventoryFormSource(client);
2724 TextDest *txt_dst = new TextDestPlayerInventory(client);
2726 create_formspec_menu(¤t_formspec, client, device, &input->joystick, fs_src, txt_dst);
2729 InventoryLocation inventoryloc;
2730 inventoryloc.setCurrentPlayer();
2731 current_formspec->setFormSpec(fs_src->getForm(), inventoryloc);
2735 void Game::openConsole(float scale, const wchar_t *line)
2737 assert(scale > 0.0f && scale <= 1.0f);
2740 porting::showInputDialog(gettext("ok"), "", "", 2);
2741 m_android_chat_open = true;
2743 if (gui_chat_console->isOpenInhibited())
2745 gui_chat_console->openConsole(scale);
2747 gui_chat_console->setCloseOnEnter(true);
2748 gui_chat_console->replaceAndAddToHistory(line);
2754 void Game::handleAndroidChatInput()
2756 if (m_android_chat_open && porting::getInputDialogState() == 0) {
2757 std::string text = porting::getInputDialogValue();
2758 client->typeChatMessage(utf8_to_wide(text));
2764 void Game::toggleFreeMove(float *statustext_time)
2766 static const wchar_t *msg[] = { L"free_move disabled", L"free_move enabled" };
2768 bool free_move = !g_settings->getBool("free_move");
2769 g_settings->set("free_move", bool_to_cstr(free_move));
2771 *statustext_time = 0;
2772 statustext = msg[free_move];
2773 if (free_move && !client->checkPrivilege("fly"))
2774 statustext += L" (note: no 'fly' privilege)";
2778 void Game::toggleFreeMoveAlt(float *statustext_time, float *jump_timer)
2780 if (m_cache_doubletap_jump && *jump_timer < 0.2f)
2781 toggleFreeMove(statustext_time);
2785 void Game::toggleFast(float *statustext_time)
2787 static const wchar_t *msg[] = { L"fast_move disabled", L"fast_move enabled" };
2788 bool fast_move = !g_settings->getBool("fast_move");
2789 g_settings->set("fast_move", bool_to_cstr(fast_move));
2791 *statustext_time = 0;
2792 statustext = msg[fast_move];
2794 bool has_fast_privs = client->checkPrivilege("fast");
2796 if (fast_move && !has_fast_privs)
2797 statustext += L" (note: no 'fast' privilege)";
2800 m_cache_hold_aux1 = fast_move && has_fast_privs;
2805 void Game::toggleNoClip(float *statustext_time)
2807 static const wchar_t *msg[] = { L"noclip disabled", L"noclip enabled" };
2808 bool noclip = !g_settings->getBool("noclip");
2809 g_settings->set("noclip", bool_to_cstr(noclip));
2811 *statustext_time = 0;
2812 statustext = msg[noclip];
2814 if (noclip && !client->checkPrivilege("noclip"))
2815 statustext += L" (note: no 'noclip' privilege)";
2818 void Game::toggleCinematic(float *statustext_time)
2820 static const wchar_t *msg[] = { L"cinematic disabled", L"cinematic enabled" };
2821 bool cinematic = !g_settings->getBool("cinematic");
2822 g_settings->set("cinematic", bool_to_cstr(cinematic));
2824 *statustext_time = 0;
2825 statustext = msg[cinematic];
2828 // Add WoW-style autorun by toggling continuous forward.
2829 void Game::toggleAutorun(float *statustext_time)
2831 static const wchar_t *msg[] = { L"autorun disabled", L"autorun enabled" };
2832 bool autorun_enabled = !g_settings->getBool("continuous_forward");
2833 g_settings->set("continuous_forward", bool_to_cstr(autorun_enabled));
2835 *statustext_time = 0;
2836 statustext = msg[autorun_enabled ? 1 : 0];
2839 void Game::toggleChat(float *statustext_time, bool *flag)
2841 static const wchar_t *msg[] = { L"Chat hidden", L"Chat shown" };
2844 *statustext_time = 0;
2845 statustext = msg[*flag];
2849 void Game::toggleHud(float *statustext_time, bool *flag)
2851 static const wchar_t *msg[] = { L"HUD hidden", L"HUD shown" };
2854 *statustext_time = 0;
2855 statustext = msg[*flag];
2858 void Game::toggleMinimap(float *statustext_time, bool *flag,
2859 bool show_hud, bool shift_pressed)
2861 if (!show_hud || !g_settings->getBool("enable_minimap"))
2864 if (shift_pressed) {
2865 mapper->toggleMinimapShape();
2869 u32 hud_flags = client->getEnv().getLocalPlayer()->hud_flags;
2871 MinimapMode mode = MINIMAP_MODE_OFF;
2872 if (hud_flags & HUD_FLAG_MINIMAP_VISIBLE) {
2873 mode = mapper->getMinimapMode();
2874 mode = (MinimapMode)((int)mode + 1);
2879 case MINIMAP_MODE_SURFACEx1:
2880 statustext = L"Minimap in surface mode, Zoom x1";
2882 case MINIMAP_MODE_SURFACEx2:
2883 statustext = L"Minimap in surface mode, Zoom x2";
2885 case MINIMAP_MODE_SURFACEx4:
2886 statustext = L"Minimap in surface mode, Zoom x4";
2888 case MINIMAP_MODE_RADARx1:
2889 statustext = L"Minimap in radar mode, Zoom x1";
2891 case MINIMAP_MODE_RADARx2:
2892 statustext = L"Minimap in radar mode, Zoom x2";
2894 case MINIMAP_MODE_RADARx4:
2895 statustext = L"Minimap in radar mode, Zoom x4";
2898 mode = MINIMAP_MODE_OFF;
2900 statustext = (hud_flags & HUD_FLAG_MINIMAP_VISIBLE) ?
2901 L"Minimap hidden" : L"Minimap disabled by server";
2904 *statustext_time = 0;
2905 mapper->setMinimapMode(mode);
2908 void Game::toggleFog(float *statustext_time, bool *flag)
2910 static const wchar_t *msg[] = { L"Fog enabled", L"Fog disabled" };
2913 *statustext_time = 0;
2914 statustext = msg[*flag];
2918 void Game::toggleDebug(float *statustext_time, bool *show_debug,
2919 bool *show_profiler_graph, bool *show_wireframe)
2921 // Initial / 4x toggle: Chat only
2922 // 1x toggle: Debug text with chat
2923 // 2x toggle: Debug text with profiler graph
2924 // 3x toggle: Debug text and wireframe
2927 *show_profiler_graph = false;
2928 *show_wireframe = false;
2929 statustext = L"Debug info shown";
2930 } else if (!*show_profiler_graph && !*show_wireframe) {
2931 *show_profiler_graph = true;
2932 statustext = L"Profiler graph shown";
2933 } else if (!*show_wireframe && client->checkPrivilege("debug")) {
2934 *show_profiler_graph = false;
2935 *show_wireframe = true;
2936 statustext = L"Wireframe shown";
2938 *show_debug = false;
2939 *show_profiler_graph = false;
2940 *show_wireframe = false;
2941 if (client->checkPrivilege("debug")) {
2942 statustext = L"Debug info, profiler graph, and wireframe hidden";
2944 statustext = L"Debug info and profiler graph hidden";
2947 *statustext_time = 0;
2951 void Game::toggleUpdateCamera(float *statustext_time, bool *flag)
2953 static const wchar_t *msg[] = {
2954 L"Camera update enabled",
2955 L"Camera update disabled"
2959 *statustext_time = 0;
2960 statustext = msg[*flag];
2964 void Game::toggleProfiler(float *statustext_time, u32 *profiler_current_page,
2965 u32 profiler_max_page)
2967 *profiler_current_page = (*profiler_current_page + 1) % (profiler_max_page + 1);
2969 // FIXME: This updates the profiler with incomplete values
2970 update_profiler_gui(guitext_profiler, g_fontengine, *profiler_current_page,
2971 profiler_max_page, driver->getScreenSize().Height);
2973 if (*profiler_current_page != 0) {
2974 std::wstringstream sstr;
2975 sstr << "Profiler shown (page " << *profiler_current_page
2976 << " of " << profiler_max_page << ")";
2977 statustext = sstr.str();
2979 statustext = L"Profiler hidden";
2981 *statustext_time = 0;
2985 void Game::increaseViewRange(float *statustext_time)
2987 s16 range = g_settings->getS16("viewing_range");
2988 s16 range_new = range + 10;
2990 if (range_new > 4000) {
2992 statustext = utf8_to_wide("Viewing range is at maximum: "
2995 statustext = utf8_to_wide("Viewing range changed to "
2998 g_settings->set("viewing_range", itos(range_new));
2999 *statustext_time = 0;
3003 void Game::decreaseViewRange(float *statustext_time)
3005 s16 range = g_settings->getS16("viewing_range");
3006 s16 range_new = range - 10;
3008 if (range_new < 20) {
3010 statustext = utf8_to_wide("Viewing range is at minimum: "
3013 statustext = utf8_to_wide("Viewing range changed to "
3016 g_settings->set("viewing_range", itos(range_new));
3017 *statustext_time = 0;
3021 void Game::toggleFullViewRange(float *statustext_time)
3023 static const wchar_t *msg[] = {
3024 L"Disabled full viewing range",
3025 L"Enabled full viewing range"
3028 draw_control->range_all = !draw_control->range_all;
3029 infostream << msg[draw_control->range_all] << std::endl;
3030 statustext = msg[draw_control->range_all];
3031 *statustext_time = 0;
3035 void Game::updateCameraDirection(CameraOrientation *cam,
3036 VolatileRunFlags *flags, float dtime)
3038 if ((device->isWindowActive() && noMenuActive()) || random_input) {
3041 if (!random_input) {
3042 // Mac OSX gets upset if this is set every frame
3043 if (device->getCursorControl()->isVisible())
3044 device->getCursorControl()->setVisible(false);
3048 if (flags->first_loop_after_window_activation)
3049 flags->first_loop_after_window_activation = false;
3051 updateCameraOrientation(cam, *flags, dtime);
3053 input->setMousePos((driver->getScreenSize().Width / 2),
3054 (driver->getScreenSize().Height / 2));
3058 // Mac OSX gets upset if this is set every frame
3059 if (device->getCursorControl()->isVisible() == false)
3060 device->getCursorControl()->setVisible(true);
3063 if (!flags->first_loop_after_window_activation)
3064 flags->first_loop_after_window_activation = true;
3069 void Game::updateCameraOrientation(CameraOrientation *cam,
3070 const VolatileRunFlags &flags, float dtime)
3072 #ifdef HAVE_TOUCHSCREENGUI
3073 if (g_touchscreengui) {
3074 cam->camera_yaw += g_touchscreengui->getYawChange();
3075 cam->camera_pitch = g_touchscreengui->getPitch();
3079 s32 dx = input->getMousePos().X - (driver->getScreenSize().Width / 2);
3080 s32 dy = input->getMousePos().Y - (driver->getScreenSize().Height / 2);
3082 if (flags.invert_mouse
3083 || camera->getCameraMode() == CAMERA_MODE_THIRD_FRONT) {
3087 cam->camera_yaw -= dx * m_cache_mouse_sensitivity;
3088 cam->camera_pitch += dy * m_cache_mouse_sensitivity;
3090 #ifdef HAVE_TOUCHSCREENGUI
3094 if (m_cache_enable_joysticks) {
3095 f32 c = m_cache_joystick_frustum_sensitivity * (1.f / 32767.f) * dtime;
3096 cam->camera_yaw -= input->joystick.getAxisWithoutDead(JA_FRUSTUM_HORIZONTAL) *
3098 cam->camera_pitch += input->joystick.getAxisWithoutDead(JA_FRUSTUM_VERTICAL) *
3102 cam->camera_pitch = rangelim(cam->camera_pitch, -89.5, 89.5);
3106 void Game::updatePlayerControl(const CameraOrientation &cam)
3108 //TimeTaker tt("update player control", NULL, PRECISION_NANO);
3110 // DO NOT use the isKeyDown method for the forward, backward, left, right
3111 // buttons, as the code that uses the controls needs to be able to
3112 // distinguish between the two in order to know when to use joysticks.
3114 PlayerControl control(
3115 input->isKeyDown(keycache.key[KeyType::FORWARD]),
3116 input->isKeyDown(keycache.key[KeyType::BACKWARD]),
3117 input->isKeyDown(keycache.key[KeyType::LEFT]),
3118 input->isKeyDown(keycache.key[KeyType::RIGHT]),
3119 isKeyDown(KeyType::JUMP),
3120 isKeyDown(KeyType::SPECIAL1),
3121 isKeyDown(KeyType::SNEAK),
3122 isKeyDown(KeyType::ZOOM),
3127 input->joystick.getAxisWithoutDead(JA_SIDEWARD_MOVE),
3128 input->joystick.getAxisWithoutDead(JA_FORWARD_MOVE)
3132 ( (u32)(isKeyDown(KeyType::FORWARD) & 0x1) << 0) |
3133 ( (u32)(isKeyDown(KeyType::BACKWARD) & 0x1) << 1) |
3134 ( (u32)(isKeyDown(KeyType::LEFT) & 0x1) << 2) |
3135 ( (u32)(isKeyDown(KeyType::RIGHT) & 0x1) << 3) |
3136 ( (u32)(isKeyDown(KeyType::JUMP) & 0x1) << 4) |
3137 ( (u32)(isKeyDown(KeyType::SPECIAL1) & 0x1) << 5) |
3138 ( (u32)(isKeyDown(KeyType::SNEAK) & 0x1) << 6) |
3139 ( (u32)(isLeftPressed() & 0x1) << 7) |
3140 ( (u32)(isRightPressed() & 0x1) << 8
3144 /* For Android, simulate holding down AUX1 (fast move) if the user has
3145 * the fast_move setting toggled on. If there is an aux1 key defined for
3146 * Android then its meaning is inverted (i.e. holding aux1 means walk and
3149 if (m_cache_hold_aux1) {
3150 control.aux1 = control.aux1 ^ true;
3151 keypress_bits ^= ((u32)(1U << 5));
3155 client->setPlayerControl(control);
3156 LocalPlayer *player = client->getEnv().getLocalPlayer();
3157 player->keyPressed = keypress_bits;
3163 inline void Game::step(f32 *dtime)
3165 bool can_be_and_is_paused =
3166 (simple_singleplayer_mode && g_menumgr.pausesGame());
3168 if (can_be_and_is_paused) { // This is for a singleplayer server
3169 *dtime = 0; // No time passes
3171 if (server != NULL) {
3172 //TimeTaker timer("server->step(dtime)");
3173 server->step(*dtime);
3176 //TimeTaker timer("client.step(dtime)");
3177 client->step(*dtime);
3182 void Game::processClientEvents(CameraOrientation *cam, float *damage_flash)
3184 ClientEvent event = client->getClientEvent();
3186 LocalPlayer *player = client->getEnv().getLocalPlayer();
3188 for ( ; event.type != CE_NONE; event = client->getClientEvent()) {
3190 if (event.type == CE_PLAYER_DAMAGE && client->getHP() != 0) {
3191 if (client->moddingEnabled()) {
3192 client->getScript()->on_damage_taken(event.player_damage.amount);
3195 *damage_flash += 95.0 + 3.2 * event.player_damage.amount;
3196 *damage_flash = MYMIN(*damage_flash, 127.0);
3198 player->hurt_tilt_timer = 1.5;
3199 player->hurt_tilt_strength =
3200 rangelim(event.player_damage.amount / 4, 1.0, 4.0);
3202 MtEvent *e = new SimpleTriggerEvent("PlayerDamage");
3203 client->event()->put(e);
3204 } else if (event.type == CE_PLAYER_FORCE_MOVE) {
3205 cam->camera_yaw = event.player_force_move.yaw;
3206 cam->camera_pitch = event.player_force_move.pitch;
3207 } else if (event.type == CE_DEATHSCREEN) {
3208 // This should be enabled for death formspec in builtin
3209 client->getScript()->on_death();
3211 /* Handle visualization */
3213 player->hurt_tilt_timer = 0;
3214 player->hurt_tilt_strength = 0;
3216 } else if (event.type == CE_SHOW_FORMSPEC) {
3217 if (*(event.show_formspec.formspec) == "") {
3218 if (current_formspec && ( *(event.show_formspec.formname) == "" || *(event.show_formspec.formname) == cur_formname) ){
3219 current_formspec->quitMenu();
3222 FormspecFormSource *fs_src =
3223 new FormspecFormSource(*(event.show_formspec.formspec));
3224 TextDestPlayerInventory *txt_dst =
3225 new TextDestPlayerInventory(client, *(event.show_formspec.formname));
3227 create_formspec_menu(¤t_formspec, client, device, &input->joystick,
3229 cur_formname = *(event.show_formspec.formname);
3232 delete(event.show_formspec.formspec);
3233 delete(event.show_formspec.formname);
3234 } else if (event.type == CE_SHOW_LOCAL_FORMSPEC) {
3235 FormspecFormSource *fs_src = new FormspecFormSource(*event.show_formspec.formspec);
3236 LocalFormspecHandler *txt_dst = new LocalFormspecHandler(*event.show_formspec.formname, client);
3237 create_formspec_menu(¤t_formspec, client, device, &input->joystick,
3239 delete event.show_formspec.formspec;
3240 delete event.show_formspec.formname;
3241 } else if ((event.type == CE_SPAWN_PARTICLE) ||
3242 (event.type == CE_ADD_PARTICLESPAWNER) ||
3243 (event.type == CE_DELETE_PARTICLESPAWNER)) {
3244 client->getParticleManager()->handleParticleEvent(&event, client,
3246 } else if (event.type == CE_HUDADD) {
3247 u32 id = event.hudadd.id;
3249 LocalPlayer *player = client->getEnv().getLocalPlayer();
3250 HudElement *e = player->getHud(id);
3253 delete event.hudadd.pos;
3254 delete event.hudadd.name;
3255 delete event.hudadd.scale;
3256 delete event.hudadd.text;
3257 delete event.hudadd.align;
3258 delete event.hudadd.offset;
3259 delete event.hudadd.world_pos;
3260 delete event.hudadd.size;
3265 e->type = (HudElementType)event.hudadd.type;
3266 e->pos = *event.hudadd.pos;
3267 e->name = *event.hudadd.name;
3268 e->scale = *event.hudadd.scale;
3269 e->text = *event.hudadd.text;
3270 e->number = event.hudadd.number;
3271 e->item = event.hudadd.item;
3272 e->dir = event.hudadd.dir;
3273 e->align = *event.hudadd.align;
3274 e->offset = *event.hudadd.offset;
3275 e->world_pos = *event.hudadd.world_pos;
3276 e->size = *event.hudadd.size;
3278 u32 new_id = player->addHud(e);
3279 //if this isn't true our huds aren't consistent
3280 sanity_check(new_id == id);
3282 delete event.hudadd.pos;
3283 delete event.hudadd.name;
3284 delete event.hudadd.scale;
3285 delete event.hudadd.text;
3286 delete event.hudadd.align;
3287 delete event.hudadd.offset;
3288 delete event.hudadd.world_pos;
3289 delete event.hudadd.size;
3290 } else if (event.type == CE_HUDRM) {
3291 HudElement *e = player->removeHud(event.hudrm.id);
3295 } else if (event.type == CE_HUDCHANGE) {
3296 u32 id = event.hudchange.id;
3297 HudElement *e = player->getHud(id);
3300 delete event.hudchange.v3fdata;
3301 delete event.hudchange.v2fdata;
3302 delete event.hudchange.sdata;
3303 delete event.hudchange.v2s32data;
3307 switch (event.hudchange.stat) {
3309 e->pos = *event.hudchange.v2fdata;
3313 e->name = *event.hudchange.sdata;
3316 case HUD_STAT_SCALE:
3317 e->scale = *event.hudchange.v2fdata;
3321 e->text = *event.hudchange.sdata;
3324 case HUD_STAT_NUMBER:
3325 e->number = event.hudchange.data;
3329 e->item = event.hudchange.data;
3333 e->dir = event.hudchange.data;
3336 case HUD_STAT_ALIGN:
3337 e->align = *event.hudchange.v2fdata;
3340 case HUD_STAT_OFFSET:
3341 e->offset = *event.hudchange.v2fdata;
3344 case HUD_STAT_WORLD_POS:
3345 e->world_pos = *event.hudchange.v3fdata;
3349 e->size = *event.hudchange.v2s32data;
3353 delete event.hudchange.v3fdata;
3354 delete event.hudchange.v2fdata;
3355 delete event.hudchange.sdata;
3356 delete event.hudchange.v2s32data;
3357 } else if (event.type == CE_SET_SKY) {
3358 sky->setVisible(false);
3365 // Handle according to type
3366 if (*event.set_sky.type == "regular") {
3367 sky->setVisible(true);
3368 } else if (*event.set_sky.type == "skybox" &&
3369 event.set_sky.params->size() == 6) {
3370 sky->setFallbackBgColor(*event.set_sky.bgcolor);
3371 skybox = smgr->addSkyBoxSceneNode(
3372 texture_src->getTextureForMesh((*event.set_sky.params)[0]),
3373 texture_src->getTextureForMesh((*event.set_sky.params)[1]),
3374 texture_src->getTextureForMesh((*event.set_sky.params)[2]),
3375 texture_src->getTextureForMesh((*event.set_sky.params)[3]),
3376 texture_src->getTextureForMesh((*event.set_sky.params)[4]),
3377 texture_src->getTextureForMesh((*event.set_sky.params)[5]));
3379 // Handle everything else as plain color
3381 if (*event.set_sky.type != "plain")
3382 infostream << "Unknown sky type: "
3383 << (*event.set_sky.type) << std::endl;
3385 sky->setFallbackBgColor(*event.set_sky.bgcolor);
3388 delete event.set_sky.bgcolor;
3389 delete event.set_sky.type;
3390 delete event.set_sky.params;
3391 } else if (event.type == CE_OVERRIDE_DAY_NIGHT_RATIO) {
3392 bool enable = event.override_day_night_ratio.do_override;
3393 u32 value = event.override_day_night_ratio.ratio_f * 1000;
3394 client->getEnv().setDayNightRatioOverride(enable, value);
3400 void Game::updateCamera(VolatileRunFlags *flags, u32 busy_time,
3401 f32 dtime, float time_from_last_punch)
3403 LocalPlayer *player = client->getEnv().getLocalPlayer();
3406 For interaction purposes, get info about the held item
3408 - Is it a usable item?
3409 - Can it point to liquids?
3411 ItemStack playeritem;
3413 InventoryList *mlist = local_inventory->getList("main");
3415 if (mlist && client->getPlayerItem() < mlist->getSize())
3416 playeritem = mlist->getItem(client->getPlayerItem());
3418 if (playeritem.getDefinition(itemdef_manager).name.empty()) { // override the hand
3419 InventoryList *hlist = local_inventory->getList("hand");
3421 playeritem = hlist->getItem(0);
3425 ToolCapabilities playeritem_toolcap =
3426 playeritem.getToolCapabilities(itemdef_manager);
3428 v3s16 old_camera_offset = camera->getOffset();
3430 if (wasKeyDown(KeyType::CAMERA_MODE)) {
3431 GenericCAO *playercao = player->getCAO();
3433 // If playercao not loaded, don't change camera
3434 if (playercao == NULL)
3437 camera->toggleCameraMode();
3439 playercao->setVisible(camera->getCameraMode() > CAMERA_MODE_FIRST);
3440 playercao->setChildrenVisible(camera->getCameraMode() > CAMERA_MODE_FIRST);
3443 float full_punch_interval = playeritem_toolcap.full_punch_interval;
3444 float tool_reload_ratio = time_from_last_punch / full_punch_interval;
3446 tool_reload_ratio = MYMIN(tool_reload_ratio, 1.0);
3447 camera->update(player, dtime, busy_time / 1000.0f, tool_reload_ratio,
3449 camera->step(dtime);
3451 v3f camera_position = camera->getPosition();
3452 v3f camera_direction = camera->getDirection();
3453 f32 camera_fov = camera->getFovMax();
3454 v3s16 camera_offset = camera->getOffset();
3456 flags->camera_offset_changed = (camera_offset != old_camera_offset);
3458 if (!flags->disable_camera_update) {
3459 client->getEnv().getClientMap().updateCamera(camera_position,
3460 camera_direction, camera_fov, camera_offset);
3462 if (flags->camera_offset_changed) {
3463 client->updateCameraOffset(camera_offset);
3464 client->getEnv().updateCameraOffset(camera_offset);
3467 clouds->updateCameraOffset(camera_offset);
3473 void Game::updateSound(f32 dtime)
3475 // Update sound listener
3476 v3s16 camera_offset = camera->getOffset();
3477 sound->updateListener(camera->getCameraNode()->getPosition() + intToFloat(camera_offset, BS),
3478 v3f(0, 0, 0), // velocity
3479 camera->getDirection(),
3480 camera->getCameraNode()->getUpVector());
3481 sound->setListenerGain(g_settings->getFloat("sound_volume"));
3484 // Update sound maker
3485 soundmaker->step(dtime);
3487 LocalPlayer *player = client->getEnv().getLocalPlayer();
3489 ClientMap &map = client->getEnv().getClientMap();
3490 MapNode n = map.getNodeNoEx(player->getFootstepNodePos());
3491 soundmaker->m_player_step_sound = nodedef_manager->get(n).sound_footstep;
3495 void Game::processPlayerInteraction(GameRunData *runData,
3496 f32 dtime, bool show_hud, bool show_debug)
3498 LocalPlayer *player = client->getEnv().getLocalPlayer();
3500 ItemStack playeritem;
3502 InventoryList *mlist = local_inventory->getList("main");
3504 if (mlist && client->getPlayerItem() < mlist->getSize())
3505 playeritem = mlist->getItem(client->getPlayerItem());
3508 if (playeritem.getDefinition(itemdef_manager).name.empty()) { // override the hand
3509 InventoryList *hlist = local_inventory->getList("hand");
3511 playeritem = hlist->getItem(0);
3513 const ItemDefinition &playeritem_def =
3514 playeritem.getDefinition(itemdef_manager);
3516 v3f player_position = player->getPosition();
3517 v3f camera_position = camera->getPosition();
3518 v3f camera_direction = camera->getDirection();
3519 v3s16 camera_offset = camera->getOffset();
3523 Calculate what block is the crosshair pointing to
3526 f32 d = playeritem_def.range; // max. distance
3527 f32 d_hand = itemdef_manager->get("").range;
3529 if (d < 0 && d_hand >= 0)
3534 core::line3d<f32> shootline;
3536 if (camera->getCameraMode() != CAMERA_MODE_THIRD_FRONT) {
3537 shootline = core::line3d<f32>(camera_position,
3538 camera_position + camera_direction * BS * d);
3540 // prevent player pointing anything in front-view
3541 shootline = core::line3d<f32>(camera_position,camera_position);
3544 #ifdef HAVE_TOUCHSCREENGUI
3546 if ((g_settings->getBool("touchtarget")) && (g_touchscreengui)) {
3547 shootline = g_touchscreengui->getShootline();
3548 shootline.start += intToFloat(camera_offset, BS);
3549 shootline.end += intToFloat(camera_offset, BS);
3554 PointedThing pointed = updatePointedThing(shootline,
3555 playeritem_def.liquids_pointable,
3556 !runData->ldown_for_dig,
3559 runData->selected_object);
3561 if (pointed != runData->pointed_old) {
3562 infostream << "Pointing at " << pointed.dump() << std::endl;
3563 hud->updateSelectionMesh(camera_offset);
3568 - releasing left mouse button
3569 - pointing away from node
3571 if (runData->digging) {
3572 if (getLeftReleased()) {
3573 infostream << "Left button released"
3574 << " (stopped digging)" << std::endl;
3575 runData->digging = false;
3576 } else if (pointed != runData->pointed_old) {
3577 if (pointed.type == POINTEDTHING_NODE
3578 && runData->pointed_old.type == POINTEDTHING_NODE
3579 && pointed.node_undersurface
3580 == runData->pointed_old.node_undersurface) {
3581 // Still pointing to the same node, but a different face.
3584 infostream << "Pointing away from node"
3585 << " (stopped digging)" << std::endl;
3586 runData->digging = false;
3587 hud->updateSelectionMesh(camera_offset);
3591 if (!runData->digging) {
3592 client->interact(1, runData->pointed_old);
3593 client->setCrack(-1, v3s16(0, 0, 0));
3594 runData->dig_time = 0.0;
3598 if (!runData->digging && runData->ldown_for_dig && !isLeftPressed()) {
3599 runData->ldown_for_dig = false;
3602 runData->left_punch = false;
3604 soundmaker->m_player_leftpunch_sound.name = "";
3606 if (isRightPressed())
3607 runData->repeat_rightclick_timer += dtime;
3609 runData->repeat_rightclick_timer = 0;
3611 if (playeritem_def.usable && isLeftPressed()) {
3612 if (getLeftClicked())
3613 client->interact(4, pointed);
3614 } else if (pointed.type == POINTEDTHING_NODE) {
3615 ToolCapabilities playeritem_toolcap =
3616 playeritem.getToolCapabilities(itemdef_manager);
3617 handlePointingAtNode(runData, pointed, playeritem_def,
3618 playeritem_toolcap, dtime);
3619 } else if (pointed.type == POINTEDTHING_OBJECT) {
3620 handlePointingAtObject(runData, pointed, playeritem,
3621 player_position, show_debug);
3622 } else if (isLeftPressed()) {
3623 // When button is held down in air, show continuous animation
3624 runData->left_punch = true;
3625 } else if (getRightClicked()) {
3626 handlePointingAtNothing(runData, playeritem);
3629 runData->pointed_old = pointed;
3631 if (runData->left_punch || getLeftClicked())
3632 camera->setDigging(0); // left click animation
3634 input->resetLeftClicked();
3635 input->resetRightClicked();
3637 input->joystick.clearWasKeyDown(KeyType::MOUSE_L);
3638 input->joystick.clearWasKeyDown(KeyType::MOUSE_R);
3640 input->resetLeftReleased();
3641 input->resetRightReleased();
3643 input->joystick.clearWasKeyReleased(KeyType::MOUSE_L);
3644 input->joystick.clearWasKeyReleased(KeyType::MOUSE_R);
3648 PointedThing Game::updatePointedThing(
3649 const core::line3d<f32> &shootline,
3650 bool liquids_pointable,
3651 bool look_for_object,
3652 const v3s16 &camera_offset,
3653 ClientActiveObject *&selected_object)
3655 std::vector<aabb3f> *selectionboxes = hud->getSelectionBoxes();
3656 selectionboxes->clear();
3657 hud->setSelectedFaceNormal(v3f(0.0, 0.0, 0.0));
3658 static const bool show_entity_selectionbox = g_settings->getBool(
3659 "show_entity_selectionbox");
3661 ClientMap &map = client->getEnv().getClientMap();
3662 INodeDefManager *nodedef=client->getNodeDefManager();
3664 selected_object = NULL;
3666 PointedThing result=client->getEnv().getPointedThing(
3667 shootline, liquids_pointable, look_for_object);
3668 if (result.type == POINTEDTHING_OBJECT) {
3669 selected_object = client->getEnv().getActiveObject(result.object_id);
3670 if (show_entity_selectionbox && selected_object->doShowSelectionBox()) {
3671 aabb3f *selection_box = selected_object->getSelectionBox();
3673 // Box should exist because object was
3674 // returned in the first place
3676 assert(selection_box);
3678 v3f pos = selected_object->getPosition();
3679 selectionboxes->push_back(aabb3f(
3680 selection_box->MinEdge, selection_box->MaxEdge));
3681 selectionboxes->push_back(
3682 aabb3f(selection_box->MinEdge, selection_box->MaxEdge));
3683 hud->setSelectionPos(pos, camera_offset);
3685 } else if (result.type == POINTEDTHING_NODE) {
3686 // Update selection boxes
3687 MapNode n = map.getNodeNoEx(result.node_undersurface);
3688 std::vector<aabb3f> boxes;
3689 n.getSelectionBoxes(nodedef, &boxes,
3690 n.getNeighbors(result.node_undersurface, &map));
3693 for (std::vector<aabb3f>::const_iterator i = boxes.begin();
3694 i != boxes.end(); ++i) {
3696 box.MinEdge -= v3f(d, d, d);
3697 box.MaxEdge += v3f(d, d, d);
3698 selectionboxes->push_back(box);
3700 hud->setSelectionPos(intToFloat(result.node_undersurface, BS),
3702 hud->setSelectedFaceNormal(v3f(
3703 result.intersection_normal.X,
3704 result.intersection_normal.Y,
3705 result.intersection_normal.Z));
3708 // Update selection mesh light level and vertex colors
3709 if (selectionboxes->size() > 0) {
3710 v3f pf = hud->getSelectionPos();
3711 v3s16 p = floatToInt(pf, BS);
3713 // Get selection mesh light level
3714 MapNode n = map.getNodeNoEx(p);
3715 u16 node_light = getInteriorLight(n, -1, nodedef);
3716 u16 light_level = node_light;
3718 for (u8 i = 0; i < 6; i++) {
3719 n = map.getNodeNoEx(p + g_6dirs[i]);
3720 node_light = getInteriorLight(n, -1, nodedef);
3721 if (node_light > light_level)
3722 light_level = node_light;
3725 u32 daynight_ratio = client->getEnv().getDayNightRatio();
3727 final_color_blend(&c, light_level, daynight_ratio);
3729 // Modify final color a bit with time
3730 u32 timer = porting::getTimeMs() % 5000;
3731 float timerf = (float) (irr::core::PI * ((timer / 2500.0) - 0.5));
3732 float sin_r = 0.08 * sin(timerf);
3733 float sin_g = 0.08 * sin(timerf + irr::core::PI * 0.5);
3734 float sin_b = 0.08 * sin(timerf + irr::core::PI);
3736 core::clamp(core::round32(c.getRed() * (0.8 + sin_r)), 0, 255));
3738 core::clamp(core::round32(c.getGreen() * (0.8 + sin_g)), 0, 255));
3740 core::clamp(core::round32(c.getBlue() * (0.8 + sin_b)), 0, 255));
3742 // Set mesh final color
3743 hud->setSelectionMeshColor(c);
3749 void Game::handlePointingAtNothing(GameRunData *runData, const ItemStack &playerItem)
3751 infostream << "Right Clicked in Air" << std::endl;
3752 PointedThing fauxPointed;
3753 fauxPointed.type = POINTEDTHING_NOTHING;
3754 client->interact(5, fauxPointed);
3758 void Game::handlePointingAtNode(GameRunData *runData,
3759 const PointedThing &pointed, const ItemDefinition &playeritem_def,
3760 const ToolCapabilities &playeritem_toolcap, f32 dtime)
3762 v3s16 nodepos = pointed.node_undersurface;
3763 v3s16 neighbourpos = pointed.node_abovesurface;
3766 Check information text of node
3769 ClientMap &map = client->getEnv().getClientMap();
3770 NodeMetadata *meta = map.getNodeMetadata(nodepos);
3773 infotext = unescape_enriched(utf8_to_wide(meta->getString("infotext")));
3775 MapNode n = map.getNodeNoEx(nodepos);
3777 if (nodedef_manager->get(n).tiledef[0].name == "unknown_node.png") {
3778 infotext = L"Unknown node: ";
3779 infotext += utf8_to_wide(nodedef_manager->get(n).name);
3783 if (runData->nodig_delay_timer <= 0.0 && isLeftPressed()
3784 && client->checkPrivilege("interact")) {
3785 handleDigging(runData, pointed, nodepos, playeritem_toolcap, dtime);
3788 if ((getRightClicked() ||
3789 runData->repeat_rightclick_timer >= m_repeat_right_click_time) &&
3790 client->checkPrivilege("interact")) {
3791 runData->repeat_rightclick_timer = 0;
3792 infostream << "Ground right-clicked" << std::endl;
3794 if (meta && meta->getString("formspec") != "" && !random_input
3795 && !isKeyDown(KeyType::SNEAK)) {
3796 infostream << "Launching custom inventory view" << std::endl;
3798 InventoryLocation inventoryloc;
3799 inventoryloc.setNodeMeta(nodepos);
3801 NodeMetadataFormSource *fs_src = new NodeMetadataFormSource(
3802 &client->getEnv().getClientMap(), nodepos);
3803 TextDest *txt_dst = new TextDestNodeMetadata(nodepos, client);
3805 create_formspec_menu(¤t_formspec, client,
3806 device, &input->joystick, fs_src, txt_dst);
3809 current_formspec->setFormSpec(meta->getString("formspec"), inventoryloc);
3811 // Report right click to server
3813 camera->setDigging(1); // right click animation (always shown for feedback)
3815 // If the wielded item has node placement prediction,
3817 bool placed = nodePlacementPrediction(*client,
3819 nodepos, neighbourpos);
3823 client->interact(3, pointed);
3825 soundmaker->m_player_rightpunch_sound =
3826 playeritem_def.sound_place;
3828 soundmaker->m_player_rightpunch_sound =
3831 if (playeritem_def.node_placement_prediction == "" ||
3832 nodedef_manager->get(map.getNodeNoEx(nodepos)).rightclickable) {
3833 client->interact(3, pointed); // Report to server
3835 soundmaker->m_player_rightpunch_sound =
3836 playeritem_def.sound_place_failed;
3844 void Game::handlePointingAtObject(GameRunData *runData,
3845 const PointedThing &pointed,
3846 const ItemStack &playeritem,
3847 const v3f &player_position,
3850 infotext = unescape_enriched(
3851 utf8_to_wide(runData->selected_object->infoText()));
3854 if (infotext != L"") {
3857 infotext += unescape_enriched(utf8_to_wide(
3858 runData->selected_object->debugInfoText()));
3861 if (isLeftPressed()) {
3862 bool do_punch = false;
3863 bool do_punch_damage = false;
3865 if (runData->object_hit_delay_timer <= 0.0) {
3867 do_punch_damage = true;
3868 runData->object_hit_delay_timer = object_hit_delay;
3871 if (getLeftClicked())
3875 infostream << "Left-clicked object" << std::endl;
3876 runData->left_punch = true;
3879 if (do_punch_damage) {
3880 // Report direct punch
3881 v3f objpos = runData->selected_object->getPosition();
3882 v3f dir = (objpos - player_position).normalize();
3884 bool disable_send = runData->selected_object->directReportPunch(
3885 dir, &playeritem, runData->time_from_last_punch);
3886 runData->time_from_last_punch = 0;
3889 client->interact(0, pointed);
3891 } else if (getRightClicked()) {
3892 infostream << "Right-clicked object" << std::endl;
3893 client->interact(3, pointed); // place
3898 void Game::handleDigging(GameRunData *runData,
3899 const PointedThing &pointed, const v3s16 &nodepos,
3900 const ToolCapabilities &playeritem_toolcap, f32 dtime)
3903 LocalPlayer *player = client->getEnv().getLocalPlayer();
3904 ClientMap &map = client->getEnv().getClientMap();
3905 MapNode n = client->getEnv().getClientMap().getNodeNoEx(nodepos);
3907 if (!runData->digging) {
3908 infostream << "Started digging" << std::endl;
3909 if (client->moddingEnabled() && client->getScript()->on_punchnode(nodepos, n))
3911 client->interact(0, pointed);
3912 runData->digging = true;
3913 runData->ldown_for_dig = true;
3916 // NOTE: Similar piece of code exists on the server side for
3918 // Get digging parameters
3919 DigParams params = getDigParams(nodedef_manager->get(n).groups,
3920 &playeritem_toolcap);
3922 // If can't dig, try hand
3923 if (!params.diggable) {
3924 const ItemDefinition &hand = itemdef_manager->get("");
3925 const ToolCapabilities *tp = hand.tool_capabilities;
3928 params = getDigParams(nodedef_manager->get(n).groups, tp);
3931 if (params.diggable == false) {
3932 // I guess nobody will wait for this long
3933 runData->dig_time_complete = 10000000.0;
3935 runData->dig_time_complete = params.time;
3937 if (m_cache_enable_particles) {
3938 const ContentFeatures &features =
3939 client->getNodeDefManager()->get(n);
3940 client->getParticleManager()->addPunchingParticles(client, smgr,
3941 player, nodepos, n, features);
3945 if (runData->dig_time_complete >= 0.001) {
3946 runData->dig_index = (float)crack_animation_length
3948 / runData->dig_time_complete;
3950 // This is for torches
3951 runData->dig_index = crack_animation_length;
3954 SimpleSoundSpec sound_dig = nodedef_manager->get(n).sound_dig;
3956 if (sound_dig.exists() && params.diggable) {
3957 if (sound_dig.name == "__group") {
3958 if (params.main_group != "") {
3959 soundmaker->m_player_leftpunch_sound.gain = 0.5;
3960 soundmaker->m_player_leftpunch_sound.name =
3961 std::string("default_dig_") +
3965 soundmaker->m_player_leftpunch_sound = sound_dig;
3969 // Don't show cracks if not diggable
3970 if (runData->dig_time_complete >= 100000.0) {
3971 } else if (runData->dig_index < crack_animation_length) {
3972 //TimeTaker timer("client.setTempMod");
3973 //infostream<<"dig_index="<<dig_index<<std::endl;
3974 client->setCrack(runData->dig_index, nodepos);
3976 infostream << "Digging completed" << std::endl;
3977 client->setCrack(-1, v3s16(0, 0, 0));
3979 runData->dig_time = 0;
3980 runData->digging = false;
3982 runData->nodig_delay_timer =
3983 runData->dig_time_complete / (float)crack_animation_length;
3985 // We don't want a corresponding delay to
3986 // very time consuming nodes
3987 if (runData->nodig_delay_timer > 0.3)
3988 runData->nodig_delay_timer = 0.3;
3990 // We want a slight delay to very little
3991 // time consuming nodes
3992 const float mindelay = 0.15;
3994 if (runData->nodig_delay_timer < mindelay)
3995 runData->nodig_delay_timer = mindelay;
3997 bool is_valid_position;
3998 MapNode wasnode = map.getNodeNoEx(nodepos, &is_valid_position);
3999 if (is_valid_position) {
4000 if (client->moddingEnabled()) {
4001 if (client->getScript()->on_dignode(nodepos, wasnode)) {
4005 client->removeNode(nodepos);
4008 client->interact(2, pointed);
4010 if (m_cache_enable_particles) {
4011 const ContentFeatures &features =
4012 client->getNodeDefManager()->get(wasnode);
4013 client->getParticleManager()->addDiggingParticles(client, smgr,
4014 player, nodepos, wasnode, features);
4018 // Send event to trigger sound
4019 MtEvent *e = new NodeDugEvent(nodepos, wasnode);
4020 client->event()->put(e);
4023 if (runData->dig_time_complete < 100000.0) {
4024 runData->dig_time += dtime;
4026 runData->dig_time = 0;
4027 client->setCrack(-1, nodepos);
4030 camera->setDigging(0); // left click animation
4034 void Game::updateFrame(ProfilerGraph *graph, RunStats *stats,
4035 GameRunData *runData, f32 dtime, const VolatileRunFlags &flags,
4036 const CameraOrientation &cam)
4038 LocalPlayer *player = client->getEnv().getLocalPlayer();
4044 if (draw_control->range_all) {
4045 runData->fog_range = 100000 * BS;
4047 runData->fog_range = draw_control->wanted_range * BS;
4051 Calculate general brightness
4053 u32 daynight_ratio = client->getEnv().getDayNightRatio();
4054 float time_brightness = decode_light_f((float)daynight_ratio / 1000.0);
4055 float direct_brightness;
4058 if (m_cache_enable_noclip && m_cache_enable_free_move) {
4059 direct_brightness = time_brightness;
4060 sunlight_seen = true;
4062 ScopeProfiler sp(g_profiler, "Detecting background light", SPT_AVG);
4063 float old_brightness = sky->getBrightness();
4064 direct_brightness = client->getEnv().getClientMap()
4065 .getBackgroundBrightness(MYMIN(runData->fog_range * 1.2, 60 * BS),
4066 daynight_ratio, (int)(old_brightness * 255.5), &sunlight_seen)
4070 float time_of_day = runData->time_of_day;
4071 float time_of_day_smooth = runData->time_of_day_smooth;
4073 time_of_day = client->getEnv().getTimeOfDayF();
4075 const float maxsm = 0.05;
4076 const float todsm = 0.05;
4078 if (fabs(time_of_day - time_of_day_smooth) > maxsm &&
4079 fabs(time_of_day - time_of_day_smooth + 1.0) > maxsm &&
4080 fabs(time_of_day - time_of_day_smooth - 1.0) > maxsm)
4081 time_of_day_smooth = time_of_day;
4083 if (time_of_day_smooth > 0.8 && time_of_day < 0.2)
4084 time_of_day_smooth = time_of_day_smooth * (1.0 - todsm)
4085 + (time_of_day + 1.0) * todsm;
4087 time_of_day_smooth = time_of_day_smooth * (1.0 - todsm)
4088 + time_of_day * todsm;
4090 runData->time_of_day = time_of_day;
4091 runData->time_of_day_smooth = time_of_day_smooth;
4093 sky->update(time_of_day_smooth, time_brightness, direct_brightness,
4094 sunlight_seen, camera->getCameraMode(), player->getYaw(),
4095 player->getPitch());
4101 v3f player_position = player->getPosition();
4102 if (sky->getCloudsVisible()) {
4103 clouds->setVisible(true);
4104 clouds->step(dtime);
4105 clouds->update(v2f(player_position.X, player_position.Z),
4106 sky->getCloudColor());
4108 clouds->setVisible(false);
4115 client->getParticleManager()->step(dtime);
4121 if (m_cache_enable_fog && !flags.force_fog_off) {
4124 video::EFT_FOG_LINEAR,
4125 runData->fog_range * m_cache_fog_start,
4126 runData->fog_range * 1.0,
4134 video::EFT_FOG_LINEAR,
4144 Get chat messages from client
4147 v2u32 screensize = driver->getScreenSize();
4149 updateChat(*client, dtime, flags.show_debug, screensize,
4150 flags.show_chat, runData->profiler_current_page,
4151 *chat_backend, guitext_chat);
4157 if (client->getPlayerItem() != runData->new_playeritem)
4158 client->selectPlayerItem(runData->new_playeritem);
4160 // Update local inventory if it has changed
4161 if (client->getLocalInventoryUpdated()) {
4162 //infostream<<"Updating local inventory"<<std::endl;
4163 client->getLocalInventory(*local_inventory);
4164 runData->update_wielded_item_trigger = true;
4167 if (runData->update_wielded_item_trigger) {
4168 // Update wielded tool
4169 InventoryList *mlist = local_inventory->getList("main");
4171 if (mlist && (client->getPlayerItem() < mlist->getSize())) {
4172 ItemStack item = mlist->getItem(client->getPlayerItem());
4173 if (item.getDefinition(itemdef_manager).name.empty()) { // override the hand
4174 InventoryList *hlist = local_inventory->getList("hand");
4176 item = hlist->getItem(0);
4178 camera->wield(item);
4181 runData->update_wielded_item_trigger = false;
4185 Update block draw list every 200ms or when camera direction has
4188 runData->update_draw_list_timer += dtime;
4190 v3f camera_direction = camera->getDirection();
4191 if (runData->update_draw_list_timer >= 0.2
4192 || runData->update_draw_list_last_cam_dir.getDistanceFrom(camera_direction) > 0.2
4193 || flags.camera_offset_changed) {
4194 runData->update_draw_list_timer = 0;
4195 client->getEnv().getClientMap().updateDrawList(driver);
4196 runData->update_draw_list_last_cam_dir = camera_direction;
4199 updateGui(&runData->statustext_time, *stats, *runData, dtime, flags, cam);
4202 make sure menu is on top
4203 1. Delete formspec menu reference if menu was removed
4204 2. Else, make sure formspec menu is on top
4206 if (current_formspec) {
4207 if (current_formspec->getReferenceCount() == 1) {
4208 current_formspec->drop();
4209 current_formspec = NULL;
4210 } else if (!noMenuActive()) {
4211 guiroot->bringToFront(current_formspec);
4219 video::SColor skycolor = sky->getSkyColor();
4221 TimeTaker tt_draw("mainloop: draw");
4223 TimeTaker timer("beginScene");
4224 driver->beginScene(true, true, skycolor);
4225 stats->beginscenetime = timer.stop(true);
4228 draw_scene(driver, smgr, *camera, *client, player, *hud, *mapper,
4229 guienv, screensize, skycolor, flags.show_hud,
4230 flags.show_minimap);
4235 if (flags.show_profiler_graph)
4236 graph->draw(10, screensize.Y - 10, driver, g_fontengine->getFont());
4241 if (runData->damage_flash > 0.0) {
4242 video::SColor color(runData->damage_flash, 180, 0, 0);
4243 driver->draw2DRectangle(color,
4244 core::rect<s32>(0, 0, screensize.X, screensize.Y),
4247 runData->damage_flash -= 100.0 * dtime;
4253 if (player->hurt_tilt_timer > 0.0) {
4254 player->hurt_tilt_timer -= dtime * 5;
4256 if (player->hurt_tilt_timer < 0)
4257 player->hurt_tilt_strength = 0;
4261 Update minimap pos and rotation
4263 if (flags.show_minimap && flags.show_hud) {
4264 mapper->setPos(floatToInt(player->getPosition(), BS));
4265 mapper->setAngle(player->getYaw());
4272 TimeTaker timer("endScene");
4274 stats->endscenetime = timer.stop(true);
4277 stats->drawtime = tt_draw.stop(true);
4278 g_profiler->graphAdd("mainloop_draw", stats->drawtime / 1000.0f);
4282 inline static const char *yawToDirectionString(int yaw)
4284 static const char *direction[4] = {"North [+Z]", "West [-X]", "South [-Z]", "East [+X]"};
4286 yaw = wrapDegrees_0_360(yaw);
4287 yaw = (yaw + 45) % 360 / 90;
4289 return direction[yaw];
4293 void Game::updateGui(float *statustext_time, const RunStats &stats,
4294 const GameRunData& runData, f32 dtime, const VolatileRunFlags &flags,
4295 const CameraOrientation &cam)
4297 v2u32 screensize = driver->getScreenSize();
4298 LocalPlayer *player = client->getEnv().getLocalPlayer();
4299 v3f player_position = player->getPosition();
4301 if (flags.show_debug) {
4302 static float drawtime_avg = 0;
4303 drawtime_avg = drawtime_avg * 0.95 + stats.drawtime * 0.05;
4305 u16 fps = 1.0 / stats.dtime_jitter.avg;
4306 //s32 fps = driver->getFPS();
4308 std::ostringstream os(std::ios_base::binary);
4310 << PROJECT_NAME_C " " << g_version_hash
4312 << " (R: range_all=" << draw_control->range_all << ")"
4313 << std::setprecision(0)
4314 << " drawtime = " << drawtime_avg
4315 << std::setprecision(1)
4316 << ", dtime_jitter = "
4317 << (stats.dtime_jitter.max_fraction * 100.0) << " %"
4318 << std::setprecision(1)
4319 << ", v_range = " << draw_control->wanted_range
4320 << std::setprecision(3)
4321 << ", RTT = " << client->getRTT();
4322 setStaticText(guitext, utf8_to_wide(os.str()).c_str());
4323 guitext->setVisible(true);
4325 guitext->setVisible(false);
4328 if (guitext->isVisible()) {
4329 core::rect<s32> rect(
4331 screensize.X, 5 + g_fontengine->getTextHeight()
4333 guitext->setRelativePosition(rect);
4336 if (flags.show_debug) {
4337 std::ostringstream os(std::ios_base::binary);
4338 os << std::setprecision(1) << std::fixed
4339 << "(" << (player_position.X / BS)
4340 << ", " << (player_position.Y / BS)
4341 << ", " << (player_position.Z / BS)
4342 << ") (yaw=" << (wrapDegrees_0_360(cam.camera_yaw))
4343 << " " << yawToDirectionString(cam.camera_yaw)
4344 << ") (seed = " << ((u64)client->getMapSeed())
4347 if (runData.pointed_old.type == POINTEDTHING_NODE) {
4348 ClientMap &map = client->getEnv().getClientMap();
4349 const INodeDefManager *nodedef = client->getNodeDefManager();
4350 MapNode n = map.getNodeNoEx(runData.pointed_old.node_undersurface);
4351 if (n.getContent() != CONTENT_IGNORE && nodedef->get(n).name != "unknown") {
4352 const ContentFeatures &features = nodedef->get(n);
4353 os << " (pointing_at = " << nodedef->get(n).name
4354 << " - " << features.tiledef[0].name.c_str()
4359 setStaticText(guitext2, utf8_to_wide(os.str()).c_str());
4360 guitext2->setVisible(true);
4362 core::rect<s32> rect(
4363 5, 5 + g_fontengine->getTextHeight(),
4364 screensize.X, 5 + g_fontengine->getTextHeight() * 2
4366 guitext2->setRelativePosition(rect);
4368 guitext2->setVisible(false);
4371 setStaticText(guitext_info, infotext.c_str());
4372 guitext_info->setVisible(flags.show_hud && g_menumgr.menuCount() == 0);
4374 float statustext_time_max = 1.5;
4376 if (!statustext.empty()) {
4377 *statustext_time += dtime;
4379 if (*statustext_time >= statustext_time_max) {
4381 *statustext_time = 0;
4385 setStaticText(guitext_status, statustext.c_str());
4386 guitext_status->setVisible(!statustext.empty());
4388 if (!statustext.empty()) {
4389 s32 status_width = guitext_status->getTextWidth();
4390 s32 status_height = guitext_status->getTextHeight();
4391 s32 status_y = screensize.Y - 150;
4392 s32 status_x = (screensize.X - status_width) / 2;
4393 core::rect<s32> rect(
4394 status_x , status_y - status_height,
4395 status_x + status_width, status_y
4397 guitext_status->setRelativePosition(rect);
4400 video::SColor initial_color(255, 0, 0, 0);
4402 if (guienv->getSkin())
4403 initial_color = guienv->getSkin()->getColor(gui::EGDC_BUTTON_TEXT);
4405 video::SColor final_color = initial_color;
4406 final_color.setAlpha(0);
4407 video::SColor fade_color = initial_color.getInterpolated_quadratic(
4408 initial_color, final_color,
4409 pow(*statustext_time / statustext_time_max, 2.0f));
4410 guitext_status->setOverrideColor(fade_color);
4411 guitext_status->enableOverrideColor(true);
4416 /* Log times and stuff for visualization */
4417 inline void Game::updateProfilerGraphs(ProfilerGraph *graph)
4419 Profiler::GraphValues values;
4420 g_profiler->graphGet(values);
4426 /****************************************************************************
4428 ****************************************************************************/
4430 /* On some computers framerate doesn't seem to be automatically limited
4432 inline void Game::limitFps(FpsControl *fps_timings, f32 *dtime)
4434 // not using getRealTime is necessary for wine
4435 device->getTimer()->tick(); // Maker sure device time is up-to-date
4436 u32 time = device->getTimer()->getTime();
4437 u32 last_time = fps_timings->last_time;
4439 if (time > last_time) // Make sure time hasn't overflowed
4440 fps_timings->busy_time = time - last_time;
4442 fps_timings->busy_time = 0;
4444 u32 frametime_min = 1000 / (g_menumgr.pausesGame()
4445 ? g_settings->getFloat("pause_fps_max")
4446 : g_settings->getFloat("fps_max"));
4448 if (fps_timings->busy_time < frametime_min) {
4449 fps_timings->sleep_time = frametime_min - fps_timings->busy_time;
4450 device->sleep(fps_timings->sleep_time);
4452 fps_timings->sleep_time = 0;
4455 /* Get the new value of the device timer. Note that device->sleep() may
4456 * not sleep for the entire requested time as sleep may be interrupted and
4457 * therefore it is arguably more accurate to get the new time from the
4458 * device rather than calculating it by adding sleep_time to time.
4461 device->getTimer()->tick(); // Update device timer
4462 time = device->getTimer()->getTime();
4464 if (time > last_time) // Make sure last_time hasn't overflowed
4465 *dtime = (time - last_time) / 1000.0;
4469 fps_timings->last_time = time;
4472 // Note: This will free (using delete[])! \p msg. If you want to use it later,
4473 // pass a copy of it to this function
4474 // Note: \p msg must be allocated using new (not malloc())
4475 void Game::showOverlayMessage(const wchar_t *msg, float dtime,
4476 int percent, bool draw_clouds)
4478 draw_load_screen(msg, device, guienv, dtime, percent, draw_clouds);
4482 void Game::settingChangedCallback(const std::string &setting_name, void *data)
4484 ((Game *)data)->readSettings();
4487 void Game::readSettings()
4489 m_cache_doubletap_jump = g_settings->getBool("doubletap_jump");
4490 m_cache_enable_clouds = g_settings->getBool("enable_clouds");
4491 m_cache_enable_joysticks = g_settings->getBool("enable_joysticks");
4492 m_cache_enable_particles = g_settings->getBool("enable_particles");
4493 m_cache_enable_fog = g_settings->getBool("enable_fog");
4494 m_cache_mouse_sensitivity = g_settings->getFloat("mouse_sensitivity");
4495 m_cache_joystick_frustum_sensitivity = g_settings->getFloat("joystick_frustum_sensitivity");
4496 m_repeat_right_click_time = g_settings->getFloat("repeat_rightclick_time");
4498 m_cache_enable_noclip = g_settings->getBool("noclip");
4499 m_cache_enable_free_move = g_settings->getBool("free_move");
4501 m_cache_fog_start = g_settings->getFloat("fog_start");
4503 m_cache_cam_smoothing = 0;
4504 if (g_settings->getBool("cinematic"))
4505 m_cache_cam_smoothing = 1 - g_settings->getFloat("cinematic_camera_smoothing");
4507 m_cache_cam_smoothing = 1 - g_settings->getFloat("camera_smoothing");
4509 m_cache_fog_start = rangelim(m_cache_fog_start, 0.0f, 0.99f);
4510 m_cache_cam_smoothing = rangelim(m_cache_cam_smoothing, 0.01f, 1.0f);
4511 m_cache_mouse_sensitivity = rangelim(m_cache_mouse_sensitivity, 0.001, 100.0);
4515 /****************************************************************************/
4516 /****************************************************************************
4518 ****************************************************************************/
4519 /****************************************************************************/
4521 void Game::extendedResourceCleanup()
4523 // Extended resource accounting
4524 infostream << "Irrlicht resources after cleanup:" << std::endl;
4525 infostream << "\tRemaining meshes : "
4526 << device->getSceneManager()->getMeshCache()->getMeshCount() << std::endl;
4527 infostream << "\tRemaining textures : "
4528 << driver->getTextureCount() << std::endl;
4530 for (unsigned int i = 0; i < driver->getTextureCount(); i++) {
4531 irr::video::ITexture *texture = driver->getTextureByIndex(i);
4532 infostream << "\t\t" << i << ":" << texture->getName().getPath().c_str()
4536 clearTextureNameCache();
4537 infostream << "\tRemaining materials: "
4538 << driver-> getMaterialRendererCount()
4539 << " (note: irrlicht doesn't support removing renderers)" << std::endl;
4543 /****************************************************************************/
4544 /****************************************************************************
4545 extern function for launching the game
4546 ****************************************************************************/
4547 /****************************************************************************/
4549 void the_game(bool *kill,
4551 InputHandler *input,
4552 IrrlichtDevice *device,
4554 const std::string &map_dir,
4555 const std::string &playername,
4556 const std::string &password,
4557 const std::string &address, // If empty local server is created
4560 std::string &error_message,
4561 ChatBackend &chat_backend,
4562 bool *reconnect_requested,
4563 const SubgameSpec &gamespec, // Used for local game
4564 bool simple_singleplayer_mode)
4568 /* Make a copy of the server address because if a local singleplayer server
4569 * is created then this is updated and we don't want to change the value
4570 * passed to us by the calling function
4572 std::string server_address = address;
4576 if (game.startup(kill, random_input, input, device, map_dir,
4577 playername, password, &server_address, port, error_message,
4578 reconnect_requested, &chat_backend, gamespec,
4579 simple_singleplayer_mode)) {
4584 } catch (SerializationError &e) {
4585 error_message = std::string("A serialization error occurred:\n")
4586 + e.what() + "\n\nThe server is probably "
4587 " running a different version of " PROJECT_NAME_C ".";
4588 errorstream << error_message << std::endl;
4589 } catch (ServerError &e) {
4590 error_message = e.what();
4591 errorstream << "ServerError: " << error_message << std::endl;
4592 } catch (ModError &e) {
4593 error_message = e.what() + strgettext("\nCheck debug.txt for details.");
4594 errorstream << "ModError: " << error_message << std::endl;