3 Copyright (C) 2010-2013 celeron55, Perttu Ahola <celeron55@gmail.com>
5 This program is free software; you can redistribute it and/or modify
6 it under the terms of the GNU Lesser General Public License as published by
7 the Free Software Foundation; either version 2.1 of the License, or
8 (at your option) any later version.
10 This program is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 GNU Lesser General Public License for more details.
15 You should have received a copy of the GNU Lesser General Public License along
16 with this program; if not, write to the Free Software Foundation, Inc.,
17 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
25 #include "client/tile.h" // For TextureSource
26 #include "clientmap.h"
29 #include "content_cao.h"
30 #include "drawscene.h"
31 #include "event_manager.h"
32 #include "fontengine.h"
37 #include "guiChatConsole.h"
38 #include "guiFormSpecMenu.h"
39 #include "guiKeyChangeMenu.h"
40 #include "guiPasswordChange.h"
41 #include "guiVolumeChange.h"
43 #include "logoutputbuffer.h"
44 #include "mainmenumanager.h"
46 #include "nodedef.h" // Needed for determining pointing to nodes
47 #include "nodemetadata.h"
48 #include "particles.h"
50 #include "quicktune_shortcutter.h"
53 #include "shader.h" // For ShaderSource
57 #include "util/directiontables.h"
58 #include "util/pointedthing.h"
64 #include "sound_openal.h"
67 #ifdef HAVE_TOUCHSCREENGUI
68 #include "touchscreengui.h"
71 extern Settings *g_settings;
72 extern Profiler *g_profiler;
78 struct TextDestNodeMetadata : public TextDest {
79 TextDestNodeMetadata(v3s16 p, Client *client)
84 // This is deprecated I guess? -celeron55
85 void gotText(std::wstring text)
87 std::string ntext = wide_to_narrow(text);
88 infostream << "Submitting 'text' field of node at (" << m_p.X << ","
89 << m_p.Y << "," << m_p.Z << "): " << ntext << std::endl;
90 std::map<std::string, std::string> fields;
91 fields["text"] = ntext;
92 m_client->sendNodemetaFields(m_p, "", fields);
94 void gotText(std::map<std::string, std::string> fields)
96 m_client->sendNodemetaFields(m_p, "", fields);
103 struct TextDestPlayerInventory : public TextDest {
104 TextDestPlayerInventory(Client *client)
109 TextDestPlayerInventory(Client *client, std::string formname)
112 m_formname = formname;
114 void gotText(std::map<std::string, std::string> fields)
116 m_client->sendInventoryFields(m_formname, fields);
122 struct LocalFormspecHandler : public TextDest {
123 LocalFormspecHandler();
124 LocalFormspecHandler(std::string formname) :
127 m_formname = formname;
130 LocalFormspecHandler(std::string formname, Client *client) :
133 m_formname = formname;
136 void gotText(std::wstring message)
138 errorstream << "LocalFormspecHandler::gotText old style message received" << std::endl;
141 void gotText(std::map<std::string, std::string> fields)
143 if (m_formname == "MT_PAUSE_MENU") {
144 if (fields.find("btn_sound") != fields.end()) {
145 g_gamecallback->changeVolume();
149 if (fields.find("btn_key_config") != fields.end()) {
150 g_gamecallback->keyConfig();
154 if (fields.find("btn_exit_menu") != fields.end()) {
155 g_gamecallback->disconnect();
159 if (fields.find("btn_exit_os") != fields.end()) {
160 g_gamecallback->exitToOS();
164 if (fields.find("btn_change_password") != fields.end()) {
165 g_gamecallback->changePassword();
169 if (fields.find("quit") != fields.end()) {
173 if (fields.find("btn_continue") != fields.end()) {
178 if (m_formname == "MT_CHAT_MENU") {
179 assert(m_client != 0);
181 if ((fields.find("btn_send") != fields.end()) ||
182 (fields.find("quit") != fields.end())) {
183 if (fields.find("f_text") != fields.end()) {
184 m_client->typeChatMessage(narrow_to_wide(fields["f_text"]));
191 if (m_formname == "MT_DEATH_SCREEN") {
192 assert(m_client != 0);
194 if ((fields.find("btn_respawn") != fields.end())) {
195 m_client->sendRespawn();
199 if (fields.find("quit") != fields.end()) {
200 m_client->sendRespawn();
205 // don't show error message for unhandled cursor keys
206 if ((fields.find("key_up") != fields.end()) ||
207 (fields.find("key_down") != fields.end()) ||
208 (fields.find("key_left") != fields.end()) ||
209 (fields.find("key_right") != fields.end())) {
213 errorstream << "LocalFormspecHandler::gotText unhandled >" << m_formname << "< event" << std::endl;
216 for (std::map<std::string, std::string>::iterator iter = fields.begin();
217 iter != fields.end(); iter++) {
218 errorstream << "\t" << i << ": " << iter->first << "=" << iter->second << std::endl;
226 /* Form update callback */
228 class NodeMetadataFormSource: public IFormSource
231 NodeMetadataFormSource(ClientMap *map, v3s16 p):
236 std::string getForm()
238 NodeMetadata *meta = m_map->getNodeMetadata(m_p);
243 return meta->getString("formspec");
245 std::string resolveText(std::string str)
247 NodeMetadata *meta = m_map->getNodeMetadata(m_p);
252 return meta->resolveString(str);
259 class PlayerInventoryFormSource: public IFormSource
262 PlayerInventoryFormSource(Client *client):
266 std::string getForm()
268 LocalPlayer *player = m_client->getEnv().getLocalPlayer();
269 return player->inventory_formspec;
276 Check if a node is pointable
278 inline bool isPointableNode(const MapNode &n,
279 Client *client, bool liquids_pointable)
281 const ContentFeatures &features = client->getNodeDefManager()->get(n);
282 return features.pointable ||
283 (liquids_pointable && features.isLiquid());
287 Find what the player is pointing at
289 PointedThing getPointedThing(Client *client, v3f player_position,
290 v3f camera_direction, v3f camera_position, core::line3d<f32> shootline,
291 f32 d, bool liquids_pointable, bool look_for_object, v3s16 camera_offset,
292 std::vector<aabb3f> &hilightboxes, ClientActiveObject *&selected_object)
296 hilightboxes.clear();
297 selected_object = NULL;
299 INodeDefManager *nodedef = client->getNodeDefManager();
300 ClientMap &map = client->getEnv().getClientMap();
302 f32 mindistance = BS * 1001;
304 // First try to find a pointed at active object
305 if (look_for_object) {
306 selected_object = client->getSelectedActiveObject(d * BS,
307 camera_position, shootline);
309 if (selected_object != NULL) {
310 if (selected_object->doShowSelectionBox()) {
311 aabb3f *selection_box = selected_object->getSelectionBox();
312 // Box should exist because object was
313 // returned in the first place
314 assert(selection_box);
316 v3f pos = selected_object->getPosition();
317 hilightboxes.push_back(aabb3f(
318 selection_box->MinEdge + pos - intToFloat(camera_offset, BS),
319 selection_box->MaxEdge + pos - intToFloat(camera_offset, BS)));
322 mindistance = (selected_object->getPosition() - camera_position).getLength();
324 result.type = POINTEDTHING_OBJECT;
325 result.object_id = selected_object->getId();
329 // That didn't work, try to find a pointed at node
332 v3s16 pos_i = floatToInt(player_position, BS);
334 /*infostream<<"pos_i=("<<pos_i.X<<","<<pos_i.Y<<","<<pos_i.Z<<")"
338 s16 ystart = pos_i.Y + 0 - (camera_direction.Y < 0 ? a : 1);
339 s16 zstart = pos_i.Z - (camera_direction.Z < 0 ? a : 1);
340 s16 xstart = pos_i.X - (camera_direction.X < 0 ? a : 1);
341 s16 yend = pos_i.Y + 1 + (camera_direction.Y > 0 ? a : 1);
342 s16 zend = pos_i.Z + (camera_direction.Z > 0 ? a : 1);
343 s16 xend = pos_i.X + (camera_direction.X > 0 ? a : 1);
345 // Prevent signed number overflow
355 for (s16 y = ystart; y <= yend; y++)
356 for (s16 z = zstart; z <= zend; z++)
357 for (s16 x = xstart; x <= xend; x++) {
359 bool is_valid_position;
361 n = map.getNodeNoEx(v3s16(x, y, z), &is_valid_position);
362 if (!is_valid_position)
365 if (!isPointableNode(n, client, liquids_pointable))
368 std::vector<aabb3f> boxes = n.getSelectionBoxes(nodedef);
371 v3f npf = intToFloat(np, BS);
373 for (std::vector<aabb3f>::const_iterator
375 i != boxes.end(); i++) {
380 for (u16 j = 0; j < 6; j++) {
381 v3s16 facedir = g_6dirs[j];
382 aabb3f facebox = box;
387 facebox.MinEdge.X = facebox.MaxEdge.X - d;
388 else if (facedir.X < 0)
389 facebox.MaxEdge.X = facebox.MinEdge.X + d;
390 else if (facedir.Y > 0)
391 facebox.MinEdge.Y = facebox.MaxEdge.Y - d;
392 else if (facedir.Y < 0)
393 facebox.MaxEdge.Y = facebox.MinEdge.Y + d;
394 else if (facedir.Z > 0)
395 facebox.MinEdge.Z = facebox.MaxEdge.Z - d;
396 else if (facedir.Z < 0)
397 facebox.MaxEdge.Z = facebox.MinEdge.Z + d;
399 v3f centerpoint = facebox.getCenter();
400 f32 distance = (centerpoint - camera_position).getLength();
402 if (distance >= mindistance)
405 if (!facebox.intersectsWithLine(shootline))
408 v3s16 np_above = np + facedir;
410 result.type = POINTEDTHING_NODE;
411 result.node_undersurface = np;
412 result.node_abovesurface = np_above;
413 mindistance = distance;
415 hilightboxes.clear();
417 if (!g_settings->getBool("enable_node_highlighting")) {
418 for (std::vector<aabb3f>::const_iterator
420 i2 != boxes.end(); i2++) {
422 box.MinEdge += npf + v3f(-d, -d, -d) - intToFloat(camera_offset, BS);
423 box.MaxEdge += npf + v3f(d, d, d) - intToFloat(camera_offset, BS);
424 hilightboxes.push_back(box);
434 /* Profiler display */
436 void update_profiler_gui(gui::IGUIStaticText *guitext_profiler, FontEngine *fe,
437 u32 show_profiler, u32 show_profiler_max, s32 screen_height)
439 if (show_profiler == 0) {
440 guitext_profiler->setVisible(false);
443 std::ostringstream os(std::ios_base::binary);
444 g_profiler->printPage(os, show_profiler, show_profiler_max);
445 std::wstring text = narrow_to_wide(os.str());
446 guitext_profiler->setText(text.c_str());
447 guitext_profiler->setVisible(true);
449 s32 w = fe->getTextWidth(text.c_str());
454 unsigned text_height = fe->getTextHeight();
456 core::position2di upper_left, lower_right;
459 upper_left.Y = (text_height + 5) * 2;
460 lower_right.X = 12 + w;
461 lower_right.Y = upper_left.Y + (text_height + 1) * MAX_PROFILER_TEXT_ROWS;
463 if (lower_right.Y > screen_height * 2 / 3)
464 lower_right.Y = screen_height * 2 / 3;
466 core::rect<s32> rect(upper_left, lower_right);
468 guitext_profiler->setRelativePosition(rect);
469 guitext_profiler->setVisible(true);
477 Profiler::GraphValues values;
483 Meta(float initial = 0,
484 video::SColor color = video::SColor(255, 255, 255, 255)):
490 std::vector<Piece> m_log;
498 void put(const Profiler::GraphValues &values)
501 piece.values = values;
502 m_log.push_back(piece);
504 while (m_log.size() > m_log_max_size)
505 m_log.erase(m_log.begin());
508 void draw(s32 x_left, s32 y_bottom, video::IVideoDriver *driver,
509 gui::IGUIFont *font) const
511 std::map<std::string, Meta> m_meta;
513 for (std::vector<Piece>::const_iterator k = m_log.begin();
514 k != m_log.end(); k++) {
515 const Piece &piece = *k;
517 for (Profiler::GraphValues::const_iterator i = piece.values.begin();
518 i != piece.values.end(); i++) {
519 const std::string &id = i->first;
520 const float &value = i->second;
521 std::map<std::string, Meta>::iterator j =
524 if (j == m_meta.end()) {
525 m_meta[id] = Meta(value);
529 if (value < j->second.min)
530 j->second.min = value;
532 if (value > j->second.max)
533 j->second.max = value;
538 static const video::SColor usable_colors[] = {
539 video::SColor(255, 255, 100, 100),
540 video::SColor(255, 90, 225, 90),
541 video::SColor(255, 100, 100, 255),
542 video::SColor(255, 255, 150, 50),
543 video::SColor(255, 220, 220, 100)
545 static const u32 usable_colors_count =
546 sizeof(usable_colors) / sizeof(*usable_colors);
547 u32 next_color_i = 0;
549 for (std::map<std::string, Meta>::iterator i = m_meta.begin();
550 i != m_meta.end(); i++) {
551 Meta &meta = i->second;
552 video::SColor color(255, 200, 200, 200);
554 if (next_color_i < usable_colors_count)
555 color = usable_colors[next_color_i++];
561 s32 textx = x_left + m_log_max_size + 15;
562 s32 textx2 = textx + 200 - 15;
565 for (std::map<std::string, Meta>::const_iterator i = m_meta.begin();
566 i != m_meta.end(); i++) {
567 const std::string &id = i->first;
568 const Meta &meta = i->second;
570 s32 y = y_bottom - meta_i * 50;
571 float show_min = meta.min;
572 float show_max = meta.max;
574 if (show_min >= -0.0001 && show_max >= -0.0001) {
575 if (show_min <= show_max * 0.5)
581 snprintf(buf, 10, "%.3g", show_max);
582 font->draw(narrow_to_wide(buf).c_str(),
583 core::rect<s32>(textx, y - graphh,
584 textx2, y - graphh + texth),
586 snprintf(buf, 10, "%.3g", show_min);
587 font->draw(narrow_to_wide(buf).c_str(),
588 core::rect<s32>(textx, y - texth,
591 font->draw(narrow_to_wide(id).c_str(),
592 core::rect<s32>(textx, y - graphh / 2 - texth / 2,
593 textx2, y - graphh / 2 + texth / 2),
596 s32 graph1h = graphh;
597 bool relativegraph = (show_min != 0 && show_min != show_max);
598 float lastscaledvalue = 0.0;
599 bool lastscaledvalue_exists = false;
601 for (std::vector<Piece>::const_iterator j = m_log.begin();
602 j != m_log.end(); j++) {
603 const Piece &piece = *j;
605 bool value_exists = false;
606 Profiler::GraphValues::const_iterator k =
607 piece.values.find(id);
609 if (k != piece.values.end()) {
616 lastscaledvalue_exists = false;
620 float scaledvalue = 1.0;
622 if (show_max != show_min)
623 scaledvalue = (value - show_min) / (show_max - show_min);
625 if (scaledvalue == 1.0 && value == 0) {
627 lastscaledvalue_exists = false;
632 if (lastscaledvalue_exists) {
633 s32 ivalue1 = lastscaledvalue * graph1h;
634 s32 ivalue2 = scaledvalue * graph1h;
635 driver->draw2DLine(v2s32(x - 1, graph1y - ivalue1),
636 v2s32(x, graph1y - ivalue2), meta.color);
639 lastscaledvalue = scaledvalue;
640 lastscaledvalue_exists = true;
642 s32 ivalue = scaledvalue * graph1h;
643 driver->draw2DLine(v2s32(x, graph1y),
644 v2s32(x, graph1y - ivalue), meta.color);
655 class NodeDugEvent: public MtEvent
661 NodeDugEvent(v3s16 p, MapNode n):
665 const char *getType() const
673 ISoundManager *m_sound;
674 INodeDefManager *m_ndef;
676 float m_player_step_timer;
678 SimpleSoundSpec m_player_step_sound;
679 SimpleSoundSpec m_player_leftpunch_sound;
680 SimpleSoundSpec m_player_rightpunch_sound;
682 SoundMaker(ISoundManager *sound, INodeDefManager *ndef):
685 m_player_step_timer(0)
689 void playPlayerStep()
691 if (m_player_step_timer <= 0 && m_player_step_sound.exists()) {
692 m_player_step_timer = 0.03;
693 m_sound->playSound(m_player_step_sound, false);
697 static void viewBobbingStep(MtEvent *e, void *data)
699 SoundMaker *sm = (SoundMaker *)data;
700 sm->playPlayerStep();
703 static void playerRegainGround(MtEvent *e, void *data)
705 SoundMaker *sm = (SoundMaker *)data;
706 sm->playPlayerStep();
709 static void playerJump(MtEvent *e, void *data)
711 //SoundMaker *sm = (SoundMaker*)data;
714 static void cameraPunchLeft(MtEvent *e, void *data)
716 SoundMaker *sm = (SoundMaker *)data;
717 sm->m_sound->playSound(sm->m_player_leftpunch_sound, false);
720 static void cameraPunchRight(MtEvent *e, void *data)
722 SoundMaker *sm = (SoundMaker *)data;
723 sm->m_sound->playSound(sm->m_player_rightpunch_sound, false);
726 static void nodeDug(MtEvent *e, void *data)
728 SoundMaker *sm = (SoundMaker *)data;
729 NodeDugEvent *nde = (NodeDugEvent *)e;
730 sm->m_sound->playSound(sm->m_ndef->get(nde->n).sound_dug, false);
733 static void playerDamage(MtEvent *e, void *data)
735 SoundMaker *sm = (SoundMaker *)data;
736 sm->m_sound->playSound(SimpleSoundSpec("player_damage", 0.5), false);
739 static void playerFallingDamage(MtEvent *e, void *data)
741 SoundMaker *sm = (SoundMaker *)data;
742 sm->m_sound->playSound(SimpleSoundSpec("player_falling_damage", 0.5), false);
745 void registerReceiver(MtEventManager *mgr)
747 mgr->reg("ViewBobbingStep", SoundMaker::viewBobbingStep, this);
748 mgr->reg("PlayerRegainGround", SoundMaker::playerRegainGround, this);
749 mgr->reg("PlayerJump", SoundMaker::playerJump, this);
750 mgr->reg("CameraPunchLeft", SoundMaker::cameraPunchLeft, this);
751 mgr->reg("CameraPunchRight", SoundMaker::cameraPunchRight, this);
752 mgr->reg("NodeDug", SoundMaker::nodeDug, this);
753 mgr->reg("PlayerDamage", SoundMaker::playerDamage, this);
754 mgr->reg("PlayerFallingDamage", SoundMaker::playerFallingDamage, this);
757 void step(float dtime)
759 m_player_step_timer -= dtime;
763 // Locally stored sounds don't need to be preloaded because of this
764 class GameOnDemandSoundFetcher: public OnDemandSoundFetcher
766 std::set<std::string> m_fetched;
768 void fetchSounds(const std::string &name,
769 std::set<std::string> &dst_paths,
770 std::set<std::string> &dst_datas)
772 if (m_fetched.count(name))
775 m_fetched.insert(name);
776 std::string base = porting::path_share + DIR_DELIM + "testsounds";
777 dst_paths.insert(base + DIR_DELIM + name + ".ogg");
778 dst_paths.insert(base + DIR_DELIM + name + ".0.ogg");
779 dst_paths.insert(base + DIR_DELIM + name + ".1.ogg");
780 dst_paths.insert(base + DIR_DELIM + name + ".2.ogg");
781 dst_paths.insert(base + DIR_DELIM + name + ".3.ogg");
782 dst_paths.insert(base + DIR_DELIM + name + ".4.ogg");
783 dst_paths.insert(base + DIR_DELIM + name + ".5.ogg");
784 dst_paths.insert(base + DIR_DELIM + name + ".6.ogg");
785 dst_paths.insert(base + DIR_DELIM + name + ".7.ogg");
786 dst_paths.insert(base + DIR_DELIM + name + ".8.ogg");
787 dst_paths.insert(base + DIR_DELIM + name + ".9.ogg");
791 class GameGlobalShaderConstantSetter : public IShaderConstantSetter
794 bool *m_force_fog_off;
800 void onSettingsChange(const std::string &name)
802 if (name == "enable_fog")
803 m_fogEnabled = g_settings->getBool("enable_fog");
806 static void SettingsCallback(const std::string name, void *userdata)
808 reinterpret_cast<GameGlobalShaderConstantSetter*>(userdata)->onSettingsChange(name);
811 GameGlobalShaderConstantSetter(Sky *sky, bool *force_fog_off,
812 f32 *fog_range, Client *client) :
814 m_force_fog_off(force_fog_off),
815 m_fog_range(fog_range),
818 g_settings->registerChangedCallback("enable_fog", SettingsCallback, this);
819 m_fogEnabled = g_settings->getBool("enable_fog");
822 ~GameGlobalShaderConstantSetter()
824 g_settings->deregisterChangedCallback("enable_fog", SettingsCallback, this);
827 virtual void onSetConstants(video::IMaterialRendererServices *services,
834 video::SColor bgcolor = m_sky->getBgColor();
835 video::SColorf bgcolorf(bgcolor);
836 float bgcolorfa[4] = {
842 services->setPixelShaderConstant("skyBgColor", bgcolorfa, 4);
845 float fog_distance = 10000 * BS;
847 if (m_fogEnabled && !*m_force_fog_off)
848 fog_distance = *m_fog_range;
850 services->setPixelShaderConstant("fogDistance", &fog_distance, 1);
853 u32 daynight_ratio = m_client->getEnv().getDayNightRatio();
854 float daynight_ratio_f = (float)daynight_ratio / 1000.0;
855 services->setPixelShaderConstant("dayNightRatio", &daynight_ratio_f, 1);
857 u32 animation_timer = porting::getTimeMs() % 100000;
858 float animation_timer_f = (float)animation_timer / 100000.0;
859 services->setPixelShaderConstant("animationTimer", &animation_timer_f, 1);
860 services->setVertexShaderConstant("animationTimer", &animation_timer_f, 1);
862 LocalPlayer *player = m_client->getEnv().getLocalPlayer();
863 v3f eye_position = player->getEyePosition();
864 services->setPixelShaderConstant("eyePosition", (irr::f32 *)&eye_position, 3);
865 services->setVertexShaderConstant("eyePosition", (irr::f32 *)&eye_position, 3);
867 // Uniform sampler layers
871 // before 1.8 there isn't a "integer interface", only float
872 #if (IRRLICHT_VERSION_MAJOR == 1 && IRRLICHT_VERSION_MINOR < 8)
873 services->setPixelShaderConstant("baseTexture" , (irr::f32 *)&layer0, 1);
874 services->setPixelShaderConstant("normalTexture" , (irr::f32 *)&layer1, 1);
875 services->setPixelShaderConstant("useNormalmap" , (irr::f32 *)&layer2, 1);
877 services->setPixelShaderConstant("baseTexture" , (irr::s32 *)&layer0, 1);
878 services->setPixelShaderConstant("normalTexture" , (irr::s32 *)&layer1, 1);
879 services->setPixelShaderConstant("useNormalmap" , (irr::s32 *)&layer2, 1);
884 bool nodePlacementPrediction(Client &client,
885 const ItemDefinition &playeritem_def, v3s16 nodepos, v3s16 neighbourpos)
887 std::string prediction = playeritem_def.node_placement_prediction;
888 INodeDefManager *nodedef = client.ndef();
889 ClientMap &map = client.getEnv().getClientMap();
891 bool is_valid_position;
893 node = map.getNodeNoEx(nodepos, &is_valid_position);
894 if (!is_valid_position)
897 if (prediction != "" && !nodedef->get(node).rightclickable) {
898 verbosestream << "Node placement prediction for "
899 << playeritem_def.name << " is "
900 << prediction << std::endl;
901 v3s16 p = neighbourpos;
903 // Place inside node itself if buildable_to
904 MapNode n_under = map.getNodeNoEx(nodepos, &is_valid_position);
905 if (is_valid_position)
907 if (nodedef->get(n_under).buildable_to)
910 node = map.getNodeNoEx(p, &is_valid_position);
911 if (is_valid_position &&!nodedef->get(node).buildable_to)
916 // Find id of predicted node
918 bool found = nodedef->getId(prediction, id);
921 errorstream << "Node placement prediction failed for "
922 << playeritem_def.name << " (places "
924 << ") - Name not known" << std::endl;
928 // Predict param2 for facedir and wallmounted nodes
931 if (nodedef->get(id).param_type_2 == CPT2_WALLMOUNTED) {
932 v3s16 dir = nodepos - neighbourpos;
934 if (abs(dir.Y) > MYMAX(abs(dir.X), abs(dir.Z))) {
935 param2 = dir.Y < 0 ? 1 : 0;
936 } else if (abs(dir.X) > abs(dir.Z)) {
937 param2 = dir.X < 0 ? 3 : 2;
939 param2 = dir.Z < 0 ? 5 : 4;
943 if (nodedef->get(id).param_type_2 == CPT2_FACEDIR) {
944 v3s16 dir = nodepos - floatToInt(client.getEnv().getLocalPlayer()->getPosition(), BS);
946 if (abs(dir.X) > abs(dir.Z)) {
947 param2 = dir.X < 0 ? 3 : 1;
949 param2 = dir.Z < 0 ? 2 : 0;
955 //Check attachment if node is in group attached_node
956 if (((ItemGroupList) nodedef->get(id).groups)["attached_node"] != 0) {
957 static v3s16 wallmounted_dirs[8] = {
967 if (nodedef->get(id).param_type_2 == CPT2_WALLMOUNTED)
968 pp = p + wallmounted_dirs[param2];
970 pp = p + v3s16(0, -1, 0);
972 if (!nodedef->get(map.getNodeNoEx(pp)).walkable)
976 // Add node to client map
977 MapNode n(id, 0, param2);
980 LocalPlayer *player = client.getEnv().getLocalPlayer();
982 // Dont place node when player would be inside new node
983 // NOTE: This is to be eventually implemented by a mod as client-side Lua
984 if (!nodedef->get(n).walkable ||
985 g_settings->getBool("enable_build_where_you_stand") ||
986 (client.checkPrivilege("noclip") && g_settings->getBool("noclip")) ||
987 (nodedef->get(n).walkable &&
988 neighbourpos != player->getStandingNodePos() + v3s16(0, 1, 0) &&
989 neighbourpos != player->getStandingNodePos() + v3s16(0, 2, 0))) {
991 // This triggers the required mesh update too
992 client.addNode(p, n);
995 } catch (InvalidPositionException &e) {
996 errorstream << "Node placement prediction failed for "
997 << playeritem_def.name << " (places "
999 << ") - Position not loaded" << std::endl;
1006 static inline void create_formspec_menu(GUIFormSpecMenu **cur_formspec,
1007 InventoryManager *invmgr, IGameDef *gamedef,
1008 IWritableTextureSource *tsrc, IrrlichtDevice *device,
1009 IFormSource *fs_src, TextDest *txt_dest, Client *client)
1012 if (*cur_formspec == 0) {
1013 *cur_formspec = new GUIFormSpecMenu(device, guiroot, -1, &g_menumgr,
1014 invmgr, gamedef, tsrc, fs_src, txt_dest, client);
1015 (*cur_formspec)->doPause = false;
1018 Caution: do not call (*cur_formspec)->drop() here --
1019 the reference might outlive the menu, so we will
1020 periodically check if *cur_formspec is the only
1021 remaining reference (i.e. the menu was removed)
1022 and delete it in that case.
1026 (*cur_formspec)->setFormSource(fs_src);
1027 (*cur_formspec)->setTextDest(txt_dest);
1032 #define SIZE_TAG "size[11,5.5]"
1034 #define SIZE_TAG "size[11,5.5,true]" // Fixed size on desktop
1037 static void show_chat_menu(GUIFormSpecMenu **cur_formspec,
1038 InventoryManager *invmgr, IGameDef *gamedef,
1039 IWritableTextureSource *tsrc, IrrlichtDevice *device,
1040 Client *client, std::string text)
1042 std::string formspec =
1043 FORMSPEC_VERSION_STRING
1045 "field[3,2.35;6,0.5;f_text;;" + text + "]"
1046 "button_exit[4,3;3,0.5;btn_send;" + wide_to_narrow(wstrgettext("Proceed")) + "]"
1050 /* Note: FormspecFormSource and LocalFormspecHandler
1051 * are deleted by guiFormSpecMenu */
1052 FormspecFormSource *fs_src = new FormspecFormSource(formspec);
1053 LocalFormspecHandler *txt_dst = new LocalFormspecHandler("MT_CHAT_MENU", client);
1055 create_formspec_menu(cur_formspec, invmgr, gamedef, tsrc, device, fs_src, txt_dst, NULL);
1058 static void show_deathscreen(GUIFormSpecMenu **cur_formspec,
1059 InventoryManager *invmgr, IGameDef *gamedef,
1060 IWritableTextureSource *tsrc, IrrlichtDevice *device, Client *client)
1062 std::string formspec =
1063 std::string(FORMSPEC_VERSION_STRING) +
1065 "bgcolor[#320000b4;true]"
1066 "label[4.85,1.35;" + gettext("You died.") + "]"
1067 "button_exit[4,3;3,0.5;btn_respawn;" + gettext("Respawn") + "]"
1071 /* Note: FormspecFormSource and LocalFormspecHandler
1072 * are deleted by guiFormSpecMenu */
1073 FormspecFormSource *fs_src = new FormspecFormSource(formspec);
1074 LocalFormspecHandler *txt_dst = new LocalFormspecHandler("MT_DEATH_SCREEN", client);
1076 create_formspec_menu(cur_formspec, invmgr, gamedef, tsrc, device, fs_src, txt_dst, NULL);
1079 /******************************************************************************/
1080 static void show_pause_menu(GUIFormSpecMenu **cur_formspec,
1081 InventoryManager *invmgr, IGameDef *gamedef,
1082 IWritableTextureSource *tsrc, IrrlichtDevice *device,
1083 bool singleplayermode)
1086 std::string control_text = wide_to_narrow(wstrgettext("Default Controls:\n"
1087 "No menu visible:\n"
1088 "- single tap: button activate\n"
1089 "- double tap: place/use\n"
1090 "- slide finger: look around\n"
1091 "Menu/Inventory visible:\n"
1092 "- double tap (outside):\n"
1094 "- touch stack, touch slot:\n"
1096 "- touch&drag, tap 2nd finger\n"
1097 " --> place single item to slot\n"
1100 std::string control_text = wide_to_narrow(wstrgettext("Default Controls:\n"
1102 "- Space: jump/climb\n"
1103 "- Shift: sneak/go down\n"
1106 "- Mouse: turn/look\n"
1107 "- Mouse left: dig/punch\n"
1108 "- Mouse right: place/use\n"
1109 "- Mouse wheel: select item\n"
1114 float ypos = singleplayermode ? 0.5 : 0.1;
1115 std::ostringstream os;
1117 os << FORMSPEC_VERSION_STRING << SIZE_TAG
1118 << "button_exit[4," << (ypos++) << ";3,0.5;btn_continue;"
1119 << wide_to_narrow(wstrgettext("Continue")) << "]";
1121 if (!singleplayermode) {
1122 os << "button_exit[4," << (ypos++) << ";3,0.5;btn_change_password;"
1123 << wide_to_narrow(wstrgettext("Change Password")) << "]";
1127 os << "button_exit[4," << (ypos++) << ";3,0.5;btn_sound;"
1128 << wide_to_narrow(wstrgettext("Sound Volume")) << "]";
1129 os << "button_exit[4," << (ypos++) << ";3,0.5;btn_key_config;"
1130 << wide_to_narrow(wstrgettext("Change Keys")) << "]";
1132 os << "button_exit[4," << (ypos++) << ";3,0.5;btn_exit_menu;"
1133 << wide_to_narrow(wstrgettext("Exit to Menu")) << "]";
1134 os << "button_exit[4," << (ypos++) << ";3,0.5;btn_exit_os;"
1135 << wide_to_narrow(wstrgettext("Exit to OS")) << "]"
1136 << "textarea[7.5,0.25;3.9,6.25;;" << control_text << ";]"
1137 << "textarea[0.4,0.25;3.5,6;;" << "Minetest\n"
1138 << minetest_build_info << "\n"
1139 << "path_user = " << wrap_rows(porting::path_user, 20)
1143 /* Note: FormspecFormSource and LocalFormspecHandler *
1144 * are deleted by guiFormSpecMenu */
1145 FormspecFormSource *fs_src = new FormspecFormSource(os.str());
1146 LocalFormspecHandler *txt_dst = new LocalFormspecHandler("MT_PAUSE_MENU");
1148 create_formspec_menu(cur_formspec, invmgr, gamedef, tsrc, device, fs_src, txt_dst, NULL);
1149 (*cur_formspec)->setFocus(L"btn_continue");
1150 (*cur_formspec)->doPause = true;
1153 /******************************************************************************/
1154 static void updateChat(Client &client, f32 dtime, bool show_debug,
1155 const v2u32 &screensize, bool show_chat, u32 show_profiler,
1156 ChatBackend &chat_backend, gui::IGUIStaticText *guitext_chat)
1158 // Add chat log output for errors to be shown in chat
1159 static LogOutputBuffer chat_log_error_buf(LMT_ERROR);
1161 // Get new messages from error log buffer
1162 while (!chat_log_error_buf.empty()) {
1163 chat_backend.addMessage(L"", narrow_to_wide(chat_log_error_buf.get()));
1166 // Get new messages from client
1167 std::wstring message;
1169 while (client.getChatMessage(message)) {
1170 chat_backend.addUnparsedMessage(message);
1173 // Remove old messages
1174 chat_backend.step(dtime);
1176 // Display all messages in a static text element
1177 unsigned int recent_chat_count = chat_backend.getRecentBuffer().getLineCount();
1178 std::wstring recent_chat = chat_backend.getRecentChat();
1179 unsigned int line_height = g_fontengine->getLineHeight();
1181 guitext_chat->setText(recent_chat.c_str());
1183 // Update gui element size and position
1184 s32 chat_y = 5 + line_height;
1187 chat_y += line_height;
1189 // first pass to calculate height of text to be set
1190 s32 width = std::min(g_fontengine->getTextWidth(recent_chat) + 10,
1191 porting::getWindowSize().X - 20);
1192 core::rect<s32> rect(10, chat_y, width, chat_y + porting::getWindowSize().Y);
1193 guitext_chat->setRelativePosition(rect);
1195 //now use real height of text and adjust rect according to this size
1196 rect = core::rect<s32>(10, chat_y, width,
1197 chat_y + guitext_chat->getTextHeight());
1200 guitext_chat->setRelativePosition(rect);
1201 // Don't show chat if disabled or empty or profiler is enabled
1202 guitext_chat->setVisible(
1203 show_chat && recent_chat_count != 0 && !show_profiler);
1207 /****************************************************************************
1208 Fast key cache for main game loop
1209 ****************************************************************************/
1211 /* This is faster than using getKeySetting with the tradeoff that functions
1212 * using it must make sure that it's initialised before using it and there is
1213 * no error handling (for example bounds checking). This is really intended for
1214 * use only in the main running loop of the client (the_game()) where the faster
1215 * (up to 10x faster) key lookup is an asset. Other parts of the codebase
1216 * (e.g. formspecs) should continue using getKeySetting().
1220 KeyCache() { populate(); }
1234 KEYMAP_ID_INVENTORY,
1241 KEYMAP_ID_CINEMATIC,
1242 KEYMAP_ID_SCREENSHOT,
1243 KEYMAP_ID_TOGGLE_HUD,
1244 KEYMAP_ID_TOGGLE_CHAT,
1245 KEYMAP_ID_TOGGLE_FORCE_FOG_OFF,
1246 KEYMAP_ID_TOGGLE_UPDATE_CAMERA,
1247 KEYMAP_ID_TOGGLE_DEBUG,
1248 KEYMAP_ID_TOGGLE_PROFILER,
1249 KEYMAP_ID_CAMERA_MODE,
1250 KEYMAP_ID_INCREASE_VIEWING_RANGE,
1251 KEYMAP_ID_DECREASE_VIEWING_RANGE,
1252 KEYMAP_ID_RANGESELECT,
1254 KEYMAP_ID_QUICKTUNE_NEXT,
1255 KEYMAP_ID_QUICKTUNE_PREV,
1256 KEYMAP_ID_QUICKTUNE_INC,
1257 KEYMAP_ID_QUICKTUNE_DEC,
1259 KEYMAP_ID_DEBUG_STACKS,
1261 // Fake keycode for array size and internal checks
1262 KEYMAP_INTERNAL_ENUM_COUNT
1269 KeyPress key[KEYMAP_INTERNAL_ENUM_COUNT];
1272 void KeyCache::populate()
1274 key[KEYMAP_ID_FORWARD] = getKeySetting("keymap_forward");
1275 key[KEYMAP_ID_BACKWARD] = getKeySetting("keymap_backward");
1276 key[KEYMAP_ID_LEFT] = getKeySetting("keymap_left");
1277 key[KEYMAP_ID_RIGHT] = getKeySetting("keymap_right");
1278 key[KEYMAP_ID_JUMP] = getKeySetting("keymap_jump");
1279 key[KEYMAP_ID_SPECIAL1] = getKeySetting("keymap_special1");
1280 key[KEYMAP_ID_SNEAK] = getKeySetting("keymap_sneak");
1282 key[KEYMAP_ID_DROP] = getKeySetting("keymap_drop");
1283 key[KEYMAP_ID_INVENTORY] = getKeySetting("keymap_inventory");
1284 key[KEYMAP_ID_CHAT] = getKeySetting("keymap_chat");
1285 key[KEYMAP_ID_CMD] = getKeySetting("keymap_cmd");
1286 key[KEYMAP_ID_CONSOLE] = getKeySetting("keymap_console");
1287 key[KEYMAP_ID_FREEMOVE] = getKeySetting("keymap_freemove");
1288 key[KEYMAP_ID_FASTMOVE] = getKeySetting("keymap_fastmove");
1289 key[KEYMAP_ID_NOCLIP] = getKeySetting("keymap_noclip");
1290 key[KEYMAP_ID_CINEMATIC] = getKeySetting("keymap_cinematic");
1291 key[KEYMAP_ID_SCREENSHOT] = getKeySetting("keymap_screenshot");
1292 key[KEYMAP_ID_TOGGLE_HUD] = getKeySetting("keymap_toggle_hud");
1293 key[KEYMAP_ID_TOGGLE_CHAT] = getKeySetting("keymap_toggle_chat");
1294 key[KEYMAP_ID_TOGGLE_FORCE_FOG_OFF]
1295 = getKeySetting("keymap_toggle_force_fog_off");
1296 key[KEYMAP_ID_TOGGLE_UPDATE_CAMERA]
1297 = getKeySetting("keymap_toggle_update_camera");
1298 key[KEYMAP_ID_TOGGLE_DEBUG]
1299 = getKeySetting("keymap_toggle_debug");
1300 key[KEYMAP_ID_TOGGLE_PROFILER]
1301 = getKeySetting("keymap_toggle_profiler");
1302 key[KEYMAP_ID_CAMERA_MODE]
1303 = getKeySetting("keymap_camera_mode");
1304 key[KEYMAP_ID_INCREASE_VIEWING_RANGE]
1305 = getKeySetting("keymap_increase_viewing_range_min");
1306 key[KEYMAP_ID_DECREASE_VIEWING_RANGE]
1307 = getKeySetting("keymap_decrease_viewing_range_min");
1308 key[KEYMAP_ID_RANGESELECT]
1309 = getKeySetting("keymap_rangeselect");
1311 key[KEYMAP_ID_QUICKTUNE_NEXT] = getKeySetting("keymap_quicktune_next");
1312 key[KEYMAP_ID_QUICKTUNE_PREV] = getKeySetting("keymap_quicktune_prev");
1313 key[KEYMAP_ID_QUICKTUNE_INC] = getKeySetting("keymap_quicktune_inc");
1314 key[KEYMAP_ID_QUICKTUNE_DEC] = getKeySetting("keymap_quicktune_dec");
1316 key[KEYMAP_ID_DEBUG_STACKS] = getKeySetting("keymap_print_debug_stacks");
1320 /****************************************************************************
1322 ****************************************************************************/
1324 const float object_hit_delay = 0.2;
1327 u32 last_time, busy_time, sleep_time;
1331 /* The reason the following structs are not anonymous structs within the
1332 * class is that they are not used by the majority of member functions and
1333 * many functions that do require objects of thse types do not modify them
1334 * (so they can be passed as a const qualified parameter)
1336 struct CameraOrientation {
1337 f32 camera_yaw; // "right/left"
1338 f32 camera_pitch; // "up/down"
1341 struct GameRunData {
1344 PointedThing pointed_old;
1348 bool update_wielded_item_trigger;
1349 bool reset_jump_timer;
1350 float nodig_delay_timer;
1352 float dig_time_complete;
1353 float repeat_rightclick_timer;
1354 float object_hit_delay_timer;
1355 float time_from_last_punch;
1356 ClientActiveObject *selected_object;
1360 float update_draw_list_timer;
1361 float statustext_time;
1365 v3f update_draw_list_last_cam_dir;
1367 u32 profiler_current_page;
1368 u32 profiler_max_page; // Number of pages
1371 float time_of_day_smooth;
1375 f32 max, min, avg, counter, max_sample, min_sample, max_fraction;
1383 Jitter dtime_jitter, busy_time_jitter;
1386 /* Flags that can, or may, change during main game loop
1388 struct VolatileRunFlags {
1394 bool show_profiler_graph;
1395 bool disable_camera_update;
1396 bool first_loop_after_window_activation;
1397 bool camera_offset_changed;
1401 /****************************************************************************
1403 ****************************************************************************/
1405 /* This is not intended to be a public class. If a public class becomes
1406 * desirable then it may be better to create another 'wrapper' class that
1407 * hides most of the stuff in this class (nothing in this class is required
1408 * by any other file) but exposes the public methods/data only.
1416 bool startup(bool *kill,
1418 InputHandler *input,
1419 IrrlichtDevice *device,
1420 const std::string &map_dir,
1421 const std::string &playername,
1422 const std::string &password,
1423 // If address is "", local server is used and address is updated
1424 std::string *address,
1426 std::wstring *error_message,
1427 ChatBackend *chat_backend,
1428 const SubgameSpec &gamespec, // Used for local game
1429 bool simple_singleplayer_mode);
1436 void extendedResourceCleanup();
1438 // Basic initialisation
1439 bool init(const std::string &map_dir, std::string *address,
1441 const SubgameSpec &gamespec);
1443 bool createSingleplayerServer(const std::string map_dir,
1444 const SubgameSpec &gamespec, u16 port, std::string *address);
1447 bool createClient(const std::string &playername,
1448 const std::string &password, std::string *address, u16 port,
1449 std::wstring *error_message);
1450 bool initGui(std::wstring *error_message);
1452 // Client connection
1453 bool connectToServer(const std::string &playername,
1454 const std::string &password, std::string *address, u16 port,
1455 bool *connect_ok, bool *aborted);
1456 bool getServerContent(bool *aborted);
1460 void updateInteractTimers(GameRunData *runData, f32 dtime);
1461 bool checkConnection();
1462 bool handleCallbacks();
1463 void processQueues();
1464 void updateProfilers(const GameRunData &runData, const RunStats &stats,
1465 const FpsControl &draw_times, f32 dtime);
1466 void addProfilerGraphs(const RunStats &stats, const FpsControl &draw_times,
1468 void updateStats(RunStats *stats, const FpsControl &draw_times, f32 dtime);
1470 void processUserInput(VolatileRunFlags *flags, GameRunData *runData,
1472 void processKeyboardInput(VolatileRunFlags *flags,
1473 float *statustext_time,
1475 bool *reset_jump_timer,
1476 u32 *profiler_current_page,
1477 u32 profiler_max_page);
1478 void processItemSelection(u16 *new_playeritem);
1480 void dropSelectedItem();
1481 void openInventory();
1483 void toggleFreeMove(float *statustext_time);
1484 void toggleFreeMoveAlt(float *statustext_time, float *jump_timer);
1485 void toggleFast(float *statustext_time);
1486 void toggleNoClip(float *statustext_time);
1487 void toggleCinematic(float *statustext_time);
1489 void toggleChat(float *statustext_time, bool *flag);
1490 void toggleHud(float *statustext_time, bool *flag);
1491 void toggleFog(float *statustext_time, bool *flag);
1492 void toggleDebug(float *statustext_time, bool *show_debug,
1493 bool *show_profiler_graph);
1494 void toggleUpdateCamera(float *statustext_time, bool *flag);
1495 void toggleProfiler(float *statustext_time, u32 *profiler_current_page,
1496 u32 profiler_max_page);
1498 void increaseViewRange(float *statustext_time);
1499 void decreaseViewRange(float *statustext_time);
1500 void toggleFullViewRange(float *statustext_time);
1502 void updateCameraDirection(CameraOrientation *cam, VolatileRunFlags *flags);
1503 void updateCameraOrientation(CameraOrientation *cam,
1504 const VolatileRunFlags &flags);
1505 void updatePlayerControl(const CameraOrientation &cam);
1506 void step(f32 *dtime);
1507 void processClientEvents(CameraOrientation *cam, float *damage_flash);
1508 void updateCamera(VolatileRunFlags *flags, u32 busy_time, f32 dtime,
1509 float time_from_last_punch);
1510 void updateSound(f32 dtime);
1511 void processPlayerInteraction(std::vector<aabb3f> &highlight_boxes,
1512 GameRunData *runData, f32 dtime, bool show_hud,
1514 void handlePointingAtNode(GameRunData *runData,
1515 const PointedThing &pointed, const ItemDefinition &playeritem_def,
1516 const ToolCapabilities &playeritem_toolcap, f32 dtime);
1517 void handlePointingAtObject(GameRunData *runData,
1518 const PointedThing &pointed, const ItemStack &playeritem,
1519 const v3f &player_position, bool show_debug);
1520 void handleDigging(GameRunData *runData, const PointedThing &pointed,
1521 const v3s16 &nodepos, const ToolCapabilities &playeritem_toolcap,
1523 void updateFrame(std::vector<aabb3f> &highlight_boxes, ProfilerGraph *graph,
1524 RunStats *stats, GameRunData *runData,
1525 f32 dtime, const VolatileRunFlags &flags, const CameraOrientation &cam);
1526 void updateGui(float *statustext_time, const RunStats &stats,
1527 const GameRunData& runData, f32 dtime, const VolatileRunFlags &flags,
1528 const CameraOrientation &cam);
1529 void updateProfilerGraphs(ProfilerGraph *graph);
1532 void limitFps(FpsControl *fps_timings, f32 *dtime);
1534 void showOverlayMessage(const wchar_t *msg, float dtime, int percent,
1535 bool draw_clouds = true);
1538 InputHandler *input;
1543 IWritableTextureSource *texture_src;
1544 IWritableShaderSource *shader_src;
1546 // When created, these will be filled with data received from the server
1547 IWritableItemDefManager *itemdef_manager;
1548 IWritableNodeDefManager *nodedef_manager;
1550 GameOnDemandSoundFetcher soundfetcher; // useful when testing
1551 ISoundManager *sound;
1552 bool sound_is_dummy;
1553 SoundMaker *soundmaker;
1555 ChatBackend *chat_backend;
1557 GUIFormSpecMenu *current_formspec;
1559 EventManager *eventmgr;
1560 QuicktuneShortcutter *quicktune;
1562 GUIChatConsole *gui_chat_console; // Free using ->Drop()
1563 MapDrawControl *draw_control;
1565 Clouds *clouds; // Free using ->Drop()
1566 Sky *sky; // Free using ->Drop()
1567 Inventory *local_inventory;
1571 This class does take ownership/responsibily for cleaning up etc of any of
1572 these items (e.g. device)
1574 IrrlichtDevice *device;
1575 video::IVideoDriver *driver;
1576 scene::ISceneManager *smgr;
1578 std::wstring *error_message;
1579 IGameDef *gamedef; // Convenience (same as *client)
1580 scene::ISceneNode *skybox;
1583 bool simple_singleplayer_mode;
1586 /* Pre-calculated values
1588 int crack_animation_length;
1592 gui::IGUIStaticText *guitext; // First line of debug text
1593 gui::IGUIStaticText *guitext2; // Second line of debug text
1594 gui::IGUIStaticText *guitext_info; // At the middle of the screen
1595 gui::IGUIStaticText *guitext_status;
1596 gui::IGUIStaticText *guitext_chat; // Chat text
1597 gui::IGUIStaticText *guitext_profiler; // Profiler text
1599 std::wstring infotext;
1600 std::wstring statustext;
1604 IntervalLimiter profiler_interval;
1606 /* TODO: Add a callback function so these can be updated when a setting
1607 * changes. At this point in time it doesn't matter (e.g. /set
1608 * is documented to change server settings only)
1610 * TODO: Local caching of settings is not optimal and should at some stage
1611 * be updated to use a global settings object for getting thse values
1612 * (as opposed to the this local caching). This can be addressed in
1615 bool m_cache_doubletap_jump;
1616 bool m_cache_enable_node_highlighting;
1617 bool m_cache_enable_clouds;
1618 bool m_cache_enable_particles;
1619 bool m_cache_enable_fog;
1620 f32 m_cache_mouse_sensitivity;
1621 f32 m_repeat_right_click_time;
1629 itemdef_manager(NULL),
1630 nodedef_manager(NULL),
1632 sound_is_dummy(false),
1635 current_formspec(NULL),
1638 gui_chat_console(NULL),
1643 local_inventory(NULL),
1646 m_cache_doubletap_jump = g_settings->getBool("doubletap_jump");
1647 m_cache_enable_node_highlighting = g_settings->getBool("enable_node_highlighting");
1648 m_cache_enable_clouds = g_settings->getBool("enable_clouds");
1649 m_cache_enable_particles = g_settings->getBool("enable_particles");
1650 m_cache_enable_fog = g_settings->getBool("enable_fog");
1651 m_cache_mouse_sensitivity = g_settings->getFloat("mouse_sensitivity");
1652 m_repeat_right_click_time = g_settings->getFloat("repeat_rightclick_time");
1654 m_cache_mouse_sensitivity = rangelim(m_cache_mouse_sensitivity, 0.001, 100.0);
1659 /****************************************************************************
1661 ****************************************************************************/
1667 if (!sound_is_dummy)
1670 delete server; // deleted first to stop all server threads
1673 delete local_inventory;
1679 delete nodedef_manager;
1680 delete itemdef_manager;
1681 delete draw_control;
1683 extendedResourceCleanup();
1686 bool Game::startup(bool *kill,
1688 InputHandler *input,
1689 IrrlichtDevice *device,
1690 const std::string &map_dir,
1691 const std::string &playername,
1692 const std::string &password,
1693 std::string *address, // can change if simple_singleplayer_mode
1695 std::wstring *error_message,
1696 ChatBackend *chat_backend,
1697 const SubgameSpec &gamespec,
1698 bool simple_singleplayer_mode)
1701 this->device = device;
1703 this->error_message = error_message;
1704 this->random_input = random_input;
1705 this->input = input;
1706 this->chat_backend = chat_backend;
1707 this->simple_singleplayer_mode = simple_singleplayer_mode;
1709 driver = device->getVideoDriver();
1710 smgr = device->getSceneManager();
1712 smgr->getParameters()->setAttribute(scene::OBJ_LOADER_IGNORE_MATERIAL_FILES, true);
1714 if (!init(map_dir, address, port, gamespec))
1717 if (!createClient(playername, password, address, port, error_message))
1726 ProfilerGraph graph;
1727 RunStats stats = { 0 };
1728 CameraOrientation cam_view_target = { 0 };
1729 CameraOrientation cam_view = { 0 };
1730 GameRunData runData = { 0 };
1731 FpsControl draw_times = { 0 };
1732 VolatileRunFlags flags = { 0 };
1733 f32 dtime; // in seconds
1735 runData.time_from_last_punch = 10.0;
1736 runData.profiler_max_page = 3;
1737 runData.update_wielded_item_trigger = true;
1739 flags.show_chat = true;
1740 flags.show_hud = true;
1741 flags.show_debug = g_settings->getBool("show_debug");
1742 flags.invert_mouse = g_settings->getBool("invert_mouse");
1743 flags.first_loop_after_window_activation = true;
1745 /* Clear the profiler */
1746 Profiler::GraphValues dummyvalues;
1747 g_profiler->graphGet(dummyvalues);
1749 draw_times.last_time = device->getTimer()->getTime();
1751 shader_src->addGlobalConstantSetter(new GameGlobalShaderConstantSetter(
1753 &flags.force_fog_off,
1757 std::vector<aabb3f> highlight_boxes;
1759 set_light_table(g_settings->getFloat("display_gamma"));
1761 while (device->run() && !(*kill || g_gamecallback->shutdown_requested)) {
1763 /* Must be called immediately after a device->run() call because it
1764 * uses device->getTimer()->getTime()
1766 limitFps(&draw_times, &dtime);
1768 updateStats(&stats, draw_times, dtime);
1769 updateInteractTimers(&runData, dtime);
1771 if (!checkConnection())
1773 if (!handleCallbacks())
1779 hud->resizeHotbar();
1781 updateProfilers(runData, stats, draw_times, dtime);
1782 processUserInput(&flags, &runData, dtime);
1783 // Update camera before player movement to avoid camera lag of one frame
1784 updateCameraDirection(&cam_view_target, &flags);
1785 float cam_smoothing = 0;
1786 if (g_settings->getBool("cinematic"))
1787 cam_smoothing = 1 - g_settings->getFloat("cinematic_camera_smoothing");
1789 cam_smoothing = 1 - g_settings->getFloat("camera_smoothing");
1790 cam_smoothing = rangelim(cam_smoothing, 0.01f, 1.0f);
1791 cam_view.camera_yaw += (cam_view_target.camera_yaw -
1792 cam_view.camera_yaw) * cam_smoothing;
1793 cam_view.camera_pitch += (cam_view_target.camera_pitch -
1794 cam_view.camera_pitch) * cam_smoothing;
1795 updatePlayerControl(cam_view);
1797 processClientEvents(&cam_view, &runData.damage_flash);
1798 updateCamera(&flags, draw_times.busy_time, dtime,
1799 runData.time_from_last_punch);
1801 processPlayerInteraction(highlight_boxes, &runData, dtime,
1802 flags.show_hud, flags.show_debug);
1803 updateFrame(highlight_boxes, &graph, &stats, &runData, dtime,
1805 updateProfilerGraphs(&graph);
1810 void Game::shutdown()
1812 showOverlayMessage(wgettext("Shutting down..."), 0, 0, false);
1817 if (gui_chat_console)
1818 gui_chat_console->drop();
1824 while (g_menumgr.menuCount() > 0) {
1825 g_menumgr.m_stack.front()->setVisible(false);
1826 g_menumgr.deletingMenu(g_menumgr.m_stack.front());
1829 if (current_formspec) {
1830 current_formspec->drop();
1831 current_formspec = NULL;
1834 chat_backend->addMessage(L"", L"# Disconnected.");
1835 chat_backend->addMessage(L"", L"");
1839 while (!client->isShutdown()) {
1840 assert(texture_src != NULL);
1841 assert(shader_src != NULL);
1842 texture_src->processQueue();
1843 shader_src->processQueue();
1850 /****************************************************************************/
1851 /****************************************************************************
1853 ****************************************************************************/
1854 /****************************************************************************/
1857 const std::string &map_dir,
1858 std::string *address,
1860 const SubgameSpec &gamespec)
1862 showOverlayMessage(wgettext("Loading..."), 0, 0);
1864 texture_src = createTextureSource(device);
1865 shader_src = createShaderSource(device);
1867 itemdef_manager = createItemDefManager();
1868 nodedef_manager = createNodeDefManager();
1870 eventmgr = new EventManager();
1871 quicktune = new QuicktuneShortcutter();
1873 if (!(texture_src && shader_src && itemdef_manager && nodedef_manager
1874 && eventmgr && quicktune))
1880 // Create a server if not connecting to an existing one
1881 if (*address == "") {
1882 if (!createSingleplayerServer(map_dir, gamespec, port, address))
1889 bool Game::initSound()
1892 if (g_settings->getBool("enable_sound")) {
1893 infostream << "Attempting to use OpenAL audio" << std::endl;
1894 sound = createOpenALSoundManager(&soundfetcher);
1896 infostream << "Failed to initialize OpenAL audio" << std::endl;
1898 infostream << "Sound disabled." << std::endl;
1902 infostream << "Using dummy audio." << std::endl;
1903 sound = &dummySoundManager;
1904 sound_is_dummy = true;
1907 soundmaker = new SoundMaker(sound, nodedef_manager);
1911 soundmaker->registerReceiver(eventmgr);
1916 bool Game::createSingleplayerServer(const std::string map_dir,
1917 const SubgameSpec &gamespec, u16 port, std::string *address)
1919 showOverlayMessage(wgettext("Creating server..."), 0, 5);
1921 std::string bind_str = g_settings->get("bind_address");
1922 Address bind_addr(0, 0, 0, 0, port);
1924 if (g_settings->getBool("ipv6_server")) {
1925 bind_addr.setAddress((IPv6AddressBytes *) NULL);
1929 bind_addr.Resolve(bind_str.c_str());
1930 } catch (ResolveError &e) {
1931 infostream << "Resolving bind address \"" << bind_str
1932 << "\" failed: " << e.what()
1933 << " -- Listening on all addresses." << std::endl;
1936 if (bind_addr.isIPv6() && !g_settings->getBool("enable_ipv6")) {
1937 *error_message = L"Unable to listen on " +
1938 narrow_to_wide(bind_addr.serializeString()) +
1939 L" because IPv6 is disabled";
1940 errorstream << wide_to_narrow(*error_message) << std::endl;
1944 server = new Server(map_dir, gamespec, simple_singleplayer_mode,
1945 bind_addr.isIPv6());
1947 server->start(bind_addr);
1952 bool Game::createClient(const std::string &playername,
1953 const std::string &password, std::string *address, u16 port,
1954 std::wstring *error_message)
1956 showOverlayMessage(wgettext("Creating client..."), 0, 10);
1958 draw_control = new MapDrawControl;
1962 bool could_connect, connect_aborted;
1964 if (!connectToServer(playername, password, address, port,
1965 &could_connect, &connect_aborted))
1968 if (!could_connect) {
1969 if (*error_message == L"" && !connect_aborted) {
1970 // Should not happen if error messages are set properly
1971 *error_message = L"Connection failed for unknown reason";
1972 errorstream << wide_to_narrow(*error_message) << std::endl;
1977 if (!getServerContent(&connect_aborted)) {
1978 if (*error_message == L"" && !connect_aborted) {
1979 // Should not happen if error messages are set properly
1980 *error_message = L"Connection failed for unknown reason";
1981 errorstream << wide_to_narrow(*error_message) << std::endl;
1986 // Update cached textures, meshes and materials
1987 client->afterContentReceived(device);
1991 camera = new Camera(smgr, *draw_control, gamedef);
1992 if (!camera || !camera->successfullyCreated(*error_message))
1997 if (m_cache_enable_clouds) {
1998 clouds = new Clouds(smgr->getRootSceneNode(), smgr, -1, time(0));
2000 *error_message = L"Memory allocation error";
2001 *error_message += narrow_to_wide(" (clouds)");
2002 errorstream << wide_to_narrow(*error_message) << std::endl;
2009 sky = new Sky(smgr->getRootSceneNode(), smgr, -1, texture_src);
2010 skybox = NULL; // This is used/set later on in the main run loop
2012 local_inventory = new Inventory(itemdef_manager);
2014 if (!(sky && local_inventory)) {
2015 *error_message = L"Memory allocation error";
2016 *error_message += narrow_to_wide(" (sky or local inventory)");
2017 errorstream << wide_to_narrow(*error_message) << std::endl;
2021 /* Pre-calculated values
2023 video::ITexture *t = texture_src->getTexture("crack_anylength.png");
2025 v2u32 size = t->getOriginalSize();
2026 crack_animation_length = size.Y / size.X;
2028 crack_animation_length = 5;
2031 if (!initGui(error_message))
2034 /* Set window caption
2036 core::stringw str = L"Minetest [";
2037 str += driver->getName();
2039 device->setWindowCaption(str.c_str());
2041 LocalPlayer *player = client->getEnv().getLocalPlayer();
2042 player->hurt_tilt_timer = 0;
2043 player->hurt_tilt_strength = 0;
2045 hud = new Hud(driver, smgr, guienv, gamedef, player, local_inventory);
2048 *error_message = L"Memory error: could not create HUD";
2049 errorstream << wide_to_narrow(*error_message) << std::endl;
2056 bool Game::initGui(std::wstring *error_message)
2058 // First line of debug text
2059 guitext = guienv->addStaticText(
2061 core::rect<s32>(0, 0, 0, 0),
2062 false, false, guiroot);
2064 // Second line of debug text
2065 guitext2 = guienv->addStaticText(
2067 core::rect<s32>(0, 0, 0, 0),
2068 false, false, guiroot);
2070 // At the middle of the screen
2071 // Object infos are shown in this
2072 guitext_info = guienv->addStaticText(
2074 core::rect<s32>(0, 0, 400, g_fontengine->getTextHeight() * 5 + 5) + v2s32(100, 200),
2075 false, true, guiroot);
2077 // Status text (displays info when showing and hiding GUI stuff, etc.)
2078 guitext_status = guienv->addStaticText(
2080 core::rect<s32>(0, 0, 0, 0),
2081 false, false, guiroot);
2082 guitext_status->setVisible(false);
2085 guitext_chat = guienv->addStaticText(
2087 core::rect<s32>(0, 0, 0, 0),
2088 //false, false); // Disable word wrap as of now
2089 false, true, guiroot);
2090 // Remove stale "recent" chat messages from previous connections
2091 chat_backend->clearRecentChat();
2093 // Chat backend and console
2094 gui_chat_console = new GUIChatConsole(guienv, guienv->getRootGUIElement(),
2095 -1, chat_backend, client);
2096 if (!gui_chat_console) {
2097 *error_message = L"Could not allocate memory for chat console";
2098 errorstream << wide_to_narrow(*error_message) << std::endl;
2102 // Profiler text (size is updated when text is updated)
2103 guitext_profiler = guienv->addStaticText(
2105 core::rect<s32>(0, 0, 0, 0),
2106 false, false, guiroot);
2107 guitext_profiler->setBackgroundColor(video::SColor(120, 0, 0, 0));
2108 guitext_profiler->setVisible(false);
2109 guitext_profiler->setWordWrap(true);
2111 #ifdef HAVE_TOUCHSCREENGUI
2113 if (g_touchscreengui)
2114 g_touchscreengui->init(texture_src, porting::getDisplayDensity());
2121 bool Game::connectToServer(const std::string &playername,
2122 const std::string &password, std::string *address, u16 port,
2123 bool *connect_ok, bool *aborted)
2125 *connect_ok = false; // Let's not be overly optimistic
2127 bool local_server_mode = false;
2129 showOverlayMessage(wgettext("Resolving address..."), 0, 15);
2131 Address connect_address(0, 0, 0, 0, port);
2134 connect_address.Resolve(address->c_str());
2136 if (connect_address.isZero()) { // i.e. INADDR_ANY, IN6ADDR_ANY
2137 //connect_address.Resolve("localhost");
2138 if (connect_address.isIPv6()) {
2139 IPv6AddressBytes addr_bytes;
2140 addr_bytes.bytes[15] = 1;
2141 connect_address.setAddress(&addr_bytes);
2143 connect_address.setAddress(127, 0, 0, 1);
2145 local_server_mode = true;
2147 } catch (ResolveError &e) {
2148 *error_message = L"Couldn't resolve address: " + narrow_to_wide(e.what());
2149 errorstream << wide_to_narrow(*error_message) << std::endl;
2153 if (connect_address.isIPv6() && !g_settings->getBool("enable_ipv6")) {
2154 *error_message = L"Unable to connect to " +
2155 narrow_to_wide(connect_address.serializeString()) +
2156 L" because IPv6 is disabled";
2157 errorstream << wide_to_narrow(*error_message) << std::endl;
2161 client = new Client(device,
2162 playername.c_str(), password,
2163 *draw_control, texture_src, shader_src,
2164 itemdef_manager, nodedef_manager, sound, eventmgr,
2165 connect_address.isIPv6());
2170 gamedef = client; // Client acts as our GameDef
2172 infostream << "Connecting to server at ";
2173 connect_address.print(&infostream);
2174 infostream << std::endl;
2176 client->connect(connect_address, *address,
2177 simple_singleplayer_mode || local_server_mode);
2180 Wait for server to accept connection
2186 FpsControl fps_control = { 0 };
2187 f32 dtime; // in seconds
2189 while (device->run()) {
2191 limitFps(&fps_control, &dtime);
2193 // Update client and server
2194 client->step(dtime);
2197 server->step(dtime);
2200 if (client->getState() == LC_Init) {
2206 if (client->accessDenied()) {
2207 *error_message = L"Access denied. Reason: "
2208 + client->accessDeniedReason();
2209 errorstream << wide_to_narrow(*error_message) << std::endl;
2213 if (input->wasKeyDown(EscapeKey) || input->wasKeyDown(CancelKey)) {
2215 infostream << "Connect aborted [Escape]" << std::endl;
2220 showOverlayMessage(wgettext("Connecting to server..."), dtime, 20);
2222 } catch (con::PeerNotFoundException &e) {
2223 // TODO: Should something be done here? At least an info/error
2231 bool Game::getServerContent(bool *aborted)
2235 FpsControl fps_control = { 0 };
2236 f32 dtime; // in seconds
2238 while (device->run()) {
2240 limitFps(&fps_control, &dtime);
2242 // Update client and server
2243 client->step(dtime);
2246 server->step(dtime);
2249 if (client->mediaReceived() && client->itemdefReceived() &&
2250 client->nodedefReceived()) {
2255 if (client->accessDenied()) {
2256 *error_message = L"Access denied. Reason: "
2257 + client->accessDeniedReason();
2258 errorstream << wide_to_narrow(*error_message) << std::endl;
2262 if (client->getState() < LC_Init) {
2263 *error_message = L"Client disconnected";
2264 errorstream << wide_to_narrow(*error_message) << std::endl;
2268 if (input->wasKeyDown(EscapeKey) || input->wasKeyDown(CancelKey)) {
2270 infostream << "Connect aborted [Escape]" << std::endl;
2277 if (!client->itemdefReceived()) {
2278 const wchar_t *text = wgettext("Item definitions...");
2280 draw_load_screen(text, device, guienv, dtime, progress);
2282 } else if (!client->nodedefReceived()) {
2283 const wchar_t *text = wgettext("Node definitions...");
2285 draw_load_screen(text, device, guienv, dtime, progress);
2288 std::stringstream message;
2289 message.precision(3);
2290 message << gettext("Media...");
2292 if ((USE_CURL == 0) ||
2293 (!g_settings->getBool("enable_remote_media_server"))) {
2294 float cur = client->getCurRate();
2295 std::string cur_unit = gettext(" KB/s");
2299 cur_unit = gettext(" MB/s");
2302 message << " ( " << cur << cur_unit << " )";
2305 progress = 30 + client->mediaReceiveProgress() * 35 + 0.5;
2306 draw_load_screen(narrow_to_wide(message.str()), device,
2307 guienv, dtime, progress);
2315 /****************************************************************************/
2316 /****************************************************************************
2318 ****************************************************************************/
2319 /****************************************************************************/
2321 inline void Game::updateInteractTimers(GameRunData *runData, f32 dtime)
2323 if (runData->nodig_delay_timer >= 0)
2324 runData->nodig_delay_timer -= dtime;
2326 if (runData->object_hit_delay_timer >= 0)
2327 runData->object_hit_delay_timer -= dtime;
2329 runData->time_from_last_punch += dtime;
2333 /* returns false if game should exit, otherwise true
2335 inline bool Game::checkConnection()
2337 if (client->accessDenied()) {
2338 *error_message = L"Access denied. Reason: "
2339 + client->accessDeniedReason();
2340 errorstream << wide_to_narrow(*error_message) << std::endl;
2348 /* returns false if game should exit, otherwise true
2350 inline bool Game::handleCallbacks()
2352 if (g_gamecallback->disconnect_requested) {
2353 g_gamecallback->disconnect_requested = false;
2357 if (g_gamecallback->changepassword_requested) {
2358 (new GUIPasswordChange(guienv, guiroot, -1,
2359 &g_menumgr, client))->drop();
2360 g_gamecallback->changepassword_requested = false;
2363 if (g_gamecallback->changevolume_requested) {
2364 (new GUIVolumeChange(guienv, guiroot, -1,
2365 &g_menumgr, client))->drop();
2366 g_gamecallback->changevolume_requested = false;
2369 if (g_gamecallback->keyconfig_requested) {
2370 (new GUIKeyChangeMenu(guienv, guiroot, -1,
2371 &g_menumgr))->drop();
2372 g_gamecallback->keyconfig_requested = false;
2375 if (g_gamecallback->keyconfig_changed) {
2376 keycache.populate(); // update the cache with new settings
2377 g_gamecallback->keyconfig_changed = false;
2384 void Game::processQueues()
2386 texture_src->processQueue();
2387 itemdef_manager->processQueue(gamedef);
2388 shader_src->processQueue();
2392 void Game::updateProfilers(const GameRunData &runData, const RunStats &stats,
2393 const FpsControl &draw_times, f32 dtime)
2395 float profiler_print_interval =
2396 g_settings->getFloat("profiler_print_interval");
2397 bool print_to_log = true;
2399 if (profiler_print_interval == 0) {
2400 print_to_log = false;
2401 profiler_print_interval = 5;
2404 if (profiler_interval.step(dtime, profiler_print_interval)) {
2406 infostream << "Profiler:" << std::endl;
2407 g_profiler->print(infostream);
2410 update_profiler_gui(guitext_profiler, g_fontengine,
2411 runData.profiler_current_page, runData.profiler_max_page,
2412 driver->getScreenSize().Height);
2414 g_profiler->clear();
2417 addProfilerGraphs(stats, draw_times, dtime);
2421 void Game::addProfilerGraphs(const RunStats &stats,
2422 const FpsControl &draw_times, f32 dtime)
2424 g_profiler->graphAdd("mainloop_other",
2425 draw_times.busy_time / 1000.0f - stats.drawtime / 1000.0f);
2427 if (draw_times.sleep_time != 0)
2428 g_profiler->graphAdd("mainloop_sleep", draw_times.sleep_time / 1000.0f);
2429 g_profiler->graphAdd("mainloop_dtime", dtime);
2431 g_profiler->add("Elapsed time", dtime);
2432 g_profiler->avg("FPS", 1. / dtime);
2436 void Game::updateStats(RunStats *stats, const FpsControl &draw_times,
2443 /* Time average and jitter calculation
2445 jp = &stats->dtime_jitter;
2446 jp->avg = jp->avg * 0.96 + dtime * 0.04;
2448 jitter = dtime - jp->avg;
2450 if (jitter > jp->max)
2453 jp->counter += dtime;
2455 if (jp->counter > 0.0) {
2457 jp->max_sample = jp->max;
2458 jp->max_fraction = jp->max_sample / (jp->avg + 0.001);
2462 /* Busytime average and jitter calculation
2464 jp = &stats->busy_time_jitter;
2465 jp->avg = jp->avg + draw_times.busy_time * 0.02;
2467 jitter = draw_times.busy_time - jp->avg;
2469 if (jitter > jp->max)
2471 if (jitter < jp->min)
2474 jp->counter += dtime;
2476 if (jp->counter > 0.0) {
2478 jp->max_sample = jp->max;
2479 jp->min_sample = jp->min;
2487 /****************************************************************************
2489 ****************************************************************************/
2491 void Game::processUserInput(VolatileRunFlags *flags,
2492 GameRunData *runData, f32 dtime)
2494 // Reset input if window not active or some menu is active
2495 if (device->isWindowActive() == false
2496 || noMenuActive() == false
2497 || guienv->hasFocus(gui_chat_console)) {
2501 if (!guienv->hasFocus(gui_chat_console) && gui_chat_console->isOpen()) {
2502 gui_chat_console->closeConsoleAtOnce();
2505 // Input handler step() (used by the random input generator)
2508 #ifdef HAVE_TOUCHSCREENGUI
2510 if (g_touchscreengui) {
2511 g_touchscreengui->step(dtime);
2517 if (current_formspec != 0)
2518 current_formspec->getAndroidUIInput();
2522 // Increase timer for double tap of "keymap_jump"
2523 if (m_cache_doubletap_jump && runData->jump_timer <= 0.2)
2524 runData->jump_timer += dtime;
2526 processKeyboardInput(
2528 &runData->statustext_time,
2529 &runData->jump_timer,
2530 &runData->reset_jump_timer,
2531 &runData->profiler_current_page,
2532 runData->profiler_max_page);
2534 processItemSelection(&runData->new_playeritem);
2538 void Game::processKeyboardInput(VolatileRunFlags *flags,
2539 float *statustext_time,
2541 bool *reset_jump_timer,
2542 u32 *profiler_current_page,
2543 u32 profiler_max_page)
2546 //TimeTaker tt("process kybd input", NULL, PRECISION_NANO);
2548 if (input->wasKeyDown(keycache.key[KeyCache::KEYMAP_ID_DROP])) {
2550 } else if (input->wasKeyDown(keycache.key[KeyCache::KEYMAP_ID_INVENTORY])) {
2552 } else if (input->wasKeyDown(EscapeKey) || input->wasKeyDown(CancelKey)) {
2553 show_pause_menu(¤t_formspec, client, gamedef, texture_src, device,
2554 simple_singleplayer_mode);
2555 } else if (input->wasKeyDown(keycache.key[KeyCache::KEYMAP_ID_CHAT])) {
2556 show_chat_menu(¤t_formspec, client, gamedef, texture_src, device,
2558 } else if (input->wasKeyDown(keycache.key[KeyCache::KEYMAP_ID_CMD])) {
2559 show_chat_menu(¤t_formspec, client, gamedef, texture_src, device,
2561 } else if (input->wasKeyDown(keycache.key[KeyCache::KEYMAP_ID_CONSOLE])) {
2563 } else if (input->wasKeyDown(keycache.key[KeyCache::KEYMAP_ID_FREEMOVE])) {
2564 toggleFreeMove(statustext_time);
2565 } else if (input->wasKeyDown(keycache.key[KeyCache::KEYMAP_ID_JUMP])) {
2566 toggleFreeMoveAlt(statustext_time, jump_timer);
2567 *reset_jump_timer = true;
2568 } else if (input->wasKeyDown(keycache.key[KeyCache::KEYMAP_ID_FASTMOVE])) {
2569 toggleFast(statustext_time);
2570 } else if (input->wasKeyDown(keycache.key[KeyCache::KEYMAP_ID_NOCLIP])) {
2571 toggleNoClip(statustext_time);
2572 } else if (input->wasKeyDown(keycache.key[KeyCache::KEYMAP_ID_CINEMATIC])) {
2573 toggleCinematic(statustext_time);
2574 } else if (input->wasKeyDown(keycache.key[KeyCache::KEYMAP_ID_SCREENSHOT])) {
2575 client->makeScreenshot(device);
2576 } else if (input->wasKeyDown(keycache.key[KeyCache::KEYMAP_ID_TOGGLE_HUD])) {
2577 toggleHud(statustext_time, &flags->show_hud);
2578 } else if (input->wasKeyDown(keycache.key[KeyCache::KEYMAP_ID_TOGGLE_CHAT])) {
2579 toggleChat(statustext_time, &flags->show_chat);
2580 } else if (input->wasKeyDown(keycache.key[KeyCache::KEYMAP_ID_TOGGLE_FORCE_FOG_OFF])) {
2581 toggleFog(statustext_time, &flags->force_fog_off);
2582 } else if (input->wasKeyDown(keycache.key[KeyCache::KEYMAP_ID_TOGGLE_UPDATE_CAMERA])) {
2583 toggleUpdateCamera(statustext_time, &flags->disable_camera_update);
2584 } else if (input->wasKeyDown(keycache.key[KeyCache::KEYMAP_ID_TOGGLE_DEBUG])) {
2585 toggleDebug(statustext_time, &flags->show_debug, &flags->show_profiler_graph);
2586 } else if (input->wasKeyDown(keycache.key[KeyCache::KEYMAP_ID_TOGGLE_PROFILER])) {
2587 toggleProfiler(statustext_time, profiler_current_page, profiler_max_page);
2588 } else if (input->wasKeyDown(keycache.key[KeyCache::KEYMAP_ID_INCREASE_VIEWING_RANGE])) {
2589 increaseViewRange(statustext_time);
2590 } else if (input->wasKeyDown(keycache.key[KeyCache::KEYMAP_ID_DECREASE_VIEWING_RANGE])) {
2591 decreaseViewRange(statustext_time);
2592 } else if (input->wasKeyDown(keycache.key[KeyCache::KEYMAP_ID_RANGESELECT])) {
2593 toggleFullViewRange(statustext_time);
2594 } else if (input->wasKeyDown(keycache.key[KeyCache::KEYMAP_ID_QUICKTUNE_NEXT]))
2596 else if (input->wasKeyDown(keycache.key[KeyCache::KEYMAP_ID_QUICKTUNE_PREV]))
2598 else if (input->wasKeyDown(keycache.key[KeyCache::KEYMAP_ID_QUICKTUNE_INC]))
2600 else if (input->wasKeyDown(keycache.key[KeyCache::KEYMAP_ID_QUICKTUNE_DEC]))
2602 else if (input->wasKeyDown(keycache.key[KeyCache::KEYMAP_ID_DEBUG_STACKS])) {
2603 // Print debug stacks
2604 dstream << "-----------------------------------------"
2606 dstream << DTIME << "Printing debug stacks:" << std::endl;
2607 dstream << "-----------------------------------------"
2609 debug_stacks_print();
2612 if (!input->isKeyDown(getKeySetting("keymap_jump")) && *reset_jump_timer) {
2613 *reset_jump_timer = false;
2619 if (quicktune->hasMessage()) {
2620 std::string msg = quicktune->getMessage();
2621 statustext = narrow_to_wide(msg);
2622 *statustext_time = 0;
2627 void Game::processItemSelection(u16 *new_playeritem)
2629 LocalPlayer *player = client->getEnv().getLocalPlayer();
2631 /* Item selection using mouse wheel
2633 *new_playeritem = client->getPlayerItem();
2635 s32 wheel = input->getMouseWheel();
2636 u16 max_item = MYMIN(PLAYER_INVENTORY_SIZE - 1,
2637 player->hud_hotbar_itemcount - 1);
2640 *new_playeritem = *new_playeritem < max_item ? *new_playeritem + 1 : 0;
2642 *new_playeritem = *new_playeritem > 0 ? *new_playeritem - 1 : max_item;
2646 /* Item selection using keyboard
2648 for (u16 i = 0; i < 10; i++) {
2649 static const KeyPress *item_keys[10] = {
2650 NumberKey + 1, NumberKey + 2, NumberKey + 3, NumberKey + 4,
2651 NumberKey + 5, NumberKey + 6, NumberKey + 7, NumberKey + 8,
2652 NumberKey + 9, NumberKey + 0,
2655 if (input->wasKeyDown(*item_keys[i])) {
2656 if (i < PLAYER_INVENTORY_SIZE && i < player->hud_hotbar_itemcount) {
2657 *new_playeritem = i;
2658 infostream << "Selected item: " << new_playeritem << std::endl;
2666 void Game::dropSelectedItem()
2668 IDropAction *a = new IDropAction();
2670 a->from_inv.setCurrentPlayer();
2671 a->from_list = "main";
2672 a->from_i = client->getPlayerItem();
2673 client->inventoryAction(a);
2677 void Game::openInventory()
2680 * Don't permit to open inventory is CAO or player doesn't exists.
2681 * This prevent showing an empty inventory at player load
2684 LocalPlayer *player = client->getEnv().getLocalPlayer();
2685 if (player == NULL || player->getCAO() == NULL)
2688 infostream << "the_game: " << "Launching inventory" << std::endl;
2690 PlayerInventoryFormSource *fs_src = new PlayerInventoryFormSource(client);
2691 TextDest *txt_dst = new TextDestPlayerInventory(client);
2693 create_formspec_menu(¤t_formspec, client, gamedef, texture_src,
2694 device, fs_src, txt_dst, client);
2696 InventoryLocation inventoryloc;
2697 inventoryloc.setCurrentPlayer();
2698 current_formspec->setFormSpec(fs_src->getForm(), inventoryloc);
2702 void Game::openConsole()
2704 if (!gui_chat_console->isOpenInhibited()) {
2705 // Open up to over half of the screen
2706 gui_chat_console->openConsole(0.6);
2707 guienv->setFocus(gui_chat_console);
2712 void Game::toggleFreeMove(float *statustext_time)
2714 static const wchar_t *msg[] = { L"free_move disabled", L"free_move enabled" };
2716 bool free_move = !g_settings->getBool("free_move");
2717 g_settings->set("free_move", bool_to_cstr(free_move));
2719 *statustext_time = 0;
2720 statustext = msg[free_move];
2721 if (free_move && !client->checkPrivilege("fly"))
2722 statustext += L" (note: no 'fly' privilege)";
2726 void Game::toggleFreeMoveAlt(float *statustext_time, float *jump_timer)
2728 if (m_cache_doubletap_jump && *jump_timer < 0.2f)
2729 toggleFreeMove(statustext_time);
2733 void Game::toggleFast(float *statustext_time)
2735 static const wchar_t *msg[] = { L"fast_move disabled", L"fast_move enabled" };
2736 bool fast_move = !g_settings->getBool("fast_move");
2737 g_settings->set("fast_move", bool_to_cstr(fast_move));
2739 *statustext_time = 0;
2740 statustext = msg[fast_move];
2742 if (fast_move && !client->checkPrivilege("fast"))
2743 statustext += L" (note: no 'fast' privilege)";
2747 void Game::toggleNoClip(float *statustext_time)
2749 static const wchar_t *msg[] = { L"noclip disabled", L"noclip enabled" };
2750 bool noclip = !g_settings->getBool("noclip");
2751 g_settings->set("noclip", bool_to_cstr(noclip));
2753 *statustext_time = 0;
2754 statustext = msg[noclip];
2756 if (noclip && !client->checkPrivilege("noclip"))
2757 statustext += L" (note: no 'noclip' privilege)";
2760 void Game::toggleCinematic(float *statustext_time)
2762 static const wchar_t *msg[] = { L"cinematic disabled", L"cinematic enabled" };
2763 bool cinematic = !g_settings->getBool("cinematic");
2764 g_settings->set("cinematic", bool_to_cstr(cinematic));
2766 *statustext_time = 0;
2767 statustext = msg[cinematic];
2771 void Game::toggleChat(float *statustext_time, bool *flag)
2773 static const wchar_t *msg[] = { L"Chat hidden", L"Chat shown" };
2776 *statustext_time = 0;
2777 statustext = msg[*flag];
2781 void Game::toggleHud(float *statustext_time, bool *flag)
2783 static const wchar_t *msg[] = { L"HUD hidden", L"HUD shown" };
2786 *statustext_time = 0;
2787 statustext = msg[*flag];
2788 if (g_settings->getBool("enable_node_highlighting"))
2789 client->setHighlighted(client->getHighlighted(), *flag);
2793 void Game::toggleFog(float *statustext_time, bool *flag)
2795 static const wchar_t *msg[] = { L"Fog enabled", L"Fog disabled" };
2798 *statustext_time = 0;
2799 statustext = msg[*flag];
2803 void Game::toggleDebug(float *statustext_time, bool *show_debug,
2804 bool *show_profiler_graph)
2806 // Initial / 3x toggle: Chat only
2807 // 1x toggle: Debug text with chat
2808 // 2x toggle: Debug text with profiler graph
2811 *show_profiler_graph = false;
2812 statustext = L"Debug info shown";
2813 } else if (*show_profiler_graph) {
2814 *show_debug = false;
2815 *show_profiler_graph = false;
2816 statustext = L"Debug info and profiler graph hidden";
2818 *show_profiler_graph = true;
2819 statustext = L"Profiler graph shown";
2821 *statustext_time = 0;
2825 void Game::toggleUpdateCamera(float *statustext_time, bool *flag)
2827 static const wchar_t *msg[] = {
2828 L"Camera update enabled",
2829 L"Camera update disabled"
2833 *statustext_time = 0;
2834 statustext = msg[*flag];
2838 void Game::toggleProfiler(float *statustext_time, u32 *profiler_current_page,
2839 u32 profiler_max_page)
2841 *profiler_current_page = (*profiler_current_page + 1) % (profiler_max_page + 1);
2843 // FIXME: This updates the profiler with incomplete values
2844 update_profiler_gui(guitext_profiler, g_fontengine, *profiler_current_page,
2845 profiler_max_page, driver->getScreenSize().Height);
2847 if (*profiler_current_page != 0) {
2848 std::wstringstream sstr;
2849 sstr << "Profiler shown (page " << *profiler_current_page
2850 << " of " << profiler_max_page << ")";
2851 statustext = sstr.str();
2853 statustext = L"Profiler hidden";
2855 *statustext_time = 0;
2859 void Game::increaseViewRange(float *statustext_time)
2861 s16 range = g_settings->getS16("viewing_range_nodes_min");
2862 s16 range_new = range + 10;
2863 g_settings->set("viewing_range_nodes_min", itos(range_new));
2864 statustext = narrow_to_wide("Minimum viewing range changed to "
2866 *statustext_time = 0;
2870 void Game::decreaseViewRange(float *statustext_time)
2872 s16 range = g_settings->getS16("viewing_range_nodes_min");
2873 s16 range_new = range - 10;
2878 g_settings->set("viewing_range_nodes_min", itos(range_new));
2879 statustext = narrow_to_wide("Minimum viewing range changed to "
2881 *statustext_time = 0;
2885 void Game::toggleFullViewRange(float *statustext_time)
2887 static const wchar_t *msg[] = {
2888 L"Disabled full viewing range",
2889 L"Enabled full viewing range"
2892 draw_control->range_all = !draw_control->range_all;
2893 infostream << msg[draw_control->range_all] << std::endl;
2894 statustext = msg[draw_control->range_all];
2895 *statustext_time = 0;
2899 void Game::updateCameraDirection(CameraOrientation *cam,
2900 VolatileRunFlags *flags)
2902 if ((device->isWindowActive() && noMenuActive()) || random_input) {
2905 if (!random_input) {
2906 // Mac OSX gets upset if this is set every frame
2907 if (device->getCursorControl()->isVisible())
2908 device->getCursorControl()->setVisible(false);
2912 if (flags->first_loop_after_window_activation)
2913 flags->first_loop_after_window_activation = false;
2915 updateCameraOrientation(cam, *flags);
2917 input->setMousePos((driver->getScreenSize().Width / 2),
2918 (driver->getScreenSize().Height / 2));
2922 // Mac OSX gets upset if this is set every frame
2923 if (device->getCursorControl()->isVisible() == false)
2924 device->getCursorControl()->setVisible(true);
2927 if (!flags->first_loop_after_window_activation)
2928 flags->first_loop_after_window_activation = true;
2934 void Game::updateCameraOrientation(CameraOrientation *cam,
2935 const VolatileRunFlags &flags)
2937 #ifdef HAVE_TOUCHSCREENGUI
2938 if (g_touchscreengui) {
2939 cam->camera_yaw = g_touchscreengui->getYaw();
2940 cam->camera_pitch = g_touchscreengui->getPitch();
2943 s32 dx = input->getMousePos().X - (driver->getScreenSize().Width / 2);
2944 s32 dy = input->getMousePos().Y - (driver->getScreenSize().Height / 2);
2946 if (flags.invert_mouse
2947 || camera->getCameraMode() == CAMERA_MODE_THIRD_FRONT) {
2951 cam->camera_yaw -= dx * m_cache_mouse_sensitivity;
2952 cam->camera_pitch += dy * m_cache_mouse_sensitivity;
2954 #ifdef HAVE_TOUCHSCREENGUI
2958 cam->camera_pitch = rangelim(cam->camera_pitch, -89.5, 89.5);
2962 void Game::updatePlayerControl(const CameraOrientation &cam)
2964 //TimeTaker tt("update player control", NULL, PRECISION_NANO);
2966 PlayerControl control(
2967 input->isKeyDown(keycache.key[KeyCache::KEYMAP_ID_FORWARD]),
2968 input->isKeyDown(keycache.key[KeyCache::KEYMAP_ID_BACKWARD]),
2969 input->isKeyDown(keycache.key[KeyCache::KEYMAP_ID_LEFT]),
2970 input->isKeyDown(keycache.key[KeyCache::KEYMAP_ID_RIGHT]),
2971 input->isKeyDown(keycache.key[KeyCache::KEYMAP_ID_JUMP]),
2972 input->isKeyDown(keycache.key[KeyCache::KEYMAP_ID_SPECIAL1]),
2973 input->isKeyDown(keycache.key[KeyCache::KEYMAP_ID_SNEAK]),
2974 input->getLeftState(),
2975 input->getRightState(),
2979 client->setPlayerControl(control);
2980 LocalPlayer *player = client->getEnv().getLocalPlayer();
2981 player->keyPressed =
2982 ( (u32)(input->isKeyDown(keycache.key[KeyCache::KEYMAP_ID_FORWARD]) & 0x1) << 0) |
2983 ( (u32)(input->isKeyDown(keycache.key[KeyCache::KEYMAP_ID_BACKWARD]) & 0x1) << 1) |
2984 ( (u32)(input->isKeyDown(keycache.key[KeyCache::KEYMAP_ID_LEFT]) & 0x1) << 2) |
2985 ( (u32)(input->isKeyDown(keycache.key[KeyCache::KEYMAP_ID_RIGHT]) & 0x1) << 3) |
2986 ( (u32)(input->isKeyDown(keycache.key[KeyCache::KEYMAP_ID_JUMP]) & 0x1) << 4) |
2987 ( (u32)(input->isKeyDown(keycache.key[KeyCache::KEYMAP_ID_SPECIAL1]) & 0x1) << 5) |
2988 ( (u32)(input->isKeyDown(keycache.key[KeyCache::KEYMAP_ID_SNEAK]) & 0x1) << 6) |
2989 ( (u32)(input->getLeftState() & 0x1) << 7) |
2990 ( (u32)(input->getRightState() & 0x1) << 8
2997 inline void Game::step(f32 *dtime)
2999 bool can_be_and_is_paused =
3000 (simple_singleplayer_mode && g_menumgr.pausesGame());
3002 if (can_be_and_is_paused) { // This is for a singleplayer server
3003 *dtime = 0; // No time passes
3005 if (server != NULL) {
3006 //TimeTaker timer("server->step(dtime)");
3007 server->step(*dtime);
3010 //TimeTaker timer("client.step(dtime)");
3011 client->step(*dtime);
3016 void Game::processClientEvents(CameraOrientation *cam, float *damage_flash)
3018 ClientEvent event = client->getClientEvent();
3020 LocalPlayer *player = client->getEnv().getLocalPlayer();
3022 for ( ; event.type != CE_NONE; event = client->getClientEvent()) {
3024 if (event.type == CE_PLAYER_DAMAGE &&
3025 client->getHP() != 0) {
3026 //u16 damage = event.player_damage.amount;
3027 //infostream<<"Player damage: "<<damage<<std::endl;
3029 *damage_flash += 100.0;
3030 *damage_flash += 8.0 * event.player_damage.amount;
3032 player->hurt_tilt_timer = 1.5;
3033 player->hurt_tilt_strength = event.player_damage.amount / 4;
3034 player->hurt_tilt_strength = rangelim(player->hurt_tilt_strength, 1.0, 4.0);
3036 MtEvent *e = new SimpleTriggerEvent("PlayerDamage");
3037 gamedef->event()->put(e);
3038 } else if (event.type == CE_PLAYER_FORCE_MOVE) {
3039 cam->camera_yaw = event.player_force_move.yaw;
3040 cam->camera_pitch = event.player_force_move.pitch;
3041 } else if (event.type == CE_DEATHSCREEN) {
3042 show_deathscreen(¤t_formspec, client, gamedef, texture_src,
3045 chat_backend->addMessage(L"", L"You died.");
3047 /* Handle visualization */
3049 player->hurt_tilt_timer = 0;
3050 player->hurt_tilt_strength = 0;
3052 } else if (event.type == CE_SHOW_FORMSPEC) {
3053 FormspecFormSource *fs_src =
3054 new FormspecFormSource(*(event.show_formspec.formspec));
3055 TextDestPlayerInventory *txt_dst =
3056 new TextDestPlayerInventory(client, *(event.show_formspec.formname));
3058 create_formspec_menu(¤t_formspec, client, gamedef,
3059 texture_src, device, fs_src, txt_dst, client);
3061 delete(event.show_formspec.formspec);
3062 delete(event.show_formspec.formname);
3063 } else if ((event.type == CE_SPAWN_PARTICLE) ||
3064 (event.type == CE_ADD_PARTICLESPAWNER) ||
3065 (event.type == CE_DELETE_PARTICLESPAWNER)) {
3066 client->getParticleManager()->handleParticleEvent(&event, gamedef,
3068 } else if (event.type == CE_HUDADD) {
3069 u32 id = event.hudadd.id;
3071 LocalPlayer *player = client->getEnv().getLocalPlayer();
3072 HudElement *e = player->getHud(id);
3075 delete event.hudadd.pos;
3076 delete event.hudadd.name;
3077 delete event.hudadd.scale;
3078 delete event.hudadd.text;
3079 delete event.hudadd.align;
3080 delete event.hudadd.offset;
3081 delete event.hudadd.world_pos;
3082 delete event.hudadd.size;
3087 e->type = (HudElementType)event.hudadd.type;
3088 e->pos = *event.hudadd.pos;
3089 e->name = *event.hudadd.name;
3090 e->scale = *event.hudadd.scale;
3091 e->text = *event.hudadd.text;
3092 e->number = event.hudadd.number;
3093 e->item = event.hudadd.item;
3094 e->dir = event.hudadd.dir;
3095 e->align = *event.hudadd.align;
3096 e->offset = *event.hudadd.offset;
3097 e->world_pos = *event.hudadd.world_pos;
3098 e->size = *event.hudadd.size;
3100 u32 new_id = player->addHud(e);
3101 //if this isn't true our huds aren't consistent
3102 sanity_check(new_id == id);
3104 delete event.hudadd.pos;
3105 delete event.hudadd.name;
3106 delete event.hudadd.scale;
3107 delete event.hudadd.text;
3108 delete event.hudadd.align;
3109 delete event.hudadd.offset;
3110 delete event.hudadd.world_pos;
3111 delete event.hudadd.size;
3112 } else if (event.type == CE_HUDRM) {
3113 HudElement *e = player->removeHud(event.hudrm.id);
3117 } else if (event.type == CE_HUDCHANGE) {
3118 u32 id = event.hudchange.id;
3119 HudElement *e = player->getHud(id);
3122 delete event.hudchange.v3fdata;
3123 delete event.hudchange.v2fdata;
3124 delete event.hudchange.sdata;
3125 delete event.hudchange.v2s32data;
3129 switch (event.hudchange.stat) {
3131 e->pos = *event.hudchange.v2fdata;
3135 e->name = *event.hudchange.sdata;
3138 case HUD_STAT_SCALE:
3139 e->scale = *event.hudchange.v2fdata;
3143 e->text = *event.hudchange.sdata;
3146 case HUD_STAT_NUMBER:
3147 e->number = event.hudchange.data;
3151 e->item = event.hudchange.data;
3155 e->dir = event.hudchange.data;
3158 case HUD_STAT_ALIGN:
3159 e->align = *event.hudchange.v2fdata;
3162 case HUD_STAT_OFFSET:
3163 e->offset = *event.hudchange.v2fdata;
3166 case HUD_STAT_WORLD_POS:
3167 e->world_pos = *event.hudchange.v3fdata;
3171 e->size = *event.hudchange.v2s32data;
3175 delete event.hudchange.v3fdata;
3176 delete event.hudchange.v2fdata;
3177 delete event.hudchange.sdata;
3178 delete event.hudchange.v2s32data;
3179 } else if (event.type == CE_SET_SKY) {
3180 sky->setVisible(false);
3187 // Handle according to type
3188 if (*event.set_sky.type == "regular") {
3189 sky->setVisible(true);
3190 } else if (*event.set_sky.type == "skybox" &&
3191 event.set_sky.params->size() == 6) {
3192 sky->setFallbackBgColor(*event.set_sky.bgcolor);
3193 skybox = smgr->addSkyBoxSceneNode(
3194 texture_src->getTexture((*event.set_sky.params)[0]),
3195 texture_src->getTexture((*event.set_sky.params)[1]),
3196 texture_src->getTexture((*event.set_sky.params)[2]),
3197 texture_src->getTexture((*event.set_sky.params)[3]),
3198 texture_src->getTexture((*event.set_sky.params)[4]),
3199 texture_src->getTexture((*event.set_sky.params)[5]));
3201 // Handle everything else as plain color
3203 if (*event.set_sky.type != "plain")
3204 infostream << "Unknown sky type: "
3205 << (*event.set_sky.type) << std::endl;
3207 sky->setFallbackBgColor(*event.set_sky.bgcolor);
3210 delete event.set_sky.bgcolor;
3211 delete event.set_sky.type;
3212 delete event.set_sky.params;
3213 } else if (event.type == CE_OVERRIDE_DAY_NIGHT_RATIO) {
3214 bool enable = event.override_day_night_ratio.do_override;
3215 u32 value = event.override_day_night_ratio.ratio_f * 1000;
3216 client->getEnv().setDayNightRatioOverride(enable, value);
3222 void Game::updateCamera(VolatileRunFlags *flags, u32 busy_time,
3223 f32 dtime, float time_from_last_punch)
3225 LocalPlayer *player = client->getEnv().getLocalPlayer();
3228 For interaction purposes, get info about the held item
3230 - Is it a usable item?
3231 - Can it point to liquids?
3233 ItemStack playeritem;
3235 InventoryList *mlist = local_inventory->getList("main");
3237 if (mlist && client->getPlayerItem() < mlist->getSize())
3238 playeritem = mlist->getItem(client->getPlayerItem());
3241 ToolCapabilities playeritem_toolcap =
3242 playeritem.getToolCapabilities(itemdef_manager);
3244 v3s16 old_camera_offset = camera->getOffset();
3246 if (input->wasKeyDown(keycache.key[KeyCache::KEYMAP_ID_CAMERA_MODE])) {
3247 GenericCAO *playercao = player->getCAO();
3249 // If playercao not loaded, don't change camera
3250 if (playercao == NULL)
3253 camera->toggleCameraMode();
3255 playercao->setVisible(camera->getCameraMode() > CAMERA_MODE_FIRST);
3258 float full_punch_interval = playeritem_toolcap.full_punch_interval;
3259 float tool_reload_ratio = time_from_last_punch / full_punch_interval;
3261 tool_reload_ratio = MYMIN(tool_reload_ratio, 1.0);
3262 camera->update(player, dtime, busy_time / 1000.0f, tool_reload_ratio,
3264 camera->step(dtime);
3266 v3f camera_position = camera->getPosition();
3267 v3f camera_direction = camera->getDirection();
3268 f32 camera_fov = camera->getFovMax();
3269 v3s16 camera_offset = camera->getOffset();
3271 flags->camera_offset_changed = (camera_offset != old_camera_offset);
3273 if (!flags->disable_camera_update) {
3274 client->getEnv().getClientMap().updateCamera(camera_position,
3275 camera_direction, camera_fov, camera_offset);
3277 if (flags->camera_offset_changed) {
3278 client->updateCameraOffset(camera_offset);
3279 client->getEnv().updateCameraOffset(camera_offset);
3282 clouds->updateCameraOffset(camera_offset);
3288 void Game::updateSound(f32 dtime)
3290 // Update sound listener
3291 v3s16 camera_offset = camera->getOffset();
3292 sound->updateListener(camera->getCameraNode()->getPosition() + intToFloat(camera_offset, BS),
3293 v3f(0, 0, 0), // velocity
3294 camera->getDirection(),
3295 camera->getCameraNode()->getUpVector());
3296 sound->setListenerGain(g_settings->getFloat("sound_volume"));
3299 // Update sound maker
3300 soundmaker->step(dtime);
3302 LocalPlayer *player = client->getEnv().getLocalPlayer();
3304 ClientMap &map = client->getEnv().getClientMap();
3305 MapNode n = map.getNodeNoEx(player->getStandingNodePos());
3306 soundmaker->m_player_step_sound = nodedef_manager->get(n).sound_footstep;
3310 void Game::processPlayerInteraction(std::vector<aabb3f> &highlight_boxes,
3311 GameRunData *runData, f32 dtime, bool show_hud, bool show_debug)
3313 LocalPlayer *player = client->getEnv().getLocalPlayer();
3315 ItemStack playeritem;
3317 InventoryList *mlist = local_inventory->getList("main");
3319 if (mlist && client->getPlayerItem() < mlist->getSize())
3320 playeritem = mlist->getItem(client->getPlayerItem());
3323 const ItemDefinition &playeritem_def =
3324 playeritem.getDefinition(itemdef_manager);
3326 v3f player_position = player->getPosition();
3327 v3f camera_position = camera->getPosition();
3328 v3f camera_direction = camera->getDirection();
3329 v3s16 camera_offset = camera->getOffset();
3333 Calculate what block is the crosshair pointing to
3336 f32 d = playeritem_def.range; // max. distance
3337 f32 d_hand = itemdef_manager->get("").range;
3339 if (d < 0 && d_hand >= 0)
3344 core::line3d<f32> shootline;
3346 if (camera->getCameraMode() != CAMERA_MODE_THIRD_FRONT) {
3348 shootline = core::line3d<f32>(camera_position,
3349 camera_position + camera_direction * BS * (d + 1));
3352 // prevent player pointing anything in front-view
3353 if (camera->getCameraMode() == CAMERA_MODE_THIRD_FRONT)
3354 shootline = core::line3d<f32>(0, 0, 0, 0, 0, 0);
3357 #ifdef HAVE_TOUCHSCREENGUI
3359 if ((g_settings->getBool("touchtarget")) && (g_touchscreengui)) {
3360 shootline = g_touchscreengui->getShootline();
3361 shootline.start += intToFloat(camera_offset, BS);
3362 shootline.end += intToFloat(camera_offset, BS);
3367 PointedThing pointed = getPointedThing(
3369 client, player_position, camera_direction,
3370 camera_position, shootline, d,
3371 playeritem_def.liquids_pointable,
3372 !runData->ldown_for_dig,
3376 runData->selected_object);
3378 if (pointed != runData->pointed_old) {
3379 infostream << "Pointing at " << pointed.dump() << std::endl;
3381 if (m_cache_enable_node_highlighting) {
3382 if (pointed.type == POINTEDTHING_NODE) {
3383 client->setHighlighted(pointed.node_undersurface, show_hud);
3385 client->setHighlighted(pointed.node_undersurface, false);
3392 - releasing left mouse button
3393 - pointing away from node
3395 if (runData->digging) {
3396 if (input->getLeftReleased()) {
3397 infostream << "Left button released"
3398 << " (stopped digging)" << std::endl;
3399 runData->digging = false;
3400 } else if (pointed != runData->pointed_old) {
3401 if (pointed.type == POINTEDTHING_NODE
3402 && runData->pointed_old.type == POINTEDTHING_NODE
3403 && pointed.node_undersurface
3404 == runData->pointed_old.node_undersurface) {
3405 // Still pointing to the same node, but a different face.
3408 infostream << "Pointing away from node"
3409 << " (stopped digging)" << std::endl;
3410 runData->digging = false;
3414 if (!runData->digging) {
3415 client->interact(1, runData->pointed_old);
3416 client->setCrack(-1, v3s16(0, 0, 0));
3417 runData->dig_time = 0.0;
3421 if (!runData->digging && runData->ldown_for_dig && !input->getLeftState()) {
3422 runData->ldown_for_dig = false;
3425 runData->left_punch = false;
3427 soundmaker->m_player_leftpunch_sound.name = "";
3429 if (input->getRightState())
3430 runData->repeat_rightclick_timer += dtime;
3432 runData->repeat_rightclick_timer = 0;
3434 if (playeritem_def.usable && input->getLeftState()) {
3435 if (input->getLeftClicked())
3436 client->interact(4, pointed);
3437 } else if (pointed.type == POINTEDTHING_NODE) {
3438 ToolCapabilities playeritem_toolcap =
3439 playeritem.getToolCapabilities(itemdef_manager);
3440 handlePointingAtNode(runData, pointed, playeritem_def,
3441 playeritem_toolcap, dtime);
3442 } else if (pointed.type == POINTEDTHING_OBJECT) {
3443 handlePointingAtObject(runData, pointed, playeritem,
3444 player_position, show_debug);
3445 } else if (input->getLeftState()) {
3446 // When button is held down in air, show continuous animation
3447 runData->left_punch = true;
3450 runData->pointed_old = pointed;
3452 if (runData->left_punch || input->getLeftClicked())
3453 camera->setDigging(0); // left click animation
3455 input->resetLeftClicked();
3456 input->resetRightClicked();
3458 input->resetLeftReleased();
3459 input->resetRightReleased();
3463 void Game::handlePointingAtNode(GameRunData *runData,
3464 const PointedThing &pointed, const ItemDefinition &playeritem_def,
3465 const ToolCapabilities &playeritem_toolcap, f32 dtime)
3467 v3s16 nodepos = pointed.node_undersurface;
3468 v3s16 neighbourpos = pointed.node_abovesurface;
3471 Check information text of node
3474 ClientMap &map = client->getEnv().getClientMap();
3475 NodeMetadata *meta = map.getNodeMetadata(nodepos);
3478 infotext = narrow_to_wide(meta->getString("infotext"));
3480 MapNode n = map.getNodeNoEx(nodepos);
3482 if (nodedef_manager->get(n).tiledef[0].name == "unknown_node.png") {
3483 infotext = L"Unknown node: ";
3484 infotext += narrow_to_wide(nodedef_manager->get(n).name);
3488 if (runData->nodig_delay_timer <= 0.0 && input->getLeftState()
3489 && client->checkPrivilege("interact")) {
3490 handleDigging(runData, pointed, nodepos, playeritem_toolcap, dtime);
3493 if ((input->getRightClicked() ||
3494 runData->repeat_rightclick_timer >= m_repeat_right_click_time) &&
3495 client->checkPrivilege("interact")) {
3496 runData->repeat_rightclick_timer = 0;
3497 infostream << "Ground right-clicked" << std::endl;
3499 if (meta && meta->getString("formspec") != "" && !random_input
3500 && !input->isKeyDown(getKeySetting("keymap_sneak"))) {
3501 infostream << "Launching custom inventory view" << std::endl;
3503 InventoryLocation inventoryloc;
3504 inventoryloc.setNodeMeta(nodepos);
3506 NodeMetadataFormSource *fs_src = new NodeMetadataFormSource(
3507 &client->getEnv().getClientMap(), nodepos);
3508 TextDest *txt_dst = new TextDestNodeMetadata(nodepos, client);
3510 create_formspec_menu(¤t_formspec, client, gamedef,
3511 texture_src, device, fs_src, txt_dst, client);
3513 current_formspec->setFormSpec(meta->getString("formspec"), inventoryloc);
3515 // Report right click to server
3517 camera->setDigging(1); // right click animation (always shown for feedback)
3519 // If the wielded item has node placement prediction,
3521 bool placed = nodePlacementPrediction(*client,
3523 nodepos, neighbourpos);
3527 client->interact(3, pointed);
3529 soundmaker->m_player_rightpunch_sound =
3530 playeritem_def.sound_place;
3532 soundmaker->m_player_rightpunch_sound =
3536 if (playeritem_def.node_placement_prediction == "" ||
3537 nodedef_manager->get(map.getNodeNoEx(nodepos)).rightclickable)
3538 client->interact(3, pointed); // Report to server
3544 void Game::handlePointingAtObject(GameRunData *runData,
3545 const PointedThing &pointed,
3546 const ItemStack &playeritem,
3547 const v3f &player_position,
3550 infotext = narrow_to_wide(runData->selected_object->infoText());
3552 if (infotext == L"" && show_debug) {
3553 infotext = narrow_to_wide(runData->selected_object->debugInfoText());
3556 if (input->getLeftState()) {
3557 bool do_punch = false;
3558 bool do_punch_damage = false;
3560 if (runData->object_hit_delay_timer <= 0.0) {
3562 do_punch_damage = true;
3563 runData->object_hit_delay_timer = object_hit_delay;
3566 if (input->getLeftClicked())
3570 infostream << "Left-clicked object" << std::endl;
3571 runData->left_punch = true;
3574 if (do_punch_damage) {
3575 // Report direct punch
3576 v3f objpos = runData->selected_object->getPosition();
3577 v3f dir = (objpos - player_position).normalize();
3579 bool disable_send = runData->selected_object->directReportPunch(
3580 dir, &playeritem, runData->time_from_last_punch);
3581 runData->time_from_last_punch = 0;
3584 client->interact(0, pointed);
3586 } else if (input->getRightClicked()) {
3587 infostream << "Right-clicked object" << std::endl;
3588 client->interact(3, pointed); // place
3593 void Game::handleDigging(GameRunData *runData,
3594 const PointedThing &pointed, const v3s16 &nodepos,
3595 const ToolCapabilities &playeritem_toolcap, f32 dtime)
3597 if (!runData->digging) {
3598 infostream << "Started digging" << std::endl;
3599 client->interact(0, pointed);
3600 runData->digging = true;
3601 runData->ldown_for_dig = true;
3604 LocalPlayer *player = client->getEnv().getLocalPlayer();
3605 ClientMap &map = client->getEnv().getClientMap();
3606 MapNode n = client->getEnv().getClientMap().getNodeNoEx(nodepos);
3608 // NOTE: Similar piece of code exists on the server side for
3610 // Get digging parameters
3611 DigParams params = getDigParams(nodedef_manager->get(n).groups,
3612 &playeritem_toolcap);
3614 // If can't dig, try hand
3615 if (!params.diggable) {
3616 const ItemDefinition &hand = itemdef_manager->get("");
3617 const ToolCapabilities *tp = hand.tool_capabilities;
3620 params = getDigParams(nodedef_manager->get(n).groups, tp);
3623 if (params.diggable == false) {
3624 // I guess nobody will wait for this long
3625 runData->dig_time_complete = 10000000.0;
3627 runData->dig_time_complete = params.time;
3629 if (m_cache_enable_particles) {
3630 const ContentFeatures &features =
3631 client->getNodeDefManager()->get(n);
3632 client->getParticleManager()->addPunchingParticles(gamedef, smgr,
3633 player, nodepos, features.tiles);
3637 if (runData->dig_time_complete >= 0.001) {
3638 runData->dig_index = (float)crack_animation_length
3640 / runData->dig_time_complete;
3642 // This is for torches
3643 runData->dig_index = crack_animation_length;
3646 SimpleSoundSpec sound_dig = nodedef_manager->get(n).sound_dig;
3648 if (sound_dig.exists() && params.diggable) {
3649 if (sound_dig.name == "__group") {
3650 if (params.main_group != "") {
3651 soundmaker->m_player_leftpunch_sound.gain = 0.5;
3652 soundmaker->m_player_leftpunch_sound.name =
3653 std::string("default_dig_") +
3657 soundmaker->m_player_leftpunch_sound = sound_dig;
3661 // Don't show cracks if not diggable
3662 if (runData->dig_time_complete >= 100000.0) {
3663 } else if (runData->dig_index < crack_animation_length) {
3664 //TimeTaker timer("client.setTempMod");
3665 //infostream<<"dig_index="<<dig_index<<std::endl;
3666 client->setCrack(runData->dig_index, nodepos);
3668 infostream << "Digging completed" << std::endl;
3669 client->interact(2, pointed);
3670 client->setCrack(-1, v3s16(0, 0, 0));
3671 bool is_valid_position;
3672 MapNode wasnode = map.getNodeNoEx(nodepos, &is_valid_position);
3673 if (is_valid_position)
3674 client->removeNode(nodepos);
3676 if (m_cache_enable_particles) {
3677 const ContentFeatures &features =
3678 client->getNodeDefManager()->get(wasnode);
3679 client->getParticleManager()->addDiggingParticles(gamedef, smgr,
3680 player, nodepos, features.tiles);
3683 runData->dig_time = 0;
3684 runData->digging = false;
3686 runData->nodig_delay_timer =
3687 runData->dig_time_complete / (float)crack_animation_length;
3689 // We don't want a corresponding delay to
3690 // very time consuming nodes
3691 if (runData->nodig_delay_timer > 0.3)
3692 runData->nodig_delay_timer = 0.3;
3694 // We want a slight delay to very little
3695 // time consuming nodes
3696 const float mindelay = 0.15;
3698 if (runData->nodig_delay_timer < mindelay)
3699 runData->nodig_delay_timer = mindelay;
3701 // Send event to trigger sound
3702 MtEvent *e = new NodeDugEvent(nodepos, wasnode);
3703 gamedef->event()->put(e);
3706 if (runData->dig_time_complete < 100000.0) {
3707 runData->dig_time += dtime;
3709 runData->dig_time = 0;
3710 client->setCrack(-1, nodepos);
3713 camera->setDigging(0); // left click animation
3717 void Game::updateFrame(std::vector<aabb3f> &highlight_boxes,
3718 ProfilerGraph *graph, RunStats *stats, GameRunData *runData,
3719 f32 dtime, const VolatileRunFlags &flags, const CameraOrientation &cam)
3721 LocalPlayer *player = client->getEnv().getLocalPlayer();
3727 if (draw_control->range_all) {
3728 runData->fog_range = 100000 * BS;
3730 runData->fog_range = draw_control->wanted_range * BS
3731 + 0.0 * MAP_BLOCKSIZE * BS;
3732 runData->fog_range = MYMIN(
3734 (draw_control->farthest_drawn + 20) * BS);
3735 runData->fog_range *= 0.9;
3739 Calculate general brightness
3741 u32 daynight_ratio = client->getEnv().getDayNightRatio();
3742 float time_brightness = decode_light_f((float)daynight_ratio / 1000.0);
3743 float direct_brightness;
3746 if (g_settings->getBool("free_move")) {
3747 direct_brightness = time_brightness;
3748 sunlight_seen = true;
3750 ScopeProfiler sp(g_profiler, "Detecting background light", SPT_AVG);
3751 float old_brightness = sky->getBrightness();
3752 direct_brightness = client->getEnv().getClientMap()
3753 .getBackgroundBrightness(MYMIN(runData->fog_range * 1.2, 60 * BS),
3754 daynight_ratio, (int)(old_brightness * 255.5), &sunlight_seen)
3758 float time_of_day = runData->time_of_day;
3759 float time_of_day_smooth = runData->time_of_day_smooth;
3761 time_of_day = client->getEnv().getTimeOfDayF();
3763 const float maxsm = 0.05;
3764 const float todsm = 0.05;
3766 if (fabs(time_of_day - time_of_day_smooth) > maxsm &&
3767 fabs(time_of_day - time_of_day_smooth + 1.0) > maxsm &&
3768 fabs(time_of_day - time_of_day_smooth - 1.0) > maxsm)
3769 time_of_day_smooth = time_of_day;
3771 if (time_of_day_smooth > 0.8 && time_of_day < 0.2)
3772 time_of_day_smooth = time_of_day_smooth * (1.0 - todsm)
3773 + (time_of_day + 1.0) * todsm;
3775 time_of_day_smooth = time_of_day_smooth * (1.0 - todsm)
3776 + time_of_day * todsm;
3778 runData->time_of_day = time_of_day;
3779 runData->time_of_day_smooth = time_of_day_smooth;
3781 sky->update(time_of_day_smooth, time_brightness, direct_brightness,
3782 sunlight_seen, camera->getCameraMode(), player->getYaw(),
3783 player->getPitch());
3789 v3f player_position = player->getPosition();
3790 if (sky->getCloudsVisible()) {
3791 clouds->setVisible(true);
3792 clouds->step(dtime);
3793 clouds->update(v2f(player_position.X, player_position.Z),
3794 sky->getCloudColor());
3796 clouds->setVisible(false);
3803 client->getParticleManager()->step(dtime);
3809 if (m_cache_enable_fog && !flags.force_fog_off) {
3812 video::EFT_FOG_LINEAR,
3813 runData->fog_range * 0.4,
3814 runData->fog_range * 1.0,
3822 video::EFT_FOG_LINEAR,
3832 Get chat messages from client
3835 v2u32 screensize = driver->getScreenSize();
3837 updateChat(*client, dtime, flags.show_debug, screensize,
3838 flags.show_chat, runData->profiler_current_page,
3839 *chat_backend, guitext_chat);
3845 if (client->getPlayerItem() != runData->new_playeritem)
3846 client->selectPlayerItem(runData->new_playeritem);
3848 // Update local inventory if it has changed
3849 if (client->getLocalInventoryUpdated()) {
3850 //infostream<<"Updating local inventory"<<std::endl;
3851 client->getLocalInventory(*local_inventory);
3852 runData->update_wielded_item_trigger = true;
3855 if (runData->update_wielded_item_trigger) {
3856 // Update wielded tool
3857 InventoryList *mlist = local_inventory->getList("main");
3859 if (mlist && (client->getPlayerItem() < mlist->getSize())) {
3860 ItemStack item = mlist->getItem(client->getPlayerItem());
3861 camera->wield(item);
3863 runData->update_wielded_item_trigger = false;
3867 Update block draw list every 200ms or when camera direction has
3870 runData->update_draw_list_timer += dtime;
3872 v3f camera_direction = camera->getDirection();
3873 if (runData->update_draw_list_timer >= 0.2
3874 || runData->update_draw_list_last_cam_dir.getDistanceFrom(camera_direction) > 0.2
3875 || flags.camera_offset_changed) {
3876 runData->update_draw_list_timer = 0;
3877 client->getEnv().getClientMap().updateDrawList(driver);
3878 runData->update_draw_list_last_cam_dir = camera_direction;
3881 updateGui(&runData->statustext_time, *stats, *runData, dtime, flags, cam);
3884 make sure menu is on top
3885 1. Delete formspec menu reference if menu was removed
3886 2. Else, make sure formspec menu is on top
3888 if (current_formspec) {
3889 if (current_formspec->getReferenceCount() == 1) {
3890 current_formspec->drop();
3891 current_formspec = NULL;
3892 } else if (!noMenuActive()) {
3893 guiroot->bringToFront(current_formspec);
3901 video::SColor skycolor = sky->getSkyColor();
3903 TimeTaker tt_draw("mainloop: draw");
3905 TimeTaker timer("beginScene");
3906 driver->beginScene(true, true, skycolor);
3907 stats->beginscenetime = timer.stop(true);
3910 draw_scene(driver, smgr, *camera, *client, player, *hud, guienv,
3911 highlight_boxes, screensize, skycolor, flags.show_hud);
3916 if (flags.show_profiler_graph)
3917 graph->draw(10, screensize.Y - 10, driver, g_fontengine->getFont());
3922 if (runData->damage_flash > 0.0) {
3923 video::SColor color(std::min(runData->damage_flash, 180.0f),
3927 driver->draw2DRectangle(color,
3928 core::rect<s32>(0, 0, screensize.X, screensize.Y),
3931 runData->damage_flash -= 100.0 * dtime;
3937 if (player->hurt_tilt_timer > 0.0) {
3938 player->hurt_tilt_timer -= dtime * 5;
3940 if (player->hurt_tilt_timer < 0)
3941 player->hurt_tilt_strength = 0;
3948 TimeTaker timer("endScene");
3950 stats->endscenetime = timer.stop(true);
3953 stats->drawtime = tt_draw.stop(true);
3954 g_profiler->graphAdd("mainloop_draw", stats->drawtime / 1000.0f);
3958 inline static const char *yawToDirectionString(int yaw)
3960 // NOTE: TODO: This can be done mathematically without the else/else-if
3963 const char *player_direction;
3965 yaw = wrapDegrees_0_360(yaw);
3967 if (yaw >= 45 && yaw < 135)
3968 player_direction = "West [-X]";
3969 else if (yaw >= 135 && yaw < 225)
3970 player_direction = "South [-Z]";
3971 else if (yaw >= 225 && yaw < 315)
3972 player_direction = "East [+X]";
3974 player_direction = "North [+Z]";
3976 return player_direction;
3980 void Game::updateGui(float *statustext_time, const RunStats &stats,
3981 const GameRunData& runData, f32 dtime, const VolatileRunFlags &flags,
3982 const CameraOrientation &cam)
3984 v2u32 screensize = driver->getScreenSize();
3985 LocalPlayer *player = client->getEnv().getLocalPlayer();
3986 v3f player_position = player->getPosition();
3988 if (flags.show_debug) {
3989 static float drawtime_avg = 0;
3990 drawtime_avg = drawtime_avg * 0.95 + stats.drawtime * 0.05;
3992 u16 fps = 1.0 / stats.dtime_jitter.avg;
3993 //s32 fps = driver->getFPS();
3995 std::ostringstream os(std::ios_base::binary);
3997 << "Minetest " << minetest_version_hash
3999 << " (R: range_all=" << draw_control->range_all << ")"
4000 << std::setprecision(0)
4001 << " drawtime = " << drawtime_avg
4002 << std::setprecision(1)
4003 << ", dtime_jitter = "
4004 << (stats.dtime_jitter.max_fraction * 100.0) << " %"
4005 << std::setprecision(1)
4006 << ", v_range = " << draw_control->wanted_range
4007 << std::setprecision(3)
4008 << ", RTT = " << client->getRTT();
4009 guitext->setText(narrow_to_wide(os.str()).c_str());
4010 guitext->setVisible(true);
4011 } else if (flags.show_hud || flags.show_chat) {
4012 std::ostringstream os(std::ios_base::binary);
4013 os << "Minetest " << minetest_version_hash;
4014 guitext->setText(narrow_to_wide(os.str()).c_str());
4015 guitext->setVisible(true);
4017 guitext->setVisible(false);
4020 if (guitext->isVisible()) {
4021 core::rect<s32> rect(
4023 screensize.X, 5 + g_fontengine->getTextHeight()
4025 guitext->setRelativePosition(rect);
4028 if (flags.show_debug) {
4029 std::ostringstream os(std::ios_base::binary);
4030 os << std::setprecision(1) << std::fixed
4031 << "(" << (player_position.X / BS)
4032 << ", " << (player_position.Y / BS)
4033 << ", " << (player_position.Z / BS)
4034 << ") (yaw=" << (wrapDegrees_0_360(cam.camera_yaw))
4035 << " " << yawToDirectionString(cam.camera_yaw)
4036 << ") (seed = " << ((u64)client->getMapSeed())
4039 if (runData.pointed_old.type == POINTEDTHING_NODE) {
4040 ClientMap &map = client->getEnv().getClientMap();
4041 const INodeDefManager *nodedef = client->getNodeDefManager();
4042 MapNode n = map.getNodeNoEx(runData.pointed_old.node_undersurface);
4043 if (n.getContent() != CONTENT_IGNORE && nodedef->get(n).name != "unknown") {
4044 const ContentFeatures &features = nodedef->get(n);
4045 os << " (pointing_at = " << nodedef->get(n).name
4046 << " - " << features.tiledef[0].name.c_str()
4051 guitext2->setText(narrow_to_wide(os.str()).c_str());
4052 guitext2->setVisible(true);
4054 core::rect<s32> rect(
4055 5, 5 + g_fontengine->getTextHeight(),
4056 screensize.X, 5 + g_fontengine->getTextHeight() * 2
4058 guitext2->setRelativePosition(rect);
4060 guitext2->setVisible(false);
4063 guitext_info->setText(infotext.c_str());
4064 guitext_info->setVisible(flags.show_hud && g_menumgr.menuCount() == 0);
4066 float statustext_time_max = 1.5;
4068 if (!statustext.empty()) {
4069 *statustext_time += dtime;
4071 if (*statustext_time >= statustext_time_max) {
4073 *statustext_time = 0;
4077 guitext_status->setText(statustext.c_str());
4078 guitext_status->setVisible(!statustext.empty());
4080 if (!statustext.empty()) {
4081 s32 status_width = guitext_status->getTextWidth();
4082 s32 status_height = guitext_status->getTextHeight();
4083 s32 status_y = screensize.Y - 150;
4084 s32 status_x = (screensize.X - status_width) / 2;
4085 core::rect<s32> rect(
4086 status_x , status_y - status_height,
4087 status_x + status_width, status_y
4089 guitext_status->setRelativePosition(rect);
4092 video::SColor initial_color(255, 0, 0, 0);
4094 if (guienv->getSkin())
4095 initial_color = guienv->getSkin()->getColor(gui::EGDC_BUTTON_TEXT);
4097 video::SColor final_color = initial_color;
4098 final_color.setAlpha(0);
4099 video::SColor fade_color = initial_color.getInterpolated_quadratic(
4100 initial_color, final_color,
4101 pow(*statustext_time / statustext_time_max, 2.0f));
4102 guitext_status->setOverrideColor(fade_color);
4103 guitext_status->enableOverrideColor(true);
4108 /* Log times and stuff for visualization */
4109 inline void Game::updateProfilerGraphs(ProfilerGraph *graph)
4111 Profiler::GraphValues values;
4112 g_profiler->graphGet(values);
4118 /****************************************************************************
4120 ****************************************************************************/
4122 /* On some computers framerate doesn't seem to be automatically limited
4124 inline void Game::limitFps(FpsControl *fps_timings, f32 *dtime)
4126 // not using getRealTime is necessary for wine
4127 device->getTimer()->tick(); // Maker sure device time is up-to-date
4128 u32 time = device->getTimer()->getTime();
4130 u32 last_time = fps_timings->last_time;
4132 if (time > last_time) // Make sure time hasn't overflowed
4133 fps_timings->busy_time = time - last_time;
4135 fps_timings->busy_time = 0;
4137 u32 frametime_min = 1000 / (g_menumgr.pausesGame()
4138 ? g_settings->getFloat("pause_fps_max")
4139 : g_settings->getFloat("fps_max"));
4141 if (fps_timings->busy_time < frametime_min) {
4142 fps_timings->sleep_time = frametime_min - fps_timings->busy_time;
4143 device->sleep(fps_timings->sleep_time);
4145 fps_timings->sleep_time = 0;
4148 /* Get the new value of the device timer. Note that device->sleep() may
4149 * not sleep for the entire requested time as sleep may be interrupted and
4150 * therefore it is arguably more accurate to get the new time from the
4151 * device rather than calculating it by adding sleep_time to time.
4154 device->getTimer()->tick(); // Update device timer
4155 time = device->getTimer()->getTime();
4157 if (time > last_time) // Make sure last_time hasn't overflowed
4158 *dtime = (time - last_time) / 1000.0;
4162 fps_timings->last_time = time;
4165 // Note: This will free (using delete[])! \p msg. If you want to use it later,
4166 // pass a copy of it to this function
4167 // Note: \p msg must be allocated using new (not malloc())
4168 void Game::showOverlayMessage(const wchar_t *msg, float dtime,
4169 int percent, bool draw_clouds)
4171 draw_load_screen(msg, device, guienv, dtime, percent, draw_clouds);
4176 /****************************************************************************/
4177 /****************************************************************************
4179 ****************************************************************************/
4180 /****************************************************************************/
4182 void Game::extendedResourceCleanup()
4184 // Extended resource accounting
4185 infostream << "Irrlicht resources after cleanup:" << std::endl;
4186 infostream << "\tRemaining meshes : "
4187 << device->getSceneManager()->getMeshCache()->getMeshCount() << std::endl;
4188 infostream << "\tRemaining textures : "
4189 << driver->getTextureCount() << std::endl;
4191 for (unsigned int i = 0; i < driver->getTextureCount(); i++) {
4192 irr::video::ITexture *texture = driver->getTextureByIndex(i);
4193 infostream << "\t\t" << i << ":" << texture->getName().getPath().c_str()
4197 clearTextureNameCache();
4198 infostream << "\tRemaining materials: "
4199 << driver-> getMaterialRendererCount()
4200 << " (note: irrlicht doesn't support removing renderers)" << std::endl;
4204 /****************************************************************************/
4205 /****************************************************************************
4206 extern function for launching the game
4207 ****************************************************************************/
4208 /****************************************************************************/
4210 void the_game(bool *kill,
4212 InputHandler *input,
4213 IrrlichtDevice *device,
4215 const std::string &map_dir,
4216 const std::string &playername,
4217 const std::string &password,
4218 const std::string &address, // If empty local server is created
4221 std::wstring &error_message,
4222 ChatBackend &chat_backend,
4223 const SubgameSpec &gamespec, // Used for local game
4224 bool simple_singleplayer_mode)
4228 /* Make a copy of the server address because if a local singleplayer server
4229 * is created then this is updated and we don't want to change the value
4230 * passed to us by the calling function
4232 std::string server_address = address;
4236 if (game.startup(kill, random_input, input, device, map_dir,
4237 playername, password, &server_address, port,
4238 &error_message, &chat_backend, gamespec,
4239 simple_singleplayer_mode)) {
4245 } catch (SerializationError &e) {
4246 error_message = L"A serialization error occurred:\n"
4247 + narrow_to_wide(e.what()) + L"\n\nThe server is probably "
4248 L" running a different version of Minetest.";
4249 errorstream << wide_to_narrow(error_message) << std::endl;
4250 } catch (ServerError &e) {
4251 error_message = narrow_to_wide(e.what());
4252 errorstream << "ServerError: " << e.what() << std::endl;
4253 } catch (ModError &e) {
4254 errorstream << "ModError: " << e.what() << std::endl;
4255 error_message = narrow_to_wide(e.what()) + wstrgettext("\nCheck debug.txt for details.");