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
84 TextDestNodeMetadata(v3s16 p, Client *client)
89 // This is deprecated I guess? -celeron55
90 void gotText(const std::wstring &text)
92 std::string ntext = wide_to_utf8(text);
93 infostream << "Submitting 'text' field of node at (" << m_p.X << ","
94 << m_p.Y << "," << m_p.Z << "): " << ntext << std::endl;
96 fields["text"] = ntext;
97 m_client->sendNodemetaFields(m_p, "", fields);
99 void gotText(const StringMap &fields)
101 m_client->sendNodemetaFields(m_p, "", fields);
108 struct TextDestPlayerInventory : public TextDest
110 TextDestPlayerInventory(Client *client)
115 TextDestPlayerInventory(Client *client, const std::string &formname)
118 m_formname = formname;
120 void gotText(const StringMap &fields)
122 m_client->sendInventoryFields(m_formname, fields);
128 struct LocalFormspecHandler : public TextDest
130 LocalFormspecHandler(std::string formname):
133 m_formname = formname;
136 LocalFormspecHandler(const std::string &formname, Client *client):
139 m_formname = formname;
142 void gotText(const std::wstring &message)
144 errorstream << "LocalFormspecHandler::gotText old style message received" << std::endl;
147 void gotText(const StringMap &fields)
149 if (m_formname == "MT_PAUSE_MENU") {
150 if (fields.find("btn_sound") != fields.end()) {
151 g_gamecallback->changeVolume();
155 if (fields.find("btn_key_config") != fields.end()) {
156 g_gamecallback->keyConfig();
160 if (fields.find("btn_exit_menu") != fields.end()) {
161 g_gamecallback->disconnect();
165 if (fields.find("btn_exit_os") != fields.end()) {
166 g_gamecallback->exitToOS();
170 if (fields.find("btn_change_password") != fields.end()) {
171 g_gamecallback->changePassword();
175 if (fields.find("quit") != fields.end()) {
179 if (fields.find("btn_continue") != fields.end()) {
184 // Don't disable this part when modding is disabled, it's used in builtin
185 m_client->getScript()->on_formspec_input(m_formname, fields);
191 /* Form update callback */
193 class NodeMetadataFormSource: public IFormSource
196 NodeMetadataFormSource(ClientMap *map, v3s16 p):
201 std::string getForm()
203 NodeMetadata *meta = m_map->getNodeMetadata(m_p);
208 return meta->getString("formspec");
210 std::string resolveText(std::string str)
212 NodeMetadata *meta = m_map->getNodeMetadata(m_p);
217 return meta->resolveString(str);
224 class PlayerInventoryFormSource: public IFormSource
227 PlayerInventoryFormSource(Client *client):
231 std::string getForm()
233 LocalPlayer *player = m_client->getEnv().getLocalPlayer();
234 return player->inventory_formspec;
240 /* Profiler display */
242 void update_profiler_gui(gui::IGUIStaticText *guitext_profiler, FontEngine *fe,
243 u32 show_profiler, u32 show_profiler_max, s32 screen_height)
245 if (show_profiler == 0) {
246 guitext_profiler->setVisible(false);
249 std::ostringstream os(std::ios_base::binary);
250 g_profiler->printPage(os, show_profiler, show_profiler_max);
251 std::wstring text = utf8_to_wide(os.str());
252 setStaticText(guitext_profiler, text.c_str());
253 guitext_profiler->setVisible(true);
255 s32 w = fe->getTextWidth(text.c_str());
260 unsigned text_height = fe->getTextHeight();
262 core::position2di upper_left, lower_right;
265 upper_left.Y = (text_height + 5) * 2;
266 lower_right.X = 12 + w;
267 lower_right.Y = upper_left.Y + (text_height + 1) * MAX_PROFILER_TEXT_ROWS;
269 if (lower_right.Y > screen_height * 2 / 3)
270 lower_right.Y = screen_height * 2 / 3;
272 core::rect<s32> rect(upper_left, lower_right);
274 guitext_profiler->setRelativePosition(rect);
275 guitext_profiler->setVisible(true);
283 Profiler::GraphValues values;
289 Meta(float initial = 0,
290 video::SColor color = video::SColor(255, 255, 255, 255)):
296 std::deque<Piece> m_log;
304 void put(const Profiler::GraphValues &values)
307 piece.values = values;
308 m_log.push_back(piece);
310 while (m_log.size() > m_log_max_size)
311 m_log.erase(m_log.begin());
314 void draw(s32 x_left, s32 y_bottom, video::IVideoDriver *driver,
315 gui::IGUIFont *font) const
317 // Do *not* use UNORDERED_MAP here as the order needs
318 // to be the same for each call to prevent flickering
319 std::map<std::string, Meta> m_meta;
321 for (std::deque<Piece>::const_iterator k = m_log.begin();
322 k != m_log.end(); ++k) {
323 const Piece &piece = *k;
325 for (Profiler::GraphValues::const_iterator i = piece.values.begin();
326 i != piece.values.end(); ++i) {
327 const std::string &id = i->first;
328 const float &value = i->second;
329 std::map<std::string, Meta>::iterator j = m_meta.find(id);
331 if (j == m_meta.end()) {
332 m_meta[id] = Meta(value);
336 if (value < j->second.min)
337 j->second.min = value;
339 if (value > j->second.max)
340 j->second.max = value;
345 static const video::SColor usable_colors[] = {
346 video::SColor(255, 255, 100, 100),
347 video::SColor(255, 90, 225, 90),
348 video::SColor(255, 100, 100, 255),
349 video::SColor(255, 255, 150, 50),
350 video::SColor(255, 220, 220, 100)
352 static const u32 usable_colors_count =
353 sizeof(usable_colors) / sizeof(*usable_colors);
354 u32 next_color_i = 0;
356 for (std::map<std::string, Meta>::iterator i = m_meta.begin();
357 i != m_meta.end(); ++i) {
358 Meta &meta = i->second;
359 video::SColor color(255, 200, 200, 200);
361 if (next_color_i < usable_colors_count)
362 color = usable_colors[next_color_i++];
368 s32 textx = x_left + m_log_max_size + 15;
369 s32 textx2 = textx + 200 - 15;
372 for (std::map<std::string, Meta>::const_iterator i = m_meta.begin();
373 i != m_meta.end(); ++i) {
374 const std::string &id = i->first;
375 const Meta &meta = i->second;
377 s32 y = y_bottom - meta_i * 50;
378 float show_min = meta.min;
379 float show_max = meta.max;
381 if (show_min >= -0.0001 && show_max >= -0.0001) {
382 if (show_min <= show_max * 0.5)
388 snprintf(buf, 10, "%.3g", show_max);
389 font->draw(utf8_to_wide(buf).c_str(),
390 core::rect<s32>(textx, y - graphh,
391 textx2, y - graphh + texth),
393 snprintf(buf, 10, "%.3g", show_min);
394 font->draw(utf8_to_wide(buf).c_str(),
395 core::rect<s32>(textx, y - texth,
398 font->draw(utf8_to_wide(id).c_str(),
399 core::rect<s32>(textx, y - graphh / 2 - texth / 2,
400 textx2, y - graphh / 2 + texth / 2),
403 s32 graph1h = graphh;
404 bool relativegraph = (show_min != 0 && show_min != show_max);
405 float lastscaledvalue = 0.0;
406 bool lastscaledvalue_exists = false;
408 for (std::deque<Piece>::const_iterator j = m_log.begin();
409 j != m_log.end(); ++j) {
410 const Piece &piece = *j;
412 bool value_exists = false;
413 Profiler::GraphValues::const_iterator k =
414 piece.values.find(id);
416 if (k != piece.values.end()) {
423 lastscaledvalue_exists = false;
427 float scaledvalue = 1.0;
429 if (show_max != show_min)
430 scaledvalue = (value - show_min) / (show_max - show_min);
432 if (scaledvalue == 1.0 && value == 0) {
434 lastscaledvalue_exists = false;
439 if (lastscaledvalue_exists) {
440 s32 ivalue1 = lastscaledvalue * graph1h;
441 s32 ivalue2 = scaledvalue * graph1h;
442 driver->draw2DLine(v2s32(x - 1, graph1y - ivalue1),
443 v2s32(x, graph1y - ivalue2), meta.color);
446 lastscaledvalue = scaledvalue;
447 lastscaledvalue_exists = true;
449 s32 ivalue = scaledvalue * graph1h;
450 driver->draw2DLine(v2s32(x, graph1y),
451 v2s32(x, graph1y - ivalue), meta.color);
462 class NodeDugEvent: public MtEvent
468 NodeDugEvent(v3s16 p, MapNode n):
472 const char *getType() const
480 ISoundManager *m_sound;
481 INodeDefManager *m_ndef;
483 float m_player_step_timer;
485 SimpleSoundSpec m_player_step_sound;
486 SimpleSoundSpec m_player_leftpunch_sound;
487 SimpleSoundSpec m_player_rightpunch_sound;
489 SoundMaker(ISoundManager *sound, INodeDefManager *ndef):
492 m_player_step_timer(0)
496 void playPlayerStep()
498 if (m_player_step_timer <= 0 && m_player_step_sound.exists()) {
499 m_player_step_timer = 0.03;
500 m_sound->playSound(m_player_step_sound, false);
504 static void viewBobbingStep(MtEvent *e, void *data)
506 SoundMaker *sm = (SoundMaker *)data;
507 sm->playPlayerStep();
510 static void playerRegainGround(MtEvent *e, void *data)
512 SoundMaker *sm = (SoundMaker *)data;
513 sm->playPlayerStep();
516 static void playerJump(MtEvent *e, void *data)
518 //SoundMaker *sm = (SoundMaker*)data;
521 static void cameraPunchLeft(MtEvent *e, void *data)
523 SoundMaker *sm = (SoundMaker *)data;
524 sm->m_sound->playSound(sm->m_player_leftpunch_sound, false);
527 static void cameraPunchRight(MtEvent *e, void *data)
529 SoundMaker *sm = (SoundMaker *)data;
530 sm->m_sound->playSound(sm->m_player_rightpunch_sound, false);
533 static void nodeDug(MtEvent *e, void *data)
535 SoundMaker *sm = (SoundMaker *)data;
536 NodeDugEvent *nde = (NodeDugEvent *)e;
537 sm->m_sound->playSound(sm->m_ndef->get(nde->n).sound_dug, false);
540 static void playerDamage(MtEvent *e, void *data)
542 SoundMaker *sm = (SoundMaker *)data;
543 sm->m_sound->playSound(SimpleSoundSpec("player_damage", 0.5), false);
546 static void playerFallingDamage(MtEvent *e, void *data)
548 SoundMaker *sm = (SoundMaker *)data;
549 sm->m_sound->playSound(SimpleSoundSpec("player_falling_damage", 0.5), false);
552 void registerReceiver(MtEventManager *mgr)
554 mgr->reg("ViewBobbingStep", SoundMaker::viewBobbingStep, this);
555 mgr->reg("PlayerRegainGround", SoundMaker::playerRegainGround, this);
556 mgr->reg("PlayerJump", SoundMaker::playerJump, this);
557 mgr->reg("CameraPunchLeft", SoundMaker::cameraPunchLeft, this);
558 mgr->reg("CameraPunchRight", SoundMaker::cameraPunchRight, this);
559 mgr->reg("NodeDug", SoundMaker::nodeDug, this);
560 mgr->reg("PlayerDamage", SoundMaker::playerDamage, this);
561 mgr->reg("PlayerFallingDamage", SoundMaker::playerFallingDamage, this);
564 void step(float dtime)
566 m_player_step_timer -= dtime;
570 // Locally stored sounds don't need to be preloaded because of this
571 class GameOnDemandSoundFetcher: public OnDemandSoundFetcher
573 std::set<std::string> m_fetched;
575 void fetchSounds(const std::string &name,
576 std::set<std::string> &dst_paths,
577 std::set<std::string> &dst_datas)
579 if (m_fetched.count(name))
582 m_fetched.insert(name);
583 std::string base = porting::path_share + DIR_DELIM + "sounds";
584 dst_paths.insert(base + DIR_DELIM + name + ".ogg");
585 dst_paths.insert(base + DIR_DELIM + name + ".0.ogg");
586 dst_paths.insert(base + DIR_DELIM + name + ".1.ogg");
587 dst_paths.insert(base + DIR_DELIM + name + ".2.ogg");
588 dst_paths.insert(base + DIR_DELIM + name + ".3.ogg");
589 dst_paths.insert(base + DIR_DELIM + name + ".4.ogg");
590 dst_paths.insert(base + DIR_DELIM + name + ".5.ogg");
591 dst_paths.insert(base + DIR_DELIM + name + ".6.ogg");
592 dst_paths.insert(base + DIR_DELIM + name + ".7.ogg");
593 dst_paths.insert(base + DIR_DELIM + name + ".8.ogg");
594 dst_paths.insert(base + DIR_DELIM + name + ".9.ogg");
599 // before 1.8 there isn't a "integer interface", only float
600 #if (IRRLICHT_VERSION_MAJOR == 1 && IRRLICHT_VERSION_MINOR < 8)
601 typedef f32 SamplerLayer_t;
603 typedef s32 SamplerLayer_t;
607 class GameGlobalShaderConstantSetter : public IShaderConstantSetter
610 bool *m_force_fog_off;
613 CachedPixelShaderSetting<float, 4> m_sky_bg_color;
614 CachedPixelShaderSetting<float> m_fog_distance;
615 CachedVertexShaderSetting<float> m_animation_timer_vertex;
616 CachedPixelShaderSetting<float> m_animation_timer_pixel;
617 CachedPixelShaderSetting<float, 3> m_day_light;
618 CachedPixelShaderSetting<float, 3> m_eye_position_pixel;
619 CachedVertexShaderSetting<float, 3> m_eye_position_vertex;
620 CachedPixelShaderSetting<float, 3> m_minimap_yaw;
621 CachedPixelShaderSetting<SamplerLayer_t> m_base_texture;
622 CachedPixelShaderSetting<SamplerLayer_t> m_normal_texture;
623 CachedPixelShaderSetting<SamplerLayer_t> m_texture_flags;
627 void onSettingsChange(const std::string &name)
629 if (name == "enable_fog")
630 m_fog_enabled = g_settings->getBool("enable_fog");
633 static void settingsCallback(const std::string &name, void *userdata)
635 reinterpret_cast<GameGlobalShaderConstantSetter*>(userdata)->onSettingsChange(name);
638 void setSky(Sky *sky) { m_sky = sky; }
640 GameGlobalShaderConstantSetter(Sky *sky, bool *force_fog_off,
641 f32 *fog_range, Client *client) :
643 m_force_fog_off(force_fog_off),
644 m_fog_range(fog_range),
645 m_sky_bg_color("skyBgColor"),
646 m_fog_distance("fogDistance"),
647 m_animation_timer_vertex("animationTimer"),
648 m_animation_timer_pixel("animationTimer"),
649 m_day_light("dayLight"),
650 m_eye_position_pixel("eyePosition"),
651 m_eye_position_vertex("eyePosition"),
652 m_minimap_yaw("yawVec"),
653 m_base_texture("baseTexture"),
654 m_normal_texture("normalTexture"),
655 m_texture_flags("textureFlags"),
658 g_settings->registerChangedCallback("enable_fog", settingsCallback, this);
659 m_fog_enabled = g_settings->getBool("enable_fog");
662 ~GameGlobalShaderConstantSetter()
664 g_settings->deregisterChangedCallback("enable_fog", settingsCallback, this);
667 virtual void onSetConstants(video::IMaterialRendererServices *services,
674 video::SColor bgcolor = m_sky->getBgColor();
675 video::SColorf bgcolorf(bgcolor);
676 float bgcolorfa[4] = {
682 m_sky_bg_color.set(bgcolorfa, services);
685 float fog_distance = 10000 * BS;
687 if (m_fog_enabled && !*m_force_fog_off)
688 fog_distance = *m_fog_range;
690 m_fog_distance.set(&fog_distance, services);
692 u32 daynight_ratio = (float)m_client->getEnv().getDayNightRatio();
693 video::SColorf sunlight;
694 get_sunlight_color(&sunlight, daynight_ratio);
699 m_day_light.set(dnc, services);
701 u32 animation_timer = porting::getTimeMs() % 100000;
702 float animation_timer_f = (float)animation_timer / 100000.f;
703 m_animation_timer_vertex.set(&animation_timer_f, services);
704 m_animation_timer_pixel.set(&animation_timer_f, services);
706 float eye_position_array[3];
707 v3f epos = m_client->getEnv().getLocalPlayer()->getEyePosition();
708 #if (IRRLICHT_VERSION_MAJOR == 1 && IRRLICHT_VERSION_MINOR < 8)
709 eye_position_array[0] = epos.X;
710 eye_position_array[1] = epos.Y;
711 eye_position_array[2] = epos.Z;
713 epos.getAs3Values(eye_position_array);
715 m_eye_position_pixel.set(eye_position_array, services);
716 m_eye_position_vertex.set(eye_position_array, services);
718 float minimap_yaw_array[3];
719 v3f minimap_yaw = m_client->getMinimap()->getYawVec();
720 #if (IRRLICHT_VERSION_MAJOR == 1 && IRRLICHT_VERSION_MINOR < 8)
721 minimap_yaw_array[0] = minimap_yaw.X;
722 minimap_yaw_array[1] = minimap_yaw.Y;
723 minimap_yaw_array[2] = minimap_yaw.Z;
725 minimap_yaw.getAs3Values(minimap_yaw_array);
727 m_minimap_yaw.set(minimap_yaw_array, services);
729 SamplerLayer_t base_tex = 0,
732 m_base_texture.set(&base_tex, services);
733 m_normal_texture.set(&normal_tex, services);
734 m_texture_flags.set(&flags_tex, services);
739 class GameGlobalShaderConstantSetterFactory : public IShaderConstantSetterFactory
742 bool *m_force_fog_off;
745 std::vector<GameGlobalShaderConstantSetter *> created_nosky;
747 GameGlobalShaderConstantSetterFactory(bool *force_fog_off,
748 f32 *fog_range, Client *client) :
750 m_force_fog_off(force_fog_off),
751 m_fog_range(fog_range),
755 void setSky(Sky *sky) {
757 for (size_t i = 0; i < created_nosky.size(); ++i) {
758 created_nosky[i]->setSky(m_sky);
760 created_nosky.clear();
763 virtual IShaderConstantSetter* create()
765 GameGlobalShaderConstantSetter *scs = new GameGlobalShaderConstantSetter(
766 m_sky, m_force_fog_off, m_fog_range, m_client);
768 created_nosky.push_back(scs);
774 bool nodePlacementPrediction(Client &client,
775 const ItemDefinition &playeritem_def, v3s16 nodepos, v3s16 neighbourpos)
777 std::string prediction = playeritem_def.node_placement_prediction;
778 INodeDefManager *nodedef = client.ndef();
779 ClientMap &map = client.getEnv().getClientMap();
781 bool is_valid_position;
783 node = map.getNodeNoEx(nodepos, &is_valid_position);
784 if (!is_valid_position)
787 if (prediction != "" && !nodedef->get(node).rightclickable) {
788 verbosestream << "Node placement prediction for "
789 << playeritem_def.name << " is "
790 << prediction << std::endl;
791 v3s16 p = neighbourpos;
793 // Place inside node itself if buildable_to
794 MapNode n_under = map.getNodeNoEx(nodepos, &is_valid_position);
795 if (is_valid_position)
797 if (nodedef->get(n_under).buildable_to)
800 node = map.getNodeNoEx(p, &is_valid_position);
801 if (is_valid_position &&!nodedef->get(node).buildable_to)
806 // Find id of predicted node
808 bool found = nodedef->getId(prediction, id);
811 errorstream << "Node placement prediction failed for "
812 << playeritem_def.name << " (places "
814 << ") - Name not known" << std::endl;
818 // Predict param2 for facedir and wallmounted nodes
821 if (nodedef->get(id).param_type_2 == CPT2_WALLMOUNTED ||
822 nodedef->get(id).param_type_2 == CPT2_COLORED_WALLMOUNTED) {
823 v3s16 dir = nodepos - neighbourpos;
825 if (abs(dir.Y) > MYMAX(abs(dir.X), abs(dir.Z))) {
826 param2 = dir.Y < 0 ? 1 : 0;
827 } else if (abs(dir.X) > abs(dir.Z)) {
828 param2 = dir.X < 0 ? 3 : 2;
830 param2 = dir.Z < 0 ? 5 : 4;
834 if (nodedef->get(id).param_type_2 == CPT2_FACEDIR ||
835 nodedef->get(id).param_type_2 == CPT2_COLORED_FACEDIR) {
836 v3s16 dir = nodepos - floatToInt(client.getEnv().getLocalPlayer()->getPosition(), BS);
838 if (abs(dir.X) > abs(dir.Z)) {
839 param2 = dir.X < 0 ? 3 : 1;
841 param2 = dir.Z < 0 ? 2 : 0;
847 //Check attachment if node is in group attached_node
848 if (((ItemGroupList) nodedef->get(id).groups)["attached_node"] != 0) {
849 static v3s16 wallmounted_dirs[8] = {
859 if (nodedef->get(id).param_type_2 == CPT2_WALLMOUNTED ||
860 nodedef->get(id).param_type_2 == CPT2_COLORED_WALLMOUNTED)
861 pp = p + wallmounted_dirs[param2];
863 pp = p + v3s16(0, -1, 0);
865 if (!nodedef->get(map.getNodeNoEx(pp)).walkable)
869 // Add node to client map
870 MapNode n(id, 0, param2);
873 LocalPlayer *player = client.getEnv().getLocalPlayer();
875 // Dont place node when player would be inside new node
876 // NOTE: This is to be eventually implemented by a mod as client-side Lua
877 if (!nodedef->get(n).walkable ||
878 g_settings->getBool("enable_build_where_you_stand") ||
879 (client.checkPrivilege("noclip") && g_settings->getBool("noclip")) ||
880 (nodedef->get(n).walkable &&
881 neighbourpos != player->getStandingNodePos() + v3s16(0, 1, 0) &&
882 neighbourpos != player->getStandingNodePos() + v3s16(0, 2, 0))) {
884 // This triggers the required mesh update too
885 client.addNode(p, n);
888 } catch (InvalidPositionException &e) {
889 errorstream << "Node placement prediction failed for "
890 << playeritem_def.name << " (places "
892 << ") - Position not loaded" << std::endl;
899 static inline void create_formspec_menu(GUIFormSpecMenu **cur_formspec,
900 Client *client, IrrlichtDevice *device, JoystickController *joystick,
901 IFormSource *fs_src, TextDest *txt_dest)
904 if (*cur_formspec == 0) {
905 *cur_formspec = new GUIFormSpecMenu(device, joystick,
906 guiroot, -1, &g_menumgr, client, client->getTextureSource(),
908 (*cur_formspec)->doPause = false;
911 Caution: do not call (*cur_formspec)->drop() here --
912 the reference might outlive the menu, so we will
913 periodically check if *cur_formspec is the only
914 remaining reference (i.e. the menu was removed)
915 and delete it in that case.
919 (*cur_formspec)->setFormSource(fs_src);
920 (*cur_formspec)->setTextDest(txt_dest);
926 #define SIZE_TAG "size[11,5.5]"
928 #define SIZE_TAG "size[11,5.5,true]" // Fixed size on desktop
931 /******************************************************************************/
932 static void updateChat(Client &client, f32 dtime, bool show_debug,
933 const v2u32 &screensize, bool show_chat, u32 show_profiler,
934 ChatBackend &chat_backend, gui::IGUIStaticText *guitext_chat)
936 // Add chat log output for errors to be shown in chat
937 static LogOutputBuffer chat_log_error_buf(g_logger, LL_ERROR);
939 // Get new messages from error log buffer
940 while (!chat_log_error_buf.empty()) {
941 std::wstring error_message = utf8_to_wide(chat_log_error_buf.get());
942 if (!g_settings->getBool("disable_escape_sequences")) {
943 error_message = L"\x1b(c@red)" + error_message + L"\x1b(c@white)";
945 chat_backend.addMessage(L"", error_message);
948 // Get new messages from client
949 std::wstring message;
951 while (client.getChatMessage(message)) {
952 chat_backend.addUnparsedMessage(message);
955 // Remove old messages
956 chat_backend.step(dtime);
958 // Display all messages in a static text element
959 unsigned int recent_chat_count = chat_backend.getRecentBuffer().getLineCount();
960 EnrichedString recent_chat = chat_backend.getRecentChat();
961 unsigned int line_height = g_fontengine->getLineHeight();
963 setStaticText(guitext_chat, recent_chat);
965 // Update gui element size and position
969 chat_y += 2 * line_height;
971 // first pass to calculate height of text to be set
972 s32 width = std::min(g_fontengine->getTextWidth(recent_chat.c_str()) + 10,
973 porting::getWindowSize().X - 20);
974 core::rect<s32> rect(10, chat_y, width, chat_y + porting::getWindowSize().Y);
975 guitext_chat->setRelativePosition(rect);
977 //now use real height of text and adjust rect according to this size
978 rect = core::rect<s32>(10, chat_y, width,
979 chat_y + guitext_chat->getTextHeight());
982 guitext_chat->setRelativePosition(rect);
983 // Don't show chat if disabled or empty or profiler is enabled
984 guitext_chat->setVisible(
985 show_chat && recent_chat_count != 0 && !show_profiler);
989 /****************************************************************************
990 Fast key cache for main game loop
991 ****************************************************************************/
993 /* This is faster than using getKeySetting with the tradeoff that functions
994 * using it must make sure that it's initialised before using it and there is
995 * no error handling (for example bounds checking). This is really intended for
996 * use only in the main running loop of the client (the_game()) where the faster
997 * (up to 10x faster) key lookup is an asset. Other parts of the codebase
998 * (e.g. formspecs) should continue using getKeySetting().
1006 populate_nonchanging();
1011 // Keys that are not settings dependent
1012 void populate_nonchanging();
1014 KeyPress key[KeyType::INTERNAL_ENUM_COUNT];
1015 InputHandler *handler;
1018 void KeyCache::populate_nonchanging()
1020 key[KeyType::ESC] = EscapeKey;
1023 void KeyCache::populate()
1025 key[KeyType::FORWARD] = getKeySetting("keymap_forward");
1026 key[KeyType::BACKWARD] = getKeySetting("keymap_backward");
1027 key[KeyType::LEFT] = getKeySetting("keymap_left");
1028 key[KeyType::RIGHT] = getKeySetting("keymap_right");
1029 key[KeyType::JUMP] = getKeySetting("keymap_jump");
1030 key[KeyType::SPECIAL1] = getKeySetting("keymap_special1");
1031 key[KeyType::SNEAK] = getKeySetting("keymap_sneak");
1033 key[KeyType::AUTORUN] = getKeySetting("keymap_autorun");
1035 key[KeyType::DROP] = getKeySetting("keymap_drop");
1036 key[KeyType::INVENTORY] = getKeySetting("keymap_inventory");
1037 key[KeyType::CHAT] = getKeySetting("keymap_chat");
1038 key[KeyType::CMD] = getKeySetting("keymap_cmd");
1039 key[KeyType::CMD_LOCAL] = getKeySetting("keymap_cmd_local");
1040 key[KeyType::CONSOLE] = getKeySetting("keymap_console");
1041 key[KeyType::MINIMAP] = getKeySetting("keymap_minimap");
1042 key[KeyType::FREEMOVE] = getKeySetting("keymap_freemove");
1043 key[KeyType::FASTMOVE] = getKeySetting("keymap_fastmove");
1044 key[KeyType::NOCLIP] = getKeySetting("keymap_noclip");
1045 key[KeyType::CINEMATIC] = getKeySetting("keymap_cinematic");
1046 key[KeyType::SCREENSHOT] = getKeySetting("keymap_screenshot");
1047 key[KeyType::TOGGLE_HUD] = getKeySetting("keymap_toggle_hud");
1048 key[KeyType::TOGGLE_CHAT] = getKeySetting("keymap_toggle_chat");
1049 key[KeyType::TOGGLE_FORCE_FOG_OFF]
1050 = getKeySetting("keymap_toggle_force_fog_off");
1051 key[KeyType::TOGGLE_UPDATE_CAMERA]
1052 = getKeySetting("keymap_toggle_update_camera");
1053 key[KeyType::TOGGLE_DEBUG]
1054 = getKeySetting("keymap_toggle_debug");
1055 key[KeyType::TOGGLE_PROFILER]
1056 = getKeySetting("keymap_toggle_profiler");
1057 key[KeyType::CAMERA_MODE]
1058 = getKeySetting("keymap_camera_mode");
1059 key[KeyType::INCREASE_VIEWING_RANGE]
1060 = getKeySetting("keymap_increase_viewing_range_min");
1061 key[KeyType::DECREASE_VIEWING_RANGE]
1062 = getKeySetting("keymap_decrease_viewing_range_min");
1063 key[KeyType::RANGESELECT]
1064 = getKeySetting("keymap_rangeselect");
1065 key[KeyType::ZOOM] = getKeySetting("keymap_zoom");
1067 key[KeyType::QUICKTUNE_NEXT] = getKeySetting("keymap_quicktune_next");
1068 key[KeyType::QUICKTUNE_PREV] = getKeySetting("keymap_quicktune_prev");
1069 key[KeyType::QUICKTUNE_INC] = getKeySetting("keymap_quicktune_inc");
1070 key[KeyType::QUICKTUNE_DEC] = getKeySetting("keymap_quicktune_dec");
1072 key[KeyType::DEBUG_STACKS] = getKeySetting("keymap_print_debug_stacks");
1075 // First clear all keys, then re-add the ones we listen for
1076 handler->dontListenForKeys();
1077 for (size_t i = 0; i < KeyType::INTERNAL_ENUM_COUNT; i++) {
1078 handler->listenForKey(key[i]);
1080 handler->listenForKey(EscapeKey);
1081 handler->listenForKey(CancelKey);
1082 for (size_t i = 0; i < 10; i++) {
1083 handler->listenForKey(NumberKey[i]);
1089 /****************************************************************************
1091 ****************************************************************************/
1093 const float object_hit_delay = 0.2;
1096 u32 last_time, busy_time, sleep_time;
1100 /* The reason the following structs are not anonymous structs within the
1101 * class is that they are not used by the majority of member functions and
1102 * many functions that do require objects of thse types do not modify them
1103 * (so they can be passed as a const qualified parameter)
1105 struct CameraOrientation {
1106 f32 camera_yaw; // "right/left"
1107 f32 camera_pitch; // "up/down"
1110 struct GameRunData {
1113 PointedThing pointed_old;
1117 bool update_wielded_item_trigger;
1118 bool reset_jump_timer;
1119 float nodig_delay_timer;
1121 float dig_time_complete;
1122 float repeat_rightclick_timer;
1123 float object_hit_delay_timer;
1124 float time_from_last_punch;
1125 ClientActiveObject *selected_object;
1129 float update_draw_list_timer;
1130 float statustext_time;
1134 v3f update_draw_list_last_cam_dir;
1136 u32 profiler_current_page;
1137 u32 profiler_max_page; // Number of pages
1140 float time_of_day_smooth;
1144 f32 max, min, avg, counter, max_sample, min_sample, max_fraction;
1150 Jitter dtime_jitter, busy_time_jitter;
1153 /****************************************************************************
1155 ****************************************************************************/
1157 /* This is not intended to be a public class. If a public class becomes
1158 * desirable then it may be better to create another 'wrapper' class that
1159 * hides most of the stuff in this class (nothing in this class is required
1160 * by any other file) but exposes the public methods/data only.
1167 bool startup(bool *kill,
1169 InputHandler *input,
1170 IrrlichtDevice *device,
1171 const std::string &map_dir,
1172 const std::string &playername,
1173 const std::string &password,
1174 // If address is "", local server is used and address is updated
1175 std::string *address,
1177 std::string &error_message,
1179 ChatBackend *chat_backend,
1180 const SubgameSpec &gamespec, // Used for local game
1181 bool simple_singleplayer_mode);
1188 void extendedResourceCleanup();
1190 // Basic initialisation
1191 bool init(const std::string &map_dir, std::string *address,
1193 const SubgameSpec &gamespec);
1195 bool createSingleplayerServer(const std::string &map_dir,
1196 const SubgameSpec &gamespec, u16 port, std::string *address);
1199 bool createClient(const std::string &playername,
1200 const std::string &password, std::string *address, u16 port);
1203 // Client connection
1204 bool connectToServer(const std::string &playername,
1205 const std::string &password, std::string *address, u16 port,
1206 bool *connect_ok, bool *aborted);
1207 bool getServerContent(bool *aborted);
1211 void updateInteractTimers(f32 dtime);
1212 bool checkConnection();
1213 bool handleCallbacks();
1214 void processQueues();
1215 void updateProfilers(const RunStats &stats, const FpsControl &draw_times, f32 dtime);
1216 void addProfilerGraphs(const RunStats &stats, const FpsControl &draw_times, f32 dtime);
1217 void updateStats(RunStats *stats, const FpsControl &draw_times, f32 dtime);
1220 void processUserInput(f32 dtime);
1221 void processKeyInput();
1222 void processItemSelection(u16 *new_playeritem);
1224 void dropSelectedItem();
1225 void openInventory();
1226 void openConsole(float scale, const wchar_t *line=NULL);
1227 void toggleFreeMove();
1228 void toggleFreeMoveAlt();
1230 void toggleNoClip();
1231 void toggleCinematic();
1232 void toggleAutorun();
1236 void toggleMinimap(bool shift_pressed);
1239 void toggleUpdateCamera();
1240 void toggleProfiler();
1242 void increaseViewRange();
1243 void decreaseViewRange();
1244 void toggleFullViewRange();
1246 void updateCameraDirection(CameraOrientation *cam, float dtime);
1247 void updateCameraOrientation(CameraOrientation *cam, float dtime);
1248 void updatePlayerControl(const CameraOrientation &cam);
1249 void step(f32 *dtime);
1250 void processClientEvents(CameraOrientation *cam);
1251 void updateCamera(u32 busy_time, f32 dtime);
1252 void updateSound(f32 dtime);
1253 void processPlayerInteraction(f32 dtime, bool show_hud, bool show_debug);
1255 * Returns the object or node the player is pointing at.
1256 * Also updates the selected thing in the Hud.
1258 * @param[in] shootline the shootline, starting from
1259 * the camera position. This also gives the maximal distance
1261 * @param[in] liquids_pointable if false, liquids are ignored
1262 * @param[in] look_for_object if false, objects are ignored
1263 * @param[in] camera_offset offset of the camera
1264 * @param[out] selected_object the selected object or
1267 PointedThing updatePointedThing(
1268 const core::line3d<f32> &shootline, bool liquids_pointable,
1269 bool look_for_object, const v3s16 &camera_offset);
1270 void handlePointingAtNothing(const ItemStack &playerItem);
1271 void handlePointingAtNode(const PointedThing &pointed, const ItemDefinition &playeritem_def,
1272 const ToolCapabilities &playeritem_toolcap, f32 dtime);
1273 void handlePointingAtObject(const PointedThing &pointed, const ItemStack &playeritem,
1274 const v3f &player_position, bool show_debug);
1275 void handleDigging(const PointedThing &pointed, const v3s16 &nodepos,
1276 const ToolCapabilities &playeritem_toolcap, f32 dtime);
1277 void updateFrame(ProfilerGraph *graph, RunStats *stats, f32 dtime,
1278 const CameraOrientation &cam);
1279 void updateGui(const RunStats &stats, f32 dtime, const CameraOrientation &cam);
1280 void updateProfilerGraphs(ProfilerGraph *graph);
1283 void limitFps(FpsControl *fps_timings, f32 *dtime);
1285 void showOverlayMessage(const wchar_t *msg, float dtime, int percent,
1286 bool draw_clouds = true);
1288 static void settingChangedCallback(const std::string &setting_name, void *data);
1289 void readSettings();
1291 inline bool getLeftClicked()
1293 return input->getLeftClicked() ||
1294 input->joystick.getWasKeyDown(KeyType::MOUSE_L);
1296 inline bool getRightClicked()
1298 return input->getRightClicked() ||
1299 input->joystick.getWasKeyDown(KeyType::MOUSE_R);
1301 inline bool isLeftPressed()
1303 return input->getLeftState() ||
1304 input->joystick.isKeyDown(KeyType::MOUSE_L);
1306 inline bool isRightPressed()
1308 return input->getRightState() ||
1309 input->joystick.isKeyDown(KeyType::MOUSE_R);
1311 inline bool getLeftReleased()
1313 return input->getLeftReleased() ||
1314 input->joystick.wasKeyReleased(KeyType::MOUSE_L);
1317 inline bool isKeyDown(GameKeyType k)
1319 return input->isKeyDown(keycache.key[k]) || input->joystick.isKeyDown(k);
1321 inline bool wasKeyDown(GameKeyType k)
1323 return input->wasKeyDown(keycache.key[k]) || input->joystick.wasKeyDown(k);
1327 void handleAndroidChatInput();
1331 void showPauseMenu();
1333 InputHandler *input;
1338 IWritableTextureSource *texture_src;
1339 IWritableShaderSource *shader_src;
1341 // When created, these will be filled with data received from the server
1342 IWritableItemDefManager *itemdef_manager;
1343 IWritableNodeDefManager *nodedef_manager;
1345 GameOnDemandSoundFetcher soundfetcher; // useful when testing
1346 ISoundManager *sound;
1347 bool sound_is_dummy;
1348 SoundMaker *soundmaker;
1350 ChatBackend *chat_backend;
1352 GUIFormSpecMenu *current_formspec;
1353 //default: "". If other than "", empty show_formspec packets will only close the formspec when the formname matches
1354 std::string cur_formname;
1356 EventManager *eventmgr;
1357 QuicktuneShortcutter *quicktune;
1359 GUIChatConsole *gui_chat_console; // Free using ->Drop()
1360 MapDrawControl *draw_control;
1362 Clouds *clouds; // Free using ->Drop()
1363 Sky *sky; // Free using ->Drop()
1364 Inventory *local_inventory;
1368 GameRunData runData;
1372 This class does take ownership/responsibily for cleaning up etc of any of
1373 these items (e.g. device)
1375 IrrlichtDevice *device;
1376 video::IVideoDriver *driver;
1377 scene::ISceneManager *smgr;
1379 std::string *error_message;
1380 bool *reconnect_requested;
1381 scene::ISceneNode *skybox;
1384 bool simple_singleplayer_mode;
1387 /* Pre-calculated values
1389 int crack_animation_length;
1393 gui::IGUIStaticText *guitext; // First line of debug text
1394 gui::IGUIStaticText *guitext2; // Second line of debug text
1395 gui::IGUIStaticText *guitext_info; // At the middle of the screen
1396 gui::IGUIStaticText *guitext_status;
1397 gui::IGUIStaticText *guitext_chat; // Chat text
1398 gui::IGUIStaticText *guitext_profiler; // Profiler text
1400 std::wstring infotext;
1401 std::wstring m_statustext;
1405 IntervalLimiter profiler_interval;
1408 * TODO: Local caching of settings is not optimal and should at some stage
1409 * be updated to use a global settings object for getting thse values
1410 * (as opposed to the this local caching). This can be addressed in
1413 bool m_cache_doubletap_jump;
1414 bool m_cache_enable_clouds;
1415 bool m_cache_enable_joysticks;
1416 bool m_cache_enable_particles;
1417 bool m_cache_enable_fog;
1418 bool m_cache_enable_noclip;
1419 bool m_cache_enable_free_move;
1420 f32 m_cache_mouse_sensitivity;
1421 f32 m_cache_joystick_frustum_sensitivity;
1422 f32 m_repeat_right_click_time;
1423 f32 m_cache_cam_smoothing;
1424 f32 m_cache_fog_start;
1426 bool m_invert_mouse;
1427 bool m_first_loop_after_window_activation;
1428 bool m_camera_offset_changed;
1431 bool m_cache_hold_aux1;
1432 bool m_android_chat_open;
1441 itemdef_manager(NULL),
1442 nodedef_manager(NULL),
1444 sound_is_dummy(false),
1447 current_formspec(NULL),
1451 gui_chat_console(NULL),
1456 local_inventory(NULL),
1459 m_invert_mouse(false),
1460 m_first_loop_after_window_activation(false),
1461 m_camera_offset_changed(false)
1463 g_settings->registerChangedCallback("doubletap_jump",
1464 &settingChangedCallback, this);
1465 g_settings->registerChangedCallback("enable_clouds",
1466 &settingChangedCallback, this);
1467 g_settings->registerChangedCallback("doubletap_joysticks",
1468 &settingChangedCallback, this);
1469 g_settings->registerChangedCallback("enable_particles",
1470 &settingChangedCallback, this);
1471 g_settings->registerChangedCallback("enable_fog",
1472 &settingChangedCallback, this);
1473 g_settings->registerChangedCallback("mouse_sensitivity",
1474 &settingChangedCallback, this);
1475 g_settings->registerChangedCallback("joystick_frustum_sensitivity",
1476 &settingChangedCallback, this);
1477 g_settings->registerChangedCallback("repeat_rightclick_time",
1478 &settingChangedCallback, this);
1479 g_settings->registerChangedCallback("noclip",
1480 &settingChangedCallback, this);
1481 g_settings->registerChangedCallback("free_move",
1482 &settingChangedCallback, this);
1483 g_settings->registerChangedCallback("cinematic",
1484 &settingChangedCallback, this);
1485 g_settings->registerChangedCallback("cinematic_camera_smoothing",
1486 &settingChangedCallback, this);
1487 g_settings->registerChangedCallback("camera_smoothing",
1488 &settingChangedCallback, this);
1493 m_cache_hold_aux1 = false; // This is initialised properly later
1500 /****************************************************************************
1502 ****************************************************************************/
1508 if (!sound_is_dummy)
1511 delete server; // deleted first to stop all server threads
1514 delete local_inventory;
1520 delete nodedef_manager;
1521 delete itemdef_manager;
1522 delete draw_control;
1524 extendedResourceCleanup();
1526 g_settings->deregisterChangedCallback("doubletap_jump",
1527 &settingChangedCallback, this);
1528 g_settings->deregisterChangedCallback("enable_clouds",
1529 &settingChangedCallback, this);
1530 g_settings->deregisterChangedCallback("enable_particles",
1531 &settingChangedCallback, this);
1532 g_settings->deregisterChangedCallback("enable_fog",
1533 &settingChangedCallback, this);
1534 g_settings->deregisterChangedCallback("mouse_sensitivity",
1535 &settingChangedCallback, this);
1536 g_settings->deregisterChangedCallback("repeat_rightclick_time",
1537 &settingChangedCallback, this);
1538 g_settings->deregisterChangedCallback("noclip",
1539 &settingChangedCallback, this);
1540 g_settings->deregisterChangedCallback("free_move",
1541 &settingChangedCallback, this);
1542 g_settings->deregisterChangedCallback("cinematic",
1543 &settingChangedCallback, this);
1544 g_settings->deregisterChangedCallback("cinematic_camera_smoothing",
1545 &settingChangedCallback, this);
1546 g_settings->deregisterChangedCallback("camera_smoothing",
1547 &settingChangedCallback, this);
1550 bool Game::startup(bool *kill,
1552 InputHandler *input,
1553 IrrlichtDevice *device,
1554 const std::string &map_dir,
1555 const std::string &playername,
1556 const std::string &password,
1557 std::string *address, // can change if simple_singleplayer_mode
1559 std::string &error_message,
1561 ChatBackend *chat_backend,
1562 const SubgameSpec &gamespec,
1563 bool simple_singleplayer_mode)
1566 this->device = device;
1568 this->error_message = &error_message;
1569 this->reconnect_requested = reconnect;
1570 this->random_input = random_input;
1571 this->input = input;
1572 this->chat_backend = chat_backend;
1573 this->simple_singleplayer_mode = simple_singleplayer_mode;
1575 keycache.handler = input;
1576 keycache.populate();
1578 driver = device->getVideoDriver();
1579 smgr = device->getSceneManager();
1581 smgr->getParameters()->setAttribute(scene::OBJ_LOADER_IGNORE_MATERIAL_FILES, true);
1583 memset(&runData, 0, sizeof(runData));
1584 runData.time_from_last_punch = 10.0;
1585 runData.profiler_max_page = 3;
1586 runData.update_wielded_item_trigger = true;
1588 memset(&flags, 0, sizeof(flags));
1589 flags.show_chat = true;
1590 flags.show_hud = true;
1591 flags.show_debug = g_settings->getBool("show_debug");
1592 m_invert_mouse = g_settings->getBool("invert_mouse");
1593 m_first_loop_after_window_activation = true;
1595 if (!init(map_dir, address, port, gamespec))
1598 if (!createClient(playername, password, address, port))
1607 ProfilerGraph graph;
1608 RunStats stats = { 0 };
1609 CameraOrientation cam_view_target = { 0 };
1610 CameraOrientation cam_view = { 0 };
1611 FpsControl draw_times = { 0 };
1612 f32 dtime; // in seconds
1614 /* Clear the profiler */
1615 Profiler::GraphValues dummyvalues;
1616 g_profiler->graphGet(dummyvalues);
1618 draw_times.last_time = device->getTimer()->getTime();
1620 set_light_table(g_settings->getFloat("display_gamma"));
1623 m_cache_hold_aux1 = g_settings->getBool("fast_move")
1624 && client->checkPrivilege("fast");
1627 while (device->run()
1628 && !(*kill || g_gamecallback->shutdown_requested
1629 || (server && server->getShutdownRequested()))) {
1631 /* Must be called immediately after a device->run() call because it
1632 * uses device->getTimer()->getTime()
1634 limitFps(&draw_times, &dtime);
1636 updateStats(&stats, draw_times, dtime);
1637 updateInteractTimers(dtime);
1639 if (!checkConnection())
1641 if (!handleCallbacks())
1647 hud->resizeHotbar();
1649 updateProfilers(stats, draw_times, dtime);
1650 processUserInput(dtime);
1651 // Update camera before player movement to avoid camera lag of one frame
1652 updateCameraDirection(&cam_view_target, dtime);
1653 cam_view.camera_yaw += (cam_view_target.camera_yaw -
1654 cam_view.camera_yaw) * m_cache_cam_smoothing;
1655 cam_view.camera_pitch += (cam_view_target.camera_pitch -
1656 cam_view.camera_pitch) * m_cache_cam_smoothing;
1657 updatePlayerControl(cam_view);
1659 processClientEvents(&cam_view_target);
1660 updateCamera(draw_times.busy_time, dtime);
1662 processPlayerInteraction(dtime, flags.show_hud, flags.show_debug);
1663 updateFrame(&graph, &stats, dtime, cam_view);
1664 updateProfilerGraphs(&graph);
1666 // Update if minimap has been disabled by the server
1667 flags.show_minimap &= client->shouldShowMinimap();
1672 void Game::shutdown()
1674 #if IRRLICHT_VERSION_MAJOR == 1 && IRRLICHT_VERSION_MINOR <= 8
1675 if (g_settings->get("3d_mode") == "pageflip") {
1676 driver->setRenderTarget(irr::video::ERT_STEREO_BOTH_BUFFERS);
1680 showOverlayMessage(wgettext("Shutting down..."), 0, 0, false);
1685 if (gui_chat_console)
1686 gui_chat_console->drop();
1692 while (g_menumgr.menuCount() > 0) {
1693 g_menumgr.m_stack.front()->setVisible(false);
1694 g_menumgr.deletingMenu(g_menumgr.m_stack.front());
1697 if (current_formspec) {
1698 current_formspec->drop();
1699 current_formspec = NULL;
1702 chat_backend->addMessage(L"", L"# Disconnected.");
1703 chat_backend->addMessage(L"", L"");
1707 while (!client->isShutdown()) {
1708 assert(texture_src != NULL);
1709 assert(shader_src != NULL);
1710 texture_src->processQueue();
1711 shader_src->processQueue();
1718 /****************************************************************************/
1719 /****************************************************************************
1721 ****************************************************************************/
1722 /****************************************************************************/
1725 const std::string &map_dir,
1726 std::string *address,
1728 const SubgameSpec &gamespec)
1730 texture_src = createTextureSource(device);
1732 showOverlayMessage(wgettext("Loading..."), 0, 0);
1734 shader_src = createShaderSource(device);
1736 itemdef_manager = createItemDefManager();
1737 nodedef_manager = createNodeDefManager();
1739 eventmgr = new EventManager();
1740 quicktune = new QuicktuneShortcutter();
1742 if (!(texture_src && shader_src && itemdef_manager && nodedef_manager
1743 && eventmgr && quicktune))
1749 // Create a server if not connecting to an existing one
1750 if (*address == "") {
1751 if (!createSingleplayerServer(map_dir, gamespec, port, address))
1758 bool Game::initSound()
1761 if (g_settings->getBool("enable_sound")) {
1762 infostream << "Attempting to use OpenAL audio" << std::endl;
1763 sound = createOpenALSoundManager(&soundfetcher);
1765 infostream << "Failed to initialize OpenAL audio" << std::endl;
1767 infostream << "Sound disabled." << std::endl;
1771 infostream << "Using dummy audio." << std::endl;
1772 sound = &dummySoundManager;
1773 sound_is_dummy = true;
1776 soundmaker = new SoundMaker(sound, nodedef_manager);
1780 soundmaker->registerReceiver(eventmgr);
1785 bool Game::createSingleplayerServer(const std::string &map_dir,
1786 const SubgameSpec &gamespec, u16 port, std::string *address)
1788 showOverlayMessage(wgettext("Creating server..."), 0, 5);
1790 std::string bind_str = g_settings->get("bind_address");
1791 Address bind_addr(0, 0, 0, 0, port);
1793 if (g_settings->getBool("ipv6_server")) {
1794 bind_addr.setAddress((IPv6AddressBytes *) NULL);
1798 bind_addr.Resolve(bind_str.c_str());
1799 } catch (ResolveError &e) {
1800 infostream << "Resolving bind address \"" << bind_str
1801 << "\" failed: " << e.what()
1802 << " -- Listening on all addresses." << std::endl;
1805 if (bind_addr.isIPv6() && !g_settings->getBool("enable_ipv6")) {
1806 *error_message = "Unable to listen on " +
1807 bind_addr.serializeString() +
1808 " because IPv6 is disabled";
1809 errorstream << *error_message << std::endl;
1813 server = new Server(map_dir, gamespec, simple_singleplayer_mode,
1814 bind_addr.isIPv6(), false);
1816 server->start(bind_addr);
1821 bool Game::createClient(const std::string &playername,
1822 const std::string &password, std::string *address, u16 port)
1824 showOverlayMessage(wgettext("Creating client..."), 0, 10);
1826 draw_control = new MapDrawControl;
1830 bool could_connect, connect_aborted;
1832 if (!connectToServer(playername, password, address, port,
1833 &could_connect, &connect_aborted))
1836 if (!could_connect) {
1837 if (error_message->empty() && !connect_aborted) {
1838 // Should not happen if error messages are set properly
1839 *error_message = "Connection failed for unknown reason";
1840 errorstream << *error_message << std::endl;
1845 if (!getServerContent(&connect_aborted)) {
1846 if (error_message->empty() && !connect_aborted) {
1847 // Should not happen if error messages are set properly
1848 *error_message = "Connection failed for unknown reason";
1849 errorstream << *error_message << std::endl;
1854 GameGlobalShaderConstantSetterFactory *scsf = new GameGlobalShaderConstantSetterFactory(
1855 &flags.force_fog_off, &runData.fog_range, client);
1856 shader_src->addShaderConstantSetterFactory(scsf);
1858 // Update cached textures, meshes and materials
1859 client->afterContentReceived(device);
1863 camera = new Camera(smgr, *draw_control, client);
1864 if (!camera || !camera->successfullyCreated(*error_message))
1866 client->setCamera(camera);
1870 if (m_cache_enable_clouds) {
1871 clouds = new Clouds(smgr->getRootSceneNode(), smgr, -1, time(0));
1873 *error_message = "Memory allocation error (clouds)";
1874 errorstream << *error_message << std::endl;
1881 sky = new Sky(smgr->getRootSceneNode(), smgr, -1, texture_src);
1883 skybox = NULL; // This is used/set later on in the main run loop
1885 local_inventory = new Inventory(itemdef_manager);
1887 if (!(sky && local_inventory)) {
1888 *error_message = "Memory allocation error (sky or local inventory)";
1889 errorstream << *error_message << std::endl;
1893 /* Pre-calculated values
1895 video::ITexture *t = texture_src->getTexture("crack_anylength.png");
1897 v2u32 size = t->getOriginalSize();
1898 crack_animation_length = size.Y / size.X;
1900 crack_animation_length = 5;
1906 /* Set window caption
1908 std::wstring str = utf8_to_wide(PROJECT_NAME_C);
1910 str += utf8_to_wide(g_version_hash);
1912 str += driver->getName();
1914 device->setWindowCaption(str.c_str());
1916 LocalPlayer *player = client->getEnv().getLocalPlayer();
1917 player->hurt_tilt_timer = 0;
1918 player->hurt_tilt_strength = 0;
1920 hud = new Hud(driver, smgr, guienv, client, player, local_inventory);
1923 *error_message = "Memory error: could not create HUD";
1924 errorstream << *error_message << std::endl;
1928 mapper = client->getMinimap();
1929 mapper->setMinimapMode(MINIMAP_MODE_OFF);
1934 bool Game::initGui()
1936 // First line of debug text
1937 guitext = addStaticText(guienv,
1938 utf8_to_wide(PROJECT_NAME_C).c_str(),
1939 core::rect<s32>(0, 0, 0, 0),
1940 false, false, guiroot);
1942 // Second line of debug text
1943 guitext2 = addStaticText(guienv,
1945 core::rect<s32>(0, 0, 0, 0),
1946 false, false, guiroot);
1948 // At the middle of the screen
1949 // Object infos are shown in this
1950 guitext_info = addStaticText(guienv,
1952 core::rect<s32>(0, 0, 400, g_fontengine->getTextHeight() * 5 + 5) + v2s32(100, 200),
1953 false, true, guiroot);
1955 // Status text (displays info when showing and hiding GUI stuff, etc.)
1956 guitext_status = addStaticText(guienv,
1958 core::rect<s32>(0, 0, 0, 0),
1959 false, false, guiroot);
1960 guitext_status->setVisible(false);
1963 guitext_chat = addStaticText(
1966 core::rect<s32>(0, 0, 0, 0),
1967 //false, false); // Disable word wrap as of now
1968 false, true, guiroot);
1970 // Remove stale "recent" chat messages from previous connections
1971 chat_backend->clearRecentChat();
1973 // Chat backend and console
1974 gui_chat_console = new GUIChatConsole(guienv, guienv->getRootGUIElement(),
1975 -1, chat_backend, client, &g_menumgr);
1976 if (!gui_chat_console) {
1977 *error_message = "Could not allocate memory for chat console";
1978 errorstream << *error_message << std::endl;
1982 // Profiler text (size is updated when text is updated)
1983 guitext_profiler = addStaticText(guienv,
1985 core::rect<s32>(0, 0, 0, 0),
1986 false, false, guiroot);
1987 guitext_profiler->setBackgroundColor(video::SColor(120, 0, 0, 0));
1988 guitext_profiler->setVisible(false);
1989 guitext_profiler->setWordWrap(true);
1991 #ifdef HAVE_TOUCHSCREENGUI
1993 if (g_touchscreengui)
1994 g_touchscreengui->init(texture_src);
2001 bool Game::connectToServer(const std::string &playername,
2002 const std::string &password, std::string *address, u16 port,
2003 bool *connect_ok, bool *aborted)
2005 *connect_ok = false; // Let's not be overly optimistic
2007 bool local_server_mode = false;
2009 showOverlayMessage(wgettext("Resolving address..."), 0, 15);
2011 Address connect_address(0, 0, 0, 0, port);
2014 connect_address.Resolve(address->c_str());
2016 if (connect_address.isZero()) { // i.e. INADDR_ANY, IN6ADDR_ANY
2017 //connect_address.Resolve("localhost");
2018 if (connect_address.isIPv6()) {
2019 IPv6AddressBytes addr_bytes;
2020 addr_bytes.bytes[15] = 1;
2021 connect_address.setAddress(&addr_bytes);
2023 connect_address.setAddress(127, 0, 0, 1);
2025 local_server_mode = true;
2027 } catch (ResolveError &e) {
2028 *error_message = std::string("Couldn't resolve address: ") + e.what();
2029 errorstream << *error_message << std::endl;
2033 if (connect_address.isIPv6() && !g_settings->getBool("enable_ipv6")) {
2034 *error_message = "Unable to connect to " +
2035 connect_address.serializeString() +
2036 " because IPv6 is disabled";
2037 errorstream << *error_message << std::endl;
2041 client = new Client(device,
2042 playername.c_str(), password,
2043 *draw_control, texture_src, shader_src,
2044 itemdef_manager, nodedef_manager, sound, eventmgr,
2045 connect_address.isIPv6(), &flags);
2050 infostream << "Connecting to server at ";
2051 connect_address.print(&infostream);
2052 infostream << std::endl;
2054 client->connect(connect_address, *address,
2055 simple_singleplayer_mode || local_server_mode);
2058 Wait for server to accept connection
2064 FpsControl fps_control = { 0 };
2066 f32 wait_time = 0; // in seconds
2068 fps_control.last_time = device->getTimer()->getTime();
2072 while (device->run()) {
2074 limitFps(&fps_control, &dtime);
2076 // Update client and server
2077 client->step(dtime);
2080 server->step(dtime);
2083 if (client->getState() == LC_Init) {
2089 if (client->accessDenied()) {
2090 *error_message = "Access denied. Reason: "
2091 + client->accessDeniedReason();
2092 *reconnect_requested = client->reconnectRequested();
2093 errorstream << *error_message << std::endl;
2097 if (wasKeyDown(KeyType::ESC) || input->wasKeyDown(CancelKey)) {
2099 infostream << "Connect aborted [Escape]" << std::endl;
2104 // Only time out if we aren't waiting for the server we started
2105 if ((*address != "") && (wait_time > 10)) {
2106 bool sent_old_init = g_settings->getFlag("send_pre_v25_init");
2107 // If no pre v25 init was sent, and no answer was received,
2108 // but the low level connection could be established
2109 // (meaning that we have a peer id), then we probably wanted
2110 // to connect to a legacy server. In this case, tell the user
2111 // to enable the option to be able to connect.
2112 if (!sent_old_init &&
2113 (client->getProtoVersion() == 0) &&
2114 client->connectedToServer()) {
2115 *error_message = "Connection failure: init packet not "
2116 "recognized by server.\n"
2117 "Most likely the server uses an old protocol version (<v25).\n"
2118 "Please ask the server owner to update to 0.4.13 or later.\n"
2119 "To still connect to the server in the meantime,\n"
2120 "you can enable the 'send_pre_v25_init' setting by editing minetest.conf,\n"
2121 "or by enabling the 'Client -> Network -> Support older Servers'\n"
2122 "entry in the advanced settings menu.";
2124 *error_message = "Connection timed out.";
2126 errorstream << *error_message << std::endl;
2131 showOverlayMessage(wgettext("Connecting to server..."), dtime, 20);
2133 } catch (con::PeerNotFoundException &e) {
2134 // TODO: Should something be done here? At least an info/error
2142 bool Game::getServerContent(bool *aborted)
2146 FpsControl fps_control = { 0 };
2147 f32 dtime; // in seconds
2149 fps_control.last_time = device->getTimer()->getTime();
2151 while (device->run()) {
2153 limitFps(&fps_control, &dtime);
2155 // Update client and server
2156 client->step(dtime);
2159 server->step(dtime);
2162 if (client->mediaReceived() && client->itemdefReceived() &&
2163 client->nodedefReceived()) {
2168 if (!checkConnection())
2171 if (client->getState() < LC_Init) {
2172 *error_message = "Client disconnected";
2173 errorstream << *error_message << std::endl;
2177 if (wasKeyDown(KeyType::ESC) || input->wasKeyDown(CancelKey)) {
2179 infostream << "Connect aborted [Escape]" << std::endl;
2186 if (!client->itemdefReceived()) {
2187 const wchar_t *text = wgettext("Item definitions...");
2189 draw_load_screen(text, device, guienv, texture_src,
2192 } else if (!client->nodedefReceived()) {
2193 const wchar_t *text = wgettext("Node definitions...");
2195 draw_load_screen(text, device, guienv, texture_src,
2199 std::stringstream message;
2200 std::fixed(message);
2201 message.precision(0);
2202 message << gettext("Media...") << " " << (client->mediaReceiveProgress()*100) << "%";
2203 message.precision(2);
2205 if ((USE_CURL == 0) ||
2206 (!g_settings->getBool("enable_remote_media_server"))) {
2207 float cur = client->getCurRate();
2208 std::string cur_unit = gettext("KiB/s");
2212 cur_unit = gettext("MiB/s");
2215 message << " (" << cur << ' ' << cur_unit << ")";
2218 progress = 30 + client->mediaReceiveProgress() * 35 + 0.5;
2219 draw_load_screen(utf8_to_wide(message.str()), device,
2220 guienv, texture_src, dtime, progress);
2228 /****************************************************************************/
2229 /****************************************************************************
2231 ****************************************************************************/
2232 /****************************************************************************/
2234 inline void Game::updateInteractTimers(f32 dtime)
2236 if (runData.nodig_delay_timer >= 0)
2237 runData.nodig_delay_timer -= dtime;
2239 if (runData.object_hit_delay_timer >= 0)
2240 runData.object_hit_delay_timer -= dtime;
2242 runData.time_from_last_punch += dtime;
2246 /* returns false if game should exit, otherwise true
2248 inline bool Game::checkConnection()
2250 if (client->accessDenied()) {
2251 *error_message = "Access denied. Reason: "
2252 + client->accessDeniedReason();
2253 *reconnect_requested = client->reconnectRequested();
2254 errorstream << *error_message << std::endl;
2262 /* returns false if game should exit, otherwise true
2264 inline bool Game::handleCallbacks()
2266 if (g_gamecallback->disconnect_requested) {
2267 g_gamecallback->disconnect_requested = false;
2271 if (g_gamecallback->changepassword_requested) {
2272 (new GUIPasswordChange(guienv, guiroot, -1,
2273 &g_menumgr, client))->drop();
2274 g_gamecallback->changepassword_requested = false;
2277 if (g_gamecallback->changevolume_requested) {
2278 (new GUIVolumeChange(guienv, guiroot, -1,
2279 &g_menumgr))->drop();
2280 g_gamecallback->changevolume_requested = false;
2283 if (g_gamecallback->keyconfig_requested) {
2284 (new GUIKeyChangeMenu(guienv, guiroot, -1,
2285 &g_menumgr))->drop();
2286 g_gamecallback->keyconfig_requested = false;
2289 if (g_gamecallback->keyconfig_changed) {
2290 keycache.populate(); // update the cache with new settings
2291 g_gamecallback->keyconfig_changed = false;
2298 void Game::processQueues()
2300 texture_src->processQueue();
2301 itemdef_manager->processQueue(client);
2302 shader_src->processQueue();
2306 void Game::updateProfilers(const RunStats &stats, const FpsControl &draw_times, f32 dtime)
2308 float profiler_print_interval =
2309 g_settings->getFloat("profiler_print_interval");
2310 bool print_to_log = true;
2312 if (profiler_print_interval == 0) {
2313 print_to_log = false;
2314 profiler_print_interval = 5;
2317 if (profiler_interval.step(dtime, profiler_print_interval)) {
2319 infostream << "Profiler:" << std::endl;
2320 g_profiler->print(infostream);
2323 update_profiler_gui(guitext_profiler, g_fontengine,
2324 runData.profiler_current_page, runData.profiler_max_page,
2325 driver->getScreenSize().Height);
2327 g_profiler->clear();
2330 addProfilerGraphs(stats, draw_times, dtime);
2334 void Game::addProfilerGraphs(const RunStats &stats,
2335 const FpsControl &draw_times, f32 dtime)
2337 g_profiler->graphAdd("mainloop_other",
2338 draw_times.busy_time / 1000.0f - stats.drawtime / 1000.0f);
2340 if (draw_times.sleep_time != 0)
2341 g_profiler->graphAdd("mainloop_sleep", draw_times.sleep_time / 1000.0f);
2342 g_profiler->graphAdd("mainloop_dtime", dtime);
2344 g_profiler->add("Elapsed time", dtime);
2345 g_profiler->avg("FPS", 1. / dtime);
2349 void Game::updateStats(RunStats *stats, const FpsControl &draw_times,
2356 /* Time average and jitter calculation
2358 jp = &stats->dtime_jitter;
2359 jp->avg = jp->avg * 0.96 + dtime * 0.04;
2361 jitter = dtime - jp->avg;
2363 if (jitter > jp->max)
2366 jp->counter += dtime;
2368 if (jp->counter > 0.0) {
2370 jp->max_sample = jp->max;
2371 jp->max_fraction = jp->max_sample / (jp->avg + 0.001);
2375 /* Busytime average and jitter calculation
2377 jp = &stats->busy_time_jitter;
2378 jp->avg = jp->avg + draw_times.busy_time * 0.02;
2380 jitter = draw_times.busy_time - jp->avg;
2382 if (jitter > jp->max)
2384 if (jitter < jp->min)
2387 jp->counter += dtime;
2389 if (jp->counter > 0.0) {
2391 jp->max_sample = jp->max;
2392 jp->min_sample = jp->min;
2400 /****************************************************************************
2402 ****************************************************************************/
2404 void Game::processUserInput(f32 dtime)
2406 // Reset input if window not active or some menu is active
2407 if (!device->isWindowActive() || !noMenuActive() || guienv->hasFocus(gui_chat_console)) {
2409 #ifdef HAVE_TOUCHSCREENGUI
2410 g_touchscreengui->hide();
2413 #ifdef HAVE_TOUCHSCREENGUI
2414 else if (g_touchscreengui) {
2415 /* on touchscreengui step may generate own input events which ain't
2416 * what we want in case we just did clear them */
2417 g_touchscreengui->step(dtime);
2421 if (!guienv->hasFocus(gui_chat_console) && gui_chat_console->isOpen()) {
2422 gui_chat_console->closeConsoleAtOnce();
2425 // Input handler step() (used by the random input generator)
2429 if (current_formspec != NULL)
2430 current_formspec->getAndroidUIInput();
2432 handleAndroidChatInput();
2435 // Increase timer for double tap of "keymap_jump"
2436 if (m_cache_doubletap_jump && runData.jump_timer <= 0.2f)
2437 runData.jump_timer += dtime;
2440 processItemSelection(&runData.new_playeritem);
2444 void Game::processKeyInput()
2446 if (wasKeyDown(KeyType::DROP)) {
2448 } else if (wasKeyDown(KeyType::AUTORUN)) {
2450 } else if (wasKeyDown(KeyType::INVENTORY)) {
2452 } else if (wasKeyDown(KeyType::ESC) || input->wasKeyDown(CancelKey)) {
2453 if (!gui_chat_console->isOpenInhibited()) {
2456 } else if (wasKeyDown(KeyType::CHAT)) {
2457 openConsole(0.2, L"");
2458 } else if (wasKeyDown(KeyType::CMD)) {
2459 openConsole(0.2, L"/");
2460 } else if (wasKeyDown(KeyType::CMD_LOCAL)) {
2461 openConsole(0.2, L".");
2462 } else if (wasKeyDown(KeyType::CONSOLE)) {
2463 openConsole(core::clamp(g_settings->getFloat("console_height"), 0.1f, 1.0f));
2464 } else if (wasKeyDown(KeyType::FREEMOVE)) {
2466 } else if (wasKeyDown(KeyType::JUMP)) {
2467 toggleFreeMoveAlt();
2468 } else if (wasKeyDown(KeyType::FASTMOVE)) {
2470 } else if (wasKeyDown(KeyType::NOCLIP)) {
2472 } else if (wasKeyDown(KeyType::CINEMATIC)) {
2474 } else if (wasKeyDown(KeyType::SCREENSHOT)) {
2475 client->makeScreenshot(device);
2476 } else if (wasKeyDown(KeyType::TOGGLE_HUD)) {
2478 } else if (wasKeyDown(KeyType::MINIMAP)) {
2479 toggleMinimap(isKeyDown(KeyType::SNEAK));
2480 } else if (wasKeyDown(KeyType::TOGGLE_CHAT)) {
2482 } else if (wasKeyDown(KeyType::TOGGLE_FORCE_FOG_OFF)) {
2484 } else if (wasKeyDown(KeyType::TOGGLE_UPDATE_CAMERA)) {
2485 toggleUpdateCamera();
2486 } else if (wasKeyDown(KeyType::TOGGLE_DEBUG)) {
2488 } else if (wasKeyDown(KeyType::TOGGLE_PROFILER)) {
2490 } else if (wasKeyDown(KeyType::INCREASE_VIEWING_RANGE)) {
2491 increaseViewRange();
2492 } else if (wasKeyDown(KeyType::DECREASE_VIEWING_RANGE)) {
2493 decreaseViewRange();
2494 } else if (wasKeyDown(KeyType::RANGESELECT)) {
2495 toggleFullViewRange();
2496 } else if (wasKeyDown(KeyType::QUICKTUNE_NEXT)) {
2498 } else if (wasKeyDown(KeyType::QUICKTUNE_PREV)) {
2500 } else if (wasKeyDown(KeyType::QUICKTUNE_INC)) {
2502 } else if (wasKeyDown(KeyType::QUICKTUNE_DEC)) {
2504 } else if (wasKeyDown(KeyType::DEBUG_STACKS)) {
2505 // Print debug stacks
2506 dstream << "-----------------------------------------"
2508 dstream << "Printing debug stacks:" << std::endl;
2509 dstream << "-----------------------------------------"
2511 debug_stacks_print();
2514 if (!isKeyDown(KeyType::JUMP) && runData.reset_jump_timer) {
2515 runData.reset_jump_timer = false;
2516 runData.jump_timer = 0.0f;
2519 if (quicktune->hasMessage()) {
2520 m_statustext = utf8_to_wide(quicktune->getMessage());
2521 runData.statustext_time = 0.0f;
2525 void Game::processItemSelection(u16 *new_playeritem)
2527 LocalPlayer *player = client->getEnv().getLocalPlayer();
2529 /* Item selection using mouse wheel
2531 *new_playeritem = client->getPlayerItem();
2533 s32 wheel = input->getMouseWheel();
2534 u16 max_item = MYMIN(PLAYER_INVENTORY_SIZE - 1,
2535 player->hud_hotbar_itemcount - 1);
2539 if (input->joystick.wasKeyDown(KeyType::SCROLL_DOWN)) {
2543 if (input->joystick.wasKeyDown(KeyType::SCROLL_UP)) {
2548 *new_playeritem = *new_playeritem < max_item ? *new_playeritem + 1 : 0;
2550 *new_playeritem = *new_playeritem > 0 ? *new_playeritem - 1 : max_item;
2553 /* Item selection using keyboard
2555 for (u16 i = 0; i < 10; i++) {
2556 static const KeyPress *item_keys[10] = {
2557 NumberKey + 1, NumberKey + 2, NumberKey + 3, NumberKey + 4,
2558 NumberKey + 5, NumberKey + 6, NumberKey + 7, NumberKey + 8,
2559 NumberKey + 9, NumberKey + 0,
2562 if (input->wasKeyDown(*item_keys[i])) {
2563 if (i < PLAYER_INVENTORY_SIZE && i < player->hud_hotbar_itemcount) {
2564 *new_playeritem = i;
2565 infostream << "Selected item: " << new_playeritem << std::endl;
2573 void Game::dropSelectedItem()
2575 IDropAction *a = new IDropAction();
2577 a->from_inv.setCurrentPlayer();
2578 a->from_list = "main";
2579 a->from_i = client->getPlayerItem();
2580 client->inventoryAction(a);
2584 void Game::openInventory()
2587 * Don't permit to open inventory is CAO or player doesn't exists.
2588 * This prevent showing an empty inventory at player load
2591 LocalPlayer *player = client->getEnv().getLocalPlayer();
2592 if (player == NULL || player->getCAO() == NULL)
2595 infostream << "the_game: " << "Launching inventory" << std::endl;
2597 PlayerInventoryFormSource *fs_src = new PlayerInventoryFormSource(client);
2598 TextDest *txt_dst = new TextDestPlayerInventory(client);
2600 create_formspec_menu(¤t_formspec, client, device, &input->joystick, fs_src, txt_dst);
2603 InventoryLocation inventoryloc;
2604 inventoryloc.setCurrentPlayer();
2605 current_formspec->setFormSpec(fs_src->getForm(), inventoryloc);
2609 void Game::openConsole(float scale, const wchar_t *line)
2611 assert(scale > 0.0f && scale <= 1.0f);
2614 porting::showInputDialog(gettext("ok"), "", "", 2);
2615 m_android_chat_open = true;
2617 if (gui_chat_console->isOpenInhibited())
2619 gui_chat_console->openConsole(scale);
2621 gui_chat_console->setCloseOnEnter(true);
2622 gui_chat_console->replaceAndAddToHistory(line);
2628 void Game::handleAndroidChatInput()
2630 if (m_android_chat_open && porting::getInputDialogState() == 0) {
2631 std::string text = porting::getInputDialogValue();
2632 client->typeChatMessage(utf8_to_wide(text));
2638 void Game::toggleFreeMove()
2640 static const wchar_t *msg[] = { L"free_move disabled", L"free_move enabled" };
2642 bool free_move = !g_settings->getBool("free_move");
2643 g_settings->set("free_move", bool_to_cstr(free_move));
2645 runData.statustext_time = 0;
2646 m_statustext = msg[free_move];
2647 if (free_move && !client->checkPrivilege("fly"))
2648 m_statustext += L" (note: no 'fly' privilege)";
2652 void Game::toggleFreeMoveAlt()
2654 if (m_cache_doubletap_jump && runData.jump_timer < 0.2f)
2657 runData.reset_jump_timer = true;
2661 void Game::toggleFast()
2663 static const wchar_t *msg[] = { L"fast_move disabled", L"fast_move enabled" };
2664 bool fast_move = !g_settings->getBool("fast_move");
2665 g_settings->set("fast_move", bool_to_cstr(fast_move));
2667 runData.statustext_time = 0;
2668 m_statustext = msg[fast_move];
2670 bool has_fast_privs = client->checkPrivilege("fast");
2672 if (fast_move && !has_fast_privs)
2673 m_statustext += L" (note: no 'fast' privilege)";
2676 m_cache_hold_aux1 = fast_move && has_fast_privs;
2681 void Game::toggleNoClip()
2683 static const wchar_t *msg[] = { L"noclip disabled", L"noclip enabled" };
2684 bool noclip = !g_settings->getBool("noclip");
2685 g_settings->set("noclip", bool_to_cstr(noclip));
2687 runData.statustext_time = 0;
2688 m_statustext = msg[noclip];
2690 if (noclip && !client->checkPrivilege("noclip"))
2691 m_statustext += L" (note: no 'noclip' privilege)";
2694 void Game::toggleCinematic()
2696 static const wchar_t *msg[] = { L"cinematic disabled", L"cinematic enabled" };
2697 bool cinematic = !g_settings->getBool("cinematic");
2698 g_settings->set("cinematic", bool_to_cstr(cinematic));
2700 runData.statustext_time = 0;
2701 m_statustext = msg[cinematic];
2704 // Add WoW-style autorun by toggling continuous forward.
2705 void Game::toggleAutorun()
2707 static const wchar_t *msg[] = { L"autorun disabled", L"autorun enabled" };
2708 bool autorun_enabled = !g_settings->getBool("continuous_forward");
2709 g_settings->set("continuous_forward", bool_to_cstr(autorun_enabled));
2711 runData.statustext_time = 0;
2712 m_statustext = msg[autorun_enabled ? 1 : 0];
2715 void Game::toggleChat()
2717 static const wchar_t *msg[] = { L"Chat hidden", L"Chat shown" };
2719 flags.show_chat = !flags.show_chat;
2720 runData.statustext_time = 0;
2721 m_statustext = msg[flags.show_chat];
2725 void Game::toggleHud()
2727 static const wchar_t *msg[] = { L"HUD hidden", L"HUD shown" };
2729 flags.show_hud = !flags.show_hud;
2730 runData.statustext_time = 0;
2731 m_statustext = msg[flags.show_hud];
2734 void Game::toggleMinimap(bool shift_pressed)
2736 if (!flags.show_hud || !g_settings->getBool("enable_minimap"))
2739 if (shift_pressed) {
2740 mapper->toggleMinimapShape();
2744 u32 hud_flags = client->getEnv().getLocalPlayer()->hud_flags;
2746 MinimapMode mode = MINIMAP_MODE_OFF;
2747 if (hud_flags & HUD_FLAG_MINIMAP_VISIBLE) {
2748 mode = mapper->getMinimapMode();
2749 mode = (MinimapMode)((int)mode + 1);
2752 flags.show_minimap = true;
2754 case MINIMAP_MODE_SURFACEx1:
2755 m_statustext = L"Minimap in surface mode, Zoom x1";
2757 case MINIMAP_MODE_SURFACEx2:
2758 m_statustext = L"Minimap in surface mode, Zoom x2";
2760 case MINIMAP_MODE_SURFACEx4:
2761 m_statustext = L"Minimap in surface mode, Zoom x4";
2763 case MINIMAP_MODE_RADARx1:
2764 m_statustext = L"Minimap in radar mode, Zoom x1";
2766 case MINIMAP_MODE_RADARx2:
2767 m_statustext = L"Minimap in radar mode, Zoom x2";
2769 case MINIMAP_MODE_RADARx4:
2770 m_statustext = L"Minimap in radar mode, Zoom x4";
2773 mode = MINIMAP_MODE_OFF;
2774 flags.show_minimap = false;
2775 m_statustext = (hud_flags & HUD_FLAG_MINIMAP_VISIBLE) ?
2776 L"Minimap hidden" : L"Minimap disabled by server";
2779 runData.statustext_time = 0;
2780 mapper->setMinimapMode(mode);
2783 void Game::toggleFog()
2785 static const wchar_t *msg[] = { L"Fog enabled", L"Fog disabled" };
2787 flags.force_fog_off = !flags.force_fog_off;
2788 runData.statustext_time = 0;
2789 m_statustext = msg[flags.force_fog_off];
2793 void Game::toggleDebug()
2795 // Initial / 4x toggle: Chat only
2796 // 1x toggle: Debug text with chat
2797 // 2x toggle: Debug text with profiler graph
2798 // 3x toggle: Debug text and wireframe
2799 if (!flags.show_debug) {
2800 flags.show_debug = true;
2801 flags.show_profiler_graph = false;
2802 draw_control->show_wireframe = false;
2803 m_statustext = L"Debug info shown";
2804 } else if (!flags.show_profiler_graph && !draw_control->show_wireframe) {
2805 flags.show_profiler_graph = true;
2806 m_statustext = L"Profiler graph shown";
2807 } else if (!draw_control->show_wireframe && client->checkPrivilege("debug")) {
2808 flags.show_profiler_graph = false;
2809 draw_control->show_wireframe = true;
2810 m_statustext = L"Wireframe shown";
2812 flags.show_debug = false;
2813 flags.show_profiler_graph = false;
2814 draw_control->show_wireframe = false;
2815 if (client->checkPrivilege("debug")) {
2816 m_statustext = L"Debug info, profiler graph, and wireframe hidden";
2818 m_statustext = L"Debug info and profiler graph hidden";
2821 runData.statustext_time = 0;
2825 void Game::toggleUpdateCamera()
2827 static const wchar_t *msg[] = {
2828 L"Camera update enabled",
2829 L"Camera update disabled"
2832 flags.disable_camera_update = !flags.disable_camera_update;
2833 runData.statustext_time = 0;
2834 m_statustext = msg[flags.disable_camera_update];
2838 void Game::toggleProfiler()
2840 runData.profiler_current_page =
2841 (runData.profiler_current_page + 1) % (runData.profiler_max_page + 1);
2843 // FIXME: This updates the profiler with incomplete values
2844 update_profiler_gui(guitext_profiler, g_fontengine, runData.profiler_current_page,
2845 runData.profiler_max_page, driver->getScreenSize().Height);
2847 if (runData.profiler_current_page != 0) {
2848 std::wstringstream sstr;
2849 sstr << "Profiler shown (page " << runData.profiler_current_page
2850 << " of " << runData.profiler_max_page << ")";
2851 m_statustext = sstr.str();
2853 m_statustext = L"Profiler hidden";
2855 runData.statustext_time = 0;
2859 void Game::increaseViewRange()
2861 s16 range = g_settings->getS16("viewing_range");
2862 s16 range_new = range + 10;
2864 if (range_new > 4000) {
2866 m_statustext = utf8_to_wide("Viewing range is at maximum: "
2869 m_statustext = utf8_to_wide("Viewing range changed to "
2872 g_settings->set("viewing_range", itos(range_new));
2873 runData.statustext_time = 0;
2877 void Game::decreaseViewRange()
2879 s16 range = g_settings->getS16("viewing_range");
2880 s16 range_new = range - 10;
2882 if (range_new < 20) {
2884 m_statustext = utf8_to_wide("Viewing range is at minimum: "
2887 m_statustext = utf8_to_wide("Viewing range changed to "
2890 g_settings->set("viewing_range", itos(range_new));
2891 runData.statustext_time = 0;
2895 void Game::toggleFullViewRange()
2897 static const wchar_t *msg[] = {
2898 L"Disabled full viewing range",
2899 L"Enabled full viewing range"
2902 draw_control->range_all = !draw_control->range_all;
2903 infostream << msg[draw_control->range_all] << std::endl;
2904 m_statustext = msg[draw_control->range_all];
2905 runData.statustext_time = 0;
2909 void Game::updateCameraDirection(CameraOrientation *cam, float dtime)
2911 if ((device->isWindowActive() && noMenuActive()) || random_input) {
2914 if (!random_input) {
2915 // Mac OSX gets upset if this is set every frame
2916 if (device->getCursorControl()->isVisible())
2917 device->getCursorControl()->setVisible(false);
2921 if (m_first_loop_after_window_activation)
2922 m_first_loop_after_window_activation = false;
2924 updateCameraOrientation(cam, dtime);
2926 input->setMousePos((driver->getScreenSize().Width / 2),
2927 (driver->getScreenSize().Height / 2));
2931 // Mac OSX gets upset if this is set every frame
2932 if (!device->getCursorControl()->isVisible())
2933 device->getCursorControl()->setVisible(true);
2936 if (!m_first_loop_after_window_activation)
2937 m_first_loop_after_window_activation = true;
2942 void Game::updateCameraOrientation(CameraOrientation *cam, float dtime)
2944 #ifdef HAVE_TOUCHSCREENGUI
2945 if (g_touchscreengui) {
2946 cam->camera_yaw += g_touchscreengui->getYawChange();
2947 cam->camera_pitch = g_touchscreengui->getPitch();
2951 s32 dx = input->getMousePos().X - (driver->getScreenSize().Width / 2);
2952 s32 dy = input->getMousePos().Y - (driver->getScreenSize().Height / 2);
2954 if (m_invert_mouse || camera->getCameraMode() == CAMERA_MODE_THIRD_FRONT) {
2958 cam->camera_yaw -= dx * m_cache_mouse_sensitivity;
2959 cam->camera_pitch += dy * m_cache_mouse_sensitivity;
2961 #ifdef HAVE_TOUCHSCREENGUI
2965 if (m_cache_enable_joysticks) {
2966 f32 c = m_cache_joystick_frustum_sensitivity * (1.f / 32767.f) * dtime;
2967 cam->camera_yaw -= input->joystick.getAxisWithoutDead(JA_FRUSTUM_HORIZONTAL) * c;
2968 cam->camera_pitch += input->joystick.getAxisWithoutDead(JA_FRUSTUM_VERTICAL) * c;
2971 cam->camera_pitch = rangelim(cam->camera_pitch, -89.5, 89.5);
2975 void Game::updatePlayerControl(const CameraOrientation &cam)
2977 //TimeTaker tt("update player control", NULL, PRECISION_NANO);
2979 // DO NOT use the isKeyDown method for the forward, backward, left, right
2980 // buttons, as the code that uses the controls needs to be able to
2981 // distinguish between the two in order to know when to use joysticks.
2983 PlayerControl control(
2984 input->isKeyDown(keycache.key[KeyType::FORWARD]),
2985 input->isKeyDown(keycache.key[KeyType::BACKWARD]),
2986 input->isKeyDown(keycache.key[KeyType::LEFT]),
2987 input->isKeyDown(keycache.key[KeyType::RIGHT]),
2988 isKeyDown(KeyType::JUMP),
2989 isKeyDown(KeyType::SPECIAL1),
2990 isKeyDown(KeyType::SNEAK),
2991 isKeyDown(KeyType::ZOOM),
2996 input->joystick.getAxisWithoutDead(JA_SIDEWARD_MOVE),
2997 input->joystick.getAxisWithoutDead(JA_FORWARD_MOVE)
3001 ( (u32)(isKeyDown(KeyType::FORWARD) & 0x1) << 0) |
3002 ( (u32)(isKeyDown(KeyType::BACKWARD) & 0x1) << 1) |
3003 ( (u32)(isKeyDown(KeyType::LEFT) & 0x1) << 2) |
3004 ( (u32)(isKeyDown(KeyType::RIGHT) & 0x1) << 3) |
3005 ( (u32)(isKeyDown(KeyType::JUMP) & 0x1) << 4) |
3006 ( (u32)(isKeyDown(KeyType::SPECIAL1) & 0x1) << 5) |
3007 ( (u32)(isKeyDown(KeyType::SNEAK) & 0x1) << 6) |
3008 ( (u32)(isLeftPressed() & 0x1) << 7) |
3009 ( (u32)(isRightPressed() & 0x1) << 8
3013 /* For Android, simulate holding down AUX1 (fast move) if the user has
3014 * the fast_move setting toggled on. If there is an aux1 key defined for
3015 * Android then its meaning is inverted (i.e. holding aux1 means walk and
3018 if (m_cache_hold_aux1) {
3019 control.aux1 = control.aux1 ^ true;
3020 keypress_bits ^= ((u32)(1U << 5));
3024 client->setPlayerControl(control);
3025 LocalPlayer *player = client->getEnv().getLocalPlayer();
3026 player->keyPressed = keypress_bits;
3032 inline void Game::step(f32 *dtime)
3034 bool can_be_and_is_paused =
3035 (simple_singleplayer_mode && g_menumgr.pausesGame());
3037 if (can_be_and_is_paused) { // This is for a singleplayer server
3038 *dtime = 0; // No time passes
3040 if (server != NULL) {
3041 //TimeTaker timer("server->step(dtime)");
3042 server->step(*dtime);
3045 //TimeTaker timer("client.step(dtime)");
3046 client->step(*dtime);
3051 void Game::processClientEvents(CameraOrientation *cam)
3053 ClientEvent event = client->getClientEvent();
3055 LocalPlayer *player = client->getEnv().getLocalPlayer();
3057 for ( ; event.type != CE_NONE; event = client->getClientEvent()) {
3059 switch (event.type) {
3060 case CE_PLAYER_DAMAGE:
3061 if (client->getHP() == 0)
3063 if (client->moddingEnabled()) {
3064 client->getScript()->on_damage_taken(event.player_damage.amount);
3067 runData.damage_flash += 95.0 + 3.2 * event.player_damage.amount;
3068 runData.damage_flash = MYMIN(runData.damage_flash, 127.0);
3070 player->hurt_tilt_timer = 1.5;
3071 player->hurt_tilt_strength =
3072 rangelim(event.player_damage.amount / 4, 1.0, 4.0);
3074 client->event()->put(new SimpleTriggerEvent("PlayerDamage"));
3077 case CE_PLAYER_FORCE_MOVE:
3078 cam->camera_yaw = event.player_force_move.yaw;
3079 cam->camera_pitch = event.player_force_move.pitch;
3082 case CE_DEATHSCREEN:
3083 // This should be enabled for death formspec in builtin
3084 client->getScript()->on_death();
3086 /* Handle visualization */
3087 runData.damage_flash = 0;
3088 player->hurt_tilt_timer = 0;
3089 player->hurt_tilt_strength = 0;
3092 case CE_SHOW_FORMSPEC:
3093 if (*(event.show_formspec.formspec) == "") {
3094 if (current_formspec && ( *(event.show_formspec.formname) == "" || *(event.show_formspec.formname) == cur_formname) ){
3095 current_formspec->quitMenu();
3098 FormspecFormSource *fs_src =
3099 new FormspecFormSource(*(event.show_formspec.formspec));
3100 TextDestPlayerInventory *txt_dst =
3101 new TextDestPlayerInventory(client, *(event.show_formspec.formname));
3103 create_formspec_menu(¤t_formspec, client, device, &input->joystick,
3105 cur_formname = *(event.show_formspec.formname);
3108 delete event.show_formspec.formspec;
3109 delete event.show_formspec.formname;
3112 case CE_SHOW_LOCAL_FORMSPEC:
3114 FormspecFormSource *fs_src = new FormspecFormSource(*event.show_formspec.formspec);
3115 LocalFormspecHandler *txt_dst = new LocalFormspecHandler(*event.show_formspec.formname, client);
3116 create_formspec_menu(¤t_formspec, client, device, &input->joystick,
3119 delete event.show_formspec.formspec;
3120 delete event.show_formspec.formname;
3123 case CE_SPAWN_PARTICLE:
3124 case CE_ADD_PARTICLESPAWNER:
3125 case CE_DELETE_PARTICLESPAWNER:
3126 client->getParticleManager()->handleParticleEvent(&event, client,
3132 u32 id = event.hudadd.id;
3134 HudElement *e = player->getHud(id);
3137 delete event.hudadd.pos;
3138 delete event.hudadd.name;
3139 delete event.hudadd.scale;
3140 delete event.hudadd.text;
3141 delete event.hudadd.align;
3142 delete event.hudadd.offset;
3143 delete event.hudadd.world_pos;
3144 delete event.hudadd.size;
3149 e->type = (HudElementType)event.hudadd.type;
3150 e->pos = *event.hudadd.pos;
3151 e->name = *event.hudadd.name;
3152 e->scale = *event.hudadd.scale;
3153 e->text = *event.hudadd.text;
3154 e->number = event.hudadd.number;
3155 e->item = event.hudadd.item;
3156 e->dir = event.hudadd.dir;
3157 e->align = *event.hudadd.align;
3158 e->offset = *event.hudadd.offset;
3159 e->world_pos = *event.hudadd.world_pos;
3160 e->size = *event.hudadd.size;
3162 u32 new_id = player->addHud(e);
3163 //if this isn't true our huds aren't consistent
3164 sanity_check(new_id == id);
3167 delete event.hudadd.pos;
3168 delete event.hudadd.name;
3169 delete event.hudadd.scale;
3170 delete event.hudadd.text;
3171 delete event.hudadd.align;
3172 delete event.hudadd.offset;
3173 delete event.hudadd.world_pos;
3174 delete event.hudadd.size;
3179 HudElement *e = player->removeHud(event.hudrm.id);
3188 u32 id = event.hudchange.id;
3189 HudElement *e = player->getHud(id);
3192 delete event.hudchange.v3fdata;
3193 delete event.hudchange.v2fdata;
3194 delete event.hudchange.sdata;
3195 delete event.hudchange.v2s32data;
3199 switch (event.hudchange.stat) {
3201 e->pos = *event.hudchange.v2fdata;
3205 e->name = *event.hudchange.sdata;
3208 case HUD_STAT_SCALE:
3209 e->scale = *event.hudchange.v2fdata;
3213 e->text = *event.hudchange.sdata;
3216 case HUD_STAT_NUMBER:
3217 e->number = event.hudchange.data;
3221 e->item = event.hudchange.data;
3225 e->dir = event.hudchange.data;
3228 case HUD_STAT_ALIGN:
3229 e->align = *event.hudchange.v2fdata;
3232 case HUD_STAT_OFFSET:
3233 e->offset = *event.hudchange.v2fdata;
3236 case HUD_STAT_WORLD_POS:
3237 e->world_pos = *event.hudchange.v3fdata;
3241 e->size = *event.hudchange.v2s32data;
3246 delete event.hudchange.v3fdata;
3247 delete event.hudchange.v2fdata;
3248 delete event.hudchange.sdata;
3249 delete event.hudchange.v2s32data;
3253 sky->setVisible(false);
3260 // Handle according to type
3261 if (*event.set_sky.type == "regular") {
3262 sky->setVisible(true);
3263 } else if (*event.set_sky.type == "skybox" &&
3264 event.set_sky.params->size() == 6) {
3265 sky->setFallbackBgColor(*event.set_sky.bgcolor);
3266 skybox = smgr->addSkyBoxSceneNode(
3267 texture_src->getTextureForMesh((*event.set_sky.params)[0]),
3268 texture_src->getTextureForMesh((*event.set_sky.params)[1]),
3269 texture_src->getTextureForMesh((*event.set_sky.params)[2]),
3270 texture_src->getTextureForMesh((*event.set_sky.params)[3]),
3271 texture_src->getTextureForMesh((*event.set_sky.params)[4]),
3272 texture_src->getTextureForMesh((*event.set_sky.params)[5]));
3274 // Handle everything else as plain color
3276 if (*event.set_sky.type != "plain")
3277 infostream << "Unknown sky type: "
3278 << (*event.set_sky.type) << std::endl;
3280 sky->setFallbackBgColor(*event.set_sky.bgcolor);
3283 delete event.set_sky.bgcolor;
3284 delete event.set_sky.type;
3285 delete event.set_sky.params;
3288 case CE_OVERRIDE_DAY_NIGHT_RATIO:
3289 client->getEnv().setDayNightRatioOverride(
3290 event.override_day_night_ratio.do_override,
3291 event.override_day_night_ratio.ratio_f * 1000);
3295 // unknown or unhandled type
3303 void Game::updateCamera(u32 busy_time, f32 dtime)
3305 LocalPlayer *player = client->getEnv().getLocalPlayer();
3308 For interaction purposes, get info about the held item
3310 - Is it a usable item?
3311 - Can it point to liquids?
3313 ItemStack playeritem;
3315 InventoryList *mlist = local_inventory->getList("main");
3317 if (mlist && client->getPlayerItem() < mlist->getSize())
3318 playeritem = mlist->getItem(client->getPlayerItem());
3321 if (playeritem.getDefinition(itemdef_manager).name.empty()) { // override the hand
3322 InventoryList *hlist = local_inventory->getList("hand");
3324 playeritem = hlist->getItem(0);
3328 ToolCapabilities playeritem_toolcap =
3329 playeritem.getToolCapabilities(itemdef_manager);
3331 v3s16 old_camera_offset = camera->getOffset();
3333 if (wasKeyDown(KeyType::CAMERA_MODE)) {
3334 GenericCAO *playercao = player->getCAO();
3336 // If playercao not loaded, don't change camera
3337 if (playercao == NULL)
3340 camera->toggleCameraMode();
3342 playercao->setVisible(camera->getCameraMode() > CAMERA_MODE_FIRST);
3343 playercao->setChildrenVisible(camera->getCameraMode() > CAMERA_MODE_FIRST);
3346 float full_punch_interval = playeritem_toolcap.full_punch_interval;
3347 float tool_reload_ratio = runData.time_from_last_punch / full_punch_interval;
3349 tool_reload_ratio = MYMIN(tool_reload_ratio, 1.0);
3350 camera->update(player, dtime, busy_time / 1000.0f, tool_reload_ratio,
3352 camera->step(dtime);
3354 v3f camera_position = camera->getPosition();
3355 v3f camera_direction = camera->getDirection();
3356 f32 camera_fov = camera->getFovMax();
3357 v3s16 camera_offset = camera->getOffset();
3359 m_camera_offset_changed = (camera_offset != old_camera_offset);
3361 if (!flags.disable_camera_update) {
3362 client->getEnv().getClientMap().updateCamera(camera_position,
3363 camera_direction, camera_fov, camera_offset);
3365 if (m_camera_offset_changed) {
3366 client->updateCameraOffset(camera_offset);
3367 client->getEnv().updateCameraOffset(camera_offset);
3370 clouds->updateCameraOffset(camera_offset);
3376 void Game::updateSound(f32 dtime)
3378 // Update sound listener
3379 v3s16 camera_offset = camera->getOffset();
3380 sound->updateListener(camera->getCameraNode()->getPosition() + intToFloat(camera_offset, BS),
3381 v3f(0, 0, 0), // velocity
3382 camera->getDirection(),
3383 camera->getCameraNode()->getUpVector());
3384 sound->setListenerGain(g_settings->getFloat("sound_volume"));
3387 // Update sound maker
3388 soundmaker->step(dtime);
3390 LocalPlayer *player = client->getEnv().getLocalPlayer();
3392 ClientMap &map = client->getEnv().getClientMap();
3393 MapNode n = map.getNodeNoEx(player->getFootstepNodePos());
3394 soundmaker->m_player_step_sound = nodedef_manager->get(n).sound_footstep;
3398 void Game::processPlayerInteraction(f32 dtime, bool show_hud, bool show_debug)
3400 LocalPlayer *player = client->getEnv().getLocalPlayer();
3402 ItemStack playeritem;
3404 InventoryList *mlist = local_inventory->getList("main");
3406 if (mlist && client->getPlayerItem() < mlist->getSize())
3407 playeritem = mlist->getItem(client->getPlayerItem());
3410 const ItemDefinition &playeritem_def =
3411 playeritem.getDefinition(itemdef_manager);
3412 InventoryList *hlist = local_inventory->getList("hand");
3413 const ItemDefinition &hand_def =
3414 hlist ? hlist->getItem(0).getDefinition(itemdef_manager) : itemdef_manager->get("");
3416 v3f player_position = player->getPosition();
3417 v3f camera_position = camera->getPosition();
3418 v3f camera_direction = camera->getDirection();
3419 v3s16 camera_offset = camera->getOffset();
3423 Calculate what block is the crosshair pointing to
3426 f32 d = playeritem_def.range; // max. distance
3427 f32 d_hand = hand_def.range;
3429 if (d < 0 && d_hand >= 0)
3434 core::line3d<f32> shootline;
3436 if (camera->getCameraMode() != CAMERA_MODE_THIRD_FRONT) {
3437 shootline = core::line3d<f32>(camera_position,
3438 camera_position + camera_direction * BS * d);
3440 // prevent player pointing anything in front-view
3441 shootline = core::line3d<f32>(camera_position,camera_position);
3444 #ifdef HAVE_TOUCHSCREENGUI
3446 if ((g_settings->getBool("touchtarget")) && (g_touchscreengui)) {
3447 shootline = g_touchscreengui->getShootline();
3448 shootline.start += intToFloat(camera_offset, BS);
3449 shootline.end += intToFloat(camera_offset, BS);
3454 PointedThing pointed = updatePointedThing(shootline,
3455 playeritem_def.liquids_pointable,
3456 !runData.ldown_for_dig,
3459 if (pointed != runData.pointed_old) {
3460 infostream << "Pointing at " << pointed.dump() << std::endl;
3461 hud->updateSelectionMesh(camera_offset);
3466 - releasing left mouse button
3467 - pointing away from node
3469 if (runData.digging) {
3470 if (getLeftReleased()) {
3471 infostream << "Left button released"
3472 << " (stopped digging)" << std::endl;
3473 runData.digging = false;
3474 } else if (pointed != runData.pointed_old) {
3475 if (pointed.type == POINTEDTHING_NODE
3476 && runData.pointed_old.type == POINTEDTHING_NODE
3477 && pointed.node_undersurface
3478 == runData.pointed_old.node_undersurface) {
3479 // Still pointing to the same node, but a different face.
3482 infostream << "Pointing away from node"
3483 << " (stopped digging)" << std::endl;
3484 runData.digging = false;
3485 hud->updateSelectionMesh(camera_offset);
3489 if (!runData.digging) {
3490 client->interact(1, runData.pointed_old);
3491 client->setCrack(-1, v3s16(0, 0, 0));
3492 runData.dig_time = 0.0;
3496 if (!runData.digging && runData.ldown_for_dig && !isLeftPressed()) {
3497 runData.ldown_for_dig = false;
3500 runData.left_punch = false;
3502 soundmaker->m_player_leftpunch_sound.name = "";
3504 if (isRightPressed())
3505 runData.repeat_rightclick_timer += dtime;
3507 runData.repeat_rightclick_timer = 0;
3509 if (playeritem_def.usable && isLeftPressed()) {
3510 if (getLeftClicked())
3511 client->interact(4, pointed);
3512 } else if (pointed.type == POINTEDTHING_NODE) {
3513 ToolCapabilities playeritem_toolcap =
3514 playeritem.getToolCapabilities(itemdef_manager);
3515 if (playeritem.name.empty()) {
3516 playeritem_toolcap = *hand_def.tool_capabilities;
3518 handlePointingAtNode(pointed, playeritem_def, playeritem_toolcap, dtime);
3519 } else if (pointed.type == POINTEDTHING_OBJECT) {
3520 handlePointingAtObject(pointed, playeritem, player_position, show_debug);
3521 } else if (isLeftPressed()) {
3522 // When button is held down in air, show continuous animation
3523 runData.left_punch = true;
3524 } else if (getRightClicked()) {
3525 handlePointingAtNothing(playeritem);
3528 runData.pointed_old = pointed;
3530 if (runData.left_punch || getLeftClicked())
3531 camera->setDigging(0); // left click animation
3533 input->resetLeftClicked();
3534 input->resetRightClicked();
3536 input->joystick.clearWasKeyDown(KeyType::MOUSE_L);
3537 input->joystick.clearWasKeyDown(KeyType::MOUSE_R);
3539 input->resetLeftReleased();
3540 input->resetRightReleased();
3542 input->joystick.clearWasKeyReleased(KeyType::MOUSE_L);
3543 input->joystick.clearWasKeyReleased(KeyType::MOUSE_R);
3547 PointedThing Game::updatePointedThing(
3548 const core::line3d<f32> &shootline,
3549 bool liquids_pointable,
3550 bool look_for_object,
3551 const v3s16 &camera_offset)
3553 std::vector<aabb3f> *selectionboxes = hud->getSelectionBoxes();
3554 selectionboxes->clear();
3555 hud->setSelectedFaceNormal(v3f(0.0, 0.0, 0.0));
3556 static const bool show_entity_selectionbox = g_settings->getBool(
3557 "show_entity_selectionbox");
3559 ClientMap &map = client->getEnv().getClientMap();
3560 INodeDefManager *nodedef=client->getNodeDefManager();
3562 runData.selected_object = NULL;
3564 PointedThing result=client->getEnv().getPointedThing(
3565 shootline, liquids_pointable, look_for_object);
3566 if (result.type == POINTEDTHING_OBJECT) {
3567 runData.selected_object = client->getEnv().getActiveObject(result.object_id);
3568 if (show_entity_selectionbox && runData.selected_object->doShowSelectionBox()) {
3569 aabb3f *selection_box = runData.selected_object->getSelectionBox();
3571 // Box should exist because object was
3572 // returned in the first place
3574 assert(selection_box);
3576 v3f pos = runData.selected_object->getPosition();
3577 selectionboxes->push_back(aabb3f(
3578 selection_box->MinEdge, selection_box->MaxEdge));
3579 selectionboxes->push_back(
3580 aabb3f(selection_box->MinEdge, selection_box->MaxEdge));
3581 hud->setSelectionPos(pos, camera_offset);
3583 } else if (result.type == POINTEDTHING_NODE) {
3584 // Update selection boxes
3585 MapNode n = map.getNodeNoEx(result.node_undersurface);
3586 std::vector<aabb3f> boxes;
3587 n.getSelectionBoxes(nodedef, &boxes,
3588 n.getNeighbors(result.node_undersurface, &map));
3591 for (std::vector<aabb3f>::const_iterator i = boxes.begin();
3592 i != boxes.end(); ++i) {
3594 box.MinEdge -= v3f(d, d, d);
3595 box.MaxEdge += v3f(d, d, d);
3596 selectionboxes->push_back(box);
3598 hud->setSelectionPos(intToFloat(result.node_undersurface, BS),
3600 hud->setSelectedFaceNormal(v3f(
3601 result.intersection_normal.X,
3602 result.intersection_normal.Y,
3603 result.intersection_normal.Z));
3606 // Update selection mesh light level and vertex colors
3607 if (selectionboxes->size() > 0) {
3608 v3f pf = hud->getSelectionPos();
3609 v3s16 p = floatToInt(pf, BS);
3611 // Get selection mesh light level
3612 MapNode n = map.getNodeNoEx(p);
3613 u16 node_light = getInteriorLight(n, -1, nodedef);
3614 u16 light_level = node_light;
3616 for (u8 i = 0; i < 6; i++) {
3617 n = map.getNodeNoEx(p + g_6dirs[i]);
3618 node_light = getInteriorLight(n, -1, nodedef);
3619 if (node_light > light_level)
3620 light_level = node_light;
3623 u32 daynight_ratio = client->getEnv().getDayNightRatio();
3625 final_color_blend(&c, light_level, daynight_ratio);
3627 // Modify final color a bit with time
3628 u32 timer = porting::getTimeMs() % 5000;
3629 float timerf = (float) (irr::core::PI * ((timer / 2500.0) - 0.5));
3630 float sin_r = 0.08 * sin(timerf);
3631 float sin_g = 0.08 * sin(timerf + irr::core::PI * 0.5);
3632 float sin_b = 0.08 * sin(timerf + irr::core::PI);
3634 core::clamp(core::round32(c.getRed() * (0.8 + sin_r)), 0, 255));
3636 core::clamp(core::round32(c.getGreen() * (0.8 + sin_g)), 0, 255));
3638 core::clamp(core::round32(c.getBlue() * (0.8 + sin_b)), 0, 255));
3640 // Set mesh final color
3641 hud->setSelectionMeshColor(c);
3647 void Game::handlePointingAtNothing(const ItemStack &playerItem)
3649 infostream << "Right Clicked in Air" << std::endl;
3650 PointedThing fauxPointed;
3651 fauxPointed.type = POINTEDTHING_NOTHING;
3652 client->interact(5, fauxPointed);
3656 void Game::handlePointingAtNode(const PointedThing &pointed, const ItemDefinition &playeritem_def,
3657 const ToolCapabilities &playeritem_toolcap, f32 dtime)
3659 v3s16 nodepos = pointed.node_undersurface;
3660 v3s16 neighbourpos = pointed.node_abovesurface;
3663 Check information text of node
3666 ClientMap &map = client->getEnv().getClientMap();
3667 NodeMetadata *meta = map.getNodeMetadata(nodepos);
3670 infotext = unescape_enriched(utf8_to_wide(meta->getString("infotext")));
3672 MapNode n = map.getNodeNoEx(nodepos);
3674 if (nodedef_manager->get(n).tiledef[0].name == "unknown_node.png") {
3675 infotext = L"Unknown node: ";
3676 infotext += utf8_to_wide(nodedef_manager->get(n).name);
3680 if (runData.nodig_delay_timer <= 0.0 && isLeftPressed()
3681 && client->checkPrivilege("interact")) {
3682 handleDigging(pointed, nodepos, playeritem_toolcap, dtime);
3685 if ((getRightClicked() ||
3686 runData.repeat_rightclick_timer >= m_repeat_right_click_time) &&
3687 client->checkPrivilege("interact")) {
3688 runData.repeat_rightclick_timer = 0;
3689 infostream << "Ground right-clicked" << std::endl;
3691 if (meta && meta->getString("formspec") != "" && !random_input
3692 && !isKeyDown(KeyType::SNEAK)) {
3693 infostream << "Launching custom inventory view" << std::endl;
3695 InventoryLocation inventoryloc;
3696 inventoryloc.setNodeMeta(nodepos);
3698 NodeMetadataFormSource *fs_src = new NodeMetadataFormSource(
3699 &client->getEnv().getClientMap(), nodepos);
3700 TextDest *txt_dst = new TextDestNodeMetadata(nodepos, client);
3702 create_formspec_menu(¤t_formspec, client,
3703 device, &input->joystick, fs_src, txt_dst);
3706 current_formspec->setFormSpec(meta->getString("formspec"), inventoryloc);
3708 // Report right click to server
3710 camera->setDigging(1); // right click animation (always shown for feedback)
3712 // If the wielded item has node placement prediction,
3714 bool placed = nodePlacementPrediction(*client,
3716 nodepos, neighbourpos);
3720 client->interact(3, pointed);
3722 soundmaker->m_player_rightpunch_sound =
3723 playeritem_def.sound_place;
3725 soundmaker->m_player_rightpunch_sound =
3728 if (playeritem_def.node_placement_prediction == "" ||
3729 nodedef_manager->get(map.getNodeNoEx(nodepos)).rightclickable) {
3730 client->interact(3, pointed); // Report to server
3732 soundmaker->m_player_rightpunch_sound =
3733 playeritem_def.sound_place_failed;
3741 void Game::handlePointingAtObject(const PointedThing &pointed, const ItemStack &playeritem,
3742 const v3f &player_position, bool show_debug)
3744 infotext = unescape_enriched(
3745 utf8_to_wide(runData.selected_object->infoText()));
3748 if (infotext != L"") {
3751 infotext += unescape_enriched(utf8_to_wide(
3752 runData.selected_object->debugInfoText()));
3755 if (isLeftPressed()) {
3756 bool do_punch = false;
3757 bool do_punch_damage = false;
3759 if (runData.object_hit_delay_timer <= 0.0) {
3761 do_punch_damage = true;
3762 runData.object_hit_delay_timer = object_hit_delay;
3765 if (getLeftClicked())
3769 infostream << "Left-clicked object" << std::endl;
3770 runData.left_punch = true;
3773 if (do_punch_damage) {
3774 // Report direct punch
3775 v3f objpos = runData.selected_object->getPosition();
3776 v3f dir = (objpos - player_position).normalize();
3777 ItemStack item = playeritem;
3778 if (playeritem.name.empty()) {
3779 InventoryList *hlist = local_inventory->getList("hand");
3781 item = hlist->getItem(0);
3785 bool disable_send = runData.selected_object->directReportPunch(
3786 dir, &item, runData.time_from_last_punch);
3787 runData.time_from_last_punch = 0;
3790 client->interact(0, pointed);
3792 } else if (getRightClicked()) {
3793 infostream << "Right-clicked object" << std::endl;
3794 client->interact(3, pointed); // place
3799 void Game::handleDigging(const PointedThing &pointed, const v3s16 &nodepos,
3800 const ToolCapabilities &playeritem_toolcap, f32 dtime)
3802 LocalPlayer *player = client->getEnv().getLocalPlayer();
3803 ClientMap &map = client->getEnv().getClientMap();
3804 MapNode n = client->getEnv().getClientMap().getNodeNoEx(nodepos);
3806 if (!runData.digging) {
3807 infostream << "Started digging" << std::endl;
3808 if (client->moddingEnabled() && client->getScript()->on_punchnode(nodepos, n))
3810 client->interact(0, pointed);
3811 runData.digging = true;
3812 runData.ldown_for_dig = true;
3815 // NOTE: Similar piece of code exists on the server side for
3817 // Get digging parameters
3818 DigParams params = getDigParams(nodedef_manager->get(n).groups,
3819 &playeritem_toolcap);
3821 // If can't dig, try hand
3822 if (!params.diggable) {
3823 InventoryList *hlist = local_inventory->getList("hand");
3824 const ItemDefinition &hand =
3825 hlist ? hlist->getItem(0).getDefinition(itemdef_manager) : itemdef_manager->get("");
3826 const ToolCapabilities *tp = hand.tool_capabilities;
3829 params = getDigParams(nodedef_manager->get(n).groups, tp);
3832 if (!params.diggable) {
3833 // I guess nobody will wait for this long
3834 runData.dig_time_complete = 10000000.0;
3836 runData.dig_time_complete = params.time;
3838 if (m_cache_enable_particles) {
3839 const ContentFeatures &features =
3840 client->getNodeDefManager()->get(n);
3841 client->getParticleManager()->addPunchingParticles(client, smgr,
3842 player, nodepos, n, features);
3846 if (runData.dig_time_complete >= 0.001) {
3847 runData.dig_index = (float)crack_animation_length
3849 / runData.dig_time_complete;
3851 // This is for torches
3852 runData.dig_index = crack_animation_length;
3855 SimpleSoundSpec sound_dig = nodedef_manager->get(n).sound_dig;
3857 if (sound_dig.exists() && params.diggable) {
3858 if (sound_dig.name == "__group") {
3859 if (params.main_group != "") {
3860 soundmaker->m_player_leftpunch_sound.gain = 0.5;
3861 soundmaker->m_player_leftpunch_sound.name =
3862 std::string("default_dig_") +
3866 soundmaker->m_player_leftpunch_sound = sound_dig;
3870 // Don't show cracks if not diggable
3871 if (runData.dig_time_complete >= 100000.0) {
3872 } else if (runData.dig_index < crack_animation_length) {
3873 //TimeTaker timer("client.setTempMod");
3874 //infostream<<"dig_index="<<dig_index<<std::endl;
3875 client->setCrack(runData.dig_index, nodepos);
3877 infostream << "Digging completed" << std::endl;
3878 client->setCrack(-1, v3s16(0, 0, 0));
3880 runData.dig_time = 0;
3881 runData.digging = false;
3883 runData.nodig_delay_timer =
3884 runData.dig_time_complete / (float)crack_animation_length;
3886 // We don't want a corresponding delay to
3887 // very time consuming nodes
3888 if (runData.nodig_delay_timer > 0.3)
3889 runData.nodig_delay_timer = 0.3;
3891 bool is_valid_position;
3892 MapNode wasnode = map.getNodeNoEx(nodepos, &is_valid_position);
3893 if (is_valid_position) {
3894 if (client->moddingEnabled()) {
3895 if (client->getScript()->on_dignode(nodepos, wasnode)) {
3899 client->removeNode(nodepos);
3902 client->interact(2, pointed);
3904 if (m_cache_enable_particles) {
3905 const ContentFeatures &features =
3906 client->getNodeDefManager()->get(wasnode);
3907 client->getParticleManager()->addDiggingParticles(client, smgr,
3908 player, nodepos, wasnode, features);
3912 // Send event to trigger sound
3913 MtEvent *e = new NodeDugEvent(nodepos, wasnode);
3914 client->event()->put(e);
3917 if (runData.dig_time_complete < 100000.0) {
3918 runData.dig_time += dtime;
3920 runData.dig_time = 0;
3921 client->setCrack(-1, nodepos);
3924 camera->setDigging(0); // left click animation
3928 void Game::updateFrame(ProfilerGraph *graph, RunStats *stats, f32 dtime,
3929 const CameraOrientation &cam)
3931 LocalPlayer *player = client->getEnv().getLocalPlayer();
3937 if (draw_control->range_all) {
3938 runData.fog_range = 100000 * BS;
3940 runData.fog_range = draw_control->wanted_range * BS;
3944 Calculate general brightness
3946 u32 daynight_ratio = client->getEnv().getDayNightRatio();
3947 float time_brightness = decode_light_f((float)daynight_ratio / 1000.0);
3948 float direct_brightness;
3951 if (m_cache_enable_noclip && m_cache_enable_free_move) {
3952 direct_brightness = time_brightness;
3953 sunlight_seen = true;
3955 ScopeProfiler sp(g_profiler, "Detecting background light", SPT_AVG);
3956 float old_brightness = sky->getBrightness();
3957 direct_brightness = client->getEnv().getClientMap()
3958 .getBackgroundBrightness(MYMIN(runData.fog_range * 1.2, 60 * BS),
3959 daynight_ratio, (int)(old_brightness * 255.5), &sunlight_seen)
3963 float time_of_day_smooth = runData.time_of_day_smooth;
3964 float time_of_day = client->getEnv().getTimeOfDayF();
3966 static const float maxsm = 0.05;
3967 static const float todsm = 0.05;
3969 if (fabs(time_of_day - time_of_day_smooth) > maxsm &&
3970 fabs(time_of_day - time_of_day_smooth + 1.0) > maxsm &&
3971 fabs(time_of_day - time_of_day_smooth - 1.0) > maxsm)
3972 time_of_day_smooth = time_of_day;
3974 if (time_of_day_smooth > 0.8 && time_of_day < 0.2)
3975 time_of_day_smooth = time_of_day_smooth * (1.0 - todsm)
3976 + (time_of_day + 1.0) * todsm;
3978 time_of_day_smooth = time_of_day_smooth * (1.0 - todsm)
3979 + time_of_day * todsm;
3981 runData.time_of_day = time_of_day;
3982 runData.time_of_day_smooth = time_of_day_smooth;
3984 sky->update(time_of_day_smooth, time_brightness, direct_brightness,
3985 sunlight_seen, camera->getCameraMode(), player->getYaw(),
3986 player->getPitch());
3992 v3f player_position = player->getPosition();
3993 if (sky->getCloudsVisible()) {
3994 clouds->setVisible(true);
3995 clouds->step(dtime);
3996 clouds->update(v2f(player_position.X, player_position.Z),
3997 sky->getCloudColor());
3999 clouds->setVisible(false);
4006 client->getParticleManager()->step(dtime);
4012 if (m_cache_enable_fog && !flags.force_fog_off) {
4015 video::EFT_FOG_LINEAR,
4016 runData.fog_range * m_cache_fog_start,
4017 runData.fog_range * 1.0,
4025 video::EFT_FOG_LINEAR,
4035 Get chat messages from client
4038 v2u32 screensize = driver->getScreenSize();
4040 updateChat(*client, dtime, flags.show_debug, screensize,
4041 flags.show_chat, runData.profiler_current_page,
4042 *chat_backend, guitext_chat);
4048 if (client->getPlayerItem() != runData.new_playeritem)
4049 client->selectPlayerItem(runData.new_playeritem);
4051 // Update local inventory if it has changed
4052 if (client->getLocalInventoryUpdated()) {
4053 //infostream<<"Updating local inventory"<<std::endl;
4054 client->getLocalInventory(*local_inventory);
4055 runData.update_wielded_item_trigger = true;
4058 if (runData.update_wielded_item_trigger) {
4059 // Update wielded tool
4060 InventoryList *mlist = local_inventory->getList("main");
4062 if (mlist && (client->getPlayerItem() < mlist->getSize())) {
4063 ItemStack item = mlist->getItem(client->getPlayerItem());
4064 if (item.getDefinition(itemdef_manager).name.empty()) { // override the hand
4065 InventoryList *hlist = local_inventory->getList("hand");
4067 item = hlist->getItem(0);
4069 camera->wield(item);
4072 runData.update_wielded_item_trigger = false;
4076 Update block draw list every 200ms or when camera direction has
4079 runData.update_draw_list_timer += dtime;
4081 v3f camera_direction = camera->getDirection();
4082 if (runData.update_draw_list_timer >= 0.2
4083 || runData.update_draw_list_last_cam_dir.getDistanceFrom(camera_direction) > 0.2
4084 || m_camera_offset_changed) {
4085 runData.update_draw_list_timer = 0;
4086 client->getEnv().getClientMap().updateDrawList(driver);
4087 runData.update_draw_list_last_cam_dir = camera_direction;
4090 updateGui(*stats, dtime, cam);
4093 make sure menu is on top
4094 1. Delete formspec menu reference if menu was removed
4095 2. Else, make sure formspec menu is on top
4097 if (current_formspec) {
4098 if (current_formspec->getReferenceCount() == 1) {
4099 current_formspec->drop();
4100 current_formspec = NULL;
4101 } else if (!noMenuActive()) {
4102 guiroot->bringToFront(current_formspec);
4110 const video::SColor &skycolor = sky->getSkyColor();
4112 TimeTaker tt_draw("mainloop: draw");
4113 driver->beginScene(true, true, skycolor);
4115 draw_scene(driver, smgr, *camera, *client, player, *hud, *mapper,
4116 guienv, screensize, skycolor, flags.show_hud,
4117 flags.show_minimap);
4122 if (flags.show_profiler_graph)
4123 graph->draw(10, screensize.Y - 10, driver, g_fontengine->getFont());
4128 if (runData.damage_flash > 0.0) {
4129 video::SColor color(runData.damage_flash, 180, 0, 0);
4130 driver->draw2DRectangle(color,
4131 core::rect<s32>(0, 0, screensize.X, screensize.Y),
4134 runData.damage_flash -= 100.0 * dtime;
4140 if (player->hurt_tilt_timer > 0.0) {
4141 player->hurt_tilt_timer -= dtime * 5;
4143 if (player->hurt_tilt_timer < 0)
4144 player->hurt_tilt_strength = 0;
4148 Update minimap pos and rotation
4150 if (flags.show_minimap && flags.show_hud) {
4151 mapper->setPos(floatToInt(player->getPosition(), BS));
4152 mapper->setAngle(player->getYaw());
4160 stats->drawtime = tt_draw.stop(true);
4161 g_profiler->graphAdd("mainloop_draw", stats->drawtime / 1000.0f);
4165 inline static const char *yawToDirectionString(int yaw)
4167 static const char *direction[4] = {"North [+Z]", "West [-X]", "South [-Z]", "East [+X]"};
4169 yaw = wrapDegrees_0_360(yaw);
4170 yaw = (yaw + 45) % 360 / 90;
4172 return direction[yaw];
4176 void Game::updateGui(const RunStats &stats, f32 dtime, const CameraOrientation &cam)
4178 v2u32 screensize = driver->getScreenSize();
4179 LocalPlayer *player = client->getEnv().getLocalPlayer();
4180 v3f player_position = player->getPosition();
4182 if (flags.show_debug) {
4183 static float drawtime_avg = 0;
4184 drawtime_avg = drawtime_avg * 0.95 + stats.drawtime * 0.05;
4186 u16 fps = 1.0 / stats.dtime_jitter.avg;
4188 std::ostringstream os(std::ios_base::binary);
4190 << PROJECT_NAME_C " " << g_version_hash
4192 << " (R: range_all=" << draw_control->range_all << ")"
4193 << std::setprecision(0)
4194 << " drawtime = " << drawtime_avg
4195 << std::setprecision(1)
4196 << ", dtime_jitter = "
4197 << (stats.dtime_jitter.max_fraction * 100.0) << " %"
4198 << std::setprecision(1)
4199 << ", v_range = " << draw_control->wanted_range
4200 << std::setprecision(3)
4201 << ", RTT = " << client->getRTT();
4202 setStaticText(guitext, utf8_to_wide(os.str()).c_str());
4203 guitext->setVisible(true);
4205 guitext->setVisible(false);
4208 if (guitext->isVisible()) {
4209 core::rect<s32> rect(
4211 screensize.X, 5 + g_fontengine->getTextHeight()
4213 guitext->setRelativePosition(rect);
4216 if (flags.show_debug) {
4217 std::ostringstream os(std::ios_base::binary);
4218 os << std::setprecision(1) << std::fixed
4219 << "(" << (player_position.X / BS)
4220 << ", " << (player_position.Y / BS)
4221 << ", " << (player_position.Z / BS)
4222 << ") (yaw=" << (wrapDegrees_0_360(cam.camera_yaw))
4223 << " " << yawToDirectionString(cam.camera_yaw)
4224 << ") (seed = " << ((u64)client->getMapSeed())
4227 if (runData.pointed_old.type == POINTEDTHING_NODE) {
4228 ClientMap &map = client->getEnv().getClientMap();
4229 const INodeDefManager *nodedef = client->getNodeDefManager();
4230 MapNode n = map.getNodeNoEx(runData.pointed_old.node_undersurface);
4231 if (n.getContent() != CONTENT_IGNORE && nodedef->get(n).name != "unknown") {
4232 const ContentFeatures &features = nodedef->get(n);
4233 os << " (pointing_at = " << nodedef->get(n).name
4234 << " - " << features.tiledef[0].name.c_str()
4239 setStaticText(guitext2, utf8_to_wide(os.str()).c_str());
4240 guitext2->setVisible(true);
4242 core::rect<s32> rect(
4243 5, 5 + g_fontengine->getTextHeight(),
4244 screensize.X, 5 + g_fontengine->getTextHeight() * 2
4246 guitext2->setRelativePosition(rect);
4248 guitext2->setVisible(false);
4251 setStaticText(guitext_info, infotext.c_str());
4252 guitext_info->setVisible(flags.show_hud && g_menumgr.menuCount() == 0);
4254 float statustext_time_max = 1.5;
4256 if (!m_statustext.empty()) {
4257 runData.statustext_time += dtime;
4259 if (runData.statustext_time >= statustext_time_max) {
4261 runData.statustext_time = 0;
4265 setStaticText(guitext_status, m_statustext.c_str());
4266 guitext_status->setVisible(!m_statustext.empty());
4268 if (!m_statustext.empty()) {
4269 s32 status_width = guitext_status->getTextWidth();
4270 s32 status_height = guitext_status->getTextHeight();
4271 s32 status_y = screensize.Y - 150;
4272 s32 status_x = (screensize.X - status_width) / 2;
4273 core::rect<s32> rect(
4274 status_x , status_y - status_height,
4275 status_x + status_width, status_y
4277 guitext_status->setRelativePosition(rect);
4280 video::SColor initial_color(255, 0, 0, 0);
4282 if (guienv->getSkin())
4283 initial_color = guienv->getSkin()->getColor(gui::EGDC_BUTTON_TEXT);
4285 video::SColor final_color = initial_color;
4286 final_color.setAlpha(0);
4287 video::SColor fade_color = initial_color.getInterpolated_quadratic(
4288 initial_color, final_color,
4289 pow(runData.statustext_time / statustext_time_max, 2.0f));
4290 guitext_status->setOverrideColor(fade_color);
4291 guitext_status->enableOverrideColor(true);
4296 /* Log times and stuff for visualization */
4297 inline void Game::updateProfilerGraphs(ProfilerGraph *graph)
4299 Profiler::GraphValues values;
4300 g_profiler->graphGet(values);
4306 /****************************************************************************
4308 ****************************************************************************/
4310 /* On some computers framerate doesn't seem to be automatically limited
4312 inline void Game::limitFps(FpsControl *fps_timings, f32 *dtime)
4314 // not using getRealTime is necessary for wine
4315 device->getTimer()->tick(); // Maker sure device time is up-to-date
4316 u32 time = device->getTimer()->getTime();
4317 u32 last_time = fps_timings->last_time;
4319 if (time > last_time) // Make sure time hasn't overflowed
4320 fps_timings->busy_time = time - last_time;
4322 fps_timings->busy_time = 0;
4324 u32 frametime_min = 1000 / (g_menumgr.pausesGame()
4325 ? g_settings->getFloat("pause_fps_max")
4326 : g_settings->getFloat("fps_max"));
4328 if (fps_timings->busy_time < frametime_min) {
4329 fps_timings->sleep_time = frametime_min - fps_timings->busy_time;
4330 device->sleep(fps_timings->sleep_time);
4332 fps_timings->sleep_time = 0;
4335 /* Get the new value of the device timer. Note that device->sleep() may
4336 * not sleep for the entire requested time as sleep may be interrupted and
4337 * therefore it is arguably more accurate to get the new time from the
4338 * device rather than calculating it by adding sleep_time to time.
4341 device->getTimer()->tick(); // Update device timer
4342 time = device->getTimer()->getTime();
4344 if (time > last_time) // Make sure last_time hasn't overflowed
4345 *dtime = (time - last_time) / 1000.0;
4349 fps_timings->last_time = time;
4352 // Note: This will free (using delete[])! \p msg. If you want to use it later,
4353 // pass a copy of it to this function
4354 // Note: \p msg must be allocated using new (not malloc())
4355 void Game::showOverlayMessage(const wchar_t *msg, float dtime,
4356 int percent, bool draw_clouds)
4358 draw_load_screen(msg, device, guienv, texture_src, dtime, percent,
4363 void Game::settingChangedCallback(const std::string &setting_name, void *data)
4365 ((Game *)data)->readSettings();
4368 void Game::readSettings()
4370 m_cache_doubletap_jump = g_settings->getBool("doubletap_jump");
4371 m_cache_enable_clouds = g_settings->getBool("enable_clouds");
4372 m_cache_enable_joysticks = g_settings->getBool("enable_joysticks");
4373 m_cache_enable_particles = g_settings->getBool("enable_particles");
4374 m_cache_enable_fog = g_settings->getBool("enable_fog");
4375 m_cache_mouse_sensitivity = g_settings->getFloat("mouse_sensitivity");
4376 m_cache_joystick_frustum_sensitivity = g_settings->getFloat("joystick_frustum_sensitivity");
4377 m_repeat_right_click_time = g_settings->getFloat("repeat_rightclick_time");
4379 m_cache_enable_noclip = g_settings->getBool("noclip");
4380 m_cache_enable_free_move = g_settings->getBool("free_move");
4382 m_cache_fog_start = g_settings->getFloat("fog_start");
4384 m_cache_cam_smoothing = 0;
4385 if (g_settings->getBool("cinematic"))
4386 m_cache_cam_smoothing = 1 - g_settings->getFloat("cinematic_camera_smoothing");
4388 m_cache_cam_smoothing = 1 - g_settings->getFloat("camera_smoothing");
4390 m_cache_fog_start = rangelim(m_cache_fog_start, 0.0f, 0.99f);
4391 m_cache_cam_smoothing = rangelim(m_cache_cam_smoothing, 0.01f, 1.0f);
4392 m_cache_mouse_sensitivity = rangelim(m_cache_mouse_sensitivity, 0.001, 100.0);
4396 /****************************************************************************/
4397 /****************************************************************************
4399 ****************************************************************************/
4400 /****************************************************************************/
4402 void Game::extendedResourceCleanup()
4404 // Extended resource accounting
4405 infostream << "Irrlicht resources after cleanup:" << std::endl;
4406 infostream << "\tRemaining meshes : "
4407 << device->getSceneManager()->getMeshCache()->getMeshCount() << std::endl;
4408 infostream << "\tRemaining textures : "
4409 << driver->getTextureCount() << std::endl;
4411 for (unsigned int i = 0; i < driver->getTextureCount(); i++) {
4412 irr::video::ITexture *texture = driver->getTextureByIndex(i);
4413 infostream << "\t\t" << i << ":" << texture->getName().getPath().c_str()
4417 clearTextureNameCache();
4418 infostream << "\tRemaining materials: "
4419 << driver-> getMaterialRendererCount()
4420 << " (note: irrlicht doesn't support removing renderers)" << std::endl;
4423 void Game::showPauseMenu()
4426 static const std::string control_text = strgettext("Default Controls:\n"
4427 "No menu visible:\n"
4428 "- single tap: button activate\n"
4429 "- double tap: place/use\n"
4430 "- slide finger: look around\n"
4431 "Menu/Inventory visible:\n"
4432 "- double tap (outside):\n"
4434 "- touch stack, touch slot:\n"
4436 "- touch&drag, tap 2nd finger\n"
4437 " --> place single item to slot\n"
4440 static const std::string control_text = strgettext("Default Controls:\n"
4442 "- Space: jump/climb\n"
4443 "- Shift: sneak/go down\n"
4446 "- Mouse: turn/look\n"
4447 "- Mouse left: dig/punch\n"
4448 "- Mouse right: place/use\n"
4449 "- Mouse wheel: select item\n"
4454 float ypos = simple_singleplayer_mode ? 0.5 : 0.1;
4455 std::ostringstream os;
4457 os << FORMSPEC_VERSION_STRING << SIZE_TAG
4458 << "button_exit[4," << (ypos++) << ";3,0.5;btn_continue;"
4459 << strgettext("Continue") << "]";
4461 if (!simple_singleplayer_mode) {
4462 os << "button_exit[4," << (ypos++) << ";3,0.5;btn_change_password;"
4463 << strgettext("Change Password") << "]";
4467 os << "button_exit[4," << (ypos++) << ";3,0.5;btn_sound;"
4468 << strgettext("Sound Volume") << "]";
4469 os << "button_exit[4," << (ypos++) << ";3,0.5;btn_key_config;"
4470 << strgettext("Change Keys") << "]";
4472 os << "button_exit[4," << (ypos++) << ";3,0.5;btn_exit_menu;"
4473 << strgettext("Exit to Menu") << "]";
4474 os << "button_exit[4," << (ypos++) << ";3,0.5;btn_exit_os;"
4475 << strgettext("Exit to OS") << "]"
4476 << "textarea[7.5,0.25;3.9,6.25;;" << control_text << ";]"
4477 << "textarea[0.4,0.25;3.5,6;;" << PROJECT_NAME_C "\n"
4478 << g_build_info << "\n"
4479 << "path_user = " << wrap_rows(porting::path_user, 20)
4483 /* Note: FormspecFormSource and LocalFormspecHandler *
4484 * are deleted by guiFormSpecMenu */
4485 FormspecFormSource *fs_src = new FormspecFormSource(os.str());
4486 LocalFormspecHandler *txt_dst = new LocalFormspecHandler("MT_PAUSE_MENU");
4488 create_formspec_menu(¤t_formspec, client, device, &input->joystick, fs_src, txt_dst);
4489 current_formspec->setFocus("btn_continue");
4490 current_formspec->doPause = true;
4493 /****************************************************************************/
4494 /****************************************************************************
4495 extern function for launching the game
4496 ****************************************************************************/
4497 /****************************************************************************/
4499 void the_game(bool *kill,
4501 InputHandler *input,
4502 IrrlichtDevice *device,
4504 const std::string &map_dir,
4505 const std::string &playername,
4506 const std::string &password,
4507 const std::string &address, // If empty local server is created
4510 std::string &error_message,
4511 ChatBackend &chat_backend,
4512 bool *reconnect_requested,
4513 const SubgameSpec &gamespec, // Used for local game
4514 bool simple_singleplayer_mode)
4518 /* Make a copy of the server address because if a local singleplayer server
4519 * is created then this is updated and we don't want to change the value
4520 * passed to us by the calling function
4522 std::string server_address = address;
4526 if (game.startup(kill, random_input, input, device, map_dir,
4527 playername, password, &server_address, port, error_message,
4528 reconnect_requested, &chat_backend, gamespec,
4529 simple_singleplayer_mode)) {
4534 } catch (SerializationError &e) {
4535 error_message = std::string("A serialization error occurred:\n")
4536 + e.what() + "\n\nThe server is probably "
4537 " running a different version of " PROJECT_NAME_C ".";
4538 errorstream << error_message << std::endl;
4539 } catch (ServerError &e) {
4540 error_message = e.what();
4541 errorstream << "ServerError: " << error_message << std::endl;
4542 } catch (ModError &e) {
4543 error_message = e.what() + strgettext("\nCheck debug.txt for details.");
4544 errorstream << "ModError: " << error_message << std::endl;