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.
21 #include "irrlichttypes_extrabloated.h"
22 #include <IGUICheckBox.h>
23 #include <IGUIEditBox.h>
24 #include <IGUIButton.h>
25 #include <IGUIStaticText.h>
27 #include <IMaterialRendererServices.h>
28 #include "IMeshCache.h"
31 #include "guiPasswordChange.h"
32 #include "guiVolumeChange.h"
33 #include "guiKeyChangeMenu.h"
34 #include "guiFormSpecMenu.h"
36 #include "guiChatConsole.h"
40 #include "particles.h"
45 #include "mainmenumanager.h"
49 // Needed for determining pointing to nodes
51 #include "nodemetadata.h"
52 #include "main.h" // For g_settings
54 #include "client/tile.h" // For TextureSource
55 #include "shader.h" // For ShaderSource
56 #include "logoutputbuffer.h"
58 #include "quicktune_shortcutter.h"
59 #include "clientmap.h"
64 #include "sound_openal.h"
66 #include "event_manager.h"
69 #include "util/directiontables.h"
70 #include "util/pointedthing.h"
71 #include "drawscene.h"
72 #include "content_cao.h"
73 #include "fontengine.h"
75 #ifdef HAVE_TOUCHSCREENGUI
76 #include "touchscreengui.h"
83 struct TextDestNodeMetadata : public TextDest {
84 TextDestNodeMetadata(v3s16 p, Client *client)
89 // This is deprecated I guess? -celeron55
90 void gotText(std::wstring text)
92 std::string ntext = wide_to_narrow(text);
93 infostream << "Submitting 'text' field of node at (" << m_p.X << ","
94 << m_p.Y << "," << m_p.Z << "): " << ntext << std::endl;
95 std::map<std::string, std::string> fields;
96 fields["text"] = ntext;
97 m_client->sendNodemetaFields(m_p, "", fields);
99 void gotText(std::map<std::string, std::string> fields)
101 m_client->sendNodemetaFields(m_p, "", fields);
108 struct TextDestPlayerInventory : public TextDest {
109 TextDestPlayerInventory(Client *client)
114 TextDestPlayerInventory(Client *client, std::string formname)
117 m_formname = formname;
119 void gotText(std::map<std::string, std::string> fields)
121 m_client->sendInventoryFields(m_formname, fields);
127 struct LocalFormspecHandler : public TextDest {
128 LocalFormspecHandler();
129 LocalFormspecHandler(std::string formname) :
132 m_formname = formname;
135 LocalFormspecHandler(std::string formname, Client *client) :
138 m_formname = formname;
141 void gotText(std::wstring message)
143 errorstream << "LocalFormspecHandler::gotText old style message received" << std::endl;
146 void gotText(std::map<std::string, std::string> fields)
148 if (m_formname == "MT_PAUSE_MENU") {
149 if (fields.find("btn_sound") != fields.end()) {
150 g_gamecallback->changeVolume();
154 if (fields.find("btn_key_config") != fields.end()) {
155 g_gamecallback->keyConfig();
159 if (fields.find("btn_exit_menu") != fields.end()) {
160 g_gamecallback->disconnect();
164 if (fields.find("btn_exit_os") != fields.end()) {
165 g_gamecallback->exitToOS();
169 if (fields.find("btn_change_password") != fields.end()) {
170 g_gamecallback->changePassword();
174 if (fields.find("quit") != fields.end()) {
178 if (fields.find("btn_continue") != fields.end()) {
183 if (m_formname == "MT_CHAT_MENU") {
184 assert(m_client != 0);
186 if ((fields.find("btn_send") != fields.end()) ||
187 (fields.find("quit") != fields.end())) {
188 if (fields.find("f_text") != fields.end()) {
189 m_client->typeChatMessage(narrow_to_wide(fields["f_text"]));
196 if (m_formname == "MT_DEATH_SCREEN") {
197 assert(m_client != 0);
199 if ((fields.find("btn_respawn") != fields.end())) {
200 m_client->sendRespawn();
204 if (fields.find("quit") != fields.end()) {
205 m_client->sendRespawn();
210 // don't show error message for unhandled cursor keys
211 if ((fields.find("key_up") != fields.end()) ||
212 (fields.find("key_down") != fields.end()) ||
213 (fields.find("key_left") != fields.end()) ||
214 (fields.find("key_right") != fields.end())) {
218 errorstream << "LocalFormspecHandler::gotText unhandled >" << m_formname << "< event" << std::endl;
221 for (std::map<std::string, std::string>::iterator iter = fields.begin();
222 iter != fields.end(); iter++) {
223 errorstream << "\t" << i << ": " << iter->first << "=" << iter->second << std::endl;
231 /* Form update callback */
233 class NodeMetadataFormSource: public IFormSource
236 NodeMetadataFormSource(ClientMap *map, v3s16 p):
241 std::string getForm()
243 NodeMetadata *meta = m_map->getNodeMetadata(m_p);
248 return meta->getString("formspec");
250 std::string resolveText(std::string str)
252 NodeMetadata *meta = m_map->getNodeMetadata(m_p);
257 return meta->resolveString(str);
264 class PlayerInventoryFormSource: public IFormSource
267 PlayerInventoryFormSource(Client *client):
271 std::string getForm()
273 LocalPlayer *player = m_client->getEnv().getLocalPlayer();
274 return player->inventory_formspec;
281 Check if a node is pointable
283 inline bool isPointableNode(const MapNode &n,
284 Client *client, bool liquids_pointable)
286 const ContentFeatures &features = client->getNodeDefManager()->get(n);
287 return features.pointable ||
288 (liquids_pointable && features.isLiquid());
292 Find what the player is pointing at
294 PointedThing getPointedThing(Client *client, v3f player_position,
295 v3f camera_direction, v3f camera_position, core::line3d<f32> shootline,
296 f32 d, bool liquids_pointable, bool look_for_object, v3s16 camera_offset,
297 std::vector<aabb3f> &hilightboxes, ClientActiveObject *&selected_object)
301 hilightboxes.clear();
302 selected_object = NULL;
304 INodeDefManager *nodedef = client->getNodeDefManager();
305 ClientMap &map = client->getEnv().getClientMap();
307 f32 mindistance = BS * 1001;
309 // First try to find a pointed at active object
310 if (look_for_object) {
311 selected_object = client->getSelectedActiveObject(d * BS,
312 camera_position, shootline);
314 if (selected_object != NULL) {
315 if (selected_object->doShowSelectionBox()) {
316 aabb3f *selection_box = selected_object->getSelectionBox();
317 // Box should exist because object was
318 // returned in the first place
319 assert(selection_box);
321 v3f pos = selected_object->getPosition();
322 hilightboxes.push_back(aabb3f(
323 selection_box->MinEdge + pos - intToFloat(camera_offset, BS),
324 selection_box->MaxEdge + pos - intToFloat(camera_offset, BS)));
327 mindistance = (selected_object->getPosition() - camera_position).getLength();
329 result.type = POINTEDTHING_OBJECT;
330 result.object_id = selected_object->getId();
334 // That didn't work, try to find a pointed at node
337 v3s16 pos_i = floatToInt(player_position, BS);
339 /*infostream<<"pos_i=("<<pos_i.X<<","<<pos_i.Y<<","<<pos_i.Z<<")"
343 s16 ystart = pos_i.Y + 0 - (camera_direction.Y < 0 ? a : 1);
344 s16 zstart = pos_i.Z - (camera_direction.Z < 0 ? a : 1);
345 s16 xstart = pos_i.X - (camera_direction.X < 0 ? a : 1);
346 s16 yend = pos_i.Y + 1 + (camera_direction.Y > 0 ? a : 1);
347 s16 zend = pos_i.Z + (camera_direction.Z > 0 ? a : 1);
348 s16 xend = pos_i.X + (camera_direction.X > 0 ? a : 1);
350 // Prevent signed number overflow
360 for (s16 y = ystart; y <= yend; y++)
361 for (s16 z = zstart; z <= zend; z++)
362 for (s16 x = xstart; x <= xend; x++) {
364 bool is_valid_position;
366 n = map.getNodeNoEx(v3s16(x, y, z), &is_valid_position);
367 if (!is_valid_position)
370 if (!isPointableNode(n, client, liquids_pointable))
373 std::vector<aabb3f> boxes = n.getSelectionBoxes(nodedef);
376 v3f npf = intToFloat(np, BS);
378 for (std::vector<aabb3f>::const_iterator
380 i != boxes.end(); i++) {
385 for (u16 j = 0; j < 6; j++) {
386 v3s16 facedir = g_6dirs[j];
387 aabb3f facebox = box;
392 facebox.MinEdge.X = facebox.MaxEdge.X - d;
393 else if (facedir.X < 0)
394 facebox.MaxEdge.X = facebox.MinEdge.X + d;
395 else if (facedir.Y > 0)
396 facebox.MinEdge.Y = facebox.MaxEdge.Y - d;
397 else if (facedir.Y < 0)
398 facebox.MaxEdge.Y = facebox.MinEdge.Y + d;
399 else if (facedir.Z > 0)
400 facebox.MinEdge.Z = facebox.MaxEdge.Z - d;
401 else if (facedir.Z < 0)
402 facebox.MaxEdge.Z = facebox.MinEdge.Z + d;
404 v3f centerpoint = facebox.getCenter();
405 f32 distance = (centerpoint - camera_position).getLength();
407 if (distance >= mindistance)
410 if (!facebox.intersectsWithLine(shootline))
413 v3s16 np_above = np + facedir;
415 result.type = POINTEDTHING_NODE;
416 result.node_undersurface = np;
417 result.node_abovesurface = np_above;
418 mindistance = distance;
420 hilightboxes.clear();
422 if (!g_settings->getBool("enable_node_highlighting")) {
423 for (std::vector<aabb3f>::const_iterator
425 i2 != boxes.end(); i2++) {
427 box.MinEdge += npf + v3f(-d, -d, -d) - intToFloat(camera_offset, BS);
428 box.MaxEdge += npf + v3f(d, d, d) - intToFloat(camera_offset, BS);
429 hilightboxes.push_back(box);
439 /* Profiler display */
441 void update_profiler_gui(gui::IGUIStaticText *guitext_profiler, FontEngine *fe,
442 u32 show_profiler, u32 show_profiler_max, s32 screen_height)
444 if (show_profiler == 0) {
445 guitext_profiler->setVisible(false);
448 std::ostringstream os(std::ios_base::binary);
449 g_profiler->printPage(os, show_profiler, show_profiler_max);
450 std::wstring text = narrow_to_wide(os.str());
451 guitext_profiler->setText(text.c_str());
452 guitext_profiler->setVisible(true);
454 s32 w = fe->getTextWidth(text.c_str());
459 unsigned text_height = fe->getTextHeight();
461 core::position2di upper_left, lower_right;
464 upper_left.Y = (text_height + 5) * 2;
465 lower_right.X = 12 + w;
466 lower_right.Y = upper_left.Y + (text_height + 1) * MAX_PROFILER_TEXT_ROWS;
468 if (lower_right.Y > screen_height * 2 / 3)
469 lower_right.Y = screen_height * 2 / 3;
471 core::rect<s32> rect(upper_left, lower_right);
473 guitext_profiler->setRelativePosition(rect);
474 guitext_profiler->setVisible(true);
482 Profiler::GraphValues values;
488 Meta(float initial = 0,
489 video::SColor color = video::SColor(255, 255, 255, 255)):
495 std::list<Piece> m_log;
503 void put(const Profiler::GraphValues &values)
506 piece.values = values;
507 m_log.push_back(piece);
509 while (m_log.size() > m_log_max_size)
510 m_log.erase(m_log.begin());
513 void draw(s32 x_left, s32 y_bottom, video::IVideoDriver *driver,
514 gui::IGUIFont *font) const
516 std::map<std::string, Meta> m_meta;
518 for (std::list<Piece>::const_iterator k = m_log.begin();
519 k != m_log.end(); k++) {
520 const Piece &piece = *k;
522 for (Profiler::GraphValues::const_iterator i = piece.values.begin();
523 i != piece.values.end(); i++) {
524 const std::string &id = i->first;
525 const float &value = i->second;
526 std::map<std::string, Meta>::iterator j =
529 if (j == m_meta.end()) {
530 m_meta[id] = Meta(value);
534 if (value < j->second.min)
535 j->second.min = value;
537 if (value > j->second.max)
538 j->second.max = value;
543 static const video::SColor usable_colors[] = {
544 video::SColor(255, 255, 100, 100),
545 video::SColor(255, 90, 225, 90),
546 video::SColor(255, 100, 100, 255),
547 video::SColor(255, 255, 150, 50),
548 video::SColor(255, 220, 220, 100)
550 static const u32 usable_colors_count =
551 sizeof(usable_colors) / sizeof(*usable_colors);
552 u32 next_color_i = 0;
554 for (std::map<std::string, Meta>::iterator i = m_meta.begin();
555 i != m_meta.end(); i++) {
556 Meta &meta = i->second;
557 video::SColor color(255, 200, 200, 200);
559 if (next_color_i < usable_colors_count)
560 color = usable_colors[next_color_i++];
566 s32 textx = x_left + m_log_max_size + 15;
567 s32 textx2 = textx + 200 - 15;
571 u32 num_graphs = m_meta.size();
572 core::rect<s32> rect(x_left, y_bottom - num_graphs*graphh,
574 video::SColor bgcolor(120,0,0,0);
575 driver->draw2DRectangle(bgcolor, rect, NULL);
580 for (std::map<std::string, Meta>::const_iterator i = m_meta.begin();
581 i != m_meta.end(); i++) {
582 const std::string &id = i->first;
583 const Meta &meta = i->second;
585 s32 y = y_bottom - meta_i * 50;
586 float show_min = meta.min;
587 float show_max = meta.max;
589 if (show_min >= -0.0001 && show_max >= -0.0001) {
590 if (show_min <= show_max * 0.5)
596 snprintf(buf, 10, "%.3g", show_max);
597 font->draw(narrow_to_wide(buf).c_str(),
598 core::rect<s32>(textx, y - graphh,
599 textx2, y - graphh + texth),
601 snprintf(buf, 10, "%.3g", show_min);
602 font->draw(narrow_to_wide(buf).c_str(),
603 core::rect<s32>(textx, y - texth,
606 font->draw(narrow_to_wide(id).c_str(),
607 core::rect<s32>(textx, y - graphh / 2 - texth / 2,
608 textx2, y - graphh / 2 + texth / 2),
611 s32 graph1h = graphh;
612 bool relativegraph = (show_min != 0 && show_min != show_max);
613 float lastscaledvalue = 0.0;
614 bool lastscaledvalue_exists = false;
616 for (std::list<Piece>::const_iterator j = m_log.begin();
617 j != m_log.end(); j++) {
618 const Piece &piece = *j;
620 bool value_exists = false;
621 Profiler::GraphValues::const_iterator k =
622 piece.values.find(id);
624 if (k != piece.values.end()) {
631 lastscaledvalue_exists = false;
635 float scaledvalue = 1.0;
637 if (show_max != show_min)
638 scaledvalue = (value - show_min) / (show_max - show_min);
640 if (scaledvalue == 1.0 && value == 0) {
642 lastscaledvalue_exists = false;
647 if (lastscaledvalue_exists) {
648 s32 ivalue1 = lastscaledvalue * graph1h;
649 s32 ivalue2 = scaledvalue * graph1h;
650 driver->draw2DLine(v2s32(x - 1, graph1y - ivalue1),
651 v2s32(x, graph1y - ivalue2), meta.color);
654 lastscaledvalue = scaledvalue;
655 lastscaledvalue_exists = true;
657 s32 ivalue = scaledvalue * graph1h;
658 driver->draw2DLine(v2s32(x, graph1y),
659 v2s32(x, graph1y - ivalue), meta.color);
670 class NodeDugEvent: public MtEvent
676 NodeDugEvent(v3s16 p, MapNode n):
680 const char *getType() const
688 ISoundManager *m_sound;
689 INodeDefManager *m_ndef;
691 float m_player_step_timer;
693 SimpleSoundSpec m_player_step_sound;
694 SimpleSoundSpec m_player_leftpunch_sound;
695 SimpleSoundSpec m_player_rightpunch_sound;
697 SoundMaker(ISoundManager *sound, INodeDefManager *ndef):
700 m_player_step_timer(0)
704 void playPlayerStep()
706 if (m_player_step_timer <= 0 && m_player_step_sound.exists()) {
707 m_player_step_timer = 0.03;
708 m_sound->playSound(m_player_step_sound, false);
712 static void viewBobbingStep(MtEvent *e, void *data)
714 SoundMaker *sm = (SoundMaker *)data;
715 sm->playPlayerStep();
718 static void playerRegainGround(MtEvent *e, void *data)
720 SoundMaker *sm = (SoundMaker *)data;
721 sm->playPlayerStep();
724 static void playerJump(MtEvent *e, void *data)
726 //SoundMaker *sm = (SoundMaker*)data;
729 static void cameraPunchLeft(MtEvent *e, void *data)
731 SoundMaker *sm = (SoundMaker *)data;
732 sm->m_sound->playSound(sm->m_player_leftpunch_sound, false);
735 static void cameraPunchRight(MtEvent *e, void *data)
737 SoundMaker *sm = (SoundMaker *)data;
738 sm->m_sound->playSound(sm->m_player_rightpunch_sound, false);
741 static void nodeDug(MtEvent *e, void *data)
743 SoundMaker *sm = (SoundMaker *)data;
744 NodeDugEvent *nde = (NodeDugEvent *)e;
745 sm->m_sound->playSound(sm->m_ndef->get(nde->n).sound_dug, false);
748 static void playerDamage(MtEvent *e, void *data)
750 SoundMaker *sm = (SoundMaker *)data;
751 sm->m_sound->playSound(SimpleSoundSpec("player_damage", 0.5), false);
754 static void playerFallingDamage(MtEvent *e, void *data)
756 SoundMaker *sm = (SoundMaker *)data;
757 sm->m_sound->playSound(SimpleSoundSpec("player_falling_damage", 0.5), false);
760 void registerReceiver(MtEventManager *mgr)
762 mgr->reg("ViewBobbingStep", SoundMaker::viewBobbingStep, this);
763 mgr->reg("PlayerRegainGround", SoundMaker::playerRegainGround, this);
764 mgr->reg("PlayerJump", SoundMaker::playerJump, this);
765 mgr->reg("CameraPunchLeft", SoundMaker::cameraPunchLeft, this);
766 mgr->reg("CameraPunchRight", SoundMaker::cameraPunchRight, this);
767 mgr->reg("NodeDug", SoundMaker::nodeDug, this);
768 mgr->reg("PlayerDamage", SoundMaker::playerDamage, this);
769 mgr->reg("PlayerFallingDamage", SoundMaker::playerFallingDamage, this);
772 void step(float dtime)
774 m_player_step_timer -= dtime;
778 // Locally stored sounds don't need to be preloaded because of this
779 class GameOnDemandSoundFetcher: public OnDemandSoundFetcher
781 std::set<std::string> m_fetched;
783 void fetchSounds(const std::string &name,
784 std::set<std::string> &dst_paths,
785 std::set<std::string> &dst_datas)
787 if (m_fetched.count(name))
790 m_fetched.insert(name);
791 std::string base = porting::path_share + DIR_DELIM + "testsounds";
792 dst_paths.insert(base + DIR_DELIM + name + ".ogg");
793 dst_paths.insert(base + DIR_DELIM + name + ".0.ogg");
794 dst_paths.insert(base + DIR_DELIM + name + ".1.ogg");
795 dst_paths.insert(base + DIR_DELIM + name + ".2.ogg");
796 dst_paths.insert(base + DIR_DELIM + name + ".3.ogg");
797 dst_paths.insert(base + DIR_DELIM + name + ".4.ogg");
798 dst_paths.insert(base + DIR_DELIM + name + ".5.ogg");
799 dst_paths.insert(base + DIR_DELIM + name + ".6.ogg");
800 dst_paths.insert(base + DIR_DELIM + name + ".7.ogg");
801 dst_paths.insert(base + DIR_DELIM + name + ".8.ogg");
802 dst_paths.insert(base + DIR_DELIM + name + ".9.ogg");
806 class GameGlobalShaderConstantSetter : public IShaderConstantSetter
809 bool *m_force_fog_off;
815 void onSettingsChange(const std::string &name)
817 if (name == "enable_fog")
818 m_fogEnabled = g_settings->getBool("enable_fog");
821 static void SettingsCallback(const std::string name, void *userdata)
823 reinterpret_cast<GameGlobalShaderConstantSetter*>(userdata)->onSettingsChange(name);
826 GameGlobalShaderConstantSetter(Sky *sky, bool *force_fog_off,
827 f32 *fog_range, Client *client) :
829 m_force_fog_off(force_fog_off),
830 m_fog_range(fog_range),
833 g_settings->registerChangedCallback("enable_fog", SettingsCallback, this);
834 m_fogEnabled = g_settings->getBool("enable_fog");
837 ~GameGlobalShaderConstantSetter()
839 g_settings->deregisterChangedCallback("enable_fog", SettingsCallback, this);
842 virtual void onSetConstants(video::IMaterialRendererServices *services,
849 video::SColor bgcolor = m_sky->getBgColor();
850 video::SColorf bgcolorf(bgcolor);
851 float bgcolorfa[4] = {
857 services->setPixelShaderConstant("skyBgColor", bgcolorfa, 4);
860 float fog_distance = 10000 * BS;
862 if (m_fogEnabled && !*m_force_fog_off)
863 fog_distance = *m_fog_range;
865 services->setPixelShaderConstant("fogDistance", &fog_distance, 1);
868 u32 daynight_ratio = m_client->getEnv().getDayNightRatio();
869 float daynight_ratio_f = (float)daynight_ratio / 1000.0;
870 services->setPixelShaderConstant("dayNightRatio", &daynight_ratio_f, 1);
872 u32 animation_timer = porting::getTimeMs() % 100000;
873 float animation_timer_f = (float)animation_timer / 100000.0;
874 services->setPixelShaderConstant("animationTimer", &animation_timer_f, 1);
875 services->setVertexShaderConstant("animationTimer", &animation_timer_f, 1);
877 LocalPlayer *player = m_client->getEnv().getLocalPlayer();
878 v3f eye_position = player->getEyePosition();
879 services->setPixelShaderConstant("eyePosition", (irr::f32 *)&eye_position, 3);
880 services->setVertexShaderConstant("eyePosition", (irr::f32 *)&eye_position, 3);
882 // Uniform sampler layers
886 // before 1.8 there isn't a "integer interface", only float
887 #if (IRRLICHT_VERSION_MAJOR == 1 && IRRLICHT_VERSION_MINOR < 8)
888 services->setPixelShaderConstant("baseTexture" , (irr::f32 *)&layer0, 1);
889 services->setPixelShaderConstant("normalTexture" , (irr::f32 *)&layer1, 1);
890 services->setPixelShaderConstant("useNormalmap" , (irr::f32 *)&layer2, 1);
892 services->setPixelShaderConstant("baseTexture" , (irr::s32 *)&layer0, 1);
893 services->setPixelShaderConstant("normalTexture" , (irr::s32 *)&layer1, 1);
894 services->setPixelShaderConstant("useNormalmap" , (irr::s32 *)&layer2, 1);
899 bool nodePlacementPrediction(Client &client,
900 const ItemDefinition &playeritem_def, v3s16 nodepos, v3s16 neighbourpos)
902 std::string prediction = playeritem_def.node_placement_prediction;
903 INodeDefManager *nodedef = client.ndef();
904 ClientMap &map = client.getEnv().getClientMap();
906 bool is_valid_position;
908 node = map.getNodeNoEx(nodepos, &is_valid_position);
909 if (!is_valid_position)
912 if (prediction != "" && !nodedef->get(node).rightclickable) {
913 verbosestream << "Node placement prediction for "
914 << playeritem_def.name << " is "
915 << prediction << std::endl;
916 v3s16 p = neighbourpos;
918 // Place inside node itself if buildable_to
919 MapNode n_under = map.getNodeNoEx(nodepos, &is_valid_position);
920 if (is_valid_position)
922 if (nodedef->get(n_under).buildable_to)
925 node = map.getNodeNoEx(p, &is_valid_position);
926 if (is_valid_position &&!nodedef->get(node).buildable_to)
931 // Find id of predicted node
933 bool found = nodedef->getId(prediction, id);
936 errorstream << "Node placement prediction failed for "
937 << playeritem_def.name << " (places "
939 << ") - Name not known" << std::endl;
943 // Predict param2 for facedir and wallmounted nodes
946 if (nodedef->get(id).param_type_2 == CPT2_WALLMOUNTED) {
947 v3s16 dir = nodepos - neighbourpos;
949 if (abs(dir.Y) > MYMAX(abs(dir.X), abs(dir.Z))) {
950 param2 = dir.Y < 0 ? 1 : 0;
951 } else if (abs(dir.X) > abs(dir.Z)) {
952 param2 = dir.X < 0 ? 3 : 2;
954 param2 = dir.Z < 0 ? 5 : 4;
958 if (nodedef->get(id).param_type_2 == CPT2_FACEDIR) {
959 v3s16 dir = nodepos - floatToInt(client.getEnv().getLocalPlayer()->getPosition(), BS);
961 if (abs(dir.X) > abs(dir.Z)) {
962 param2 = dir.X < 0 ? 3 : 1;
964 param2 = dir.Z < 0 ? 2 : 0;
970 //Check attachment if node is in group attached_node
971 if (((ItemGroupList) nodedef->get(id).groups)["attached_node"] != 0) {
972 static v3s16 wallmounted_dirs[8] = {
982 if (nodedef->get(id).param_type_2 == CPT2_WALLMOUNTED)
983 pp = p + wallmounted_dirs[param2];
985 pp = p + v3s16(0, -1, 0);
987 if (!nodedef->get(map.getNodeNoEx(pp)).walkable)
991 // Add node to client map
992 MapNode n(id, 0, param2);
995 LocalPlayer *player = client.getEnv().getLocalPlayer();
997 // Dont place node when player would be inside new node
998 // NOTE: This is to be eventually implemented by a mod as client-side Lua
999 if (!nodedef->get(n).walkable ||
1000 g_settings->getBool("enable_build_where_you_stand") ||
1001 (client.checkPrivilege("noclip") && g_settings->getBool("noclip")) ||
1002 (nodedef->get(n).walkable &&
1003 neighbourpos != player->getStandingNodePos() + v3s16(0, 1, 0) &&
1004 neighbourpos != player->getStandingNodePos() + v3s16(0, 2, 0))) {
1006 // This triggers the required mesh update too
1007 client.addNode(p, n);
1010 } catch (InvalidPositionException &e) {
1011 errorstream << "Node placement prediction failed for "
1012 << playeritem_def.name << " (places "
1014 << ") - Position not loaded" << std::endl;
1021 static inline void create_formspec_menu(GUIFormSpecMenu **cur_formspec,
1022 InventoryManager *invmgr, IGameDef *gamedef,
1023 IWritableTextureSource *tsrc, IrrlichtDevice *device,
1024 IFormSource *fs_src, TextDest *txt_dest, Client *client)
1027 if (*cur_formspec == 0) {
1028 *cur_formspec = new GUIFormSpecMenu(device, guiroot, -1, &g_menumgr,
1029 invmgr, gamedef, tsrc, fs_src, txt_dest, client);
1030 (*cur_formspec)->doPause = false;
1033 Caution: do not call (*cur_formspec)->drop() here --
1034 the reference might outlive the menu, so we will
1035 periodically check if *cur_formspec is the only
1036 remaining reference (i.e. the menu was removed)
1037 and delete it in that case.
1041 (*cur_formspec)->setFormSource(fs_src);
1042 (*cur_formspec)->setTextDest(txt_dest);
1047 #define SIZE_TAG "size[11,5.5]"
1049 #define SIZE_TAG "size[11,5.5,true]" // Fixed size on desktop
1052 static void show_chat_menu(GUIFormSpecMenu **cur_formspec,
1053 InventoryManager *invmgr, IGameDef *gamedef,
1054 IWritableTextureSource *tsrc, IrrlichtDevice *device,
1055 Client *client, std::string text)
1057 std::string formspec =
1058 FORMSPEC_VERSION_STRING
1060 "field[3,2.35;6,0.5;f_text;;" + text + "]"
1061 "button_exit[4,3;3,0.5;btn_send;" + wide_to_narrow(wstrgettext("Proceed")) + "]"
1065 /* Note: FormspecFormSource and LocalFormspecHandler
1066 * are deleted by guiFormSpecMenu */
1067 FormspecFormSource *fs_src = new FormspecFormSource(formspec);
1068 LocalFormspecHandler *txt_dst = new LocalFormspecHandler("MT_CHAT_MENU", client);
1070 create_formspec_menu(cur_formspec, invmgr, gamedef, tsrc, device, fs_src, txt_dst, NULL);
1073 static void show_deathscreen(GUIFormSpecMenu **cur_formspec,
1074 InventoryManager *invmgr, IGameDef *gamedef,
1075 IWritableTextureSource *tsrc, IrrlichtDevice *device, Client *client)
1077 std::string formspec =
1078 std::string(FORMSPEC_VERSION_STRING) +
1080 "bgcolor[#320000b4;true]"
1081 "label[4.85,1.35;" + gettext("You died.") + "]"
1082 "button_exit[4,3;3,0.5;btn_respawn;" + gettext("Respawn") + "]"
1086 /* Note: FormspecFormSource and LocalFormspecHandler
1087 * are deleted by guiFormSpecMenu */
1088 FormspecFormSource *fs_src = new FormspecFormSource(formspec);
1089 LocalFormspecHandler *txt_dst = new LocalFormspecHandler("MT_DEATH_SCREEN", client);
1091 create_formspec_menu(cur_formspec, invmgr, gamedef, tsrc, device, fs_src, txt_dst, NULL);
1094 /******************************************************************************/
1095 static void show_pause_menu(GUIFormSpecMenu **cur_formspec,
1096 InventoryManager *invmgr, IGameDef *gamedef,
1097 IWritableTextureSource *tsrc, IrrlichtDevice *device,
1098 bool singleplayermode)
1101 std::string control_text = wide_to_narrow(wstrgettext("Default Controls:\n"
1102 "No menu visible:\n"
1103 "- single tap: button activate\n"
1104 "- double tap: place/use\n"
1105 "- slide finger: look around\n"
1106 "Menu/Inventory visible:\n"
1107 "- double tap (outside):\n"
1109 "- touch stack, touch slot:\n"
1111 "- touch&drag, tap 2nd finger\n"
1112 " --> place single item to slot\n"
1115 std::string control_text = wide_to_narrow(wstrgettext("Default Controls:\n"
1117 "- Space: jump/climb\n"
1118 "- Shift: sneak/go down\n"
1121 "- Mouse: turn/look\n"
1122 "- Mouse left: dig/punch\n"
1123 "- Mouse right: place/use\n"
1124 "- Mouse wheel: select item\n"
1129 float ypos = singleplayermode ? 0.5 : 0.1;
1130 std::ostringstream os;
1132 os << FORMSPEC_VERSION_STRING << SIZE_TAG
1133 << "button_exit[4," << (ypos++) << ";3,0.5;btn_continue;"
1134 << wide_to_narrow(wstrgettext("Continue")) << "]";
1136 if (!singleplayermode) {
1137 os << "button_exit[4," << (ypos++) << ";3,0.5;btn_change_password;"
1138 << wide_to_narrow(wstrgettext("Change Password")) << "]";
1142 os << "button_exit[4," << (ypos++) << ";3,0.5;btn_sound;"
1143 << wide_to_narrow(wstrgettext("Sound Volume")) << "]";
1144 os << "button_exit[4," << (ypos++) << ";3,0.5;btn_key_config;"
1145 << wide_to_narrow(wstrgettext("Change Keys")) << "]";
1147 os << "button_exit[4," << (ypos++) << ";3,0.5;btn_exit_menu;"
1148 << wide_to_narrow(wstrgettext("Exit to Menu")) << "]";
1149 os << "button_exit[4," << (ypos++) << ";3,0.5;btn_exit_os;"
1150 << wide_to_narrow(wstrgettext("Exit to OS")) << "]"
1151 << "textarea[7.5,0.25;3.9,6.25;;" << control_text << ";]"
1152 << "textarea[0.4,0.25;3.5,6;;" << "Minetest\n"
1153 << minetest_build_info << "\n"
1154 << "path_user = " << wrap_rows(porting::path_user, 20)
1158 /* Note: FormspecFormSource and LocalFormspecHandler *
1159 * are deleted by guiFormSpecMenu */
1160 FormspecFormSource *fs_src = new FormspecFormSource(os.str());
1161 LocalFormspecHandler *txt_dst = new LocalFormspecHandler("MT_PAUSE_MENU");
1163 create_formspec_menu(cur_formspec, invmgr, gamedef, tsrc, device, fs_src, txt_dst, NULL);
1164 (*cur_formspec)->setFocus(L"btn_continue");
1165 (*cur_formspec)->doPause = true;
1168 /******************************************************************************/
1169 static void updateChat(Client &client, f32 dtime, bool show_debug,
1170 const v2u32 &screensize, bool show_chat, u32 show_profiler,
1171 ChatBackend &chat_backend, gui::IGUIStaticText *guitext_chat)
1173 // Add chat log output for errors to be shown in chat
1174 static LogOutputBuffer chat_log_error_buf(LMT_ERROR);
1176 // Get new messages from error log buffer
1177 while (!chat_log_error_buf.empty()) {
1178 chat_backend.addMessage(L"", narrow_to_wide(chat_log_error_buf.get()));
1181 // Get new messages from client
1182 std::wstring message;
1184 while (client.getChatMessage(message)) {
1185 chat_backend.addUnparsedMessage(message);
1188 // Remove old messages
1189 chat_backend.step(dtime);
1191 // Display all messages in a static text element
1192 unsigned int recent_chat_count = chat_backend.getRecentBuffer().getLineCount();
1193 std::wstring recent_chat = chat_backend.getRecentChat();
1194 unsigned int line_height = g_fontengine->getLineHeight();
1196 guitext_chat->setText(recent_chat.c_str());
1198 // Update gui element size and position
1199 s32 chat_y = 5 + line_height;
1202 chat_y += line_height;
1204 // first pass to calculate height of text to be set
1205 s32 width = std::min(g_fontengine->getTextWidth(recent_chat) + 10,
1206 porting::getWindowSize().X - 20);
1207 core::rect<s32> rect(10, chat_y, width, chat_y + porting::getWindowSize().Y);
1208 guitext_chat->setRelativePosition(rect);
1210 //now use real height of text and adjust rect according to this size
1211 rect = core::rect<s32>(10, chat_y, width,
1212 chat_y + guitext_chat->getTextHeight());
1215 guitext_chat->setRelativePosition(rect);
1216 // Don't show chat if disabled or empty or profiler is enabled
1217 guitext_chat->setVisible(
1218 show_chat && recent_chat_count != 0 && !show_profiler);
1222 /****************************************************************************
1223 Fast key cache for main game loop
1224 ****************************************************************************/
1226 /* This is faster than using getKeySetting with the tradeoff that functions
1227 * using it must make sure that it's initialised before using it and there is
1228 * no error handling (for example bounds checking). This is really intended for
1229 * use only in the main running loop of the client (the_game()) where the faster
1230 * (up to 10x faster) key lookup is an asset. Other parts of the codebase
1231 * (e.g. formspecs) should continue using getKeySetting().
1235 KeyCache() { populate(); }
1249 KEYMAP_ID_INVENTORY,
1256 KEYMAP_ID_CINEMATIC,
1257 KEYMAP_ID_SCREENSHOT,
1258 KEYMAP_ID_TOGGLE_HUD,
1259 KEYMAP_ID_TOGGLE_CHAT,
1260 KEYMAP_ID_TOGGLE_FORCE_FOG_OFF,
1261 KEYMAP_ID_TOGGLE_UPDATE_CAMERA,
1262 KEYMAP_ID_TOGGLE_DEBUG,
1263 KEYMAP_ID_TOGGLE_PROFILER,
1264 KEYMAP_ID_CAMERA_MODE,
1265 KEYMAP_ID_INCREASE_VIEWING_RANGE,
1266 KEYMAP_ID_DECREASE_VIEWING_RANGE,
1267 KEYMAP_ID_RANGESELECT,
1269 KEYMAP_ID_QUICKTUNE_NEXT,
1270 KEYMAP_ID_QUICKTUNE_PREV,
1271 KEYMAP_ID_QUICKTUNE_INC,
1272 KEYMAP_ID_QUICKTUNE_DEC,
1274 KEYMAP_ID_DEBUG_STACKS,
1276 // Fake keycode for array size and internal checks
1277 KEYMAP_INTERNAL_ENUM_COUNT
1284 KeyPress key[KEYMAP_INTERNAL_ENUM_COUNT];
1287 void KeyCache::populate()
1289 key[KEYMAP_ID_FORWARD] = getKeySetting("keymap_forward");
1290 key[KEYMAP_ID_BACKWARD] = getKeySetting("keymap_backward");
1291 key[KEYMAP_ID_LEFT] = getKeySetting("keymap_left");
1292 key[KEYMAP_ID_RIGHT] = getKeySetting("keymap_right");
1293 key[KEYMAP_ID_JUMP] = getKeySetting("keymap_jump");
1294 key[KEYMAP_ID_SPECIAL1] = getKeySetting("keymap_special1");
1295 key[KEYMAP_ID_SNEAK] = getKeySetting("keymap_sneak");
1297 key[KEYMAP_ID_DROP] = getKeySetting("keymap_drop");
1298 key[KEYMAP_ID_INVENTORY] = getKeySetting("keymap_inventory");
1299 key[KEYMAP_ID_CHAT] = getKeySetting("keymap_chat");
1300 key[KEYMAP_ID_CMD] = getKeySetting("keymap_cmd");
1301 key[KEYMAP_ID_CONSOLE] = getKeySetting("keymap_console");
1302 key[KEYMAP_ID_FREEMOVE] = getKeySetting("keymap_freemove");
1303 key[KEYMAP_ID_FASTMOVE] = getKeySetting("keymap_fastmove");
1304 key[KEYMAP_ID_NOCLIP] = getKeySetting("keymap_noclip");
1305 key[KEYMAP_ID_CINEMATIC] = getKeySetting("keymap_cinematic");
1306 key[KEYMAP_ID_SCREENSHOT] = getKeySetting("keymap_screenshot");
1307 key[KEYMAP_ID_TOGGLE_HUD] = getKeySetting("keymap_toggle_hud");
1308 key[KEYMAP_ID_TOGGLE_CHAT] = getKeySetting("keymap_toggle_chat");
1309 key[KEYMAP_ID_TOGGLE_FORCE_FOG_OFF]
1310 = getKeySetting("keymap_toggle_force_fog_off");
1311 key[KEYMAP_ID_TOGGLE_UPDATE_CAMERA]
1312 = getKeySetting("keymap_toggle_update_camera");
1313 key[KEYMAP_ID_TOGGLE_DEBUG]
1314 = getKeySetting("keymap_toggle_debug");
1315 key[KEYMAP_ID_TOGGLE_PROFILER]
1316 = getKeySetting("keymap_toggle_profiler");
1317 key[KEYMAP_ID_CAMERA_MODE]
1318 = getKeySetting("keymap_camera_mode");
1319 key[KEYMAP_ID_INCREASE_VIEWING_RANGE]
1320 = getKeySetting("keymap_increase_viewing_range_min");
1321 key[KEYMAP_ID_DECREASE_VIEWING_RANGE]
1322 = getKeySetting("keymap_decrease_viewing_range_min");
1323 key[KEYMAP_ID_RANGESELECT]
1324 = getKeySetting("keymap_rangeselect");
1326 key[KEYMAP_ID_QUICKTUNE_NEXT] = getKeySetting("keymap_quicktune_next");
1327 key[KEYMAP_ID_QUICKTUNE_PREV] = getKeySetting("keymap_quicktune_prev");
1328 key[KEYMAP_ID_QUICKTUNE_INC] = getKeySetting("keymap_quicktune_inc");
1329 key[KEYMAP_ID_QUICKTUNE_DEC] = getKeySetting("keymap_quicktune_dec");
1331 key[KEYMAP_ID_DEBUG_STACKS] = getKeySetting("keymap_print_debug_stacks");
1335 /****************************************************************************
1337 ****************************************************************************/
1339 const float object_hit_delay = 0.2;
1342 u32 last_time, busy_time, sleep_time;
1346 /* The reason the following structs are not anonymous structs within the
1347 * class is that they are not used by the majority of member functions and
1348 * many functions that do require objects of thse types do not modify them
1349 * (so they can be passed as a const qualified parameter)
1351 struct CameraOrientation {
1352 f32 camera_yaw; // "right/left"
1353 f32 camera_pitch; // "up/down"
1356 struct GameRunData {
1359 PointedThing pointed_old;
1363 bool update_wielded_item_trigger;
1364 bool reset_jump_timer;
1365 float nodig_delay_timer;
1367 float dig_time_complete;
1368 float repeat_rightclick_timer;
1369 float object_hit_delay_timer;
1370 float time_from_last_punch;
1371 ClientActiveObject *selected_object;
1375 float update_draw_list_timer;
1376 float statustext_time;
1380 v3f update_draw_list_last_cam_dir;
1382 u32 profiler_current_page;
1383 u32 profiler_max_page; // Number of pages
1386 float time_of_day_smooth;
1390 f32 max, min, avg, counter, max_sample, min_sample, max_fraction;
1398 Jitter dtime_jitter, busy_time_jitter;
1401 /* Flags that can, or may, change during main game loop
1403 struct VolatileRunFlags {
1409 bool show_profiler_graph;
1410 bool disable_camera_update;
1411 bool first_loop_after_window_activation;
1412 bool camera_offset_changed;
1416 /****************************************************************************
1418 ****************************************************************************/
1420 /* This is not intended to be a public class. If a public class becomes
1421 * desirable then it may be better to create another 'wrapper' class that
1422 * hides most of the stuff in this class (nothing in this class is required
1423 * by any other file) but exposes the public methods/data only.
1431 bool startup(bool *kill,
1433 InputHandler *input,
1434 IrrlichtDevice *device,
1435 const std::string &map_dir,
1436 const std::string &playername,
1437 const std::string &password,
1438 // If address is "", local server is used and address is updated
1439 std::string *address,
1441 std::wstring *error_message,
1442 ChatBackend *chat_backend,
1443 const SubgameSpec &gamespec, // Used for local game
1444 bool simple_singleplayer_mode);
1451 void extendedResourceCleanup();
1453 // Basic initialisation
1454 bool init(const std::string &map_dir, std::string *address,
1456 const SubgameSpec &gamespec);
1458 bool createSingleplayerServer(const std::string map_dir,
1459 const SubgameSpec &gamespec, u16 port, std::string *address);
1462 bool createClient(const std::string &playername,
1463 const std::string &password, std::string *address, u16 port,
1464 std::wstring *error_message);
1465 bool initGui(std::wstring *error_message);
1467 // Client connection
1468 bool connectToServer(const std::string &playername,
1469 const std::string &password, std::string *address, u16 port,
1470 bool *connect_ok, bool *aborted);
1471 bool getServerContent(bool *aborted);
1475 void updateInteractTimers(GameRunData *args, f32 dtime);
1476 bool checkConnection();
1477 bool handleCallbacks();
1478 void processQueues();
1479 void updateProfilers(const GameRunData &run_data, const RunStats &stats,
1480 const FpsControl &draw_times, f32 dtime);
1481 void addProfilerGraphs(const RunStats &stats, const FpsControl &draw_times,
1483 void updateStats(RunStats *stats, const FpsControl &draw_times, f32 dtime);
1485 void processUserInput(VolatileRunFlags *flags, GameRunData *interact_args,
1487 void processKeyboardInput(VolatileRunFlags *flags,
1488 float *statustext_time,
1490 bool *reset_jump_timer,
1491 u32 *profiler_current_page,
1492 u32 profiler_max_page);
1493 void processItemSelection(u16 *new_playeritem);
1495 void dropSelectedItem();
1496 void openInventory();
1498 void toggleFreeMove(float *statustext_time);
1499 void toggleFreeMoveAlt(float *statustext_time, float *jump_timer);
1500 void toggleFast(float *statustext_time);
1501 void toggleNoClip(float *statustext_time);
1502 void toggleCinematic(float *statustext_time);
1504 void toggleChat(float *statustext_time, bool *flag);
1505 void toggleHud(float *statustext_time, bool *flag);
1506 void toggleFog(float *statustext_time, bool *flag);
1507 void toggleDebug(float *statustext_time, bool *show_debug,
1508 bool *show_profiler_graph);
1509 void toggleUpdateCamera(float *statustext_time, bool *flag);
1510 void toggleProfiler(float *statustext_time, u32 *profiler_current_page,
1511 u32 profiler_max_page);
1513 void increaseViewRange(float *statustext_time);
1514 void decreaseViewRange(float *statustext_time);
1515 void toggleFullViewRange(float *statustext_time);
1517 void updateCameraDirection(CameraOrientation *cam, VolatileRunFlags *flags);
1518 void updateCameraOrientation(CameraOrientation *cam,
1519 const VolatileRunFlags &flags);
1520 void updatePlayerControl(const CameraOrientation &cam);
1521 void step(f32 *dtime);
1522 void processClientEvents(CameraOrientation *cam, float *damage_flash);
1523 void updateCamera(VolatileRunFlags *flags, u32 busy_time, f32 dtime,
1524 float time_from_last_punch);
1525 void updateSound(f32 dtime);
1526 void processPlayerInteraction(std::vector<aabb3f> &highlight_boxes,
1527 GameRunData *runData, f32 dtime, bool show_hud,
1529 void handlePointingAtNode(GameRunData *runData,
1530 const PointedThing &pointed, const ItemDefinition &playeritem_def,
1531 const ToolCapabilities &playeritem_toolcap, f32 dtime);
1532 void handlePointingAtObject(GameRunData *runData,
1533 const PointedThing &pointed, const ItemStack &playeritem,
1534 const v3f &player_position, bool show_debug);
1535 void handleDigging(GameRunData *runData, const PointedThing &pointed,
1536 const v3s16 &nodepos, const ToolCapabilities &playeritem_toolcap,
1538 void updateFrame(std::vector<aabb3f> &highlight_boxes, ProfilerGraph *graph,
1539 RunStats *stats, GameRunData *runData,
1540 f32 dtime, const VolatileRunFlags &flags, const CameraOrientation &cam);
1541 void updateGui(float *statustext_time, const RunStats &stats,
1542 const GameRunData& runData, f32 dtime, const VolatileRunFlags &flags,
1543 const CameraOrientation &cam);
1544 void updateProfilerGraphs(ProfilerGraph *graph);
1547 void limitFps(FpsControl *fps_timings, f32 *dtime);
1549 void showOverlayMessage(const wchar_t *msg, float dtime, int percent,
1550 bool draw_clouds = true);
1553 InputHandler *input;
1558 IWritableTextureSource *texture_src;
1559 IWritableShaderSource *shader_src;
1561 // When created, these will be filled with data received from the server
1562 IWritableItemDefManager *itemdef_manager;
1563 IWritableNodeDefManager *nodedef_manager;
1565 GameOnDemandSoundFetcher soundfetcher; // useful when testing
1566 ISoundManager *sound;
1567 bool sound_is_dummy;
1568 SoundMaker *soundmaker;
1570 ChatBackend *chat_backend;
1572 GUIFormSpecMenu *current_formspec;
1574 EventManager *eventmgr;
1575 QuicktuneShortcutter *quicktune;
1577 GUIChatConsole *gui_chat_console; // Free using ->Drop()
1578 MapDrawControl *draw_control;
1580 Clouds *clouds; // Free using ->Drop()
1581 Sky *sky; // Free using ->Drop()
1582 Inventory *local_inventory;
1586 This class does take ownership/responsibily for cleaning up etc of any of
1587 these items (e.g. device)
1589 IrrlichtDevice *device;
1590 video::IVideoDriver *driver;
1591 scene::ISceneManager *smgr;
1593 std::wstring *error_message;
1594 IGameDef *gamedef; // Convenience (same as *client)
1595 scene::ISceneNode *skybox;
1598 bool simple_singleplayer_mode;
1601 /* Pre-calculated values
1603 int crack_animation_length;
1607 gui::IGUIStaticText *guitext; // First line of debug text
1608 gui::IGUIStaticText *guitext2; // Second line of debug text
1609 gui::IGUIStaticText *guitext_info; // At the middle of the screen
1610 gui::IGUIStaticText *guitext_status;
1611 gui::IGUIStaticText *guitext_chat; // Chat text
1612 gui::IGUIStaticText *guitext_profiler; // Profiler text
1614 std::wstring infotext;
1615 std::wstring statustext;
1619 IntervalLimiter profiler_interval;
1621 /* TODO: Add a callback function so these can be updated when a setting
1622 * changes. At this point in time it doesn't matter (e.g. /set
1623 * is documented to change server settings only)
1625 * TODO: Local caching of settings is not optimal and should at some stage
1626 * be updated to use a global settings object for getting thse values
1627 * (as opposed to the this local caching). This can be addressed in
1630 bool m_cache_doubletap_jump;
1631 bool m_cache_enable_node_highlighting;
1632 bool m_cache_enable_clouds;
1633 bool m_cache_enable_particles;
1634 bool m_cache_enable_fog;
1635 f32 m_cache_mouse_sensitivity;
1636 f32 m_repeat_right_click_time;
1644 itemdef_manager(NULL),
1645 nodedef_manager(NULL),
1647 sound_is_dummy(false),
1650 current_formspec(NULL),
1653 gui_chat_console(NULL),
1658 local_inventory(NULL),
1661 m_cache_doubletap_jump = g_settings->getBool("doubletap_jump");
1662 m_cache_enable_node_highlighting = g_settings->getBool("enable_node_highlighting");
1663 m_cache_enable_clouds = g_settings->getBool("enable_clouds");
1664 m_cache_enable_particles = g_settings->getBool("enable_particles");
1665 m_cache_enable_fog = g_settings->getBool("enable_fog");
1666 m_cache_mouse_sensitivity = g_settings->getFloat("mouse_sensitivity");
1667 m_repeat_right_click_time = g_settings->getFloat("repeat_rightclick_time");
1669 m_cache_mouse_sensitivity = rangelim(m_cache_mouse_sensitivity, 0.001, 100.0);
1674 /****************************************************************************
1676 ****************************************************************************/
1682 if (!sound_is_dummy)
1685 delete server; // deleted first to stop all server threads
1688 delete local_inventory;
1694 delete nodedef_manager;
1695 delete itemdef_manager;
1696 delete draw_control;
1698 extendedResourceCleanup();
1701 bool Game::startup(bool *kill,
1703 InputHandler *input,
1704 IrrlichtDevice *device,
1705 const std::string &map_dir,
1706 const std::string &playername,
1707 const std::string &password,
1708 std::string *address, // can change if simple_singleplayer_mode
1710 std::wstring *error_message,
1711 ChatBackend *chat_backend,
1712 const SubgameSpec &gamespec,
1713 bool simple_singleplayer_mode)
1716 this->device = device;
1718 this->error_message = error_message;
1719 this->random_input = random_input;
1720 this->input = input;
1721 this->chat_backend = chat_backend;
1722 this->simple_singleplayer_mode = simple_singleplayer_mode;
1724 driver = device->getVideoDriver();
1725 smgr = device->getSceneManager();
1727 smgr->getParameters()->setAttribute(scene::OBJ_LOADER_IGNORE_MATERIAL_FILES, true);
1729 if (!init(map_dir, address, port, gamespec))
1732 if (!createClient(playername, password, address, port, error_message))
1741 ProfilerGraph graph;
1742 RunStats stats = { 0 };
1743 CameraOrientation cam_view_target = { 0 };
1744 CameraOrientation cam_view = { 0 };
1745 GameRunData runData = { 0 };
1746 FpsControl draw_times = { 0 };
1747 VolatileRunFlags flags = { 0 };
1748 f32 dtime; // in seconds
1750 runData.time_from_last_punch = 10.0;
1751 runData.profiler_max_page = 3;
1752 runData.update_wielded_item_trigger = true;
1754 flags.show_chat = true;
1755 flags.show_hud = true;
1756 flags.show_debug = g_settings->getBool("show_debug");
1757 flags.invert_mouse = g_settings->getBool("invert_mouse");
1758 flags.first_loop_after_window_activation = true;
1760 /* Clear the profiler */
1761 Profiler::GraphValues dummyvalues;
1762 g_profiler->graphGet(dummyvalues);
1764 draw_times.last_time = device->getTimer()->getTime();
1766 shader_src->addGlobalConstantSetter(new GameGlobalShaderConstantSetter(
1768 &flags.force_fog_off,
1772 std::vector<aabb3f> highlight_boxes;
1774 set_light_table(g_settings->getFloat("display_gamma"));
1776 while (device->run() && !(*kill || g_gamecallback->shutdown_requested)) {
1778 /* Must be called immediately after a device->run() call because it
1779 * uses device->getTimer()->getTime()
1781 limitFps(&draw_times, &dtime);
1783 updateStats(&stats, draw_times, dtime);
1784 updateInteractTimers(&runData, dtime);
1786 if (!checkConnection())
1788 if (!handleCallbacks())
1794 hud->resizeHotbar();
1796 updateProfilers(runData, stats, draw_times, dtime);
1797 processUserInput(&flags, &runData, dtime);
1798 // Update camera before player movement to avoid camera lag of one frame
1799 updateCameraDirection(&cam_view_target, &flags);
1800 float cam_smoothing = 0;
1801 if (g_settings->getBool("cinematic"))
1802 cam_smoothing = 1 - g_settings->getFloat("cinematic_camera_smoothing");
1804 cam_smoothing = 1 - g_settings->getFloat("camera_smoothing");
1805 cam_smoothing = rangelim(cam_smoothing, 0.01f, 1.0f);
1806 cam_view.camera_yaw += (cam_view_target.camera_yaw -
1807 cam_view.camera_yaw) * cam_smoothing;
1808 cam_view.camera_pitch += (cam_view_target.camera_pitch -
1809 cam_view.camera_pitch) * cam_smoothing;
1810 updatePlayerControl(cam_view);
1812 processClientEvents(&cam_view, &runData.damage_flash);
1813 updateCamera(&flags, draw_times.busy_time, dtime,
1814 runData.time_from_last_punch);
1816 processPlayerInteraction(highlight_boxes, &runData, dtime,
1817 flags.show_hud, flags.show_debug);
1818 updateFrame(highlight_boxes, &graph, &stats, &runData, dtime,
1820 updateProfilerGraphs(&graph);
1825 void Game::shutdown()
1827 showOverlayMessage(wgettext("Shutting down..."), 0, 0, false);
1832 if (gui_chat_console)
1833 gui_chat_console->drop();
1839 while (g_menumgr.menuCount() > 0) {
1840 g_menumgr.m_stack.front()->setVisible(false);
1841 g_menumgr.deletingMenu(g_menumgr.m_stack.front());
1844 if (current_formspec) {
1845 current_formspec->drop();
1846 current_formspec = NULL;
1849 chat_backend->addMessage(L"", L"# Disconnected.");
1850 chat_backend->addMessage(L"", L"");
1854 while (!client->isShutdown()) {
1855 assert(texture_src != NULL);
1856 assert(shader_src != NULL);
1857 texture_src->processQueue();
1858 shader_src->processQueue();
1866 /****************************************************************************
1868 ****************************************************************************/
1871 const std::string &map_dir,
1872 std::string *address,
1874 const SubgameSpec &gamespec)
1876 showOverlayMessage(wgettext("Loading..."), 0, 0);
1878 texture_src = createTextureSource(device);
1879 shader_src = createShaderSource(device);
1881 itemdef_manager = createItemDefManager();
1882 nodedef_manager = createNodeDefManager();
1884 eventmgr = new EventManager();
1885 quicktune = new QuicktuneShortcutter();
1887 if (!(texture_src && shader_src && itemdef_manager && nodedef_manager
1888 && eventmgr && quicktune))
1894 // Create a server if not connecting to an existing one
1895 if (*address == "") {
1896 if (!createSingleplayerServer(map_dir, gamespec, port, address))
1903 bool Game::initSound()
1906 if (g_settings->getBool("enable_sound")) {
1907 infostream << "Attempting to use OpenAL audio" << std::endl;
1908 sound = createOpenALSoundManager(&soundfetcher);
1910 infostream << "Failed to initialize OpenAL audio" << std::endl;
1912 infostream << "Sound disabled." << std::endl;
1916 infostream << "Using dummy audio." << std::endl;
1917 sound = &dummySoundManager;
1918 sound_is_dummy = true;
1921 soundmaker = new SoundMaker(sound, nodedef_manager);
1925 soundmaker->registerReceiver(eventmgr);
1930 bool Game::createSingleplayerServer(const std::string map_dir,
1931 const SubgameSpec &gamespec, u16 port, std::string *address)
1933 showOverlayMessage(wgettext("Creating server..."), 0, 5);
1935 std::string bind_str = g_settings->get("bind_address");
1936 Address bind_addr(0, 0, 0, 0, port);
1938 if (g_settings->getBool("ipv6_server")) {
1939 bind_addr.setAddress((IPv6AddressBytes *) NULL);
1943 bind_addr.Resolve(bind_str.c_str());
1944 } catch (ResolveError &e) {
1945 infostream << "Resolving bind address \"" << bind_str
1946 << "\" failed: " << e.what()
1947 << " -- Listening on all addresses." << std::endl;
1950 if (bind_addr.isIPv6() && !g_settings->getBool("enable_ipv6")) {
1951 *error_message = L"Unable to listen on " +
1952 narrow_to_wide(bind_addr.serializeString()) +
1953 L" because IPv6 is disabled";
1954 errorstream << wide_to_narrow(*error_message) << std::endl;
1958 server = new Server(map_dir, gamespec, simple_singleplayer_mode,
1959 bind_addr.isIPv6());
1961 server->start(bind_addr);
1966 bool Game::createClient(const std::string &playername,
1967 const std::string &password, std::string *address, u16 port,
1968 std::wstring *error_message)
1970 showOverlayMessage(wgettext("Creating client..."), 0, 10);
1972 draw_control = new MapDrawControl;
1976 bool could_connect, connect_aborted;
1978 if (!connectToServer(playername, password, address, port,
1979 &could_connect, &connect_aborted))
1982 if (!could_connect) {
1983 if (*error_message == L"" && !connect_aborted) {
1984 // Should not happen if error messages are set properly
1985 *error_message = L"Connection failed for unknown reason";
1986 errorstream << wide_to_narrow(*error_message) << std::endl;
1991 if (!getServerContent(&connect_aborted)) {
1992 if (*error_message == L"" && !connect_aborted) {
1993 // Should not happen if error messages are set properly
1994 *error_message = L"Connection failed for unknown reason";
1995 errorstream << wide_to_narrow(*error_message) << std::endl;
2000 // Update cached textures, meshes and materials
2001 client->afterContentReceived(device, g_fontengine->getFont());
2005 camera = new Camera(smgr, *draw_control, gamedef);
2006 if (!camera || !camera->successfullyCreated(*error_message))
2011 if (m_cache_enable_clouds) {
2012 clouds = new Clouds(smgr->getRootSceneNode(), smgr, -1, time(0));
2014 *error_message = L"Memory allocation error";
2015 *error_message += narrow_to_wide(" (clouds)");
2016 errorstream << wide_to_narrow(*error_message) << std::endl;
2023 sky = new Sky(smgr->getRootSceneNode(), smgr, -1, texture_src);
2024 skybox = NULL; // This is used/set later on in the main run loop
2026 local_inventory = new Inventory(itemdef_manager);
2028 if (!(sky && local_inventory)) {
2029 *error_message = L"Memory allocation error";
2030 *error_message += narrow_to_wide(" (sky or local inventory)");
2031 errorstream << wide_to_narrow(*error_message) << std::endl;
2035 /* Pre-calculated values
2037 video::ITexture *t = texture_src->getTexture("crack_anylength.png");
2039 v2u32 size = t->getOriginalSize();
2040 crack_animation_length = size.Y / size.X;
2042 crack_animation_length = 5;
2045 if (!initGui(error_message))
2048 /* Set window caption
2050 core::stringw str = L"Minetest [";
2051 str += driver->getName();
2053 device->setWindowCaption(str.c_str());
2055 LocalPlayer *player = client->getEnv().getLocalPlayer();
2056 player->hurt_tilt_timer = 0;
2057 player->hurt_tilt_strength = 0;
2059 hud = new Hud(driver, smgr, guienv, gamedef, player, local_inventory);
2062 *error_message = L"Memory error: could not create HUD";
2063 errorstream << wide_to_narrow(*error_message) << std::endl;
2070 bool Game::initGui(std::wstring *error_message)
2072 // First line of debug text
2073 guitext = guienv->addStaticText(
2075 core::rect<s32>(0, 0, 0, 0),
2076 false, false, guiroot);
2078 // Second line of debug text
2079 guitext2 = guienv->addStaticText(
2081 core::rect<s32>(0, 0, 0, 0),
2082 false, false, guiroot);
2084 // At the middle of the screen
2085 // Object infos are shown in this
2086 guitext_info = guienv->addStaticText(
2088 core::rect<s32>(0, 0, 400, g_fontengine->getTextHeight() * 5 + 5) + v2s32(100, 200),
2089 false, true, guiroot);
2091 // Status text (displays info when showing and hiding GUI stuff, etc.)
2092 guitext_status = guienv->addStaticText(
2094 core::rect<s32>(0, 0, 0, 0),
2095 false, false, guiroot);
2096 guitext_status->setVisible(false);
2099 guitext_chat = guienv->addStaticText(
2101 core::rect<s32>(0, 0, 0, 0),
2102 //false, false); // Disable word wrap as of now
2103 false, true, guiroot);
2104 // Remove stale "recent" chat messages from previous connections
2105 chat_backend->clearRecentChat();
2107 // Chat backend and console
2108 gui_chat_console = new GUIChatConsole(guienv, guienv->getRootGUIElement(),
2109 -1, chat_backend, client);
2110 if (!gui_chat_console) {
2111 *error_message = L"Could not allocate memory for chat console";
2112 errorstream << wide_to_narrow(*error_message) << std::endl;
2116 // Profiler text (size is updated when text is updated)
2117 guitext_profiler = guienv->addStaticText(
2119 core::rect<s32>(0, 0, 0, 0),
2120 false, false, guiroot);
2121 guitext_profiler->setBackgroundColor(video::SColor(120, 0, 0, 0));
2122 guitext_profiler->setVisible(false);
2123 guitext_profiler->setWordWrap(true);
2125 #ifdef HAVE_TOUCHSCREENGUI
2127 if (g_touchscreengui)
2128 g_touchscreengui->init(texture_src, porting::getDisplayDensity());
2135 bool Game::connectToServer(const std::string &playername,
2136 const std::string &password, std::string *address, u16 port,
2137 bool *connect_ok, bool *aborted)
2139 *connect_ok = false; // Let's not be overly optimistic
2141 bool local_server_mode = false;
2143 showOverlayMessage(wgettext("Resolving address..."), 0, 15);
2145 Address connect_address(0, 0, 0, 0, port);
2148 connect_address.Resolve(address->c_str());
2150 if (connect_address.isZero()) { // i.e. INADDR_ANY, IN6ADDR_ANY
2151 //connect_address.Resolve("localhost");
2152 if (connect_address.isIPv6()) {
2153 IPv6AddressBytes addr_bytes;
2154 addr_bytes.bytes[15] = 1;
2155 connect_address.setAddress(&addr_bytes);
2157 connect_address.setAddress(127, 0, 0, 1);
2159 local_server_mode = true;
2161 } catch (ResolveError &e) {
2162 *error_message = L"Couldn't resolve address: " + narrow_to_wide(e.what());
2163 errorstream << wide_to_narrow(*error_message) << std::endl;
2167 if (connect_address.isIPv6() && !g_settings->getBool("enable_ipv6")) {
2168 *error_message = L"Unable to connect to " +
2169 narrow_to_wide(connect_address.serializeString()) +
2170 L" because IPv6 is disabled";
2171 errorstream << wide_to_narrow(*error_message) << std::endl;
2175 client = new Client(device,
2176 playername.c_str(), password,
2177 *draw_control, texture_src, shader_src,
2178 itemdef_manager, nodedef_manager, sound, eventmgr,
2179 connect_address.isIPv6());
2184 gamedef = client; // Client acts as our GameDef
2186 infostream << "Connecting to server at ";
2187 connect_address.print(&infostream);
2188 infostream << std::endl;
2190 client->connect(connect_address, *address,
2191 simple_singleplayer_mode || local_server_mode);
2194 Wait for server to accept connection
2200 FpsControl fps_control = { 0 };
2201 f32 dtime; // in seconds
2203 while (device->run()) {
2205 limitFps(&fps_control, &dtime);
2207 // Update client and server
2208 client->step(dtime);
2211 server->step(dtime);
2214 if (client->getState() == LC_Init) {
2220 if (client->accessDenied()) {
2221 *error_message = L"Access denied. Reason: "
2222 + client->accessDeniedReason();
2223 errorstream << wide_to_narrow(*error_message) << std::endl;
2227 if (input->wasKeyDown(EscapeKey) || input->wasKeyDown(CancelKey)) {
2229 infostream << "Connect aborted [Escape]" << std::endl;
2234 showOverlayMessage(wgettext("Connecting to server..."), dtime, 20);
2236 } catch (con::PeerNotFoundException &e) {
2237 // TODO: Should something be done here? At least an info/error
2245 bool Game::getServerContent(bool *aborted)
2249 FpsControl fps_control = { 0 };
2250 f32 dtime; // in seconds
2252 while (device->run()) {
2254 limitFps(&fps_control, &dtime);
2256 // Update client and server
2257 client->step(dtime);
2260 server->step(dtime);
2263 if (client->mediaReceived() && client->itemdefReceived() &&
2264 client->nodedefReceived()) {
2269 if (client->accessDenied()) {
2270 *error_message = L"Access denied. Reason: "
2271 + client->accessDeniedReason();
2272 errorstream << wide_to_narrow(*error_message) << std::endl;
2276 if (client->getState() < LC_Init) {
2277 *error_message = L"Client disconnected";
2278 errorstream << wide_to_narrow(*error_message) << std::endl;
2282 if (input->wasKeyDown(EscapeKey) || input->wasKeyDown(CancelKey)) {
2284 infostream << "Connect aborted [Escape]" << std::endl;
2291 if (!client->itemdefReceived()) {
2292 const wchar_t *text = wgettext("Item definitions...");
2294 draw_load_screen(text, device, guienv, dtime, progress);
2296 } else if (!client->nodedefReceived()) {
2297 const wchar_t *text = wgettext("Node definitions...");
2299 draw_load_screen(text, device, guienv, dtime, progress);
2302 std::stringstream message;
2303 message.precision(3);
2304 message << gettext("Media...");
2306 if ((USE_CURL == 0) ||
2307 (!g_settings->getBool("enable_remote_media_server"))) {
2308 float cur = client->getCurRate();
2309 std::string cur_unit = gettext(" KB/s");
2313 cur_unit = gettext(" MB/s");
2316 message << " ( " << cur << cur_unit << " )";
2319 progress = 30 + client->mediaReceiveProgress() * 35 + 0.5;
2320 draw_load_screen(narrow_to_wide(message.str()), device,
2321 guienv, dtime, progress);
2330 /****************************************************************************
2332 ****************************************************************************/
2334 inline void Game::updateInteractTimers(GameRunData *args, f32 dtime)
2336 if (args->nodig_delay_timer >= 0)
2337 args->nodig_delay_timer -= dtime;
2339 if (args->object_hit_delay_timer >= 0)
2340 args->object_hit_delay_timer -= dtime;
2342 args->time_from_last_punch += dtime;
2346 /* returns false if game should exit, otherwise true
2348 inline bool Game::checkConnection()
2350 if (client->accessDenied()) {
2351 *error_message = L"Access denied. Reason: "
2352 + client->accessDeniedReason();
2353 errorstream << wide_to_narrow(*error_message) << std::endl;
2361 /* returns false if game should exit, otherwise true
2363 inline bool Game::handleCallbacks()
2365 if (g_gamecallback->disconnect_requested) {
2366 g_gamecallback->disconnect_requested = false;
2370 if (g_gamecallback->changepassword_requested) {
2371 (new GUIPasswordChange(guienv, guiroot, -1,
2372 &g_menumgr, client))->drop();
2373 g_gamecallback->changepassword_requested = false;
2376 if (g_gamecallback->changevolume_requested) {
2377 (new GUIVolumeChange(guienv, guiroot, -1,
2378 &g_menumgr, client))->drop();
2379 g_gamecallback->changevolume_requested = false;
2382 if (g_gamecallback->keyconfig_requested) {
2383 (new GUIKeyChangeMenu(guienv, guiroot, -1,
2384 &g_menumgr))->drop();
2385 g_gamecallback->keyconfig_requested = false;
2388 if (g_gamecallback->keyconfig_changed) {
2389 keycache.populate(); // update the cache with new settings
2390 g_gamecallback->keyconfig_changed = false;
2397 void Game::processQueues()
2399 texture_src->processQueue();
2400 itemdef_manager->processQueue(gamedef);
2401 shader_src->processQueue();
2405 void Game::updateProfilers(const GameRunData &run_data, const RunStats &stats,
2406 const FpsControl &draw_times, f32 dtime)
2408 float profiler_print_interval =
2409 g_settings->getFloat("profiler_print_interval");
2410 bool print_to_log = true;
2412 if (profiler_print_interval == 0) {
2413 print_to_log = false;
2414 profiler_print_interval = 5;
2417 if (profiler_interval.step(dtime, profiler_print_interval)) {
2419 infostream << "Profiler:" << std::endl;
2420 g_profiler->print(infostream);
2423 update_profiler_gui(guitext_profiler, g_fontengine,
2424 run_data.profiler_current_page, run_data.profiler_max_page,
2425 driver->getScreenSize().Height);
2427 g_profiler->clear();
2430 addProfilerGraphs(stats, draw_times, dtime);
2434 void Game::addProfilerGraphs(const RunStats &stats,
2435 const FpsControl &draw_times, f32 dtime)
2437 g_profiler->graphAdd("mainloop_other",
2438 draw_times.busy_time / 1000.0f - stats.drawtime / 1000.0f);
2440 if (draw_times.sleep_time != 0)
2441 g_profiler->graphAdd("mainloop_sleep", draw_times.sleep_time / 1000.0f);
2442 g_profiler->graphAdd("mainloop_dtime", dtime);
2444 g_profiler->add("Elapsed time", dtime);
2445 g_profiler->avg("FPS", 1. / dtime);
2449 void Game::updateStats(RunStats *stats, const FpsControl &draw_times,
2456 /* Time average and jitter calculation
2458 jp = &stats->dtime_jitter;
2459 jp->avg = jp->avg * 0.96 + dtime * 0.04;
2461 jitter = dtime - jp->avg;
2463 if (jitter > jp->max)
2466 jp->counter += dtime;
2468 if (jp->counter > 0.0) {
2470 jp->max_sample = jp->max;
2471 jp->max_fraction = jp->max_sample / (jp->avg + 0.001);
2475 /* Busytime average and jitter calculation
2477 jp = &stats->busy_time_jitter;
2478 jp->avg = jp->avg + draw_times.busy_time * 0.02;
2480 jitter = draw_times.busy_time - jp->avg;
2482 if (jitter > jp->max)
2484 if (jitter < jp->min)
2487 jp->counter += dtime;
2489 if (jp->counter > 0.0) {
2491 jp->max_sample = jp->max;
2492 jp->min_sample = jp->min;
2500 /****************************************************************************
2502 ****************************************************************************/
2504 void Game::processUserInput(VolatileRunFlags *flags,
2505 GameRunData *interact_args, f32 dtime)
2507 // Reset input if window not active or some menu is active
2508 if (device->isWindowActive() == false
2509 || noMenuActive() == false
2510 || guienv->hasFocus(gui_chat_console)) {
2514 if (!guienv->hasFocus(gui_chat_console) && gui_chat_console->isOpen()) {
2515 gui_chat_console->closeConsoleAtOnce();
2518 // Input handler step() (used by the random input generator)
2521 #ifdef HAVE_TOUCHSCREENGUI
2523 if (g_touchscreengui) {
2524 g_touchscreengui->step(dtime);
2530 if (current_formspec != 0)
2531 current_formspec->getAndroidUIInput();
2535 // Increase timer for double tap of "keymap_jump"
2536 if (m_cache_doubletap_jump && interact_args->jump_timer <= 0.2)
2537 interact_args->jump_timer += dtime;
2539 processKeyboardInput(
2541 &interact_args->statustext_time,
2542 &interact_args->jump_timer,
2543 &interact_args->reset_jump_timer,
2544 &interact_args->profiler_current_page,
2545 interact_args->profiler_max_page);
2547 processItemSelection(&interact_args->new_playeritem);
2551 void Game::processKeyboardInput(VolatileRunFlags *flags,
2552 float *statustext_time,
2554 bool *reset_jump_timer,
2555 u32 *profiler_current_page,
2556 u32 profiler_max_page)
2559 //TimeTaker tt("process kybd input", NULL, PRECISION_NANO);
2561 if (input->wasKeyDown(keycache.key[KeyCache::KEYMAP_ID_DROP])) {
2563 } else if (input->wasKeyDown(keycache.key[KeyCache::KEYMAP_ID_INVENTORY])) {
2565 } else if (input->wasKeyDown(EscapeKey) || input->wasKeyDown(CancelKey)) {
2566 show_pause_menu(¤t_formspec, client, gamedef, texture_src, device,
2567 simple_singleplayer_mode);
2568 } else if (input->wasKeyDown(keycache.key[KeyCache::KEYMAP_ID_CHAT])) {
2569 show_chat_menu(¤t_formspec, client, gamedef, texture_src, device,
2571 } else if (input->wasKeyDown(keycache.key[KeyCache::KEYMAP_ID_CMD])) {
2572 show_chat_menu(¤t_formspec, client, gamedef, texture_src, device,
2574 } else if (input->wasKeyDown(keycache.key[KeyCache::KEYMAP_ID_CONSOLE])) {
2576 } else if (input->wasKeyDown(keycache.key[KeyCache::KEYMAP_ID_FREEMOVE])) {
2577 toggleFreeMove(statustext_time);
2578 } else if (input->wasKeyDown(keycache.key[KeyCache::KEYMAP_ID_JUMP])) {
2579 toggleFreeMoveAlt(statustext_time, jump_timer);
2580 *reset_jump_timer = true;
2581 } else if (input->wasKeyDown(keycache.key[KeyCache::KEYMAP_ID_FASTMOVE])) {
2582 toggleFast(statustext_time);
2583 } else if (input->wasKeyDown(keycache.key[KeyCache::KEYMAP_ID_NOCLIP])) {
2584 toggleNoClip(statustext_time);
2585 } else if (input->wasKeyDown(keycache.key[KeyCache::KEYMAP_ID_CINEMATIC])) {
2586 toggleCinematic(statustext_time);
2587 } else if (input->wasKeyDown(keycache.key[KeyCache::KEYMAP_ID_SCREENSHOT])) {
2588 client->makeScreenshot(device);
2589 } else if (input->wasKeyDown(keycache.key[KeyCache::KEYMAP_ID_TOGGLE_HUD])) {
2590 toggleHud(statustext_time, &flags->show_hud);
2591 } else if (input->wasKeyDown(keycache.key[KeyCache::KEYMAP_ID_TOGGLE_CHAT])) {
2592 toggleChat(statustext_time, &flags->show_chat);
2593 } else if (input->wasKeyDown(keycache.key[KeyCache::KEYMAP_ID_TOGGLE_FORCE_FOG_OFF])) {
2594 toggleFog(statustext_time, &flags->force_fog_off);
2595 } else if (input->wasKeyDown(keycache.key[KeyCache::KEYMAP_ID_TOGGLE_UPDATE_CAMERA])) {
2596 toggleUpdateCamera(statustext_time, &flags->disable_camera_update);
2597 } else if (input->wasKeyDown(keycache.key[KeyCache::KEYMAP_ID_TOGGLE_DEBUG])) {
2598 toggleDebug(statustext_time, &flags->show_debug, &flags->show_profiler_graph);
2599 } else if (input->wasKeyDown(keycache.key[KeyCache::KEYMAP_ID_TOGGLE_PROFILER])) {
2600 toggleProfiler(statustext_time, profiler_current_page, profiler_max_page);
2601 } else if (input->wasKeyDown(keycache.key[KeyCache::KEYMAP_ID_INCREASE_VIEWING_RANGE])) {
2602 increaseViewRange(statustext_time);
2603 } else if (input->wasKeyDown(keycache.key[KeyCache::KEYMAP_ID_DECREASE_VIEWING_RANGE])) {
2604 decreaseViewRange(statustext_time);
2605 } else if (input->wasKeyDown(keycache.key[KeyCache::KEYMAP_ID_RANGESELECT])) {
2606 toggleFullViewRange(statustext_time);
2607 } else if (input->wasKeyDown(keycache.key[KeyCache::KEYMAP_ID_QUICKTUNE_NEXT]))
2609 else if (input->wasKeyDown(keycache.key[KeyCache::KEYMAP_ID_QUICKTUNE_PREV]))
2611 else if (input->wasKeyDown(keycache.key[KeyCache::KEYMAP_ID_QUICKTUNE_INC]))
2613 else if (input->wasKeyDown(keycache.key[KeyCache::KEYMAP_ID_QUICKTUNE_DEC]))
2615 else if (input->wasKeyDown(keycache.key[KeyCache::KEYMAP_ID_DEBUG_STACKS])) {
2616 // Print debug stacks
2617 dstream << "-----------------------------------------"
2619 dstream << DTIME << "Printing debug stacks:" << std::endl;
2620 dstream << "-----------------------------------------"
2622 debug_stacks_print();
2625 if (!input->isKeyDown(getKeySetting("keymap_jump")) && *reset_jump_timer) {
2626 *reset_jump_timer = false;
2632 if (quicktune->hasMessage()) {
2633 std::string msg = quicktune->getMessage();
2634 statustext = narrow_to_wide(msg);
2635 *statustext_time = 0;
2640 void Game::processItemSelection(u16 *new_playeritem)
2642 LocalPlayer *player = client->getEnv().getLocalPlayer();
2644 /* Item selection using mouse wheel
2646 *new_playeritem = client->getPlayerItem();
2648 s32 wheel = input->getMouseWheel();
2649 u16 max_item = MYMIN(PLAYER_INVENTORY_SIZE - 1,
2650 player->hud_hotbar_itemcount - 1);
2653 *new_playeritem = *new_playeritem < max_item ? *new_playeritem + 1 : 0;
2655 *new_playeritem = *new_playeritem > 0 ? *new_playeritem - 1 : max_item;
2659 /* Item selection using keyboard
2661 for (u16 i = 0; i < 10; i++) {
2662 static const KeyPress *item_keys[10] = {
2663 NumberKey + 1, NumberKey + 2, NumberKey + 3, NumberKey + 4,
2664 NumberKey + 5, NumberKey + 6, NumberKey + 7, NumberKey + 8,
2665 NumberKey + 9, NumberKey + 0,
2668 if (input->wasKeyDown(*item_keys[i])) {
2669 if (i < PLAYER_INVENTORY_SIZE && i < player->hud_hotbar_itemcount) {
2670 *new_playeritem = i;
2671 infostream << "Selected item: " << new_playeritem << std::endl;
2679 void Game::dropSelectedItem()
2681 IDropAction *a = new IDropAction();
2683 a->from_inv.setCurrentPlayer();
2684 a->from_list = "main";
2685 a->from_i = client->getPlayerItem();
2686 client->inventoryAction(a);
2690 void Game::openInventory()
2693 * Don't permit to open inventory is CAO or player doesn't exists.
2694 * This prevent showing an empty inventory at player load
2697 LocalPlayer *player = client->getEnv().getLocalPlayer();
2698 if (player == NULL || player->getCAO() == NULL)
2701 infostream << "the_game: " << "Launching inventory" << std::endl;
2703 PlayerInventoryFormSource *fs_src = new PlayerInventoryFormSource(client);
2704 TextDest *txt_dst = new TextDestPlayerInventory(client);
2706 create_formspec_menu(¤t_formspec, client, gamedef, texture_src,
2707 device, fs_src, txt_dst, client);
2709 InventoryLocation inventoryloc;
2710 inventoryloc.setCurrentPlayer();
2711 current_formspec->setFormSpec(fs_src->getForm(), inventoryloc);
2715 void Game::openConsole()
2717 if (!gui_chat_console->isOpenInhibited()) {
2718 // Open up to over half of the screen
2719 gui_chat_console->openConsole(0.6);
2720 guienv->setFocus(gui_chat_console);
2725 void Game::toggleFreeMove(float *statustext_time)
2727 static const wchar_t *msg[] = { L"free_move disabled", L"free_move enabled" };
2729 bool free_move = !g_settings->getBool("free_move");
2730 g_settings->set("free_move", bool_to_cstr(free_move));
2732 *statustext_time = 0;
2733 statustext = msg[free_move];
2734 if (free_move && !client->checkPrivilege("fly"))
2735 statustext += L" (note: no 'fly' privilege)";
2739 void Game::toggleFreeMoveAlt(float *statustext_time, float *jump_timer)
2741 if (m_cache_doubletap_jump && *jump_timer < 0.2f)
2742 toggleFreeMove(statustext_time);
2746 void Game::toggleFast(float *statustext_time)
2748 static const wchar_t *msg[] = { L"fast_move disabled", L"fast_move enabled" };
2749 bool fast_move = !g_settings->getBool("fast_move");
2750 g_settings->set("fast_move", bool_to_cstr(fast_move));
2752 *statustext_time = 0;
2753 statustext = msg[fast_move];
2755 if (fast_move && !client->checkPrivilege("fast"))
2756 statustext += L" (note: no 'fast' privilege)";
2760 void Game::toggleNoClip(float *statustext_time)
2762 static const wchar_t *msg[] = { L"noclip disabled", L"noclip enabled" };
2763 bool noclip = !g_settings->getBool("noclip");
2764 g_settings->set("noclip", bool_to_cstr(noclip));
2766 *statustext_time = 0;
2767 statustext = msg[noclip];
2769 if (noclip && !client->checkPrivilege("noclip"))
2770 statustext += L" (note: no 'noclip' privilege)";
2773 void Game::toggleCinematic(float *statustext_time)
2775 static const wchar_t *msg[] = { L"cinematic disabled", L"cinematic enabled" };
2776 bool cinematic = !g_settings->getBool("cinematic");
2777 g_settings->set("cinematic", bool_to_cstr(cinematic));
2779 *statustext_time = 0;
2780 statustext = msg[cinematic];
2784 void Game::toggleChat(float *statustext_time, bool *flag)
2786 static const wchar_t *msg[] = { L"Chat hidden", L"Chat shown" };
2789 *statustext_time = 0;
2790 statustext = msg[*flag];
2794 void Game::toggleHud(float *statustext_time, bool *flag)
2796 static const wchar_t *msg[] = { L"HUD hidden", L"HUD shown" };
2799 *statustext_time = 0;
2800 statustext = msg[*flag];
2801 if (g_settings->getBool("enable_node_highlighting"))
2802 client->setHighlighted(client->getHighlighted(), *flag);
2806 void Game::toggleFog(float *statustext_time, bool *flag)
2808 static const wchar_t *msg[] = { L"Fog enabled", L"Fog disabled" };
2811 *statustext_time = 0;
2812 statustext = msg[*flag];
2816 void Game::toggleDebug(float *statustext_time, bool *show_debug,
2817 bool *show_profiler_graph)
2819 // Initial / 3x toggle: Chat only
2820 // 1x toggle: Debug text with chat
2821 // 2x toggle: Debug text with profiler graph
2824 *show_profiler_graph = false;
2825 statustext = L"Debug info shown";
2826 } else if (*show_profiler_graph) {
2827 *show_debug = false;
2828 *show_profiler_graph = false;
2829 statustext = L"Debug info and profiler graph hidden";
2831 *show_profiler_graph = true;
2832 statustext = L"Profiler graph shown";
2834 *statustext_time = 0;
2838 void Game::toggleUpdateCamera(float *statustext_time, bool *flag)
2840 static const wchar_t *msg[] = {
2841 L"Camera update enabled",
2842 L"Camera update disabled"
2846 *statustext_time = 0;
2847 statustext = msg[*flag];
2851 void Game::toggleProfiler(float *statustext_time, u32 *profiler_current_page,
2852 u32 profiler_max_page)
2854 *profiler_current_page = (*profiler_current_page + 1) % (profiler_max_page + 1);
2856 // FIXME: This updates the profiler with incomplete values
2857 update_profiler_gui(guitext_profiler, g_fontengine, *profiler_current_page,
2858 profiler_max_page, driver->getScreenSize().Height);
2860 if (*profiler_current_page != 0) {
2861 std::wstringstream sstr;
2862 sstr << "Profiler shown (page " << *profiler_current_page
2863 << " of " << profiler_max_page << ")";
2864 statustext = sstr.str();
2866 statustext = L"Profiler hidden";
2868 *statustext_time = 0;
2872 void Game::increaseViewRange(float *statustext_time)
2874 s16 range = g_settings->getS16("viewing_range_nodes_min");
2875 s16 range_new = range + 10;
2876 g_settings->set("viewing_range_nodes_min", itos(range_new));
2877 statustext = narrow_to_wide("Minimum viewing range changed to "
2879 *statustext_time = 0;
2883 void Game::decreaseViewRange(float *statustext_time)
2885 s16 range = g_settings->getS16("viewing_range_nodes_min");
2886 s16 range_new = range - 10;
2891 g_settings->set("viewing_range_nodes_min", itos(range_new));
2892 statustext = narrow_to_wide("Minimum viewing range changed to "
2894 *statustext_time = 0;
2898 void Game::toggleFullViewRange(float *statustext_time)
2900 static const wchar_t *msg[] = {
2901 L"Disabled full viewing range",
2902 L"Enabled full viewing range"
2905 draw_control->range_all = !draw_control->range_all;
2906 infostream << msg[draw_control->range_all] << std::endl;
2907 statustext = msg[draw_control->range_all];
2908 *statustext_time = 0;
2912 void Game::updateCameraDirection(CameraOrientation *cam,
2913 VolatileRunFlags *flags)
2915 if ((device->isWindowActive() && noMenuActive()) || random_input) {
2918 if (!random_input) {
2919 // Mac OSX gets upset if this is set every frame
2920 if (device->getCursorControl()->isVisible())
2921 device->getCursorControl()->setVisible(false);
2925 if (flags->first_loop_after_window_activation)
2926 flags->first_loop_after_window_activation = false;
2928 updateCameraOrientation(cam, *flags);
2930 input->setMousePos((driver->getScreenSize().Width / 2),
2931 (driver->getScreenSize().Height / 2));
2935 // Mac OSX gets upset if this is set every frame
2936 if (device->getCursorControl()->isVisible() == false)
2937 device->getCursorControl()->setVisible(true);
2940 if (!flags->first_loop_after_window_activation)
2941 flags->first_loop_after_window_activation = true;
2947 void Game::updateCameraOrientation(CameraOrientation *cam,
2948 const VolatileRunFlags &flags)
2950 #ifdef HAVE_TOUCHSCREENGUI
2951 if (g_touchscreengui) {
2952 cam->camera_yaw = g_touchscreengui->getYaw();
2953 cam->camera_pitch = g_touchscreengui->getPitch();
2956 s32 dx = input->getMousePos().X - (driver->getScreenSize().Width / 2);
2957 s32 dy = input->getMousePos().Y - (driver->getScreenSize().Height / 2);
2959 if (flags.invert_mouse
2960 || camera->getCameraMode() == CAMERA_MODE_THIRD_FRONT) {
2964 cam->camera_yaw -= dx * m_cache_mouse_sensitivity;
2965 cam->camera_pitch += dy * m_cache_mouse_sensitivity;
2967 #ifdef HAVE_TOUCHSCREENGUI
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 PlayerControl control(
2980 input->isKeyDown(keycache.key[KeyCache::KEYMAP_ID_FORWARD]),
2981 input->isKeyDown(keycache.key[KeyCache::KEYMAP_ID_BACKWARD]),
2982 input->isKeyDown(keycache.key[KeyCache::KEYMAP_ID_LEFT]),
2983 input->isKeyDown(keycache.key[KeyCache::KEYMAP_ID_RIGHT]),
2984 input->isKeyDown(keycache.key[KeyCache::KEYMAP_ID_JUMP]),
2985 input->isKeyDown(keycache.key[KeyCache::KEYMAP_ID_SPECIAL1]),
2986 input->isKeyDown(keycache.key[KeyCache::KEYMAP_ID_SNEAK]),
2987 input->getLeftState(),
2988 input->getRightState(),
2992 client->setPlayerControl(control);
2993 LocalPlayer *player = client->getEnv().getLocalPlayer();
2994 player->keyPressed =
2995 ( (u32)(input->isKeyDown(keycache.key[KeyCache::KEYMAP_ID_FORWARD]) & 0x1) << 0) |
2996 ( (u32)(input->isKeyDown(keycache.key[KeyCache::KEYMAP_ID_BACKWARD]) & 0x1) << 1) |
2997 ( (u32)(input->isKeyDown(keycache.key[KeyCache::KEYMAP_ID_LEFT]) & 0x1) << 2) |
2998 ( (u32)(input->isKeyDown(keycache.key[KeyCache::KEYMAP_ID_RIGHT]) & 0x1) << 3) |
2999 ( (u32)(input->isKeyDown(keycache.key[KeyCache::KEYMAP_ID_JUMP]) & 0x1) << 4) |
3000 ( (u32)(input->isKeyDown(keycache.key[KeyCache::KEYMAP_ID_SPECIAL1]) & 0x1) << 5) |
3001 ( (u32)(input->isKeyDown(keycache.key[KeyCache::KEYMAP_ID_SNEAK]) & 0x1) << 6) |
3002 ( (u32)(input->getLeftState() & 0x1) << 7) |
3003 ( (u32)(input->getRightState() & 0x1) << 8
3010 inline void Game::step(f32 *dtime)
3012 bool can_be_and_is_paused =
3013 (simple_singleplayer_mode && g_menumgr.pausesGame());
3015 if (can_be_and_is_paused) { // This is for a singleplayer server
3016 *dtime = 0; // No time passes
3018 if (server != NULL) {
3019 //TimeTaker timer("server->step(dtime)");
3020 server->step(*dtime);
3023 //TimeTaker timer("client.step(dtime)");
3024 client->step(*dtime);
3029 void Game::processClientEvents(CameraOrientation *cam, float *damage_flash)
3031 ClientEvent event = client->getClientEvent();
3033 LocalPlayer *player = client->getEnv().getLocalPlayer();
3035 for ( ; event.type != CE_NONE; event = client->getClientEvent()) {
3037 if (event.type == CE_PLAYER_DAMAGE &&
3038 client->getHP() != 0) {
3039 //u16 damage = event.player_damage.amount;
3040 //infostream<<"Player damage: "<<damage<<std::endl;
3042 *damage_flash += 100.0;
3043 *damage_flash += 8.0 * event.player_damage.amount;
3045 player->hurt_tilt_timer = 1.5;
3046 player->hurt_tilt_strength = event.player_damage.amount / 4;
3047 player->hurt_tilt_strength = rangelim(player->hurt_tilt_strength, 1.0, 4.0);
3049 MtEvent *e = new SimpleTriggerEvent("PlayerDamage");
3050 gamedef->event()->put(e);
3051 } else if (event.type == CE_PLAYER_FORCE_MOVE) {
3052 cam->camera_yaw = event.player_force_move.yaw;
3053 cam->camera_pitch = event.player_force_move.pitch;
3054 } else if (event.type == CE_DEATHSCREEN) {
3055 show_deathscreen(¤t_formspec, client, gamedef, texture_src,
3058 chat_backend->addMessage(L"", L"You died.");
3060 /* Handle visualization */
3062 player->hurt_tilt_timer = 0;
3063 player->hurt_tilt_strength = 0;
3065 } else if (event.type == CE_SHOW_FORMSPEC) {
3066 FormspecFormSource *fs_src =
3067 new FormspecFormSource(*(event.show_formspec.formspec));
3068 TextDestPlayerInventory *txt_dst =
3069 new TextDestPlayerInventory(client, *(event.show_formspec.formname));
3071 create_formspec_menu(¤t_formspec, client, gamedef,
3072 texture_src, device, fs_src, txt_dst, client);
3074 delete(event.show_formspec.formspec);
3075 delete(event.show_formspec.formname);
3076 } else if ((event.type == CE_SPAWN_PARTICLE) ||
3077 (event.type == CE_ADD_PARTICLESPAWNER) ||
3078 (event.type == CE_DELETE_PARTICLESPAWNER)) {
3079 client->getParticleManager()->handleParticleEvent(&event, gamedef,
3081 } else if (event.type == CE_HUDADD) {
3082 u32 id = event.hudadd.id;
3084 LocalPlayer *player = client->getEnv().getLocalPlayer();
3085 HudElement *e = player->getHud(id);
3088 delete event.hudadd.pos;
3089 delete event.hudadd.name;
3090 delete event.hudadd.scale;
3091 delete event.hudadd.text;
3092 delete event.hudadd.align;
3093 delete event.hudadd.offset;
3094 delete event.hudadd.world_pos;
3095 delete event.hudadd.size;
3100 e->type = (HudElementType)event.hudadd.type;
3101 e->pos = *event.hudadd.pos;
3102 e->name = *event.hudadd.name;
3103 e->scale = *event.hudadd.scale;
3104 e->text = *event.hudadd.text;
3105 e->number = event.hudadd.number;
3106 e->item = event.hudadd.item;
3107 e->dir = event.hudadd.dir;
3108 e->align = *event.hudadd.align;
3109 e->offset = *event.hudadd.offset;
3110 e->world_pos = *event.hudadd.world_pos;
3111 e->size = *event.hudadd.size;
3113 u32 new_id = player->addHud(e);
3114 //if this isn't true our huds aren't consistent
3115 assert(new_id == id);
3117 delete event.hudadd.pos;
3118 delete event.hudadd.name;
3119 delete event.hudadd.scale;
3120 delete event.hudadd.text;
3121 delete event.hudadd.align;
3122 delete event.hudadd.offset;
3123 delete event.hudadd.world_pos;
3124 delete event.hudadd.size;
3125 } else if (event.type == CE_HUDRM) {
3126 HudElement *e = player->removeHud(event.hudrm.id);
3130 } else if (event.type == CE_HUDCHANGE) {
3131 u32 id = event.hudchange.id;
3132 HudElement *e = player->getHud(id);
3135 delete event.hudchange.v3fdata;
3136 delete event.hudchange.v2fdata;
3137 delete event.hudchange.sdata;
3138 delete event.hudchange.v2s32data;
3142 switch (event.hudchange.stat) {
3144 e->pos = *event.hudchange.v2fdata;
3148 e->name = *event.hudchange.sdata;
3151 case HUD_STAT_SCALE:
3152 e->scale = *event.hudchange.v2fdata;
3156 e->text = *event.hudchange.sdata;
3159 case HUD_STAT_NUMBER:
3160 e->number = event.hudchange.data;
3164 e->item = event.hudchange.data;
3168 e->dir = event.hudchange.data;
3171 case HUD_STAT_ALIGN:
3172 e->align = *event.hudchange.v2fdata;
3175 case HUD_STAT_OFFSET:
3176 e->offset = *event.hudchange.v2fdata;
3179 case HUD_STAT_WORLD_POS:
3180 e->world_pos = *event.hudchange.v3fdata;
3184 e->size = *event.hudchange.v2s32data;
3188 delete event.hudchange.v3fdata;
3189 delete event.hudchange.v2fdata;
3190 delete event.hudchange.sdata;
3191 delete event.hudchange.v2s32data;
3192 } else if (event.type == CE_SET_SKY) {
3193 sky->setVisible(false);
3200 // Handle according to type
3201 if (*event.set_sky.type == "regular") {
3202 sky->setVisible(true);
3203 } else if (*event.set_sky.type == "skybox" &&
3204 event.set_sky.params->size() == 6) {
3205 sky->setFallbackBgColor(*event.set_sky.bgcolor);
3206 skybox = smgr->addSkyBoxSceneNode(
3207 texture_src->getTexture((*event.set_sky.params)[0]),
3208 texture_src->getTexture((*event.set_sky.params)[1]),
3209 texture_src->getTexture((*event.set_sky.params)[2]),
3210 texture_src->getTexture((*event.set_sky.params)[3]),
3211 texture_src->getTexture((*event.set_sky.params)[4]),
3212 texture_src->getTexture((*event.set_sky.params)[5]));
3214 // Handle everything else as plain color
3216 if (*event.set_sky.type != "plain")
3217 infostream << "Unknown sky type: "
3218 << (*event.set_sky.type) << std::endl;
3220 sky->setFallbackBgColor(*event.set_sky.bgcolor);
3223 delete event.set_sky.bgcolor;
3224 delete event.set_sky.type;
3225 delete event.set_sky.params;
3226 } else if (event.type == CE_OVERRIDE_DAY_NIGHT_RATIO) {
3227 bool enable = event.override_day_night_ratio.do_override;
3228 u32 value = event.override_day_night_ratio.ratio_f * 1000;
3229 client->getEnv().setDayNightRatioOverride(enable, value);
3235 void Game::updateCamera(VolatileRunFlags *flags, u32 busy_time,
3236 f32 dtime, float time_from_last_punch)
3238 LocalPlayer *player = client->getEnv().getLocalPlayer();
3241 For interaction purposes, get info about the held item
3243 - Is it a usable item?
3244 - Can it point to liquids?
3246 ItemStack playeritem;
3248 InventoryList *mlist = local_inventory->getList("main");
3250 if (mlist && client->getPlayerItem() < mlist->getSize())
3251 playeritem = mlist->getItem(client->getPlayerItem());
3254 ToolCapabilities playeritem_toolcap =
3255 playeritem.getToolCapabilities(itemdef_manager);
3257 v3s16 old_camera_offset = camera->getOffset();
3259 if (input->wasKeyDown(keycache.key[KeyCache::KEYMAP_ID_CAMERA_MODE])) {
3260 GenericCAO *playercao = player->getCAO();
3262 // If playercao not loaded, don't change camera
3263 if (playercao == NULL)
3266 camera->toggleCameraMode();
3268 playercao->setVisible(camera->getCameraMode() > CAMERA_MODE_FIRST);
3271 float full_punch_interval = playeritem_toolcap.full_punch_interval;
3272 float tool_reload_ratio = time_from_last_punch / full_punch_interval;
3274 tool_reload_ratio = MYMIN(tool_reload_ratio, 1.0);
3275 camera->update(player, dtime, busy_time / 1000.0f, tool_reload_ratio,
3277 camera->step(dtime);
3279 v3f camera_position = camera->getPosition();
3280 v3f camera_direction = camera->getDirection();
3281 f32 camera_fov = camera->getFovMax();
3282 v3s16 camera_offset = camera->getOffset();
3284 flags->camera_offset_changed = (camera_offset != old_camera_offset);
3286 if (!flags->disable_camera_update) {
3287 client->getEnv().getClientMap().updateCamera(camera_position,
3288 camera_direction, camera_fov, camera_offset);
3290 if (flags->camera_offset_changed) {
3291 client->updateCameraOffset(camera_offset);
3292 client->getEnv().updateCameraOffset(camera_offset);
3295 clouds->updateCameraOffset(camera_offset);
3301 void Game::updateSound(f32 dtime)
3303 // Update sound listener
3304 v3s16 camera_offset = camera->getOffset();
3305 sound->updateListener(camera->getCameraNode()->getPosition() + intToFloat(camera_offset, BS),
3306 v3f(0, 0, 0), // velocity
3307 camera->getDirection(),
3308 camera->getCameraNode()->getUpVector());
3309 sound->setListenerGain(g_settings->getFloat("sound_volume"));
3312 // Update sound maker
3313 soundmaker->step(dtime);
3315 LocalPlayer *player = client->getEnv().getLocalPlayer();
3317 ClientMap &map = client->getEnv().getClientMap();
3318 MapNode n = map.getNodeNoEx(player->getStandingNodePos());
3319 soundmaker->m_player_step_sound = nodedef_manager->get(n).sound_footstep;
3323 void Game::processPlayerInteraction(std::vector<aabb3f> &highlight_boxes,
3324 GameRunData *runData, f32 dtime, bool show_hud, bool show_debug)
3326 LocalPlayer *player = client->getEnv().getLocalPlayer();
3328 ItemStack playeritem;
3330 InventoryList *mlist = local_inventory->getList("main");
3332 if (mlist && client->getPlayerItem() < mlist->getSize())
3333 playeritem = mlist->getItem(client->getPlayerItem());
3336 const ItemDefinition &playeritem_def =
3337 playeritem.getDefinition(itemdef_manager);
3339 v3f player_position = player->getPosition();
3340 v3f camera_position = camera->getPosition();
3341 v3f camera_direction = camera->getDirection();
3342 v3s16 camera_offset = camera->getOffset();
3346 Calculate what block is the crosshair pointing to
3349 f32 d = playeritem_def.range; // max. distance
3350 f32 d_hand = itemdef_manager->get("").range;
3352 if (d < 0 && d_hand >= 0)
3357 core::line3d<f32> shootline;
3359 if (camera->getCameraMode() != CAMERA_MODE_THIRD_FRONT) {
3361 shootline = core::line3d<f32>(camera_position,
3362 camera_position + camera_direction * BS * (d + 1));
3365 // prevent player pointing anything in front-view
3366 if (camera->getCameraMode() == CAMERA_MODE_THIRD_FRONT)
3367 shootline = core::line3d<f32>(0, 0, 0, 0, 0, 0);
3370 #ifdef HAVE_TOUCHSCREENGUI
3372 if ((g_settings->getBool("touchtarget")) && (g_touchscreengui)) {
3373 shootline = g_touchscreengui->getShootline();
3374 shootline.start += intToFloat(camera_offset, BS);
3375 shootline.end += intToFloat(camera_offset, BS);
3380 PointedThing pointed = getPointedThing(
3382 client, player_position, camera_direction,
3383 camera_position, shootline, d,
3384 playeritem_def.liquids_pointable,
3385 !runData->ldown_for_dig,
3389 runData->selected_object);
3391 if (pointed != runData->pointed_old) {
3392 infostream << "Pointing at " << pointed.dump() << std::endl;
3394 if (m_cache_enable_node_highlighting) {
3395 if (pointed.type == POINTEDTHING_NODE) {
3396 client->setHighlighted(pointed.node_undersurface, show_hud);
3398 client->setHighlighted(pointed.node_undersurface, false);
3405 - releasing left mouse button
3406 - pointing away from node
3408 if (runData->digging) {
3409 if (input->getLeftReleased()) {
3410 infostream << "Left button released"
3411 << " (stopped digging)" << std::endl;
3412 runData->digging = false;
3413 } else if (pointed != runData->pointed_old) {
3414 if (pointed.type == POINTEDTHING_NODE
3415 && runData->pointed_old.type == POINTEDTHING_NODE
3416 && pointed.node_undersurface
3417 == runData->pointed_old.node_undersurface) {
3418 // Still pointing to the same node, but a different face.
3421 infostream << "Pointing away from node"
3422 << " (stopped digging)" << std::endl;
3423 runData->digging = false;
3427 if (!runData->digging) {
3428 client->interact(1, runData->pointed_old);
3429 client->setCrack(-1, v3s16(0, 0, 0));
3430 runData->dig_time = 0.0;
3434 if (!runData->digging && runData->ldown_for_dig && !input->getLeftState()) {
3435 runData->ldown_for_dig = false;
3438 runData->left_punch = false;
3440 soundmaker->m_player_leftpunch_sound.name = "";
3442 if (input->getRightState())
3443 runData->repeat_rightclick_timer += dtime;
3445 runData->repeat_rightclick_timer = 0;
3447 if (playeritem_def.usable && input->getLeftState()) {
3448 if (input->getLeftClicked())
3449 client->interact(4, pointed);
3450 } else if (pointed.type == POINTEDTHING_NODE) {
3451 ToolCapabilities playeritem_toolcap =
3452 playeritem.getToolCapabilities(itemdef_manager);
3453 handlePointingAtNode(runData, pointed, playeritem_def,
3454 playeritem_toolcap, dtime);
3455 } else if (pointed.type == POINTEDTHING_OBJECT) {
3456 handlePointingAtObject(runData, pointed, playeritem,
3457 player_position, show_debug);
3458 } else if (input->getLeftState()) {
3459 // When button is held down in air, show continuous animation
3460 runData->left_punch = true;
3463 runData->pointed_old = pointed;
3465 if (runData->left_punch || input->getLeftClicked())
3466 camera->setDigging(0); // left click animation
3468 input->resetLeftClicked();
3469 input->resetRightClicked();
3471 input->resetLeftReleased();
3472 input->resetRightReleased();
3476 void Game::handlePointingAtNode(GameRunData *runData,
3477 const PointedThing &pointed, const ItemDefinition &playeritem_def,
3478 const ToolCapabilities &playeritem_toolcap, f32 dtime)
3480 v3s16 nodepos = pointed.node_undersurface;
3481 v3s16 neighbourpos = pointed.node_abovesurface;
3484 Check information text of node
3487 ClientMap &map = client->getEnv().getClientMap();
3488 NodeMetadata *meta = map.getNodeMetadata(nodepos);
3491 infotext = narrow_to_wide(meta->getString("infotext"));
3493 MapNode n = map.getNodeNoEx(nodepos);
3495 if (nodedef_manager->get(n).tiledef[0].name == "unknown_node.png") {
3496 infotext = L"Unknown node: ";
3497 infotext += narrow_to_wide(nodedef_manager->get(n).name);
3501 if (runData->nodig_delay_timer <= 0.0 && input->getLeftState()
3502 && client->checkPrivilege("interact")) {
3503 handleDigging(runData, pointed, nodepos, playeritem_toolcap, dtime);
3506 if ((input->getRightClicked() ||
3507 runData->repeat_rightclick_timer >= m_repeat_right_click_time) &&
3508 client->checkPrivilege("interact")) {
3509 runData->repeat_rightclick_timer = 0;
3510 infostream << "Ground right-clicked" << std::endl;
3512 if (meta && meta->getString("formspec") != "" && !random_input
3513 && !input->isKeyDown(getKeySetting("keymap_sneak"))) {
3514 infostream << "Launching custom inventory view" << std::endl;
3516 InventoryLocation inventoryloc;
3517 inventoryloc.setNodeMeta(nodepos);
3519 NodeMetadataFormSource *fs_src = new NodeMetadataFormSource(
3520 &client->getEnv().getClientMap(), nodepos);
3521 TextDest *txt_dst = new TextDestNodeMetadata(nodepos, client);
3523 create_formspec_menu(¤t_formspec, client, gamedef,
3524 texture_src, device, fs_src, txt_dst, client);
3526 current_formspec->setFormSpec(meta->getString("formspec"), inventoryloc);
3528 // Report right click to server
3530 camera->setDigging(1); // right click animation (always shown for feedback)
3532 // If the wielded item has node placement prediction,
3534 bool placed = nodePlacementPrediction(*client,
3536 nodepos, neighbourpos);
3540 client->interact(3, pointed);
3542 soundmaker->m_player_rightpunch_sound =
3543 playeritem_def.sound_place;
3545 soundmaker->m_player_rightpunch_sound =
3549 if (playeritem_def.node_placement_prediction == "" ||
3550 nodedef_manager->get(map.getNodeNoEx(nodepos)).rightclickable)
3551 client->interact(3, pointed); // Report to server
3557 void Game::handlePointingAtObject(GameRunData *runData,
3558 const PointedThing &pointed,
3559 const ItemStack &playeritem,
3560 const v3f &player_position,
3563 infotext = narrow_to_wide(runData->selected_object->infoText());
3565 if (infotext == L"" && show_debug) {
3566 infotext = narrow_to_wide(runData->selected_object->debugInfoText());
3569 if (input->getLeftState()) {
3570 bool do_punch = false;
3571 bool do_punch_damage = false;
3573 if (runData->object_hit_delay_timer <= 0.0) {
3575 do_punch_damage = true;
3576 runData->object_hit_delay_timer = object_hit_delay;
3579 if (input->getLeftClicked())
3583 infostream << "Left-clicked object" << std::endl;
3584 runData->left_punch = true;
3587 if (do_punch_damage) {
3588 // Report direct punch
3589 v3f objpos = runData->selected_object->getPosition();
3590 v3f dir = (objpos - player_position).normalize();
3592 bool disable_send = runData->selected_object->directReportPunch(
3593 dir, &playeritem, runData->time_from_last_punch);
3594 runData->time_from_last_punch = 0;
3597 client->interact(0, pointed);
3599 } else if (input->getRightClicked()) {
3600 infostream << "Right-clicked object" << std::endl;
3601 client->interact(3, pointed); // place
3606 void Game::handleDigging(GameRunData *runData,
3607 const PointedThing &pointed, const v3s16 &nodepos,
3608 const ToolCapabilities &playeritem_toolcap, f32 dtime)
3610 if (!runData->digging) {
3611 infostream << "Started digging" << std::endl;
3612 client->interact(0, pointed);
3613 runData->digging = true;
3614 runData->ldown_for_dig = true;
3617 LocalPlayer *player = client->getEnv().getLocalPlayer();
3618 ClientMap &map = client->getEnv().getClientMap();
3619 MapNode n = client->getEnv().getClientMap().getNodeNoEx(nodepos);
3621 // NOTE: Similar piece of code exists on the server side for
3623 // Get digging parameters
3624 DigParams params = getDigParams(nodedef_manager->get(n).groups,
3625 &playeritem_toolcap);
3627 // If can't dig, try hand
3628 if (!params.diggable) {
3629 const ItemDefinition &hand = itemdef_manager->get("");
3630 const ToolCapabilities *tp = hand.tool_capabilities;
3633 params = getDigParams(nodedef_manager->get(n).groups, tp);
3636 if (params.diggable == false) {
3637 // I guess nobody will wait for this long
3638 runData->dig_time_complete = 10000000.0;
3640 runData->dig_time_complete = params.time;
3642 if (m_cache_enable_particles) {
3643 const ContentFeatures &features =
3644 client->getNodeDefManager()->get(n);
3645 client->getParticleManager()->addPunchingParticles(gamedef, smgr,
3646 player, nodepos, features.tiles);
3650 if (runData->dig_time_complete >= 0.001) {
3651 runData->dig_index = (float)crack_animation_length
3653 / runData->dig_time_complete;
3655 // This is for torches
3656 runData->dig_index = crack_animation_length;
3659 SimpleSoundSpec sound_dig = nodedef_manager->get(n).sound_dig;
3661 if (sound_dig.exists() && params.diggable) {
3662 if (sound_dig.name == "__group") {
3663 if (params.main_group != "") {
3664 soundmaker->m_player_leftpunch_sound.gain = 0.5;
3665 soundmaker->m_player_leftpunch_sound.name =
3666 std::string("default_dig_") +
3670 soundmaker->m_player_leftpunch_sound = sound_dig;
3674 // Don't show cracks if not diggable
3675 if (runData->dig_time_complete >= 100000.0) {
3676 } else if (runData->dig_index < crack_animation_length) {
3677 //TimeTaker timer("client.setTempMod");
3678 //infostream<<"dig_index="<<dig_index<<std::endl;
3679 client->setCrack(runData->dig_index, nodepos);
3681 infostream << "Digging completed" << std::endl;
3682 client->interact(2, pointed);
3683 client->setCrack(-1, v3s16(0, 0, 0));
3684 bool is_valid_position;
3685 MapNode wasnode = map.getNodeNoEx(nodepos, &is_valid_position);
3686 if (is_valid_position)
3687 client->removeNode(nodepos);
3689 if (m_cache_enable_particles) {
3690 const ContentFeatures &features =
3691 client->getNodeDefManager()->get(wasnode);
3692 client->getParticleManager()->addDiggingParticles(gamedef, smgr,
3693 player, nodepos, features.tiles);
3696 runData->dig_time = 0;
3697 runData->digging = false;
3699 runData->nodig_delay_timer =
3700 runData->dig_time_complete / (float)crack_animation_length;
3702 // We don't want a corresponding delay to
3703 // very time consuming nodes
3704 if (runData->nodig_delay_timer > 0.3)
3705 runData->nodig_delay_timer = 0.3;
3707 // We want a slight delay to very little
3708 // time consuming nodes
3709 const float mindelay = 0.15;
3711 if (runData->nodig_delay_timer < mindelay)
3712 runData->nodig_delay_timer = mindelay;
3714 // Send event to trigger sound
3715 MtEvent *e = new NodeDugEvent(nodepos, wasnode);
3716 gamedef->event()->put(e);
3719 if (runData->dig_time_complete < 100000.0) {
3720 runData->dig_time += dtime;
3722 runData->dig_time = 0;
3723 client->setCrack(-1, nodepos);
3726 camera->setDigging(0); // left click animation
3730 void Game::updateFrame(std::vector<aabb3f> &highlight_boxes,
3731 ProfilerGraph *graph, RunStats *stats, GameRunData *runData,
3732 f32 dtime, const VolatileRunFlags &flags, const CameraOrientation &cam)
3734 LocalPlayer *player = client->getEnv().getLocalPlayer();
3740 if (draw_control->range_all) {
3741 runData->fog_range = 100000 * BS;
3743 runData->fog_range = draw_control->wanted_range * BS
3744 + 0.0 * MAP_BLOCKSIZE * BS;
3745 runData->fog_range = MYMIN(
3747 (draw_control->farthest_drawn + 20) * BS);
3748 runData->fog_range *= 0.9;
3752 Calculate general brightness
3754 u32 daynight_ratio = client->getEnv().getDayNightRatio();
3755 float time_brightness = decode_light_f((float)daynight_ratio / 1000.0);
3756 float direct_brightness;
3759 if (g_settings->getBool("free_move")) {
3760 direct_brightness = time_brightness;
3761 sunlight_seen = true;
3763 ScopeProfiler sp(g_profiler, "Detecting background light", SPT_AVG);
3764 float old_brightness = sky->getBrightness();
3765 direct_brightness = client->getEnv().getClientMap()
3766 .getBackgroundBrightness(MYMIN(runData->fog_range * 1.2, 60 * BS),
3767 daynight_ratio, (int)(old_brightness * 255.5), &sunlight_seen)
3771 float time_of_day = runData->time_of_day;
3772 float time_of_day_smooth = runData->time_of_day_smooth;
3774 time_of_day = client->getEnv().getTimeOfDayF();
3776 const float maxsm = 0.05;
3777 const float todsm = 0.05;
3779 if (fabs(time_of_day - time_of_day_smooth) > maxsm &&
3780 fabs(time_of_day - time_of_day_smooth + 1.0) > maxsm &&
3781 fabs(time_of_day - time_of_day_smooth - 1.0) > maxsm)
3782 time_of_day_smooth = time_of_day;
3784 if (time_of_day_smooth > 0.8 && time_of_day < 0.2)
3785 time_of_day_smooth = time_of_day_smooth * (1.0 - todsm)
3786 + (time_of_day + 1.0) * todsm;
3788 time_of_day_smooth = time_of_day_smooth * (1.0 - todsm)
3789 + time_of_day * todsm;
3791 runData->time_of_day = time_of_day;
3792 runData->time_of_day_smooth = time_of_day_smooth;
3794 sky->update(time_of_day_smooth, time_brightness, direct_brightness,
3795 sunlight_seen, camera->getCameraMode(), player->getYaw(),
3796 player->getPitch());
3802 v3f player_position = player->getPosition();
3803 if (sky->getCloudsVisible()) {
3804 clouds->setVisible(true);
3805 clouds->step(dtime);
3806 clouds->update(v2f(player_position.X, player_position.Z),
3807 sky->getCloudColor());
3809 clouds->setVisible(false);
3816 client->getParticleManager()->step(dtime);
3822 if (m_cache_enable_fog && !flags.force_fog_off) {
3825 video::EFT_FOG_LINEAR,
3826 runData->fog_range * 0.4,
3827 runData->fog_range * 1.0,
3835 video::EFT_FOG_LINEAR,
3845 Get chat messages from client
3848 v2u32 screensize = driver->getScreenSize();
3850 updateChat(*client, dtime, flags.show_debug, screensize,
3851 flags.show_chat, runData->profiler_current_page,
3852 *chat_backend, guitext_chat);
3858 if (client->getPlayerItem() != runData->new_playeritem)
3859 client->selectPlayerItem(runData->new_playeritem);
3861 // Update local inventory if it has changed
3862 if (client->getLocalInventoryUpdated()) {
3863 //infostream<<"Updating local inventory"<<std::endl;
3864 client->getLocalInventory(*local_inventory);
3865 runData->update_wielded_item_trigger = true;
3868 if (runData->update_wielded_item_trigger) {
3869 // Update wielded tool
3870 InventoryList *mlist = local_inventory->getList("main");
3872 if (mlist && (client->getPlayerItem() < mlist->getSize())) {
3873 ItemStack item = mlist->getItem(client->getPlayerItem());
3874 camera->wield(item);
3876 runData->update_wielded_item_trigger = false;
3880 Update block draw list every 200ms or when camera direction has
3883 runData->update_draw_list_timer += dtime;
3885 v3f camera_direction = camera->getDirection();
3886 if (runData->update_draw_list_timer >= 0.2
3887 || runData->update_draw_list_last_cam_dir.getDistanceFrom(camera_direction) > 0.2
3888 || flags.camera_offset_changed) {
3889 runData->update_draw_list_timer = 0;
3890 client->getEnv().getClientMap().updateDrawList(driver);
3891 runData->update_draw_list_last_cam_dir = camera_direction;
3894 updateGui(&runData->statustext_time, *stats, *runData, dtime, flags, cam);
3897 make sure menu is on top
3898 1. Delete formspec menu reference if menu was removed
3899 2. Else, make sure formspec menu is on top
3901 if (current_formspec) {
3902 if (current_formspec->getReferenceCount() == 1) {
3903 current_formspec->drop();
3904 current_formspec = NULL;
3905 } else if (!noMenuActive()) {
3906 guiroot->bringToFront(current_formspec);
3914 video::SColor skycolor = sky->getSkyColor();
3916 TimeTaker tt_draw("mainloop: draw");
3918 TimeTaker timer("beginScene");
3919 driver->beginScene(true, true, skycolor);
3920 stats->beginscenetime = timer.stop(true);
3923 draw_scene(driver, smgr, *camera, *client, player, *hud, guienv,
3924 highlight_boxes, screensize, skycolor, flags.show_hud);
3929 if (flags.show_profiler_graph)
3930 graph->draw(10, screensize.Y - 10, driver, g_fontengine->getFont());
3935 if (runData->damage_flash > 0.0) {
3936 video::SColor color(std::min(runData->damage_flash, 180.0f),
3940 driver->draw2DRectangle(color,
3941 core::rect<s32>(0, 0, screensize.X, screensize.Y),
3944 runData->damage_flash -= 100.0 * dtime;
3950 if (player->hurt_tilt_timer > 0.0) {
3951 player->hurt_tilt_timer -= dtime * 5;
3953 if (player->hurt_tilt_timer < 0)
3954 player->hurt_tilt_strength = 0;
3961 TimeTaker timer("endScene");
3963 stats->endscenetime = timer.stop(true);
3966 stats->drawtime = tt_draw.stop(true);
3967 g_profiler->graphAdd("mainloop_draw", stats->drawtime / 1000.0f);
3971 inline static const char *yawToDirectionString(int yaw)
3973 // NOTE: TODO: This can be done mathematically without the else/else-if
3976 const char *player_direction;
3978 yaw = wrapDegrees_0_360(yaw);
3980 if (yaw >= 45 && yaw < 135)
3981 player_direction = "West [-X]";
3982 else if (yaw >= 135 && yaw < 225)
3983 player_direction = "South [-Z]";
3984 else if (yaw >= 225 && yaw < 315)
3985 player_direction = "East [+X]";
3987 player_direction = "North [+Z]";
3989 return player_direction;
3993 void Game::updateGui(float *statustext_time, const RunStats &stats,
3994 const GameRunData& runData, f32 dtime, const VolatileRunFlags &flags,
3995 const CameraOrientation &cam)
3997 v2u32 screensize = driver->getScreenSize();
3998 LocalPlayer *player = client->getEnv().getLocalPlayer();
3999 v3f player_position = player->getPosition();
4001 if (flags.show_debug) {
4002 static float drawtime_avg = 0;
4003 drawtime_avg = drawtime_avg * 0.95 + stats.drawtime * 0.05;
4005 u16 fps = 1.0 / stats.dtime_jitter.avg;
4006 //s32 fps = driver->getFPS();
4008 std::ostringstream os(std::ios_base::binary);
4010 << "Minetest " << minetest_version_hash
4012 << " (R: range_all=" << draw_control->range_all << ")"
4013 << std::setprecision(0)
4014 << " drawtime = " << drawtime_avg
4015 << std::setprecision(1)
4016 << ", dtime_jitter = "
4017 << (stats.dtime_jitter.max_fraction * 100.0) << " %"
4018 << std::setprecision(1)
4019 << ", v_range = " << draw_control->wanted_range
4020 << std::setprecision(3)
4021 << ", RTT = " << client->getRTT();
4022 guitext->setText(narrow_to_wide(os.str()).c_str());
4023 guitext->setVisible(true);
4024 } else if (flags.show_hud || flags.show_chat) {
4025 std::ostringstream os(std::ios_base::binary);
4026 os << "Minetest " << minetest_version_hash;
4027 guitext->setText(narrow_to_wide(os.str()).c_str());
4028 guitext->setVisible(true);
4030 guitext->setVisible(false);
4033 if (guitext->isVisible()) {
4034 core::rect<s32> rect(
4036 screensize.X, 5 + g_fontengine->getTextHeight()
4038 guitext->setRelativePosition(rect);
4041 if (flags.show_debug) {
4042 std::ostringstream os(std::ios_base::binary);
4043 os << std::setprecision(1) << std::fixed
4044 << "(" << (player_position.X / BS)
4045 << ", " << (player_position.Y / BS)
4046 << ", " << (player_position.Z / BS)
4047 << ") (yaw=" << (wrapDegrees_0_360(cam.camera_yaw))
4048 << " " << yawToDirectionString(cam.camera_yaw)
4049 << ") (seed = " << ((u64)client->getMapSeed())
4052 if (runData.pointed_old.type == POINTEDTHING_NODE) {
4053 ClientMap &map = client->getEnv().getClientMap();
4054 const INodeDefManager *nodedef = client->getNodeDefManager();
4055 MapNode n = map.getNodeNoEx(runData.pointed_old.node_undersurface);
4056 if (n.getContent() != CONTENT_IGNORE && nodedef->get(n).name != "unknown") {
4057 const ContentFeatures &features = nodedef->get(n);
4058 os << " (pointing_at = " << nodedef->get(n).name
4059 << " - " << features.tiledef[0].name.c_str()
4064 guitext2->setText(narrow_to_wide(os.str()).c_str());
4065 guitext2->setVisible(true);
4067 core::rect<s32> rect(
4068 5, 5 + g_fontengine->getTextHeight(),
4069 screensize.X, 5 + g_fontengine->getTextHeight() * 2
4071 guitext2->setRelativePosition(rect);
4073 guitext2->setVisible(false);
4076 guitext_info->setText(infotext.c_str());
4077 guitext_info->setVisible(flags.show_hud && g_menumgr.menuCount() == 0);
4079 float statustext_time_max = 1.5;
4081 if (!statustext.empty()) {
4082 *statustext_time += dtime;
4084 if (*statustext_time >= statustext_time_max) {
4086 *statustext_time = 0;
4090 guitext_status->setText(statustext.c_str());
4091 guitext_status->setVisible(!statustext.empty());
4093 if (!statustext.empty()) {
4094 s32 status_width = guitext_status->getTextWidth();
4095 s32 status_height = guitext_status->getTextHeight();
4096 s32 status_y = screensize.Y - 150;
4097 s32 status_x = (screensize.X - status_width) / 2;
4098 core::rect<s32> rect(
4099 status_x , status_y - status_height,
4100 status_x + status_width, status_y
4102 guitext_status->setRelativePosition(rect);
4105 video::SColor initial_color(255, 0, 0, 0);
4107 if (guienv->getSkin())
4108 initial_color = guienv->getSkin()->getColor(gui::EGDC_BUTTON_TEXT);
4110 video::SColor final_color = initial_color;
4111 final_color.setAlpha(0);
4112 video::SColor fade_color = initial_color.getInterpolated_quadratic(
4113 initial_color, final_color,
4114 pow(*statustext_time / statustext_time_max, 2.0f));
4115 guitext_status->setOverrideColor(fade_color);
4116 guitext_status->enableOverrideColor(true);
4121 /* Log times and stuff for visualization */
4122 inline void Game::updateProfilerGraphs(ProfilerGraph *graph)
4124 Profiler::GraphValues values;
4125 g_profiler->graphGet(values);
4131 /****************************************************************************
4133 ****************************************************************************/
4135 /* On some computers framerate doesn't seem to be automatically limited
4137 inline void Game::limitFps(FpsControl *fps_timings, f32 *dtime)
4139 // not using getRealTime is necessary for wine
4140 device->getTimer()->tick(); // Maker sure device time is up-to-date
4141 u32 time = device->getTimer()->getTime();
4143 u32 last_time = fps_timings->last_time;
4145 if (time > last_time) // Make sure time hasn't overflowed
4146 fps_timings->busy_time = time - last_time;
4148 fps_timings->busy_time = 0;
4150 u32 frametime_min = 1000 / (g_menumgr.pausesGame()
4151 ? g_settings->getFloat("pause_fps_max")
4152 : g_settings->getFloat("fps_max"));
4154 if (fps_timings->busy_time < frametime_min) {
4155 fps_timings->sleep_time = frametime_min - fps_timings->busy_time;
4156 device->sleep(fps_timings->sleep_time);
4158 fps_timings->sleep_time = 0;
4161 /* Get the new value of the device timer. Note that device->sleep() may
4162 * not sleep for the entire requested time as sleep may be interrupted and
4163 * therefore it is arguably more accurate to get the new time from the
4164 * device rather than calculating it by adding sleep_time to time.
4167 device->getTimer()->tick(); // Update device timer
4168 time = device->getTimer()->getTime();
4170 if (time > last_time) // Make sure last_time hasn't overflowed
4171 *dtime = (time - last_time) / 1000.0;
4175 fps_timings->last_time = time;
4179 void Game::showOverlayMessage(const wchar_t *msg, float dtime,
4180 int percent, bool draw_clouds)
4182 draw_load_screen(msg, device, guienv, dtime, percent, draw_clouds);
4187 /****************************************************************************
4189 ****************************************************************************/
4191 void Game::extendedResourceCleanup()
4193 // Extended resource accounting
4194 infostream << "Irrlicht resources after cleanup:" << std::endl;
4195 infostream << "\tRemaining meshes : "
4196 << device->getSceneManager()->getMeshCache()->getMeshCount() << std::endl;
4197 infostream << "\tRemaining textures : "
4198 << driver->getTextureCount() << std::endl;
4200 for (unsigned int i = 0; i < driver->getTextureCount(); i++) {
4201 irr::video::ITexture *texture = driver->getTextureByIndex(i);
4202 infostream << "\t\t" << i << ":" << texture->getName().getPath().c_str()
4206 clearTextureNameCache();
4207 infostream << "\tRemaining materials: "
4208 << driver-> getMaterialRendererCount()
4209 << " (note: irrlicht doesn't support removing renderers)" << std::endl;
4214 /****************************************************************************
4215 extern function for launching the game
4216 ****************************************************************************/
4218 void the_game(bool *kill,
4220 InputHandler *input,
4221 IrrlichtDevice *device,
4223 const std::string &map_dir,
4224 const std::string &playername,
4225 const std::string &password,
4226 const std::string &address, // If empty local server is created
4229 std::wstring &error_message,
4230 ChatBackend &chat_backend,
4231 const SubgameSpec &gamespec, // Used for local game
4232 bool simple_singleplayer_mode)
4236 /* Make a copy of the server address because if a local singleplayer server
4237 * is created then this is updated and we don't want to change the value
4238 * passed to us by the calling function
4240 std::string server_address = address;
4244 if (game.startup(kill, random_input, input, device, map_dir,
4245 playername, password, &server_address, port,
4246 &error_message, &chat_backend, gamespec,
4247 simple_singleplayer_mode)) {
4253 } catch (SerializationError &e) {
4254 error_message = L"A serialization error occurred:\n"
4255 + narrow_to_wide(e.what()) + L"\n\nThe server is probably "
4256 L" running a different version of Minetest.";
4257 errorstream << wide_to_narrow(error_message) << std::endl;
4258 } catch (ServerError &e) {
4259 error_message = narrow_to_wide(e.what());
4260 errorstream << "ServerError: " << e.what() << std::endl;
4261 } catch (ModError &e) {
4262 errorstream << "ModError: " << e.what() << std::endl;
4263 error_message = narrow_to_wide(e.what()) + wstrgettext("\nCheck debug.txt for details.");