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;
91 fields["text"] = ntext;
92 m_client->sendNodemetaFields(m_p, "", fields);
94 void gotText(const StringMap &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(const StringMap &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(const StringMap &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 StringMap::const_iterator it = fields.find("f_text");
184 if (it != fields.end())
185 m_client->typeChatMessage(narrow_to_wide(it->second));
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 >"
214 << m_formname << "< event" << std::endl;
217 StringMap::const_iterator it;
218 for (it = fields.begin(); it != fields.end(); ++it) {
219 errorstream << "\t" << i << ": " << it->first
220 << "=" << it->second << std::endl;
228 /* Form update callback */
230 class NodeMetadataFormSource: public IFormSource
233 NodeMetadataFormSource(ClientMap *map, v3s16 p):
238 std::string getForm()
240 NodeMetadata *meta = m_map->getNodeMetadata(m_p);
245 return meta->getString("formspec");
247 std::string resolveText(std::string str)
249 NodeMetadata *meta = m_map->getNodeMetadata(m_p);
254 return meta->resolveString(str);
261 class PlayerInventoryFormSource: public IFormSource
264 PlayerInventoryFormSource(Client *client):
268 std::string getForm()
270 LocalPlayer *player = m_client->getEnv().getLocalPlayer();
271 return player->inventory_formspec;
278 Check if a node is pointable
280 inline bool isPointableNode(const MapNode &n,
281 Client *client, bool liquids_pointable)
283 const ContentFeatures &features = client->getNodeDefManager()->get(n);
284 return features.pointable ||
285 (liquids_pointable && features.isLiquid());
289 Find what the player is pointing at
291 PointedThing getPointedThing(Client *client, v3f player_position,
292 v3f camera_direction, v3f camera_position, core::line3d<f32> shootline,
293 f32 d, bool liquids_pointable, bool look_for_object, v3s16 camera_offset,
294 std::vector<aabb3f> &hilightboxes, ClientActiveObject *&selected_object)
298 hilightboxes.clear();
299 selected_object = NULL;
301 INodeDefManager *nodedef = client->getNodeDefManager();
302 ClientMap &map = client->getEnv().getClientMap();
304 f32 mindistance = BS * 1001;
306 // First try to find a pointed at active object
307 if (look_for_object) {
308 selected_object = client->getSelectedActiveObject(d * BS,
309 camera_position, shootline);
311 if (selected_object != NULL) {
312 if (selected_object->doShowSelectionBox()) {
313 aabb3f *selection_box = selected_object->getSelectionBox();
314 // Box should exist because object was
315 // returned in the first place
316 assert(selection_box);
318 v3f pos = selected_object->getPosition();
319 hilightboxes.push_back(aabb3f(
320 selection_box->MinEdge + pos - intToFloat(camera_offset, BS),
321 selection_box->MaxEdge + pos - intToFloat(camera_offset, BS)));
324 mindistance = (selected_object->getPosition() - camera_position).getLength();
326 result.type = POINTEDTHING_OBJECT;
327 result.object_id = selected_object->getId();
331 // That didn't work, try to find a pointed at node
334 v3s16 pos_i = floatToInt(player_position, BS);
336 /*infostream<<"pos_i=("<<pos_i.X<<","<<pos_i.Y<<","<<pos_i.Z<<")"
340 s16 ystart = pos_i.Y + 0 - (camera_direction.Y < 0 ? a : 1);
341 s16 zstart = pos_i.Z - (camera_direction.Z < 0 ? a : 1);
342 s16 xstart = pos_i.X - (camera_direction.X < 0 ? a : 1);
343 s16 yend = pos_i.Y + 1 + (camera_direction.Y > 0 ? a : 1);
344 s16 zend = pos_i.Z + (camera_direction.Z > 0 ? a : 1);
345 s16 xend = pos_i.X + (camera_direction.X > 0 ? a : 1);
347 // Prevent signed number overflow
357 for (s16 y = ystart; y <= yend; y++)
358 for (s16 z = zstart; z <= zend; z++)
359 for (s16 x = xstart; x <= xend; x++) {
361 bool is_valid_position;
363 n = map.getNodeNoEx(v3s16(x, y, z), &is_valid_position);
364 if (!is_valid_position)
367 if (!isPointableNode(n, client, liquids_pointable))
370 std::vector<aabb3f> boxes = n.getSelectionBoxes(nodedef);
373 v3f npf = intToFloat(np, BS);
375 for (std::vector<aabb3f>::const_iterator
377 i != boxes.end(); i++) {
382 for (u16 j = 0; j < 6; j++) {
383 v3s16 facedir = g_6dirs[j];
384 aabb3f facebox = box;
389 facebox.MinEdge.X = facebox.MaxEdge.X - d;
390 else if (facedir.X < 0)
391 facebox.MaxEdge.X = facebox.MinEdge.X + d;
392 else if (facedir.Y > 0)
393 facebox.MinEdge.Y = facebox.MaxEdge.Y - d;
394 else if (facedir.Y < 0)
395 facebox.MaxEdge.Y = facebox.MinEdge.Y + d;
396 else if (facedir.Z > 0)
397 facebox.MinEdge.Z = facebox.MaxEdge.Z - d;
398 else if (facedir.Z < 0)
399 facebox.MaxEdge.Z = facebox.MinEdge.Z + d;
401 v3f centerpoint = facebox.getCenter();
402 f32 distance = (centerpoint - camera_position).getLength();
404 if (distance >= mindistance)
407 if (!facebox.intersectsWithLine(shootline))
410 v3s16 np_above = np + facedir;
412 result.type = POINTEDTHING_NODE;
413 result.node_undersurface = np;
414 result.node_abovesurface = np_above;
415 mindistance = distance;
417 hilightboxes.clear();
419 if (!g_settings->getBool("enable_node_highlighting")) {
420 for (std::vector<aabb3f>::const_iterator
422 i2 != boxes.end(); i2++) {
424 box.MinEdge += npf + v3f(-d, -d, -d) - intToFloat(camera_offset, BS);
425 box.MaxEdge += npf + v3f(d, d, d) - intToFloat(camera_offset, BS);
426 hilightboxes.push_back(box);
436 /* Profiler display */
438 void update_profiler_gui(gui::IGUIStaticText *guitext_profiler, FontEngine *fe,
439 u32 show_profiler, u32 show_profiler_max, s32 screen_height)
441 if (show_profiler == 0) {
442 guitext_profiler->setVisible(false);
445 std::ostringstream os(std::ios_base::binary);
446 g_profiler->printPage(os, show_profiler, show_profiler_max);
447 std::wstring text = narrow_to_wide(os.str());
448 guitext_profiler->setText(text.c_str());
449 guitext_profiler->setVisible(true);
451 s32 w = fe->getTextWidth(text.c_str());
456 unsigned text_height = fe->getTextHeight();
458 core::position2di upper_left, lower_right;
461 upper_left.Y = (text_height + 5) * 2;
462 lower_right.X = 12 + w;
463 lower_right.Y = upper_left.Y + (text_height + 1) * MAX_PROFILER_TEXT_ROWS;
465 if (lower_right.Y > screen_height * 2 / 3)
466 lower_right.Y = screen_height * 2 / 3;
468 core::rect<s32> rect(upper_left, lower_right);
470 guitext_profiler->setRelativePosition(rect);
471 guitext_profiler->setVisible(true);
479 Profiler::GraphValues values;
485 Meta(float initial = 0,
486 video::SColor color = video::SColor(255, 255, 255, 255)):
492 std::vector<Piece> m_log;
500 void put(const Profiler::GraphValues &values)
503 piece.values = values;
504 m_log.push_back(piece);
506 while (m_log.size() > m_log_max_size)
507 m_log.erase(m_log.begin());
510 void draw(s32 x_left, s32 y_bottom, video::IVideoDriver *driver,
511 gui::IGUIFont *font) const
513 std::map<std::string, Meta> m_meta;
515 for (std::vector<Piece>::const_iterator k = m_log.begin();
516 k != m_log.end(); k++) {
517 const Piece &piece = *k;
519 for (Profiler::GraphValues::const_iterator i = piece.values.begin();
520 i != piece.values.end(); i++) {
521 const std::string &id = i->first;
522 const float &value = i->second;
523 std::map<std::string, Meta>::iterator j =
526 if (j == m_meta.end()) {
527 m_meta[id] = Meta(value);
531 if (value < j->second.min)
532 j->second.min = value;
534 if (value > j->second.max)
535 j->second.max = value;
540 static const video::SColor usable_colors[] = {
541 video::SColor(255, 255, 100, 100),
542 video::SColor(255, 90, 225, 90),
543 video::SColor(255, 100, 100, 255),
544 video::SColor(255, 255, 150, 50),
545 video::SColor(255, 220, 220, 100)
547 static const u32 usable_colors_count =
548 sizeof(usable_colors) / sizeof(*usable_colors);
549 u32 next_color_i = 0;
551 for (std::map<std::string, Meta>::iterator i = m_meta.begin();
552 i != m_meta.end(); i++) {
553 Meta &meta = i->second;
554 video::SColor color(255, 200, 200, 200);
556 if (next_color_i < usable_colors_count)
557 color = usable_colors[next_color_i++];
563 s32 textx = x_left + m_log_max_size + 15;
564 s32 textx2 = textx + 200 - 15;
567 for (std::map<std::string, Meta>::const_iterator i = m_meta.begin();
568 i != m_meta.end(); i++) {
569 const std::string &id = i->first;
570 const Meta &meta = i->second;
572 s32 y = y_bottom - meta_i * 50;
573 float show_min = meta.min;
574 float show_max = meta.max;
576 if (show_min >= -0.0001 && show_max >= -0.0001) {
577 if (show_min <= show_max * 0.5)
583 snprintf(buf, 10, "%.3g", show_max);
584 font->draw(narrow_to_wide(buf).c_str(),
585 core::rect<s32>(textx, y - graphh,
586 textx2, y - graphh + texth),
588 snprintf(buf, 10, "%.3g", show_min);
589 font->draw(narrow_to_wide(buf).c_str(),
590 core::rect<s32>(textx, y - texth,
593 font->draw(narrow_to_wide(id).c_str(),
594 core::rect<s32>(textx, y - graphh / 2 - texth / 2,
595 textx2, y - graphh / 2 + texth / 2),
598 s32 graph1h = graphh;
599 bool relativegraph = (show_min != 0 && show_min != show_max);
600 float lastscaledvalue = 0.0;
601 bool lastscaledvalue_exists = false;
603 for (std::vector<Piece>::const_iterator j = m_log.begin();
604 j != m_log.end(); j++) {
605 const Piece &piece = *j;
607 bool value_exists = false;
608 Profiler::GraphValues::const_iterator k =
609 piece.values.find(id);
611 if (k != piece.values.end()) {
618 lastscaledvalue_exists = false;
622 float scaledvalue = 1.0;
624 if (show_max != show_min)
625 scaledvalue = (value - show_min) / (show_max - show_min);
627 if (scaledvalue == 1.0 && value == 0) {
629 lastscaledvalue_exists = false;
634 if (lastscaledvalue_exists) {
635 s32 ivalue1 = lastscaledvalue * graph1h;
636 s32 ivalue2 = scaledvalue * graph1h;
637 driver->draw2DLine(v2s32(x - 1, graph1y - ivalue1),
638 v2s32(x, graph1y - ivalue2), meta.color);
641 lastscaledvalue = scaledvalue;
642 lastscaledvalue_exists = true;
644 s32 ivalue = scaledvalue * graph1h;
645 driver->draw2DLine(v2s32(x, graph1y),
646 v2s32(x, graph1y - ivalue), meta.color);
657 class NodeDugEvent: public MtEvent
663 NodeDugEvent(v3s16 p, MapNode n):
667 const char *getType() const
675 ISoundManager *m_sound;
676 INodeDefManager *m_ndef;
678 float m_player_step_timer;
680 SimpleSoundSpec m_player_step_sound;
681 SimpleSoundSpec m_player_leftpunch_sound;
682 SimpleSoundSpec m_player_rightpunch_sound;
684 SoundMaker(ISoundManager *sound, INodeDefManager *ndef):
687 m_player_step_timer(0)
691 void playPlayerStep()
693 if (m_player_step_timer <= 0 && m_player_step_sound.exists()) {
694 m_player_step_timer = 0.03;
695 m_sound->playSound(m_player_step_sound, false);
699 static void viewBobbingStep(MtEvent *e, void *data)
701 SoundMaker *sm = (SoundMaker *)data;
702 sm->playPlayerStep();
705 static void playerRegainGround(MtEvent *e, void *data)
707 SoundMaker *sm = (SoundMaker *)data;
708 sm->playPlayerStep();
711 static void playerJump(MtEvent *e, void *data)
713 //SoundMaker *sm = (SoundMaker*)data;
716 static void cameraPunchLeft(MtEvent *e, void *data)
718 SoundMaker *sm = (SoundMaker *)data;
719 sm->m_sound->playSound(sm->m_player_leftpunch_sound, false);
722 static void cameraPunchRight(MtEvent *e, void *data)
724 SoundMaker *sm = (SoundMaker *)data;
725 sm->m_sound->playSound(sm->m_player_rightpunch_sound, false);
728 static void nodeDug(MtEvent *e, void *data)
730 SoundMaker *sm = (SoundMaker *)data;
731 NodeDugEvent *nde = (NodeDugEvent *)e;
732 sm->m_sound->playSound(sm->m_ndef->get(nde->n).sound_dug, false);
735 static void playerDamage(MtEvent *e, void *data)
737 SoundMaker *sm = (SoundMaker *)data;
738 sm->m_sound->playSound(SimpleSoundSpec("player_damage", 0.5), false);
741 static void playerFallingDamage(MtEvent *e, void *data)
743 SoundMaker *sm = (SoundMaker *)data;
744 sm->m_sound->playSound(SimpleSoundSpec("player_falling_damage", 0.5), false);
747 void registerReceiver(MtEventManager *mgr)
749 mgr->reg("ViewBobbingStep", SoundMaker::viewBobbingStep, this);
750 mgr->reg("PlayerRegainGround", SoundMaker::playerRegainGround, this);
751 mgr->reg("PlayerJump", SoundMaker::playerJump, this);
752 mgr->reg("CameraPunchLeft", SoundMaker::cameraPunchLeft, this);
753 mgr->reg("CameraPunchRight", SoundMaker::cameraPunchRight, this);
754 mgr->reg("NodeDug", SoundMaker::nodeDug, this);
755 mgr->reg("PlayerDamage", SoundMaker::playerDamage, this);
756 mgr->reg("PlayerFallingDamage", SoundMaker::playerFallingDamage, this);
759 void step(float dtime)
761 m_player_step_timer -= dtime;
765 // Locally stored sounds don't need to be preloaded because of this
766 class GameOnDemandSoundFetcher: public OnDemandSoundFetcher
768 std::set<std::string> m_fetched;
770 void fetchSounds(const std::string &name,
771 std::set<std::string> &dst_paths,
772 std::set<std::string> &dst_datas)
774 if (m_fetched.count(name))
777 m_fetched.insert(name);
778 std::string base = porting::path_share + DIR_DELIM + "testsounds";
779 dst_paths.insert(base + DIR_DELIM + name + ".ogg");
780 dst_paths.insert(base + DIR_DELIM + name + ".0.ogg");
781 dst_paths.insert(base + DIR_DELIM + name + ".1.ogg");
782 dst_paths.insert(base + DIR_DELIM + name + ".2.ogg");
783 dst_paths.insert(base + DIR_DELIM + name + ".3.ogg");
784 dst_paths.insert(base + DIR_DELIM + name + ".4.ogg");
785 dst_paths.insert(base + DIR_DELIM + name + ".5.ogg");
786 dst_paths.insert(base + DIR_DELIM + name + ".6.ogg");
787 dst_paths.insert(base + DIR_DELIM + name + ".7.ogg");
788 dst_paths.insert(base + DIR_DELIM + name + ".8.ogg");
789 dst_paths.insert(base + DIR_DELIM + name + ".9.ogg");
793 class GameGlobalShaderConstantSetter : public IShaderConstantSetter
796 bool *m_force_fog_off;
802 void onSettingsChange(const std::string &name)
804 if (name == "enable_fog")
805 m_fogEnabled = g_settings->getBool("enable_fog");
808 static void SettingsCallback(const std::string name, void *userdata)
810 reinterpret_cast<GameGlobalShaderConstantSetter*>(userdata)->onSettingsChange(name);
813 GameGlobalShaderConstantSetter(Sky *sky, bool *force_fog_off,
814 f32 *fog_range, Client *client) :
816 m_force_fog_off(force_fog_off),
817 m_fog_range(fog_range),
820 g_settings->registerChangedCallback("enable_fog", SettingsCallback, this);
821 m_fogEnabled = g_settings->getBool("enable_fog");
824 ~GameGlobalShaderConstantSetter()
826 g_settings->deregisterChangedCallback("enable_fog", SettingsCallback, this);
829 virtual void onSetConstants(video::IMaterialRendererServices *services,
836 video::SColor bgcolor = m_sky->getBgColor();
837 video::SColorf bgcolorf(bgcolor);
838 float bgcolorfa[4] = {
844 services->setPixelShaderConstant("skyBgColor", bgcolorfa, 4);
847 float fog_distance = 10000 * BS;
849 if (m_fogEnabled && !*m_force_fog_off)
850 fog_distance = *m_fog_range;
852 services->setPixelShaderConstant("fogDistance", &fog_distance, 1);
855 u32 daynight_ratio = m_client->getEnv().getDayNightRatio();
856 float daynight_ratio_f = (float)daynight_ratio / 1000.0;
857 services->setPixelShaderConstant("dayNightRatio", &daynight_ratio_f, 1);
859 u32 animation_timer = porting::getTimeMs() % 100000;
860 float animation_timer_f = (float)animation_timer / 100000.0;
861 services->setPixelShaderConstant("animationTimer", &animation_timer_f, 1);
862 services->setVertexShaderConstant("animationTimer", &animation_timer_f, 1);
864 LocalPlayer *player = m_client->getEnv().getLocalPlayer();
865 v3f eye_position = player->getEyePosition();
866 services->setPixelShaderConstant("eyePosition", (irr::f32 *)&eye_position, 3);
867 services->setVertexShaderConstant("eyePosition", (irr::f32 *)&eye_position, 3);
869 // Uniform sampler layers
873 // before 1.8 there isn't a "integer interface", only float
874 #if (IRRLICHT_VERSION_MAJOR == 1 && IRRLICHT_VERSION_MINOR < 8)
875 services->setPixelShaderConstant("baseTexture" , (irr::f32 *)&layer0, 1);
876 services->setPixelShaderConstant("normalTexture" , (irr::f32 *)&layer1, 1);
877 services->setPixelShaderConstant("useNormalmap" , (irr::f32 *)&layer2, 1);
879 services->setPixelShaderConstant("baseTexture" , (irr::s32 *)&layer0, 1);
880 services->setPixelShaderConstant("normalTexture" , (irr::s32 *)&layer1, 1);
881 services->setPixelShaderConstant("useNormalmap" , (irr::s32 *)&layer2, 1);
886 bool nodePlacementPrediction(Client &client,
887 const ItemDefinition &playeritem_def, v3s16 nodepos, v3s16 neighbourpos)
889 std::string prediction = playeritem_def.node_placement_prediction;
890 INodeDefManager *nodedef = client.ndef();
891 ClientMap &map = client.getEnv().getClientMap();
893 bool is_valid_position;
895 node = map.getNodeNoEx(nodepos, &is_valid_position);
896 if (!is_valid_position)
899 if (prediction != "" && !nodedef->get(node).rightclickable) {
900 verbosestream << "Node placement prediction for "
901 << playeritem_def.name << " is "
902 << prediction << std::endl;
903 v3s16 p = neighbourpos;
905 // Place inside node itself if buildable_to
906 MapNode n_under = map.getNodeNoEx(nodepos, &is_valid_position);
907 if (is_valid_position)
909 if (nodedef->get(n_under).buildable_to)
912 node = map.getNodeNoEx(p, &is_valid_position);
913 if (is_valid_position &&!nodedef->get(node).buildable_to)
918 // Find id of predicted node
920 bool found = nodedef->getId(prediction, id);
923 errorstream << "Node placement prediction failed for "
924 << playeritem_def.name << " (places "
926 << ") - Name not known" << std::endl;
930 // Predict param2 for facedir and wallmounted nodes
933 if (nodedef->get(id).param_type_2 == CPT2_WALLMOUNTED) {
934 v3s16 dir = nodepos - neighbourpos;
936 if (abs(dir.Y) > MYMAX(abs(dir.X), abs(dir.Z))) {
937 param2 = dir.Y < 0 ? 1 : 0;
938 } else if (abs(dir.X) > abs(dir.Z)) {
939 param2 = dir.X < 0 ? 3 : 2;
941 param2 = dir.Z < 0 ? 5 : 4;
945 if (nodedef->get(id).param_type_2 == CPT2_FACEDIR) {
946 v3s16 dir = nodepos - floatToInt(client.getEnv().getLocalPlayer()->getPosition(), BS);
948 if (abs(dir.X) > abs(dir.Z)) {
949 param2 = dir.X < 0 ? 3 : 1;
951 param2 = dir.Z < 0 ? 2 : 0;
957 //Check attachment if node is in group attached_node
958 if (((ItemGroupList) nodedef->get(id).groups)["attached_node"] != 0) {
959 static v3s16 wallmounted_dirs[8] = {
969 if (nodedef->get(id).param_type_2 == CPT2_WALLMOUNTED)
970 pp = p + wallmounted_dirs[param2];
972 pp = p + v3s16(0, -1, 0);
974 if (!nodedef->get(map.getNodeNoEx(pp)).walkable)
978 // Add node to client map
979 MapNode n(id, 0, param2);
982 LocalPlayer *player = client.getEnv().getLocalPlayer();
984 // Dont place node when player would be inside new node
985 // NOTE: This is to be eventually implemented by a mod as client-side Lua
986 if (!nodedef->get(n).walkable ||
987 g_settings->getBool("enable_build_where_you_stand") ||
988 (client.checkPrivilege("noclip") && g_settings->getBool("noclip")) ||
989 (nodedef->get(n).walkable &&
990 neighbourpos != player->getStandingNodePos() + v3s16(0, 1, 0) &&
991 neighbourpos != player->getStandingNodePos() + v3s16(0, 2, 0))) {
993 // This triggers the required mesh update too
994 client.addNode(p, n);
997 } catch (InvalidPositionException &e) {
998 errorstream << "Node placement prediction failed for "
999 << playeritem_def.name << " (places "
1001 << ") - Position not loaded" << std::endl;
1008 static inline void create_formspec_menu(GUIFormSpecMenu **cur_formspec,
1009 InventoryManager *invmgr, IGameDef *gamedef,
1010 IWritableTextureSource *tsrc, IrrlichtDevice *device,
1011 IFormSource *fs_src, TextDest *txt_dest, Client *client)
1014 if (*cur_formspec == 0) {
1015 *cur_formspec = new GUIFormSpecMenu(device, guiroot, -1, &g_menumgr,
1016 invmgr, gamedef, tsrc, fs_src, txt_dest, client);
1017 (*cur_formspec)->doPause = false;
1020 Caution: do not call (*cur_formspec)->drop() here --
1021 the reference might outlive the menu, so we will
1022 periodically check if *cur_formspec is the only
1023 remaining reference (i.e. the menu was removed)
1024 and delete it in that case.
1028 (*cur_formspec)->setFormSource(fs_src);
1029 (*cur_formspec)->setTextDest(txt_dest);
1034 #define SIZE_TAG "size[11,5.5]"
1036 #define SIZE_TAG "size[11,5.5,true]" // Fixed size on desktop
1039 static void show_chat_menu(GUIFormSpecMenu **cur_formspec,
1040 InventoryManager *invmgr, IGameDef *gamedef,
1041 IWritableTextureSource *tsrc, IrrlichtDevice *device,
1042 Client *client, std::string text)
1044 std::string formspec =
1045 FORMSPEC_VERSION_STRING
1047 "field[3,2.35;6,0.5;f_text;;" + text + "]"
1048 "button_exit[4,3;3,0.5;btn_send;" + wide_to_narrow(wstrgettext("Proceed")) + "]"
1052 /* Note: FormspecFormSource and LocalFormspecHandler
1053 * are deleted by guiFormSpecMenu */
1054 FormspecFormSource *fs_src = new FormspecFormSource(formspec);
1055 LocalFormspecHandler *txt_dst = new LocalFormspecHandler("MT_CHAT_MENU", client);
1057 create_formspec_menu(cur_formspec, invmgr, gamedef, tsrc, device, fs_src, txt_dst, NULL);
1060 static void show_deathscreen(GUIFormSpecMenu **cur_formspec,
1061 InventoryManager *invmgr, IGameDef *gamedef,
1062 IWritableTextureSource *tsrc, IrrlichtDevice *device, Client *client)
1064 std::string formspec =
1065 std::string(FORMSPEC_VERSION_STRING) +
1067 "bgcolor[#320000b4;true]"
1068 "label[4.85,1.35;" + gettext("You died.") + "]"
1069 "button_exit[4,3;3,0.5;btn_respawn;" + gettext("Respawn") + "]"
1073 /* Note: FormspecFormSource and LocalFormspecHandler
1074 * are deleted by guiFormSpecMenu */
1075 FormspecFormSource *fs_src = new FormspecFormSource(formspec);
1076 LocalFormspecHandler *txt_dst = new LocalFormspecHandler("MT_DEATH_SCREEN", client);
1078 create_formspec_menu(cur_formspec, invmgr, gamedef, tsrc, device, fs_src, txt_dst, NULL);
1081 /******************************************************************************/
1082 static void show_pause_menu(GUIFormSpecMenu **cur_formspec,
1083 InventoryManager *invmgr, IGameDef *gamedef,
1084 IWritableTextureSource *tsrc, IrrlichtDevice *device,
1085 bool singleplayermode)
1088 std::string control_text = wide_to_narrow(wstrgettext("Default Controls:\n"
1089 "No menu visible:\n"
1090 "- single tap: button activate\n"
1091 "- double tap: place/use\n"
1092 "- slide finger: look around\n"
1093 "Menu/Inventory visible:\n"
1094 "- double tap (outside):\n"
1096 "- touch stack, touch slot:\n"
1098 "- touch&drag, tap 2nd finger\n"
1099 " --> place single item to slot\n"
1102 std::string control_text = wide_to_narrow(wstrgettext("Default Controls:\n"
1104 "- Space: jump/climb\n"
1105 "- Shift: sneak/go down\n"
1108 "- Mouse: turn/look\n"
1109 "- Mouse left: dig/punch\n"
1110 "- Mouse right: place/use\n"
1111 "- Mouse wheel: select item\n"
1116 float ypos = singleplayermode ? 0.5 : 0.1;
1117 std::ostringstream os;
1119 os << FORMSPEC_VERSION_STRING << SIZE_TAG
1120 << "button_exit[4," << (ypos++) << ";3,0.5;btn_continue;"
1121 << wide_to_narrow(wstrgettext("Continue")) << "]";
1123 if (!singleplayermode) {
1124 os << "button_exit[4," << (ypos++) << ";3,0.5;btn_change_password;"
1125 << wide_to_narrow(wstrgettext("Change Password")) << "]";
1129 os << "button_exit[4," << (ypos++) << ";3,0.5;btn_sound;"
1130 << wide_to_narrow(wstrgettext("Sound Volume")) << "]";
1131 os << "button_exit[4," << (ypos++) << ";3,0.5;btn_key_config;"
1132 << wide_to_narrow(wstrgettext("Change Keys")) << "]";
1134 os << "button_exit[4," << (ypos++) << ";3,0.5;btn_exit_menu;"
1135 << wide_to_narrow(wstrgettext("Exit to Menu")) << "]";
1136 os << "button_exit[4," << (ypos++) << ";3,0.5;btn_exit_os;"
1137 << wide_to_narrow(wstrgettext("Exit to OS")) << "]"
1138 << "textarea[7.5,0.25;3.9,6.25;;" << control_text << ";]"
1139 << "textarea[0.4,0.25;3.5,6;;" << PROJECT_NAME_C "\n"
1140 << g_build_info << "\n"
1141 << "path_user = " << wrap_rows(porting::path_user, 20)
1145 /* Note: FormspecFormSource and LocalFormspecHandler *
1146 * are deleted by guiFormSpecMenu */
1147 FormspecFormSource *fs_src = new FormspecFormSource(os.str());
1148 LocalFormspecHandler *txt_dst = new LocalFormspecHandler("MT_PAUSE_MENU");
1150 create_formspec_menu(cur_formspec, invmgr, gamedef, tsrc, device, fs_src, txt_dst, NULL);
1151 std::string con("btn_continue");
1152 (*cur_formspec)->setFocus(con);
1153 (*cur_formspec)->doPause = true;
1156 /******************************************************************************/
1157 static void updateChat(Client &client, f32 dtime, bool show_debug,
1158 const v2u32 &screensize, bool show_chat, u32 show_profiler,
1159 ChatBackend &chat_backend, gui::IGUIStaticText *guitext_chat)
1161 // Add chat log output for errors to be shown in chat
1162 static LogOutputBuffer chat_log_error_buf(LMT_ERROR);
1164 // Get new messages from error log buffer
1165 while (!chat_log_error_buf.empty()) {
1166 chat_backend.addMessage(L"", narrow_to_wide(chat_log_error_buf.get()));
1169 // Get new messages from client
1170 std::wstring message;
1172 while (client.getChatMessage(message)) {
1173 chat_backend.addUnparsedMessage(message);
1176 // Remove old messages
1177 chat_backend.step(dtime);
1179 // Display all messages in a static text element
1180 unsigned int recent_chat_count = chat_backend.getRecentBuffer().getLineCount();
1181 std::wstring recent_chat = chat_backend.getRecentChat();
1182 unsigned int line_height = g_fontengine->getLineHeight();
1184 guitext_chat->setText(recent_chat.c_str());
1186 // Update gui element size and position
1187 s32 chat_y = 5 + line_height;
1190 chat_y += line_height;
1192 // first pass to calculate height of text to be set
1193 s32 width = std::min(g_fontengine->getTextWidth(recent_chat) + 10,
1194 porting::getWindowSize().X - 20);
1195 core::rect<s32> rect(10, chat_y, width, chat_y + porting::getWindowSize().Y);
1196 guitext_chat->setRelativePosition(rect);
1198 //now use real height of text and adjust rect according to this size
1199 rect = core::rect<s32>(10, chat_y, width,
1200 chat_y + guitext_chat->getTextHeight());
1203 guitext_chat->setRelativePosition(rect);
1204 // Don't show chat if disabled or empty or profiler is enabled
1205 guitext_chat->setVisible(
1206 show_chat && recent_chat_count != 0 && !show_profiler);
1210 /****************************************************************************
1211 Fast key cache for main game loop
1212 ****************************************************************************/
1214 /* This is faster than using getKeySetting with the tradeoff that functions
1215 * using it must make sure that it's initialised before using it and there is
1216 * no error handling (for example bounds checking). This is really intended for
1217 * use only in the main running loop of the client (the_game()) where the faster
1218 * (up to 10x faster) key lookup is an asset. Other parts of the codebase
1219 * (e.g. formspecs) should continue using getKeySetting().
1223 KeyCache() { populate(); }
1237 KEYMAP_ID_INVENTORY,
1244 KEYMAP_ID_CINEMATIC,
1245 KEYMAP_ID_SCREENSHOT,
1246 KEYMAP_ID_TOGGLE_HUD,
1247 KEYMAP_ID_TOGGLE_CHAT,
1248 KEYMAP_ID_TOGGLE_FORCE_FOG_OFF,
1249 KEYMAP_ID_TOGGLE_UPDATE_CAMERA,
1250 KEYMAP_ID_TOGGLE_DEBUG,
1251 KEYMAP_ID_TOGGLE_PROFILER,
1252 KEYMAP_ID_CAMERA_MODE,
1253 KEYMAP_ID_INCREASE_VIEWING_RANGE,
1254 KEYMAP_ID_DECREASE_VIEWING_RANGE,
1255 KEYMAP_ID_RANGESELECT,
1257 KEYMAP_ID_QUICKTUNE_NEXT,
1258 KEYMAP_ID_QUICKTUNE_PREV,
1259 KEYMAP_ID_QUICKTUNE_INC,
1260 KEYMAP_ID_QUICKTUNE_DEC,
1262 KEYMAP_ID_DEBUG_STACKS,
1264 // Fake keycode for array size and internal checks
1265 KEYMAP_INTERNAL_ENUM_COUNT
1272 KeyPress key[KEYMAP_INTERNAL_ENUM_COUNT];
1275 void KeyCache::populate()
1277 key[KEYMAP_ID_FORWARD] = getKeySetting("keymap_forward");
1278 key[KEYMAP_ID_BACKWARD] = getKeySetting("keymap_backward");
1279 key[KEYMAP_ID_LEFT] = getKeySetting("keymap_left");
1280 key[KEYMAP_ID_RIGHT] = getKeySetting("keymap_right");
1281 key[KEYMAP_ID_JUMP] = getKeySetting("keymap_jump");
1282 key[KEYMAP_ID_SPECIAL1] = getKeySetting("keymap_special1");
1283 key[KEYMAP_ID_SNEAK] = getKeySetting("keymap_sneak");
1285 key[KEYMAP_ID_DROP] = getKeySetting("keymap_drop");
1286 key[KEYMAP_ID_INVENTORY] = getKeySetting("keymap_inventory");
1287 key[KEYMAP_ID_CHAT] = getKeySetting("keymap_chat");
1288 key[KEYMAP_ID_CMD] = getKeySetting("keymap_cmd");
1289 key[KEYMAP_ID_CONSOLE] = getKeySetting("keymap_console");
1290 key[KEYMAP_ID_FREEMOVE] = getKeySetting("keymap_freemove");
1291 key[KEYMAP_ID_FASTMOVE] = getKeySetting("keymap_fastmove");
1292 key[KEYMAP_ID_NOCLIP] = getKeySetting("keymap_noclip");
1293 key[KEYMAP_ID_CINEMATIC] = getKeySetting("keymap_cinematic");
1294 key[KEYMAP_ID_SCREENSHOT] = getKeySetting("keymap_screenshot");
1295 key[KEYMAP_ID_TOGGLE_HUD] = getKeySetting("keymap_toggle_hud");
1296 key[KEYMAP_ID_TOGGLE_CHAT] = getKeySetting("keymap_toggle_chat");
1297 key[KEYMAP_ID_TOGGLE_FORCE_FOG_OFF]
1298 = getKeySetting("keymap_toggle_force_fog_off");
1299 key[KEYMAP_ID_TOGGLE_UPDATE_CAMERA]
1300 = getKeySetting("keymap_toggle_update_camera");
1301 key[KEYMAP_ID_TOGGLE_DEBUG]
1302 = getKeySetting("keymap_toggle_debug");
1303 key[KEYMAP_ID_TOGGLE_PROFILER]
1304 = getKeySetting("keymap_toggle_profiler");
1305 key[KEYMAP_ID_CAMERA_MODE]
1306 = getKeySetting("keymap_camera_mode");
1307 key[KEYMAP_ID_INCREASE_VIEWING_RANGE]
1308 = getKeySetting("keymap_increase_viewing_range_min");
1309 key[KEYMAP_ID_DECREASE_VIEWING_RANGE]
1310 = getKeySetting("keymap_decrease_viewing_range_min");
1311 key[KEYMAP_ID_RANGESELECT]
1312 = getKeySetting("keymap_rangeselect");
1314 key[KEYMAP_ID_QUICKTUNE_NEXT] = getKeySetting("keymap_quicktune_next");
1315 key[KEYMAP_ID_QUICKTUNE_PREV] = getKeySetting("keymap_quicktune_prev");
1316 key[KEYMAP_ID_QUICKTUNE_INC] = getKeySetting("keymap_quicktune_inc");
1317 key[KEYMAP_ID_QUICKTUNE_DEC] = getKeySetting("keymap_quicktune_dec");
1319 key[KEYMAP_ID_DEBUG_STACKS] = getKeySetting("keymap_print_debug_stacks");
1323 /****************************************************************************
1325 ****************************************************************************/
1327 const float object_hit_delay = 0.2;
1330 u32 last_time, busy_time, sleep_time;
1334 /* The reason the following structs are not anonymous structs within the
1335 * class is that they are not used by the majority of member functions and
1336 * many functions that do require objects of thse types do not modify them
1337 * (so they can be passed as a const qualified parameter)
1339 struct CameraOrientation {
1340 f32 camera_yaw; // "right/left"
1341 f32 camera_pitch; // "up/down"
1344 struct GameRunData {
1347 PointedThing pointed_old;
1351 bool update_wielded_item_trigger;
1352 bool reset_jump_timer;
1353 float nodig_delay_timer;
1355 float dig_time_complete;
1356 float repeat_rightclick_timer;
1357 float object_hit_delay_timer;
1358 float time_from_last_punch;
1359 ClientActiveObject *selected_object;
1363 float update_draw_list_timer;
1364 float statustext_time;
1368 v3f update_draw_list_last_cam_dir;
1370 u32 profiler_current_page;
1371 u32 profiler_max_page; // Number of pages
1374 float time_of_day_smooth;
1378 f32 max, min, avg, counter, max_sample, min_sample, max_fraction;
1386 Jitter dtime_jitter, busy_time_jitter;
1389 /* Flags that can, or may, change during main game loop
1391 struct VolatileRunFlags {
1397 bool show_profiler_graph;
1398 bool disable_camera_update;
1399 bool first_loop_after_window_activation;
1400 bool camera_offset_changed;
1404 /****************************************************************************
1406 ****************************************************************************/
1408 /* This is not intended to be a public class. If a public class becomes
1409 * desirable then it may be better to create another 'wrapper' class that
1410 * hides most of the stuff in this class (nothing in this class is required
1411 * by any other file) but exposes the public methods/data only.
1419 bool startup(bool *kill,
1421 InputHandler *input,
1422 IrrlichtDevice *device,
1423 const std::string &map_dir,
1424 const std::string &playername,
1425 const std::string &password,
1426 // If address is "", local server is used and address is updated
1427 std::string *address,
1429 std::string &error_message,
1430 ChatBackend *chat_backend,
1431 const SubgameSpec &gamespec, // Used for local game
1432 bool simple_singleplayer_mode);
1439 void extendedResourceCleanup();
1441 // Basic initialisation
1442 bool init(const std::string &map_dir, std::string *address,
1444 const SubgameSpec &gamespec);
1446 bool createSingleplayerServer(const std::string map_dir,
1447 const SubgameSpec &gamespec, u16 port, std::string *address);
1450 bool createClient(const std::string &playername,
1451 const std::string &password, std::string *address, u16 port);
1454 // Client connection
1455 bool connectToServer(const std::string &playername,
1456 const std::string &password, std::string *address, u16 port,
1457 bool *connect_ok, bool *aborted);
1458 bool getServerContent(bool *aborted);
1462 void updateInteractTimers(GameRunData *runData, f32 dtime);
1463 bool checkConnection();
1464 bool handleCallbacks();
1465 void processQueues();
1466 void updateProfilers(const GameRunData &runData, const RunStats &stats,
1467 const FpsControl &draw_times, f32 dtime);
1468 void addProfilerGraphs(const RunStats &stats, const FpsControl &draw_times,
1470 void updateStats(RunStats *stats, const FpsControl &draw_times, f32 dtime);
1472 void processUserInput(VolatileRunFlags *flags, GameRunData *runData,
1474 void processKeyboardInput(VolatileRunFlags *flags,
1475 float *statustext_time,
1477 bool *reset_jump_timer,
1478 u32 *profiler_current_page,
1479 u32 profiler_max_page);
1480 void processItemSelection(u16 *new_playeritem);
1482 void dropSelectedItem();
1483 void openInventory();
1485 void toggleFreeMove(float *statustext_time);
1486 void toggleFreeMoveAlt(float *statustext_time, float *jump_timer);
1487 void toggleFast(float *statustext_time);
1488 void toggleNoClip(float *statustext_time);
1489 void toggleCinematic(float *statustext_time);
1491 void toggleChat(float *statustext_time, bool *flag);
1492 void toggleHud(float *statustext_time, bool *flag);
1493 void toggleFog(float *statustext_time, bool *flag);
1494 void toggleDebug(float *statustext_time, bool *show_debug,
1495 bool *show_profiler_graph);
1496 void toggleUpdateCamera(float *statustext_time, bool *flag);
1497 void toggleProfiler(float *statustext_time, u32 *profiler_current_page,
1498 u32 profiler_max_page);
1500 void increaseViewRange(float *statustext_time);
1501 void decreaseViewRange(float *statustext_time);
1502 void toggleFullViewRange(float *statustext_time);
1504 void updateCameraDirection(CameraOrientation *cam, VolatileRunFlags *flags);
1505 void updateCameraOrientation(CameraOrientation *cam,
1506 const VolatileRunFlags &flags);
1507 void updatePlayerControl(const CameraOrientation &cam);
1508 void step(f32 *dtime);
1509 void processClientEvents(CameraOrientation *cam, float *damage_flash);
1510 void updateCamera(VolatileRunFlags *flags, u32 busy_time, f32 dtime,
1511 float time_from_last_punch);
1512 void updateSound(f32 dtime);
1513 void processPlayerInteraction(std::vector<aabb3f> &highlight_boxes,
1514 GameRunData *runData, f32 dtime, bool show_hud,
1516 void handlePointingAtNode(GameRunData *runData,
1517 const PointedThing &pointed, const ItemDefinition &playeritem_def,
1518 const ToolCapabilities &playeritem_toolcap, f32 dtime);
1519 void handlePointingAtObject(GameRunData *runData,
1520 const PointedThing &pointed, const ItemStack &playeritem,
1521 const v3f &player_position, bool show_debug);
1522 void handleDigging(GameRunData *runData, const PointedThing &pointed,
1523 const v3s16 &nodepos, const ToolCapabilities &playeritem_toolcap,
1525 void updateFrame(std::vector<aabb3f> &highlight_boxes, ProfilerGraph *graph,
1526 RunStats *stats, GameRunData *runData,
1527 f32 dtime, const VolatileRunFlags &flags, const CameraOrientation &cam);
1528 void updateGui(float *statustext_time, const RunStats &stats,
1529 const GameRunData& runData, f32 dtime, const VolatileRunFlags &flags,
1530 const CameraOrientation &cam);
1531 void updateProfilerGraphs(ProfilerGraph *graph);
1534 void limitFps(FpsControl *fps_timings, f32 *dtime);
1536 void showOverlayMessage(const wchar_t *msg, float dtime, int percent,
1537 bool draw_clouds = true);
1540 InputHandler *input;
1545 IWritableTextureSource *texture_src;
1546 IWritableShaderSource *shader_src;
1548 // When created, these will be filled with data received from the server
1549 IWritableItemDefManager *itemdef_manager;
1550 IWritableNodeDefManager *nodedef_manager;
1552 GameOnDemandSoundFetcher soundfetcher; // useful when testing
1553 ISoundManager *sound;
1554 bool sound_is_dummy;
1555 SoundMaker *soundmaker;
1557 ChatBackend *chat_backend;
1559 GUIFormSpecMenu *current_formspec;
1561 EventManager *eventmgr;
1562 QuicktuneShortcutter *quicktune;
1564 GUIChatConsole *gui_chat_console; // Free using ->Drop()
1565 MapDrawControl *draw_control;
1567 Clouds *clouds; // Free using ->Drop()
1568 Sky *sky; // Free using ->Drop()
1569 Inventory *local_inventory;
1573 This class does take ownership/responsibily for cleaning up etc of any of
1574 these items (e.g. device)
1576 IrrlichtDevice *device;
1577 video::IVideoDriver *driver;
1578 scene::ISceneManager *smgr;
1580 std::string *error_message;
1581 IGameDef *gamedef; // Convenience (same as *client)
1582 scene::ISceneNode *skybox;
1585 bool simple_singleplayer_mode;
1588 /* Pre-calculated values
1590 int crack_animation_length;
1594 gui::IGUIStaticText *guitext; // First line of debug text
1595 gui::IGUIStaticText *guitext2; // Second line of debug text
1596 gui::IGUIStaticText *guitext_info; // At the middle of the screen
1597 gui::IGUIStaticText *guitext_status;
1598 gui::IGUIStaticText *guitext_chat; // Chat text
1599 gui::IGUIStaticText *guitext_profiler; // Profiler text
1601 std::wstring infotext;
1602 std::wstring statustext;
1606 IntervalLimiter profiler_interval;
1608 /* TODO: Add a callback function so these can be updated when a setting
1609 * changes. At this point in time it doesn't matter (e.g. /set
1610 * is documented to change server settings only)
1612 * TODO: Local caching of settings is not optimal and should at some stage
1613 * be updated to use a global settings object for getting thse values
1614 * (as opposed to the this local caching). This can be addressed in
1617 bool m_cache_doubletap_jump;
1618 bool m_cache_enable_node_highlighting;
1619 bool m_cache_enable_clouds;
1620 bool m_cache_enable_particles;
1621 bool m_cache_enable_fog;
1622 f32 m_cache_mouse_sensitivity;
1623 f32 m_repeat_right_click_time;
1626 bool m_cache_hold_aux1;
1636 itemdef_manager(NULL),
1637 nodedef_manager(NULL),
1639 sound_is_dummy(false),
1642 current_formspec(NULL),
1645 gui_chat_console(NULL),
1650 local_inventory(NULL),
1653 m_cache_doubletap_jump = g_settings->getBool("doubletap_jump");
1654 m_cache_enable_node_highlighting = g_settings->getBool("enable_node_highlighting");
1655 m_cache_enable_clouds = g_settings->getBool("enable_clouds");
1656 m_cache_enable_particles = g_settings->getBool("enable_particles");
1657 m_cache_enable_fog = g_settings->getBool("enable_fog");
1658 m_cache_mouse_sensitivity = g_settings->getFloat("mouse_sensitivity");
1659 m_repeat_right_click_time = g_settings->getFloat("repeat_rightclick_time");
1661 m_cache_mouse_sensitivity = rangelim(m_cache_mouse_sensitivity, 0.001, 100.0);
1664 m_cache_hold_aux1 = false; // This is initialised properly later
1671 /****************************************************************************
1673 ****************************************************************************/
1679 if (!sound_is_dummy)
1682 delete server; // deleted first to stop all server threads
1685 delete local_inventory;
1691 delete nodedef_manager;
1692 delete itemdef_manager;
1693 delete draw_control;
1695 extendedResourceCleanup();
1698 bool Game::startup(bool *kill,
1700 InputHandler *input,
1701 IrrlichtDevice *device,
1702 const std::string &map_dir,
1703 const std::string &playername,
1704 const std::string &password,
1705 std::string *address, // can change if simple_singleplayer_mode
1707 std::string &error_message,
1708 ChatBackend *chat_backend,
1709 const SubgameSpec &gamespec,
1710 bool simple_singleplayer_mode)
1713 this->device = device;
1715 this->error_message = &error_message;
1716 this->random_input = random_input;
1717 this->input = input;
1718 this->chat_backend = chat_backend;
1719 this->simple_singleplayer_mode = simple_singleplayer_mode;
1721 driver = device->getVideoDriver();
1722 smgr = device->getSceneManager();
1724 smgr->getParameters()->setAttribute(scene::OBJ_LOADER_IGNORE_MATERIAL_FILES, true);
1726 if (!init(map_dir, address, port, gamespec))
1729 if (!createClient(playername, password, address, port))
1738 ProfilerGraph graph;
1739 RunStats stats = { 0 };
1740 CameraOrientation cam_view_target = { 0 };
1741 CameraOrientation cam_view = { 0 };
1742 GameRunData runData = { 0 };
1743 FpsControl draw_times = { 0 };
1744 VolatileRunFlags flags = { 0 };
1745 f32 dtime; // in seconds
1747 runData.time_from_last_punch = 10.0;
1748 runData.profiler_max_page = 3;
1749 runData.update_wielded_item_trigger = true;
1751 flags.show_chat = true;
1752 flags.show_hud = true;
1753 flags.show_debug = g_settings->getBool("show_debug");
1754 flags.invert_mouse = g_settings->getBool("invert_mouse");
1755 flags.first_loop_after_window_activation = true;
1757 /* Clear the profiler */
1758 Profiler::GraphValues dummyvalues;
1759 g_profiler->graphGet(dummyvalues);
1761 draw_times.last_time = device->getTimer()->getTime();
1763 shader_src->addGlobalConstantSetter(new GameGlobalShaderConstantSetter(
1765 &flags.force_fog_off,
1769 std::vector<aabb3f> highlight_boxes;
1771 set_light_table(g_settings->getFloat("display_gamma"));
1774 m_cache_hold_aux1 = g_settings->getBool("fast_move")
1775 && client->checkPrivilege("fast");
1778 while (device->run() && !(*kill || g_gamecallback->shutdown_requested)) {
1780 /* Must be called immediately after a device->run() call because it
1781 * uses device->getTimer()->getTime()
1783 limitFps(&draw_times, &dtime);
1785 updateStats(&stats, draw_times, dtime);
1786 updateInteractTimers(&runData, dtime);
1788 if (!checkConnection())
1790 if (!handleCallbacks())
1796 hud->resizeHotbar();
1798 updateProfilers(runData, stats, draw_times, dtime);
1799 processUserInput(&flags, &runData, dtime);
1800 // Update camera before player movement to avoid camera lag of one frame
1801 updateCameraDirection(&cam_view_target, &flags);
1802 float cam_smoothing = 0;
1803 if (g_settings->getBool("cinematic"))
1804 cam_smoothing = 1 - g_settings->getFloat("cinematic_camera_smoothing");
1806 cam_smoothing = 1 - g_settings->getFloat("camera_smoothing");
1807 cam_smoothing = rangelim(cam_smoothing, 0.01f, 1.0f);
1808 cam_view.camera_yaw += (cam_view_target.camera_yaw -
1809 cam_view.camera_yaw) * cam_smoothing;
1810 cam_view.camera_pitch += (cam_view_target.camera_pitch -
1811 cam_view.camera_pitch) * cam_smoothing;
1812 updatePlayerControl(cam_view);
1814 processClientEvents(&cam_view_target, &runData.damage_flash);
1815 updateCamera(&flags, draw_times.busy_time, dtime,
1816 runData.time_from_last_punch);
1818 processPlayerInteraction(highlight_boxes, &runData, dtime,
1819 flags.show_hud, flags.show_debug);
1820 updateFrame(highlight_boxes, &graph, &stats, &runData, dtime,
1822 updateProfilerGraphs(&graph);
1827 void Game::shutdown()
1829 showOverlayMessage(wgettext("Shutting down..."), 0, 0, false);
1834 if (gui_chat_console)
1835 gui_chat_console->drop();
1841 while (g_menumgr.menuCount() > 0) {
1842 g_menumgr.m_stack.front()->setVisible(false);
1843 g_menumgr.deletingMenu(g_menumgr.m_stack.front());
1846 if (current_formspec) {
1847 current_formspec->drop();
1848 current_formspec = NULL;
1851 chat_backend->addMessage(L"", L"# Disconnected.");
1852 chat_backend->addMessage(L"", L"");
1856 while (!client->isShutdown()) {
1857 assert(texture_src != NULL);
1858 assert(shader_src != NULL);
1859 texture_src->processQueue();
1860 shader_src->processQueue();
1867 /****************************************************************************/
1868 /****************************************************************************
1870 ****************************************************************************/
1871 /****************************************************************************/
1874 const std::string &map_dir,
1875 std::string *address,
1877 const SubgameSpec &gamespec)
1879 showOverlayMessage(wgettext("Loading..."), 0, 0);
1881 texture_src = createTextureSource(device);
1882 shader_src = createShaderSource(device);
1884 itemdef_manager = createItemDefManager();
1885 nodedef_manager = createNodeDefManager();
1887 eventmgr = new EventManager();
1888 quicktune = new QuicktuneShortcutter();
1890 if (!(texture_src && shader_src && itemdef_manager && nodedef_manager
1891 && eventmgr && quicktune))
1897 // Create a server if not connecting to an existing one
1898 if (*address == "") {
1899 if (!createSingleplayerServer(map_dir, gamespec, port, address))
1906 bool Game::initSound()
1909 if (g_settings->getBool("enable_sound")) {
1910 infostream << "Attempting to use OpenAL audio" << std::endl;
1911 sound = createOpenALSoundManager(&soundfetcher);
1913 infostream << "Failed to initialize OpenAL audio" << std::endl;
1915 infostream << "Sound disabled." << std::endl;
1919 infostream << "Using dummy audio." << std::endl;
1920 sound = &dummySoundManager;
1921 sound_is_dummy = true;
1924 soundmaker = new SoundMaker(sound, nodedef_manager);
1928 soundmaker->registerReceiver(eventmgr);
1933 bool Game::createSingleplayerServer(const std::string map_dir,
1934 const SubgameSpec &gamespec, u16 port, std::string *address)
1936 showOverlayMessage(wgettext("Creating server..."), 0, 5);
1938 std::string bind_str = g_settings->get("bind_address");
1939 Address bind_addr(0, 0, 0, 0, port);
1941 if (g_settings->getBool("ipv6_server")) {
1942 bind_addr.setAddress((IPv6AddressBytes *) NULL);
1946 bind_addr.Resolve(bind_str.c_str());
1947 } catch (ResolveError &e) {
1948 infostream << "Resolving bind address \"" << bind_str
1949 << "\" failed: " << e.what()
1950 << " -- Listening on all addresses." << std::endl;
1953 if (bind_addr.isIPv6() && !g_settings->getBool("enable_ipv6")) {
1954 *error_message = "Unable to listen on " +
1955 bind_addr.serializeString() +
1956 " because IPv6 is disabled";
1957 errorstream << *error_message << std::endl;
1961 server = new Server(map_dir, gamespec, simple_singleplayer_mode,
1962 bind_addr.isIPv6());
1964 server->start(bind_addr);
1969 bool Game::createClient(const std::string &playername,
1970 const std::string &password, std::string *address, u16 port)
1972 showOverlayMessage(wgettext("Creating client..."), 0, 10);
1974 draw_control = new MapDrawControl;
1978 bool could_connect, connect_aborted;
1980 if (!connectToServer(playername, password, address, port,
1981 &could_connect, &connect_aborted))
1984 if (!could_connect) {
1985 if (error_message->empty() && !connect_aborted) {
1986 // Should not happen if error messages are set properly
1987 *error_message = "Connection failed for unknown reason";
1988 errorstream << *error_message << std::endl;
1993 if (!getServerContent(&connect_aborted)) {
1994 if (error_message->empty() && !connect_aborted) {
1995 // Should not happen if error messages are set properly
1996 *error_message = "Connection failed for unknown reason";
1997 errorstream << *error_message << std::endl;
2002 // Update cached textures, meshes and materials
2003 client->afterContentReceived(device);
2007 camera = new Camera(smgr, *draw_control, gamedef);
2008 if (!camera || !camera->successfullyCreated(*error_message))
2013 if (m_cache_enable_clouds) {
2014 clouds = new Clouds(smgr->getRootSceneNode(), smgr, -1, time(0));
2016 *error_message = "Memory allocation error (clouds)";
2017 errorstream << *error_message << std::endl;
2024 sky = new Sky(smgr->getRootSceneNode(), smgr, -1, texture_src);
2025 skybox = NULL; // This is used/set later on in the main run loop
2027 local_inventory = new Inventory(itemdef_manager);
2029 if (!(sky && local_inventory)) {
2030 *error_message = "Memory allocation error (sky or local inventory)";
2031 errorstream << *error_message << std::endl;
2035 /* Pre-calculated values
2037 video::ITexture *t = texture_src->getTexture("crack_anylength.png");
2039 v2u32 size = t->getOriginalSize();
2040 crack_animation_length = size.Y / size.X;
2042 crack_animation_length = 5;
2048 /* Set window caption
2050 std::wstring str = narrow_to_wide(PROJECT_NAME_C);
2052 str += driver->getName();
2054 device->setWindowCaption(str.c_str());
2056 LocalPlayer *player = client->getEnv().getLocalPlayer();
2057 player->hurt_tilt_timer = 0;
2058 player->hurt_tilt_strength = 0;
2060 hud = new Hud(driver, smgr, guienv, gamedef, player, local_inventory);
2063 *error_message = "Memory error: could not create HUD";
2064 errorstream << *error_message << std::endl;
2071 bool Game::initGui()
2073 // First line of debug text
2074 guitext = guienv->addStaticText(
2075 narrow_to_wide(PROJECT_NAME_C).c_str(),
2076 core::rect<s32>(0, 0, 0, 0),
2077 false, false, guiroot);
2079 // Second line of debug text
2080 guitext2 = guienv->addStaticText(
2082 core::rect<s32>(0, 0, 0, 0),
2083 false, false, guiroot);
2085 // At the middle of the screen
2086 // Object infos are shown in this
2087 guitext_info = guienv->addStaticText(
2089 core::rect<s32>(0, 0, 400, g_fontengine->getTextHeight() * 5 + 5) + v2s32(100, 200),
2090 false, true, guiroot);
2092 // Status text (displays info when showing and hiding GUI stuff, etc.)
2093 guitext_status = guienv->addStaticText(
2095 core::rect<s32>(0, 0, 0, 0),
2096 false, false, guiroot);
2097 guitext_status->setVisible(false);
2100 guitext_chat = guienv->addStaticText(
2102 core::rect<s32>(0, 0, 0, 0),
2103 //false, false); // Disable word wrap as of now
2104 false, true, guiroot);
2105 // Remove stale "recent" chat messages from previous connections
2106 chat_backend->clearRecentChat();
2108 // Chat backend and console
2109 gui_chat_console = new GUIChatConsole(guienv, guienv->getRootGUIElement(),
2110 -1, chat_backend, client);
2111 if (!gui_chat_console) {
2112 *error_message = "Could not allocate memory for chat console";
2113 errorstream << *error_message << std::endl;
2117 // Profiler text (size is updated when text is updated)
2118 guitext_profiler = guienv->addStaticText(
2120 core::rect<s32>(0, 0, 0, 0),
2121 false, false, guiroot);
2122 guitext_profiler->setBackgroundColor(video::SColor(120, 0, 0, 0));
2123 guitext_profiler->setVisible(false);
2124 guitext_profiler->setWordWrap(true);
2126 #ifdef HAVE_TOUCHSCREENGUI
2128 if (g_touchscreengui)
2129 g_touchscreengui->init(texture_src, porting::getDisplayDensity());
2136 bool Game::connectToServer(const std::string &playername,
2137 const std::string &password, std::string *address, u16 port,
2138 bool *connect_ok, bool *aborted)
2140 *connect_ok = false; // Let's not be overly optimistic
2142 bool local_server_mode = false;
2144 showOverlayMessage(wgettext("Resolving address..."), 0, 15);
2146 Address connect_address(0, 0, 0, 0, port);
2149 connect_address.Resolve(address->c_str());
2151 if (connect_address.isZero()) { // i.e. INADDR_ANY, IN6ADDR_ANY
2152 //connect_address.Resolve("localhost");
2153 if (connect_address.isIPv6()) {
2154 IPv6AddressBytes addr_bytes;
2155 addr_bytes.bytes[15] = 1;
2156 connect_address.setAddress(&addr_bytes);
2158 connect_address.setAddress(127, 0, 0, 1);
2160 local_server_mode = true;
2162 } catch (ResolveError &e) {
2163 *error_message = std::string("Couldn't resolve address: ") + e.what();
2164 errorstream << *error_message << std::endl;
2168 if (connect_address.isIPv6() && !g_settings->getBool("enable_ipv6")) {
2169 *error_message = "Unable to connect to " +
2170 connect_address.serializeString() +
2171 " because IPv6 is disabled";
2172 errorstream << *error_message << std::endl;
2176 client = new Client(device,
2177 playername.c_str(), password,
2178 *draw_control, texture_src, shader_src,
2179 itemdef_manager, nodedef_manager, sound, eventmgr,
2180 connect_address.isIPv6());
2185 gamedef = client; // Client acts as our GameDef
2187 infostream << "Connecting to server at ";
2188 connect_address.print(&infostream);
2189 infostream << std::endl;
2191 client->connect(connect_address, *address,
2192 simple_singleplayer_mode || local_server_mode);
2195 Wait for server to accept connection
2201 FpsControl fps_control = { 0 };
2203 f32 wait_time = 0; // in seconds
2205 fps_control.last_time = device->getTimer()->getTime();
2207 while (device->run()) {
2209 limitFps(&fps_control, &dtime);
2211 // Update client and server
2212 client->step(dtime);
2215 server->step(dtime);
2218 if (client->getState() == LC_Init) {
2224 if (client->accessDenied()) {
2225 *error_message = "Access denied. Reason: "
2226 + client->accessDeniedReason();
2227 errorstream << *error_message << std::endl;
2231 if (input->wasKeyDown(EscapeKey) || input->wasKeyDown(CancelKey)) {
2233 infostream << "Connect aborted [Escape]" << std::endl;
2238 // Only time out if we aren't waiting for the server we started
2239 if ((*address != "") && (wait_time > 10)) {
2240 *error_message = "Connection timed out.";
2241 errorstream << *error_message << std::endl;
2246 showOverlayMessage(wgettext("Connecting to server..."), dtime, 20);
2248 } catch (con::PeerNotFoundException &e) {
2249 // TODO: Should something be done here? At least an info/error
2257 bool Game::getServerContent(bool *aborted)
2261 FpsControl fps_control = { 0 };
2262 f32 dtime; // in seconds
2264 fps_control.last_time = device->getTimer()->getTime();
2266 while (device->run()) {
2268 limitFps(&fps_control, &dtime);
2270 // Update client and server
2271 client->step(dtime);
2274 server->step(dtime);
2277 if (client->mediaReceived() && client->itemdefReceived() &&
2278 client->nodedefReceived()) {
2283 if (!checkConnection())
2286 if (client->getState() < LC_Init) {
2287 *error_message = "Client disconnected";
2288 errorstream << *error_message << std::endl;
2292 if (input->wasKeyDown(EscapeKey) || input->wasKeyDown(CancelKey)) {
2294 infostream << "Connect aborted [Escape]" << std::endl;
2301 if (!client->itemdefReceived()) {
2302 const wchar_t *text = wgettext("Item definitions...");
2304 draw_load_screen(text, device, guienv, dtime, progress);
2306 } else if (!client->nodedefReceived()) {
2307 const wchar_t *text = wgettext("Node definitions...");
2309 draw_load_screen(text, device, guienv, dtime, progress);
2312 std::stringstream message;
2313 message.precision(3);
2314 message << gettext("Media...");
2316 if ((USE_CURL == 0) ||
2317 (!g_settings->getBool("enable_remote_media_server"))) {
2318 float cur = client->getCurRate();
2319 std::string cur_unit = gettext("KiB/s");
2323 cur_unit = gettext("MiB/s");
2326 message << " (" << cur << ' ' << cur_unit << ")";
2329 progress = 30 + client->mediaReceiveProgress() * 35 + 0.5;
2330 draw_load_screen(narrow_to_wide(message.str()), device,
2331 guienv, dtime, progress);
2339 /****************************************************************************/
2340 /****************************************************************************
2342 ****************************************************************************/
2343 /****************************************************************************/
2345 inline void Game::updateInteractTimers(GameRunData *runData, f32 dtime)
2347 if (runData->nodig_delay_timer >= 0)
2348 runData->nodig_delay_timer -= dtime;
2350 if (runData->object_hit_delay_timer >= 0)
2351 runData->object_hit_delay_timer -= dtime;
2353 runData->time_from_last_punch += dtime;
2357 /* returns false if game should exit, otherwise true
2359 inline bool Game::checkConnection()
2361 if (client->accessDenied()) {
2362 *error_message = "Access denied. Reason: "
2363 + client->accessDeniedReason();
2364 errorstream << *error_message << std::endl;
2372 /* returns false if game should exit, otherwise true
2374 inline bool Game::handleCallbacks()
2376 if (g_gamecallback->disconnect_requested) {
2377 g_gamecallback->disconnect_requested = false;
2381 if (g_gamecallback->changepassword_requested) {
2382 (new GUIPasswordChange(guienv, guiroot, -1,
2383 &g_menumgr, client))->drop();
2384 g_gamecallback->changepassword_requested = false;
2387 if (g_gamecallback->changevolume_requested) {
2388 (new GUIVolumeChange(guienv, guiroot, -1,
2389 &g_menumgr, client))->drop();
2390 g_gamecallback->changevolume_requested = false;
2393 if (g_gamecallback->keyconfig_requested) {
2394 (new GUIKeyChangeMenu(guienv, guiroot, -1,
2395 &g_menumgr))->drop();
2396 g_gamecallback->keyconfig_requested = false;
2399 if (g_gamecallback->keyconfig_changed) {
2400 keycache.populate(); // update the cache with new settings
2401 g_gamecallback->keyconfig_changed = false;
2408 void Game::processQueues()
2410 texture_src->processQueue();
2411 itemdef_manager->processQueue(gamedef);
2412 shader_src->processQueue();
2416 void Game::updateProfilers(const GameRunData &runData, const RunStats &stats,
2417 const FpsControl &draw_times, f32 dtime)
2419 float profiler_print_interval =
2420 g_settings->getFloat("profiler_print_interval");
2421 bool print_to_log = true;
2423 if (profiler_print_interval == 0) {
2424 print_to_log = false;
2425 profiler_print_interval = 5;
2428 if (profiler_interval.step(dtime, profiler_print_interval)) {
2430 infostream << "Profiler:" << std::endl;
2431 g_profiler->print(infostream);
2434 update_profiler_gui(guitext_profiler, g_fontengine,
2435 runData.profiler_current_page, runData.profiler_max_page,
2436 driver->getScreenSize().Height);
2438 g_profiler->clear();
2441 addProfilerGraphs(stats, draw_times, dtime);
2445 void Game::addProfilerGraphs(const RunStats &stats,
2446 const FpsControl &draw_times, f32 dtime)
2448 g_profiler->graphAdd("mainloop_other",
2449 draw_times.busy_time / 1000.0f - stats.drawtime / 1000.0f);
2451 if (draw_times.sleep_time != 0)
2452 g_profiler->graphAdd("mainloop_sleep", draw_times.sleep_time / 1000.0f);
2453 g_profiler->graphAdd("mainloop_dtime", dtime);
2455 g_profiler->add("Elapsed time", dtime);
2456 g_profiler->avg("FPS", 1. / dtime);
2460 void Game::updateStats(RunStats *stats, const FpsControl &draw_times,
2467 /* Time average and jitter calculation
2469 jp = &stats->dtime_jitter;
2470 jp->avg = jp->avg * 0.96 + dtime * 0.04;
2472 jitter = dtime - jp->avg;
2474 if (jitter > jp->max)
2477 jp->counter += dtime;
2479 if (jp->counter > 0.0) {
2481 jp->max_sample = jp->max;
2482 jp->max_fraction = jp->max_sample / (jp->avg + 0.001);
2486 /* Busytime average and jitter calculation
2488 jp = &stats->busy_time_jitter;
2489 jp->avg = jp->avg + draw_times.busy_time * 0.02;
2491 jitter = draw_times.busy_time - jp->avg;
2493 if (jitter > jp->max)
2495 if (jitter < jp->min)
2498 jp->counter += dtime;
2500 if (jp->counter > 0.0) {
2502 jp->max_sample = jp->max;
2503 jp->min_sample = jp->min;
2511 /****************************************************************************
2513 ****************************************************************************/
2515 void Game::processUserInput(VolatileRunFlags *flags,
2516 GameRunData *runData, f32 dtime)
2518 // Reset input if window not active or some menu is active
2519 if (device->isWindowActive() == false
2520 || noMenuActive() == false
2521 || guienv->hasFocus(gui_chat_console)) {
2525 if (!guienv->hasFocus(gui_chat_console) && gui_chat_console->isOpen()) {
2526 gui_chat_console->closeConsoleAtOnce();
2529 // Input handler step() (used by the random input generator)
2532 #ifdef HAVE_TOUCHSCREENGUI
2534 if (g_touchscreengui) {
2535 g_touchscreengui->step(dtime);
2541 if (current_formspec != 0)
2542 current_formspec->getAndroidUIInput();
2546 // Increase timer for double tap of "keymap_jump"
2547 if (m_cache_doubletap_jump && runData->jump_timer <= 0.2)
2548 runData->jump_timer += dtime;
2550 processKeyboardInput(
2552 &runData->statustext_time,
2553 &runData->jump_timer,
2554 &runData->reset_jump_timer,
2555 &runData->profiler_current_page,
2556 runData->profiler_max_page);
2558 processItemSelection(&runData->new_playeritem);
2562 void Game::processKeyboardInput(VolatileRunFlags *flags,
2563 float *statustext_time,
2565 bool *reset_jump_timer,
2566 u32 *profiler_current_page,
2567 u32 profiler_max_page)
2570 //TimeTaker tt("process kybd input", NULL, PRECISION_NANO);
2572 if (input->wasKeyDown(keycache.key[KeyCache::KEYMAP_ID_DROP])) {
2574 } else if (input->wasKeyDown(keycache.key[KeyCache::KEYMAP_ID_INVENTORY])) {
2576 } else if (input->wasKeyDown(EscapeKey) || input->wasKeyDown(CancelKey)) {
2577 show_pause_menu(¤t_formspec, client, gamedef, texture_src, device,
2578 simple_singleplayer_mode);
2579 } else if (input->wasKeyDown(keycache.key[KeyCache::KEYMAP_ID_CHAT])) {
2580 show_chat_menu(¤t_formspec, client, gamedef, texture_src, device,
2582 } else if (input->wasKeyDown(keycache.key[KeyCache::KEYMAP_ID_CMD])) {
2583 show_chat_menu(¤t_formspec, client, gamedef, texture_src, device,
2585 } else if (input->wasKeyDown(keycache.key[KeyCache::KEYMAP_ID_CONSOLE])) {
2587 } else if (input->wasKeyDown(keycache.key[KeyCache::KEYMAP_ID_FREEMOVE])) {
2588 toggleFreeMove(statustext_time);
2589 } else if (input->wasKeyDown(keycache.key[KeyCache::KEYMAP_ID_JUMP])) {
2590 toggleFreeMoveAlt(statustext_time, jump_timer);
2591 *reset_jump_timer = true;
2592 } else if (input->wasKeyDown(keycache.key[KeyCache::KEYMAP_ID_FASTMOVE])) {
2593 toggleFast(statustext_time);
2594 } else if (input->wasKeyDown(keycache.key[KeyCache::KEYMAP_ID_NOCLIP])) {
2595 toggleNoClip(statustext_time);
2596 } else if (input->wasKeyDown(keycache.key[KeyCache::KEYMAP_ID_CINEMATIC])) {
2597 toggleCinematic(statustext_time);
2598 } else if (input->wasKeyDown(keycache.key[KeyCache::KEYMAP_ID_SCREENSHOT])) {
2599 client->makeScreenshot(device);
2600 } else if (input->wasKeyDown(keycache.key[KeyCache::KEYMAP_ID_TOGGLE_HUD])) {
2601 toggleHud(statustext_time, &flags->show_hud);
2602 } else if (input->wasKeyDown(keycache.key[KeyCache::KEYMAP_ID_TOGGLE_CHAT])) {
2603 toggleChat(statustext_time, &flags->show_chat);
2604 } else if (input->wasKeyDown(keycache.key[KeyCache::KEYMAP_ID_TOGGLE_FORCE_FOG_OFF])) {
2605 toggleFog(statustext_time, &flags->force_fog_off);
2606 } else if (input->wasKeyDown(keycache.key[KeyCache::KEYMAP_ID_TOGGLE_UPDATE_CAMERA])) {
2607 toggleUpdateCamera(statustext_time, &flags->disable_camera_update);
2608 } else if (input->wasKeyDown(keycache.key[KeyCache::KEYMAP_ID_TOGGLE_DEBUG])) {
2609 toggleDebug(statustext_time, &flags->show_debug, &flags->show_profiler_graph);
2610 } else if (input->wasKeyDown(keycache.key[KeyCache::KEYMAP_ID_TOGGLE_PROFILER])) {
2611 toggleProfiler(statustext_time, profiler_current_page, profiler_max_page);
2612 } else if (input->wasKeyDown(keycache.key[KeyCache::KEYMAP_ID_INCREASE_VIEWING_RANGE])) {
2613 increaseViewRange(statustext_time);
2614 } else if (input->wasKeyDown(keycache.key[KeyCache::KEYMAP_ID_DECREASE_VIEWING_RANGE])) {
2615 decreaseViewRange(statustext_time);
2616 } else if (input->wasKeyDown(keycache.key[KeyCache::KEYMAP_ID_RANGESELECT])) {
2617 toggleFullViewRange(statustext_time);
2618 } else if (input->wasKeyDown(keycache.key[KeyCache::KEYMAP_ID_QUICKTUNE_NEXT]))
2620 else if (input->wasKeyDown(keycache.key[KeyCache::KEYMAP_ID_QUICKTUNE_PREV]))
2622 else if (input->wasKeyDown(keycache.key[KeyCache::KEYMAP_ID_QUICKTUNE_INC]))
2624 else if (input->wasKeyDown(keycache.key[KeyCache::KEYMAP_ID_QUICKTUNE_DEC]))
2626 else if (input->wasKeyDown(keycache.key[KeyCache::KEYMAP_ID_DEBUG_STACKS])) {
2627 // Print debug stacks
2628 dstream << "-----------------------------------------"
2630 dstream << DTIME << "Printing debug stacks:" << std::endl;
2631 dstream << "-----------------------------------------"
2633 debug_stacks_print();
2636 if (!input->isKeyDown(getKeySetting("keymap_jump")) && *reset_jump_timer) {
2637 *reset_jump_timer = false;
2643 if (quicktune->hasMessage()) {
2644 std::string msg = quicktune->getMessage();
2645 statustext = narrow_to_wide(msg);
2646 *statustext_time = 0;
2651 void Game::processItemSelection(u16 *new_playeritem)
2653 LocalPlayer *player = client->getEnv().getLocalPlayer();
2655 /* Item selection using mouse wheel
2657 *new_playeritem = client->getPlayerItem();
2659 s32 wheel = input->getMouseWheel();
2660 u16 max_item = MYMIN(PLAYER_INVENTORY_SIZE - 1,
2661 player->hud_hotbar_itemcount - 1);
2664 *new_playeritem = *new_playeritem < max_item ? *new_playeritem + 1 : 0;
2666 *new_playeritem = *new_playeritem > 0 ? *new_playeritem - 1 : max_item;
2670 /* Item selection using keyboard
2672 for (u16 i = 0; i < 10; i++) {
2673 static const KeyPress *item_keys[10] = {
2674 NumberKey + 1, NumberKey + 2, NumberKey + 3, NumberKey + 4,
2675 NumberKey + 5, NumberKey + 6, NumberKey + 7, NumberKey + 8,
2676 NumberKey + 9, NumberKey + 0,
2679 if (input->wasKeyDown(*item_keys[i])) {
2680 if (i < PLAYER_INVENTORY_SIZE && i < player->hud_hotbar_itemcount) {
2681 *new_playeritem = i;
2682 infostream << "Selected item: " << new_playeritem << std::endl;
2690 void Game::dropSelectedItem()
2692 IDropAction *a = new IDropAction();
2694 a->from_inv.setCurrentPlayer();
2695 a->from_list = "main";
2696 a->from_i = client->getPlayerItem();
2697 client->inventoryAction(a);
2701 void Game::openInventory()
2704 * Don't permit to open inventory is CAO or player doesn't exists.
2705 * This prevent showing an empty inventory at player load
2708 LocalPlayer *player = client->getEnv().getLocalPlayer();
2709 if (player == NULL || player->getCAO() == NULL)
2712 infostream << "the_game: " << "Launching inventory" << std::endl;
2714 PlayerInventoryFormSource *fs_src = new PlayerInventoryFormSource(client);
2715 TextDest *txt_dst = new TextDestPlayerInventory(client);
2717 create_formspec_menu(¤t_formspec, client, gamedef, texture_src,
2718 device, fs_src, txt_dst, client);
2720 InventoryLocation inventoryloc;
2721 inventoryloc.setCurrentPlayer();
2722 current_formspec->setFormSpec(fs_src->getForm(), inventoryloc);
2726 void Game::openConsole()
2728 if (!gui_chat_console->isOpenInhibited()) {
2729 // Open up to over half of the screen
2730 gui_chat_console->openConsole(0.6);
2731 guienv->setFocus(gui_chat_console);
2736 void Game::toggleFreeMove(float *statustext_time)
2738 static const wchar_t *msg[] = { L"free_move disabled", L"free_move enabled" };
2740 bool free_move = !g_settings->getBool("free_move");
2741 g_settings->set("free_move", bool_to_cstr(free_move));
2743 *statustext_time = 0;
2744 statustext = msg[free_move];
2745 if (free_move && !client->checkPrivilege("fly"))
2746 statustext += L" (note: no 'fly' privilege)";
2750 void Game::toggleFreeMoveAlt(float *statustext_time, float *jump_timer)
2752 if (m_cache_doubletap_jump && *jump_timer < 0.2f)
2753 toggleFreeMove(statustext_time);
2757 void Game::toggleFast(float *statustext_time)
2759 static const wchar_t *msg[] = { L"fast_move disabled", L"fast_move enabled" };
2760 bool fast_move = !g_settings->getBool("fast_move");
2761 g_settings->set("fast_move", bool_to_cstr(fast_move));
2763 *statustext_time = 0;
2764 statustext = msg[fast_move];
2766 bool has_fast_privs = client->checkPrivilege("fast");
2768 if (fast_move && !has_fast_privs)
2769 statustext += L" (note: no 'fast' privilege)";
2772 m_cache_hold_aux1 = fast_move && has_fast_privs;
2777 void Game::toggleNoClip(float *statustext_time)
2779 static const wchar_t *msg[] = { L"noclip disabled", L"noclip enabled" };
2780 bool noclip = !g_settings->getBool("noclip");
2781 g_settings->set("noclip", bool_to_cstr(noclip));
2783 *statustext_time = 0;
2784 statustext = msg[noclip];
2786 if (noclip && !client->checkPrivilege("noclip"))
2787 statustext += L" (note: no 'noclip' privilege)";
2790 void Game::toggleCinematic(float *statustext_time)
2792 static const wchar_t *msg[] = { L"cinematic disabled", L"cinematic enabled" };
2793 bool cinematic = !g_settings->getBool("cinematic");
2794 g_settings->set("cinematic", bool_to_cstr(cinematic));
2796 *statustext_time = 0;
2797 statustext = msg[cinematic];
2801 void Game::toggleChat(float *statustext_time, bool *flag)
2803 static const wchar_t *msg[] = { L"Chat hidden", L"Chat shown" };
2806 *statustext_time = 0;
2807 statustext = msg[*flag];
2811 void Game::toggleHud(float *statustext_time, bool *flag)
2813 static const wchar_t *msg[] = { L"HUD hidden", L"HUD shown" };
2816 *statustext_time = 0;
2817 statustext = msg[*flag];
2818 if (g_settings->getBool("enable_node_highlighting"))
2819 client->setHighlighted(client->getHighlighted(), *flag);
2823 void Game::toggleFog(float *statustext_time, bool *flag)
2825 static const wchar_t *msg[] = { L"Fog enabled", L"Fog disabled" };
2828 *statustext_time = 0;
2829 statustext = msg[*flag];
2833 void Game::toggleDebug(float *statustext_time, bool *show_debug,
2834 bool *show_profiler_graph)
2836 // Initial / 3x toggle: Chat only
2837 // 1x toggle: Debug text with chat
2838 // 2x toggle: Debug text with profiler graph
2841 *show_profiler_graph = false;
2842 statustext = L"Debug info shown";
2843 } else if (*show_profiler_graph) {
2844 *show_debug = false;
2845 *show_profiler_graph = false;
2846 statustext = L"Debug info and profiler graph hidden";
2848 *show_profiler_graph = true;
2849 statustext = L"Profiler graph shown";
2851 *statustext_time = 0;
2855 void Game::toggleUpdateCamera(float *statustext_time, bool *flag)
2857 static const wchar_t *msg[] = {
2858 L"Camera update enabled",
2859 L"Camera update disabled"
2863 *statustext_time = 0;
2864 statustext = msg[*flag];
2868 void Game::toggleProfiler(float *statustext_time, u32 *profiler_current_page,
2869 u32 profiler_max_page)
2871 *profiler_current_page = (*profiler_current_page + 1) % (profiler_max_page + 1);
2873 // FIXME: This updates the profiler with incomplete values
2874 update_profiler_gui(guitext_profiler, g_fontengine, *profiler_current_page,
2875 profiler_max_page, driver->getScreenSize().Height);
2877 if (*profiler_current_page != 0) {
2878 std::wstringstream sstr;
2879 sstr << "Profiler shown (page " << *profiler_current_page
2880 << " of " << profiler_max_page << ")";
2881 statustext = sstr.str();
2883 statustext = L"Profiler hidden";
2885 *statustext_time = 0;
2889 void Game::increaseViewRange(float *statustext_time)
2891 s16 range = g_settings->getS16("viewing_range_nodes_min");
2892 s16 range_new = range + 10;
2893 g_settings->set("viewing_range_nodes_min", itos(range_new));
2894 statustext = narrow_to_wide("Minimum viewing range changed to "
2896 *statustext_time = 0;
2900 void Game::decreaseViewRange(float *statustext_time)
2902 s16 range = g_settings->getS16("viewing_range_nodes_min");
2903 s16 range_new = range - 10;
2908 g_settings->set("viewing_range_nodes_min", itos(range_new));
2909 statustext = narrow_to_wide("Minimum viewing range changed to "
2911 *statustext_time = 0;
2915 void Game::toggleFullViewRange(float *statustext_time)
2917 static const wchar_t *msg[] = {
2918 L"Disabled full viewing range",
2919 L"Enabled full viewing range"
2922 draw_control->range_all = !draw_control->range_all;
2923 infostream << msg[draw_control->range_all] << std::endl;
2924 statustext = msg[draw_control->range_all];
2925 *statustext_time = 0;
2929 void Game::updateCameraDirection(CameraOrientation *cam,
2930 VolatileRunFlags *flags)
2932 if ((device->isWindowActive() && noMenuActive()) || random_input) {
2935 if (!random_input) {
2936 // Mac OSX gets upset if this is set every frame
2937 if (device->getCursorControl()->isVisible())
2938 device->getCursorControl()->setVisible(false);
2942 if (flags->first_loop_after_window_activation)
2943 flags->first_loop_after_window_activation = false;
2945 updateCameraOrientation(cam, *flags);
2947 input->setMousePos((driver->getScreenSize().Width / 2),
2948 (driver->getScreenSize().Height / 2));
2952 // Mac OSX gets upset if this is set every frame
2953 if (device->getCursorControl()->isVisible() == false)
2954 device->getCursorControl()->setVisible(true);
2957 if (!flags->first_loop_after_window_activation)
2958 flags->first_loop_after_window_activation = true;
2964 void Game::updateCameraOrientation(CameraOrientation *cam,
2965 const VolatileRunFlags &flags)
2967 #ifdef HAVE_TOUCHSCREENGUI
2968 if (g_touchscreengui) {
2969 cam->camera_yaw = g_touchscreengui->getYaw();
2970 cam->camera_pitch = g_touchscreengui->getPitch();
2973 s32 dx = input->getMousePos().X - (driver->getScreenSize().Width / 2);
2974 s32 dy = input->getMousePos().Y - (driver->getScreenSize().Height / 2);
2976 if (flags.invert_mouse
2977 || camera->getCameraMode() == CAMERA_MODE_THIRD_FRONT) {
2981 cam->camera_yaw -= dx * m_cache_mouse_sensitivity;
2982 cam->camera_pitch += dy * m_cache_mouse_sensitivity;
2984 #ifdef HAVE_TOUCHSCREENGUI
2988 cam->camera_pitch = rangelim(cam->camera_pitch, -89.5, 89.5);
2992 void Game::updatePlayerControl(const CameraOrientation &cam)
2994 //TimeTaker tt("update player control", NULL, PRECISION_NANO);
2996 PlayerControl control(
2997 input->isKeyDown(keycache.key[KeyCache::KEYMAP_ID_FORWARD]),
2998 input->isKeyDown(keycache.key[KeyCache::KEYMAP_ID_BACKWARD]),
2999 input->isKeyDown(keycache.key[KeyCache::KEYMAP_ID_LEFT]),
3000 input->isKeyDown(keycache.key[KeyCache::KEYMAP_ID_RIGHT]),
3001 input->isKeyDown(keycache.key[KeyCache::KEYMAP_ID_JUMP]),
3002 input->isKeyDown(keycache.key[KeyCache::KEYMAP_ID_SPECIAL1]),
3003 input->isKeyDown(keycache.key[KeyCache::KEYMAP_ID_SNEAK]),
3004 input->getLeftState(),
3005 input->getRightState(),
3011 ( (u32)(input->isKeyDown(keycache.key[KeyCache::KEYMAP_ID_FORWARD]) & 0x1) << 0) |
3012 ( (u32)(input->isKeyDown(keycache.key[KeyCache::KEYMAP_ID_BACKWARD]) & 0x1) << 1) |
3013 ( (u32)(input->isKeyDown(keycache.key[KeyCache::KEYMAP_ID_LEFT]) & 0x1) << 2) |
3014 ( (u32)(input->isKeyDown(keycache.key[KeyCache::KEYMAP_ID_RIGHT]) & 0x1) << 3) |
3015 ( (u32)(input->isKeyDown(keycache.key[KeyCache::KEYMAP_ID_JUMP]) & 0x1) << 4) |
3016 ( (u32)(input->isKeyDown(keycache.key[KeyCache::KEYMAP_ID_SPECIAL1]) & 0x1) << 5) |
3017 ( (u32)(input->isKeyDown(keycache.key[KeyCache::KEYMAP_ID_SNEAK]) & 0x1) << 6) |
3018 ( (u32)(input->getLeftState() & 0x1) << 7) |
3019 ( (u32)(input->getRightState() & 0x1) << 8
3023 /* For Android, simulate holding down AUX1 (fast move) if the user has
3024 * the fast_move setting toggled on. If there is an aux1 key defined for
3025 * Android then its meaning is inverted (i.e. holding aux1 means walk and
3028 if (m_cache_hold_aux1) {
3029 control.aux1 = control.aux1 ^ true;
3030 keypress_bits ^= ((u32)(1U << 5));
3034 client->setPlayerControl(control);
3035 LocalPlayer *player = client->getEnv().getLocalPlayer();
3036 player->keyPressed = keypress_bits;
3042 inline void Game::step(f32 *dtime)
3044 bool can_be_and_is_paused =
3045 (simple_singleplayer_mode && g_menumgr.pausesGame());
3047 if (can_be_and_is_paused) { // This is for a singleplayer server
3048 *dtime = 0; // No time passes
3050 if (server != NULL) {
3051 //TimeTaker timer("server->step(dtime)");
3052 server->step(*dtime);
3055 //TimeTaker timer("client.step(dtime)");
3056 client->step(*dtime);
3061 void Game::processClientEvents(CameraOrientation *cam, float *damage_flash)
3063 ClientEvent event = client->getClientEvent();
3065 LocalPlayer *player = client->getEnv().getLocalPlayer();
3067 for ( ; event.type != CE_NONE; event = client->getClientEvent()) {
3069 if (event.type == CE_PLAYER_DAMAGE &&
3070 client->getHP() != 0) {
3071 //u16 damage = event.player_damage.amount;
3072 //infostream<<"Player damage: "<<damage<<std::endl;
3074 *damage_flash += 100.0;
3075 *damage_flash += 8.0 * event.player_damage.amount;
3077 player->hurt_tilt_timer = 1.5;
3078 player->hurt_tilt_strength = event.player_damage.amount / 4;
3079 player->hurt_tilt_strength = rangelim(player->hurt_tilt_strength, 1.0, 4.0);
3081 MtEvent *e = new SimpleTriggerEvent("PlayerDamage");
3082 gamedef->event()->put(e);
3083 } else if (event.type == CE_PLAYER_FORCE_MOVE) {
3084 cam->camera_yaw = event.player_force_move.yaw;
3085 cam->camera_pitch = event.player_force_move.pitch;
3086 } else if (event.type == CE_DEATHSCREEN) {
3087 show_deathscreen(¤t_formspec, client, gamedef, texture_src,
3090 chat_backend->addMessage(L"", L"You died.");
3092 /* Handle visualization */
3094 player->hurt_tilt_timer = 0;
3095 player->hurt_tilt_strength = 0;
3097 } else if (event.type == CE_SHOW_FORMSPEC) {
3098 FormspecFormSource *fs_src =
3099 new FormspecFormSource(*(event.show_formspec.formspec));
3100 TextDestPlayerInventory *txt_dst =
3101 new TextDestPlayerInventory(client, *(event.show_formspec.formname));
3103 create_formspec_menu(¤t_formspec, client, gamedef,
3104 texture_src, device, fs_src, txt_dst, client);
3106 delete(event.show_formspec.formspec);
3107 delete(event.show_formspec.formname);
3108 } else if ((event.type == CE_SPAWN_PARTICLE) ||
3109 (event.type == CE_ADD_PARTICLESPAWNER) ||
3110 (event.type == CE_DELETE_PARTICLESPAWNER)) {
3111 client->getParticleManager()->handleParticleEvent(&event, gamedef,
3113 } else if (event.type == CE_HUDADD) {
3114 u32 id = event.hudadd.id;
3116 LocalPlayer *player = client->getEnv().getLocalPlayer();
3117 HudElement *e = player->getHud(id);
3120 delete event.hudadd.pos;
3121 delete event.hudadd.name;
3122 delete event.hudadd.scale;
3123 delete event.hudadd.text;
3124 delete event.hudadd.align;
3125 delete event.hudadd.offset;
3126 delete event.hudadd.world_pos;
3127 delete event.hudadd.size;
3132 e->type = (HudElementType)event.hudadd.type;
3133 e->pos = *event.hudadd.pos;
3134 e->name = *event.hudadd.name;
3135 e->scale = *event.hudadd.scale;
3136 e->text = *event.hudadd.text;
3137 e->number = event.hudadd.number;
3138 e->item = event.hudadd.item;
3139 e->dir = event.hudadd.dir;
3140 e->align = *event.hudadd.align;
3141 e->offset = *event.hudadd.offset;
3142 e->world_pos = *event.hudadd.world_pos;
3143 e->size = *event.hudadd.size;
3145 u32 new_id = player->addHud(e);
3146 //if this isn't true our huds aren't consistent
3147 sanity_check(new_id == id);
3149 delete event.hudadd.pos;
3150 delete event.hudadd.name;
3151 delete event.hudadd.scale;
3152 delete event.hudadd.text;
3153 delete event.hudadd.align;
3154 delete event.hudadd.offset;
3155 delete event.hudadd.world_pos;
3156 delete event.hudadd.size;
3157 } else if (event.type == CE_HUDRM) {
3158 HudElement *e = player->removeHud(event.hudrm.id);
3162 } else if (event.type == CE_HUDCHANGE) {
3163 u32 id = event.hudchange.id;
3164 HudElement *e = player->getHud(id);
3167 delete event.hudchange.v3fdata;
3168 delete event.hudchange.v2fdata;
3169 delete event.hudchange.sdata;
3170 delete event.hudchange.v2s32data;
3174 switch (event.hudchange.stat) {
3176 e->pos = *event.hudchange.v2fdata;
3180 e->name = *event.hudchange.sdata;
3183 case HUD_STAT_SCALE:
3184 e->scale = *event.hudchange.v2fdata;
3188 e->text = *event.hudchange.sdata;
3191 case HUD_STAT_NUMBER:
3192 e->number = event.hudchange.data;
3196 e->item = event.hudchange.data;
3200 e->dir = event.hudchange.data;
3203 case HUD_STAT_ALIGN:
3204 e->align = *event.hudchange.v2fdata;
3207 case HUD_STAT_OFFSET:
3208 e->offset = *event.hudchange.v2fdata;
3211 case HUD_STAT_WORLD_POS:
3212 e->world_pos = *event.hudchange.v3fdata;
3216 e->size = *event.hudchange.v2s32data;
3220 delete event.hudchange.v3fdata;
3221 delete event.hudchange.v2fdata;
3222 delete event.hudchange.sdata;
3223 delete event.hudchange.v2s32data;
3224 } else if (event.type == CE_SET_SKY) {
3225 sky->setVisible(false);
3232 // Handle according to type
3233 if (*event.set_sky.type == "regular") {
3234 sky->setVisible(true);
3235 } else if (*event.set_sky.type == "skybox" &&
3236 event.set_sky.params->size() == 6) {
3237 sky->setFallbackBgColor(*event.set_sky.bgcolor);
3238 skybox = smgr->addSkyBoxSceneNode(
3239 texture_src->getTextureForMesh((*event.set_sky.params)[0]),
3240 texture_src->getTextureForMesh((*event.set_sky.params)[1]),
3241 texture_src->getTextureForMesh((*event.set_sky.params)[2]),
3242 texture_src->getTextureForMesh((*event.set_sky.params)[3]),
3243 texture_src->getTextureForMesh((*event.set_sky.params)[4]),
3244 texture_src->getTextureForMesh((*event.set_sky.params)[5]));
3246 // Handle everything else as plain color
3248 if (*event.set_sky.type != "plain")
3249 infostream << "Unknown sky type: "
3250 << (*event.set_sky.type) << std::endl;
3252 sky->setFallbackBgColor(*event.set_sky.bgcolor);
3255 delete event.set_sky.bgcolor;
3256 delete event.set_sky.type;
3257 delete event.set_sky.params;
3258 } else if (event.type == CE_OVERRIDE_DAY_NIGHT_RATIO) {
3259 bool enable = event.override_day_night_ratio.do_override;
3260 u32 value = event.override_day_night_ratio.ratio_f * 1000;
3261 client->getEnv().setDayNightRatioOverride(enable, value);
3267 void Game::updateCamera(VolatileRunFlags *flags, u32 busy_time,
3268 f32 dtime, float time_from_last_punch)
3270 LocalPlayer *player = client->getEnv().getLocalPlayer();
3273 For interaction purposes, get info about the held item
3275 - Is it a usable item?
3276 - Can it point to liquids?
3278 ItemStack playeritem;
3280 InventoryList *mlist = local_inventory->getList("main");
3282 if (mlist && client->getPlayerItem() < mlist->getSize())
3283 playeritem = mlist->getItem(client->getPlayerItem());
3286 ToolCapabilities playeritem_toolcap =
3287 playeritem.getToolCapabilities(itemdef_manager);
3289 v3s16 old_camera_offset = camera->getOffset();
3291 if (input->wasKeyDown(keycache.key[KeyCache::KEYMAP_ID_CAMERA_MODE])) {
3292 GenericCAO *playercao = player->getCAO();
3294 // If playercao not loaded, don't change camera
3295 if (playercao == NULL)
3298 camera->toggleCameraMode();
3300 playercao->setVisible(camera->getCameraMode() > CAMERA_MODE_FIRST);
3301 playercao->setChildrenVisible(camera->getCameraMode() > CAMERA_MODE_FIRST);
3304 float full_punch_interval = playeritem_toolcap.full_punch_interval;
3305 float tool_reload_ratio = time_from_last_punch / full_punch_interval;
3307 tool_reload_ratio = MYMIN(tool_reload_ratio, 1.0);
3308 camera->update(player, dtime, busy_time / 1000.0f, tool_reload_ratio,
3310 camera->step(dtime);
3312 v3f camera_position = camera->getPosition();
3313 v3f camera_direction = camera->getDirection();
3314 f32 camera_fov = camera->getFovMax();
3315 v3s16 camera_offset = camera->getOffset();
3317 flags->camera_offset_changed = (camera_offset != old_camera_offset);
3319 if (!flags->disable_camera_update) {
3320 client->getEnv().getClientMap().updateCamera(camera_position,
3321 camera_direction, camera_fov, camera_offset);
3323 if (flags->camera_offset_changed) {
3324 client->updateCameraOffset(camera_offset);
3325 client->getEnv().updateCameraOffset(camera_offset);
3328 clouds->updateCameraOffset(camera_offset);
3334 void Game::updateSound(f32 dtime)
3336 // Update sound listener
3337 v3s16 camera_offset = camera->getOffset();
3338 sound->updateListener(camera->getCameraNode()->getPosition() + intToFloat(camera_offset, BS),
3339 v3f(0, 0, 0), // velocity
3340 camera->getDirection(),
3341 camera->getCameraNode()->getUpVector());
3342 sound->setListenerGain(g_settings->getFloat("sound_volume"));
3345 // Update sound maker
3346 soundmaker->step(dtime);
3348 LocalPlayer *player = client->getEnv().getLocalPlayer();
3350 ClientMap &map = client->getEnv().getClientMap();
3351 MapNode n = map.getNodeNoEx(player->getStandingNodePos());
3352 soundmaker->m_player_step_sound = nodedef_manager->get(n).sound_footstep;
3356 void Game::processPlayerInteraction(std::vector<aabb3f> &highlight_boxes,
3357 GameRunData *runData, f32 dtime, bool show_hud, bool show_debug)
3359 LocalPlayer *player = client->getEnv().getLocalPlayer();
3361 ItemStack playeritem;
3363 InventoryList *mlist = local_inventory->getList("main");
3365 if (mlist && client->getPlayerItem() < mlist->getSize())
3366 playeritem = mlist->getItem(client->getPlayerItem());
3369 const ItemDefinition &playeritem_def =
3370 playeritem.getDefinition(itemdef_manager);
3372 v3f player_position = player->getPosition();
3373 v3f camera_position = camera->getPosition();
3374 v3f camera_direction = camera->getDirection();
3375 v3s16 camera_offset = camera->getOffset();
3379 Calculate what block is the crosshair pointing to
3382 f32 d = playeritem_def.range; // max. distance
3383 f32 d_hand = itemdef_manager->get("").range;
3385 if (d < 0 && d_hand >= 0)
3390 core::line3d<f32> shootline;
3392 if (camera->getCameraMode() != CAMERA_MODE_THIRD_FRONT) {
3394 shootline = core::line3d<f32>(camera_position,
3395 camera_position + camera_direction * BS * (d + 1));
3398 // prevent player pointing anything in front-view
3399 if (camera->getCameraMode() == CAMERA_MODE_THIRD_FRONT)
3400 shootline = core::line3d<f32>(0, 0, 0, 0, 0, 0);
3403 #ifdef HAVE_TOUCHSCREENGUI
3405 if ((g_settings->getBool("touchtarget")) && (g_touchscreengui)) {
3406 shootline = g_touchscreengui->getShootline();
3407 shootline.start += intToFloat(camera_offset, BS);
3408 shootline.end += intToFloat(camera_offset, BS);
3413 PointedThing pointed = getPointedThing(
3415 client, player_position, camera_direction,
3416 camera_position, shootline, d,
3417 playeritem_def.liquids_pointable,
3418 !runData->ldown_for_dig,
3422 runData->selected_object);
3424 if (pointed != runData->pointed_old) {
3425 infostream << "Pointing at " << pointed.dump() << std::endl;
3427 if (m_cache_enable_node_highlighting) {
3428 if (pointed.type == POINTEDTHING_NODE) {
3429 client->setHighlighted(pointed.node_undersurface, show_hud);
3431 client->setHighlighted(pointed.node_undersurface, false);
3438 - releasing left mouse button
3439 - pointing away from node
3441 if (runData->digging) {
3442 if (input->getLeftReleased()) {
3443 infostream << "Left button released"
3444 << " (stopped digging)" << std::endl;
3445 runData->digging = false;
3446 } else if (pointed != runData->pointed_old) {
3447 if (pointed.type == POINTEDTHING_NODE
3448 && runData->pointed_old.type == POINTEDTHING_NODE
3449 && pointed.node_undersurface
3450 == runData->pointed_old.node_undersurface) {
3451 // Still pointing to the same node, but a different face.
3454 infostream << "Pointing away from node"
3455 << " (stopped digging)" << std::endl;
3456 runData->digging = false;
3460 if (!runData->digging) {
3461 client->interact(1, runData->pointed_old);
3462 client->setCrack(-1, v3s16(0, 0, 0));
3463 runData->dig_time = 0.0;
3467 if (!runData->digging && runData->ldown_for_dig && !input->getLeftState()) {
3468 runData->ldown_for_dig = false;
3471 runData->left_punch = false;
3473 soundmaker->m_player_leftpunch_sound.name = "";
3475 if (input->getRightState())
3476 runData->repeat_rightclick_timer += dtime;
3478 runData->repeat_rightclick_timer = 0;
3480 if (playeritem_def.usable && input->getLeftState()) {
3481 if (input->getLeftClicked())
3482 client->interact(4, pointed);
3483 } else if (pointed.type == POINTEDTHING_NODE) {
3484 ToolCapabilities playeritem_toolcap =
3485 playeritem.getToolCapabilities(itemdef_manager);
3486 handlePointingAtNode(runData, pointed, playeritem_def,
3487 playeritem_toolcap, dtime);
3488 } else if (pointed.type == POINTEDTHING_OBJECT) {
3489 handlePointingAtObject(runData, pointed, playeritem,
3490 player_position, show_debug);
3491 } else if (input->getLeftState()) {
3492 // When button is held down in air, show continuous animation
3493 runData->left_punch = true;
3496 runData->pointed_old = pointed;
3498 if (runData->left_punch || input->getLeftClicked())
3499 camera->setDigging(0); // left click animation
3501 input->resetLeftClicked();
3502 input->resetRightClicked();
3504 input->resetLeftReleased();
3505 input->resetRightReleased();
3509 void Game::handlePointingAtNode(GameRunData *runData,
3510 const PointedThing &pointed, const ItemDefinition &playeritem_def,
3511 const ToolCapabilities &playeritem_toolcap, f32 dtime)
3513 v3s16 nodepos = pointed.node_undersurface;
3514 v3s16 neighbourpos = pointed.node_abovesurface;
3517 Check information text of node
3520 ClientMap &map = client->getEnv().getClientMap();
3521 NodeMetadata *meta = map.getNodeMetadata(nodepos);
3524 infotext = narrow_to_wide(meta->getString("infotext"));
3526 MapNode n = map.getNodeNoEx(nodepos);
3528 if (nodedef_manager->get(n).tiledef[0].name == "unknown_node.png") {
3529 infotext = L"Unknown node: ";
3530 infotext += narrow_to_wide(nodedef_manager->get(n).name);
3534 if (runData->nodig_delay_timer <= 0.0 && input->getLeftState()
3535 && client->checkPrivilege("interact")) {
3536 handleDigging(runData, pointed, nodepos, playeritem_toolcap, dtime);
3539 if ((input->getRightClicked() ||
3540 runData->repeat_rightclick_timer >= m_repeat_right_click_time) &&
3541 client->checkPrivilege("interact")) {
3542 runData->repeat_rightclick_timer = 0;
3543 infostream << "Ground right-clicked" << std::endl;
3545 if (meta && meta->getString("formspec") != "" && !random_input
3546 && !input->isKeyDown(getKeySetting("keymap_sneak"))) {
3547 infostream << "Launching custom inventory view" << std::endl;
3549 InventoryLocation inventoryloc;
3550 inventoryloc.setNodeMeta(nodepos);
3552 NodeMetadataFormSource *fs_src = new NodeMetadataFormSource(
3553 &client->getEnv().getClientMap(), nodepos);
3554 TextDest *txt_dst = new TextDestNodeMetadata(nodepos, client);
3556 create_formspec_menu(¤t_formspec, client, gamedef,
3557 texture_src, device, fs_src, txt_dst, client);
3559 current_formspec->setFormSpec(meta->getString("formspec"), inventoryloc);
3561 // Report right click to server
3563 camera->setDigging(1); // right click animation (always shown for feedback)
3565 // If the wielded item has node placement prediction,
3567 bool placed = nodePlacementPrediction(*client,
3569 nodepos, neighbourpos);
3573 client->interact(3, pointed);
3575 soundmaker->m_player_rightpunch_sound =
3576 playeritem_def.sound_place;
3578 soundmaker->m_player_rightpunch_sound =
3582 if (playeritem_def.node_placement_prediction == "" ||
3583 nodedef_manager->get(map.getNodeNoEx(nodepos)).rightclickable)
3584 client->interact(3, pointed); // Report to server
3590 void Game::handlePointingAtObject(GameRunData *runData,
3591 const PointedThing &pointed,
3592 const ItemStack &playeritem,
3593 const v3f &player_position,
3596 infotext = narrow_to_wide(runData->selected_object->infoText());
3598 if (infotext == L"" && show_debug) {
3599 infotext = narrow_to_wide(runData->selected_object->debugInfoText());
3602 if (input->getLeftState()) {
3603 bool do_punch = false;
3604 bool do_punch_damage = false;
3606 if (runData->object_hit_delay_timer <= 0.0) {
3608 do_punch_damage = true;
3609 runData->object_hit_delay_timer = object_hit_delay;
3612 if (input->getLeftClicked())
3616 infostream << "Left-clicked object" << std::endl;
3617 runData->left_punch = true;
3620 if (do_punch_damage) {
3621 // Report direct punch
3622 v3f objpos = runData->selected_object->getPosition();
3623 v3f dir = (objpos - player_position).normalize();
3625 bool disable_send = runData->selected_object->directReportPunch(
3626 dir, &playeritem, runData->time_from_last_punch);
3627 runData->time_from_last_punch = 0;
3630 client->interact(0, pointed);
3632 } else if (input->getRightClicked()) {
3633 infostream << "Right-clicked object" << std::endl;
3634 client->interact(3, pointed); // place
3639 void Game::handleDigging(GameRunData *runData,
3640 const PointedThing &pointed, const v3s16 &nodepos,
3641 const ToolCapabilities &playeritem_toolcap, f32 dtime)
3643 if (!runData->digging) {
3644 infostream << "Started digging" << std::endl;
3645 client->interact(0, pointed);
3646 runData->digging = true;
3647 runData->ldown_for_dig = true;
3650 LocalPlayer *player = client->getEnv().getLocalPlayer();
3651 ClientMap &map = client->getEnv().getClientMap();
3652 MapNode n = client->getEnv().getClientMap().getNodeNoEx(nodepos);
3654 // NOTE: Similar piece of code exists on the server side for
3656 // Get digging parameters
3657 DigParams params = getDigParams(nodedef_manager->get(n).groups,
3658 &playeritem_toolcap);
3660 // If can't dig, try hand
3661 if (!params.diggable) {
3662 const ItemDefinition &hand = itemdef_manager->get("");
3663 const ToolCapabilities *tp = hand.tool_capabilities;
3666 params = getDigParams(nodedef_manager->get(n).groups, tp);
3669 if (params.diggable == false) {
3670 // I guess nobody will wait for this long
3671 runData->dig_time_complete = 10000000.0;
3673 runData->dig_time_complete = params.time;
3675 if (m_cache_enable_particles) {
3676 const ContentFeatures &features =
3677 client->getNodeDefManager()->get(n);
3678 client->getParticleManager()->addPunchingParticles(gamedef, smgr,
3679 player, nodepos, features.tiles);
3683 if (runData->dig_time_complete >= 0.001) {
3684 runData->dig_index = (float)crack_animation_length
3686 / runData->dig_time_complete;
3688 // This is for torches
3689 runData->dig_index = crack_animation_length;
3692 SimpleSoundSpec sound_dig = nodedef_manager->get(n).sound_dig;
3694 if (sound_dig.exists() && params.diggable) {
3695 if (sound_dig.name == "__group") {
3696 if (params.main_group != "") {
3697 soundmaker->m_player_leftpunch_sound.gain = 0.5;
3698 soundmaker->m_player_leftpunch_sound.name =
3699 std::string("default_dig_") +
3703 soundmaker->m_player_leftpunch_sound = sound_dig;
3707 // Don't show cracks if not diggable
3708 if (runData->dig_time_complete >= 100000.0) {
3709 } else if (runData->dig_index < crack_animation_length) {
3710 //TimeTaker timer("client.setTempMod");
3711 //infostream<<"dig_index="<<dig_index<<std::endl;
3712 client->setCrack(runData->dig_index, nodepos);
3714 infostream << "Digging completed" << std::endl;
3715 client->interact(2, pointed);
3716 client->setCrack(-1, v3s16(0, 0, 0));
3717 bool is_valid_position;
3718 MapNode wasnode = map.getNodeNoEx(nodepos, &is_valid_position);
3719 if (is_valid_position)
3720 client->removeNode(nodepos);
3722 if (m_cache_enable_particles) {
3723 const ContentFeatures &features =
3724 client->getNodeDefManager()->get(wasnode);
3725 client->getParticleManager()->addDiggingParticles(gamedef, smgr,
3726 player, nodepos, features.tiles);
3729 runData->dig_time = 0;
3730 runData->digging = false;
3732 runData->nodig_delay_timer =
3733 runData->dig_time_complete / (float)crack_animation_length;
3735 // We don't want a corresponding delay to
3736 // very time consuming nodes
3737 if (runData->nodig_delay_timer > 0.3)
3738 runData->nodig_delay_timer = 0.3;
3740 // We want a slight delay to very little
3741 // time consuming nodes
3742 const float mindelay = 0.15;
3744 if (runData->nodig_delay_timer < mindelay)
3745 runData->nodig_delay_timer = mindelay;
3747 // Send event to trigger sound
3748 MtEvent *e = new NodeDugEvent(nodepos, wasnode);
3749 gamedef->event()->put(e);
3752 if (runData->dig_time_complete < 100000.0) {
3753 runData->dig_time += dtime;
3755 runData->dig_time = 0;
3756 client->setCrack(-1, nodepos);
3759 camera->setDigging(0); // left click animation
3763 void Game::updateFrame(std::vector<aabb3f> &highlight_boxes,
3764 ProfilerGraph *graph, RunStats *stats, GameRunData *runData,
3765 f32 dtime, const VolatileRunFlags &flags, const CameraOrientation &cam)
3767 LocalPlayer *player = client->getEnv().getLocalPlayer();
3773 if (draw_control->range_all) {
3774 runData->fog_range = 100000 * BS;
3776 runData->fog_range = draw_control->wanted_range * BS
3777 + 0.0 * MAP_BLOCKSIZE * BS;
3778 runData->fog_range = MYMIN(
3780 (draw_control->farthest_drawn + 20) * BS);
3781 runData->fog_range *= 0.9;
3785 Calculate general brightness
3787 u32 daynight_ratio = client->getEnv().getDayNightRatio();
3788 float time_brightness = decode_light_f((float)daynight_ratio / 1000.0);
3789 float direct_brightness;
3792 if (g_settings->getBool("free_move")) {
3793 direct_brightness = time_brightness;
3794 sunlight_seen = true;
3796 ScopeProfiler sp(g_profiler, "Detecting background light", SPT_AVG);
3797 float old_brightness = sky->getBrightness();
3798 direct_brightness = client->getEnv().getClientMap()
3799 .getBackgroundBrightness(MYMIN(runData->fog_range * 1.2, 60 * BS),
3800 daynight_ratio, (int)(old_brightness * 255.5), &sunlight_seen)
3804 float time_of_day = runData->time_of_day;
3805 float time_of_day_smooth = runData->time_of_day_smooth;
3807 time_of_day = client->getEnv().getTimeOfDayF();
3809 const float maxsm = 0.05;
3810 const float todsm = 0.05;
3812 if (fabs(time_of_day - time_of_day_smooth) > maxsm &&
3813 fabs(time_of_day - time_of_day_smooth + 1.0) > maxsm &&
3814 fabs(time_of_day - time_of_day_smooth - 1.0) > maxsm)
3815 time_of_day_smooth = time_of_day;
3817 if (time_of_day_smooth > 0.8 && time_of_day < 0.2)
3818 time_of_day_smooth = time_of_day_smooth * (1.0 - todsm)
3819 + (time_of_day + 1.0) * todsm;
3821 time_of_day_smooth = time_of_day_smooth * (1.0 - todsm)
3822 + time_of_day * todsm;
3824 runData->time_of_day = time_of_day;
3825 runData->time_of_day_smooth = time_of_day_smooth;
3827 sky->update(time_of_day_smooth, time_brightness, direct_brightness,
3828 sunlight_seen, camera->getCameraMode(), player->getYaw(),
3829 player->getPitch());
3835 v3f player_position = player->getPosition();
3836 if (sky->getCloudsVisible()) {
3837 clouds->setVisible(true);
3838 clouds->step(dtime);
3839 clouds->update(v2f(player_position.X, player_position.Z),
3840 sky->getCloudColor());
3842 clouds->setVisible(false);
3849 client->getParticleManager()->step(dtime);
3855 if (m_cache_enable_fog && !flags.force_fog_off) {
3858 video::EFT_FOG_LINEAR,
3859 runData->fog_range * 0.4,
3860 runData->fog_range * 1.0,
3868 video::EFT_FOG_LINEAR,
3878 Get chat messages from client
3881 v2u32 screensize = driver->getScreenSize();
3883 updateChat(*client, dtime, flags.show_debug, screensize,
3884 flags.show_chat, runData->profiler_current_page,
3885 *chat_backend, guitext_chat);
3891 if (client->getPlayerItem() != runData->new_playeritem)
3892 client->selectPlayerItem(runData->new_playeritem);
3894 // Update local inventory if it has changed
3895 if (client->getLocalInventoryUpdated()) {
3896 //infostream<<"Updating local inventory"<<std::endl;
3897 client->getLocalInventory(*local_inventory);
3898 runData->update_wielded_item_trigger = true;
3901 if (runData->update_wielded_item_trigger) {
3902 // Update wielded tool
3903 InventoryList *mlist = local_inventory->getList("main");
3905 if (mlist && (client->getPlayerItem() < mlist->getSize())) {
3906 ItemStack item = mlist->getItem(client->getPlayerItem());
3907 camera->wield(item);
3909 runData->update_wielded_item_trigger = false;
3913 Update block draw list every 200ms or when camera direction has
3916 runData->update_draw_list_timer += dtime;
3918 v3f camera_direction = camera->getDirection();
3919 if (runData->update_draw_list_timer >= 0.2
3920 || runData->update_draw_list_last_cam_dir.getDistanceFrom(camera_direction) > 0.2
3921 || flags.camera_offset_changed) {
3922 runData->update_draw_list_timer = 0;
3923 client->getEnv().getClientMap().updateDrawList(driver);
3924 runData->update_draw_list_last_cam_dir = camera_direction;
3927 updateGui(&runData->statustext_time, *stats, *runData, dtime, flags, cam);
3930 make sure menu is on top
3931 1. Delete formspec menu reference if menu was removed
3932 2. Else, make sure formspec menu is on top
3934 if (current_formspec) {
3935 if (current_formspec->getReferenceCount() == 1) {
3936 current_formspec->drop();
3937 current_formspec = NULL;
3938 } else if (!noMenuActive()) {
3939 guiroot->bringToFront(current_formspec);
3947 video::SColor skycolor = sky->getSkyColor();
3949 TimeTaker tt_draw("mainloop: draw");
3951 TimeTaker timer("beginScene");
3952 driver->beginScene(true, true, skycolor);
3953 stats->beginscenetime = timer.stop(true);
3956 draw_scene(driver, smgr, *camera, *client, player, *hud, guienv,
3957 highlight_boxes, screensize, skycolor, flags.show_hud);
3962 if (flags.show_profiler_graph)
3963 graph->draw(10, screensize.Y - 10, driver, g_fontengine->getFont());
3968 if (runData->damage_flash > 0.0) {
3969 video::SColor color(std::min(runData->damage_flash, 180.0f),
3973 driver->draw2DRectangle(color,
3974 core::rect<s32>(0, 0, screensize.X, screensize.Y),
3977 runData->damage_flash -= 100.0 * dtime;
3983 if (player->hurt_tilt_timer > 0.0) {
3984 player->hurt_tilt_timer -= dtime * 5;
3986 if (player->hurt_tilt_timer < 0)
3987 player->hurt_tilt_strength = 0;
3994 TimeTaker timer("endScene");
3996 stats->endscenetime = timer.stop(true);
3999 stats->drawtime = tt_draw.stop(true);
4000 g_profiler->graphAdd("mainloop_draw", stats->drawtime / 1000.0f);
4004 inline static const char *yawToDirectionString(int yaw)
4006 // NOTE: TODO: This can be done mathematically without the else/else-if
4009 const char *player_direction;
4011 yaw = wrapDegrees_0_360(yaw);
4013 if (yaw >= 45 && yaw < 135)
4014 player_direction = "West [-X]";
4015 else if (yaw >= 135 && yaw < 225)
4016 player_direction = "South [-Z]";
4017 else if (yaw >= 225 && yaw < 315)
4018 player_direction = "East [+X]";
4020 player_direction = "North [+Z]";
4022 return player_direction;
4026 void Game::updateGui(float *statustext_time, const RunStats &stats,
4027 const GameRunData& runData, f32 dtime, const VolatileRunFlags &flags,
4028 const CameraOrientation &cam)
4030 v2u32 screensize = driver->getScreenSize();
4031 LocalPlayer *player = client->getEnv().getLocalPlayer();
4032 v3f player_position = player->getPosition();
4034 if (flags.show_debug) {
4035 static float drawtime_avg = 0;
4036 drawtime_avg = drawtime_avg * 0.95 + stats.drawtime * 0.05;
4038 u16 fps = 1.0 / stats.dtime_jitter.avg;
4039 //s32 fps = driver->getFPS();
4041 std::ostringstream os(std::ios_base::binary);
4043 << PROJECT_NAME_C " " << g_version_hash
4045 << " (R: range_all=" << draw_control->range_all << ")"
4046 << std::setprecision(0)
4047 << " drawtime = " << drawtime_avg
4048 << std::setprecision(1)
4049 << ", dtime_jitter = "
4050 << (stats.dtime_jitter.max_fraction * 100.0) << " %"
4051 << std::setprecision(1)
4052 << ", v_range = " << draw_control->wanted_range
4053 << std::setprecision(3)
4054 << ", RTT = " << client->getRTT();
4055 guitext->setText(narrow_to_wide(os.str()).c_str());
4056 guitext->setVisible(true);
4057 } else if (flags.show_hud || flags.show_chat) {
4058 std::ostringstream os(std::ios_base::binary);
4059 os << PROJECT_NAME_C " " << g_version_hash;
4060 guitext->setText(narrow_to_wide(os.str()).c_str());
4061 guitext->setVisible(true);
4063 guitext->setVisible(false);
4066 if (guitext->isVisible()) {
4067 core::rect<s32> rect(
4069 screensize.X, 5 + g_fontengine->getTextHeight()
4071 guitext->setRelativePosition(rect);
4074 if (flags.show_debug) {
4075 std::ostringstream os(std::ios_base::binary);
4076 os << std::setprecision(1) << std::fixed
4077 << "(" << (player_position.X / BS)
4078 << ", " << (player_position.Y / BS)
4079 << ", " << (player_position.Z / BS)
4080 << ") (yaw=" << (wrapDegrees_0_360(cam.camera_yaw))
4081 << " " << yawToDirectionString(cam.camera_yaw)
4082 << ") (seed = " << ((u64)client->getMapSeed())
4085 if (runData.pointed_old.type == POINTEDTHING_NODE) {
4086 ClientMap &map = client->getEnv().getClientMap();
4087 const INodeDefManager *nodedef = client->getNodeDefManager();
4088 MapNode n = map.getNodeNoEx(runData.pointed_old.node_undersurface);
4089 if (n.getContent() != CONTENT_IGNORE && nodedef->get(n).name != "unknown") {
4090 const ContentFeatures &features = nodedef->get(n);
4091 os << " (pointing_at = " << nodedef->get(n).name
4092 << " - " << features.tiledef[0].name.c_str()
4097 guitext2->setText(narrow_to_wide(os.str()).c_str());
4098 guitext2->setVisible(true);
4100 core::rect<s32> rect(
4101 5, 5 + g_fontengine->getTextHeight(),
4102 screensize.X, 5 + g_fontengine->getTextHeight() * 2
4104 guitext2->setRelativePosition(rect);
4106 guitext2->setVisible(false);
4109 guitext_info->setText(infotext.c_str());
4110 guitext_info->setVisible(flags.show_hud && g_menumgr.menuCount() == 0);
4112 float statustext_time_max = 1.5;
4114 if (!statustext.empty()) {
4115 *statustext_time += dtime;
4117 if (*statustext_time >= statustext_time_max) {
4119 *statustext_time = 0;
4123 guitext_status->setText(statustext.c_str());
4124 guitext_status->setVisible(!statustext.empty());
4126 if (!statustext.empty()) {
4127 s32 status_width = guitext_status->getTextWidth();
4128 s32 status_height = guitext_status->getTextHeight();
4129 s32 status_y = screensize.Y - 150;
4130 s32 status_x = (screensize.X - status_width) / 2;
4131 core::rect<s32> rect(
4132 status_x , status_y - status_height,
4133 status_x + status_width, status_y
4135 guitext_status->setRelativePosition(rect);
4138 video::SColor initial_color(255, 0, 0, 0);
4140 if (guienv->getSkin())
4141 initial_color = guienv->getSkin()->getColor(gui::EGDC_BUTTON_TEXT);
4143 video::SColor final_color = initial_color;
4144 final_color.setAlpha(0);
4145 video::SColor fade_color = initial_color.getInterpolated_quadratic(
4146 initial_color, final_color,
4147 pow(*statustext_time / statustext_time_max, 2.0f));
4148 guitext_status->setOverrideColor(fade_color);
4149 guitext_status->enableOverrideColor(true);
4154 /* Log times and stuff for visualization */
4155 inline void Game::updateProfilerGraphs(ProfilerGraph *graph)
4157 Profiler::GraphValues values;
4158 g_profiler->graphGet(values);
4164 /****************************************************************************
4166 ****************************************************************************/
4168 /* On some computers framerate doesn't seem to be automatically limited
4170 inline void Game::limitFps(FpsControl *fps_timings, f32 *dtime)
4172 // not using getRealTime is necessary for wine
4173 device->getTimer()->tick(); // Maker sure device time is up-to-date
4174 u32 time = device->getTimer()->getTime();
4175 u32 last_time = fps_timings->last_time;
4177 if (time > last_time) // Make sure time hasn't overflowed
4178 fps_timings->busy_time = time - last_time;
4180 fps_timings->busy_time = 0;
4182 u32 frametime_min = 1000 / (g_menumgr.pausesGame()
4183 ? g_settings->getFloat("pause_fps_max")
4184 : g_settings->getFloat("fps_max"));
4186 if (fps_timings->busy_time < frametime_min) {
4187 fps_timings->sleep_time = frametime_min - fps_timings->busy_time;
4188 device->sleep(fps_timings->sleep_time);
4190 fps_timings->sleep_time = 0;
4193 /* Get the new value of the device timer. Note that device->sleep() may
4194 * not sleep for the entire requested time as sleep may be interrupted and
4195 * therefore it is arguably more accurate to get the new time from the
4196 * device rather than calculating it by adding sleep_time to time.
4199 device->getTimer()->tick(); // Update device timer
4200 time = device->getTimer()->getTime();
4202 if (time > last_time) // Make sure last_time hasn't overflowed
4203 *dtime = (time - last_time) / 1000.0;
4207 fps_timings->last_time = time;
4210 // Note: This will free (using delete[])! \p msg. If you want to use it later,
4211 // pass a copy of it to this function
4212 // Note: \p msg must be allocated using new (not malloc())
4213 void Game::showOverlayMessage(const wchar_t *msg, float dtime,
4214 int percent, bool draw_clouds)
4216 draw_load_screen(msg, device, guienv, dtime, percent, draw_clouds);
4221 /****************************************************************************/
4222 /****************************************************************************
4224 ****************************************************************************/
4225 /****************************************************************************/
4227 void Game::extendedResourceCleanup()
4229 // Extended resource accounting
4230 infostream << "Irrlicht resources after cleanup:" << std::endl;
4231 infostream << "\tRemaining meshes : "
4232 << device->getSceneManager()->getMeshCache()->getMeshCount() << std::endl;
4233 infostream << "\tRemaining textures : "
4234 << driver->getTextureCount() << std::endl;
4236 for (unsigned int i = 0; i < driver->getTextureCount(); i++) {
4237 irr::video::ITexture *texture = driver->getTextureByIndex(i);
4238 infostream << "\t\t" << i << ":" << texture->getName().getPath().c_str()
4242 clearTextureNameCache();
4243 infostream << "\tRemaining materials: "
4244 << driver-> getMaterialRendererCount()
4245 << " (note: irrlicht doesn't support removing renderers)" << std::endl;
4249 /****************************************************************************/
4250 /****************************************************************************
4251 extern function for launching the game
4252 ****************************************************************************/
4253 /****************************************************************************/
4255 void the_game(bool *kill,
4257 InputHandler *input,
4258 IrrlichtDevice *device,
4260 const std::string &map_dir,
4261 const std::string &playername,
4262 const std::string &password,
4263 const std::string &address, // If empty local server is created
4266 std::string &error_message,
4267 ChatBackend &chat_backend,
4268 const SubgameSpec &gamespec, // Used for local game
4269 bool simple_singleplayer_mode)
4273 /* Make a copy of the server address because if a local singleplayer server
4274 * is created then this is updated and we don't want to change the value
4275 * passed to us by the calling function
4277 std::string server_address = address;
4281 if (game.startup(kill, random_input, input, device, map_dir,
4282 playername, password, &server_address, port,
4283 error_message, &chat_backend, gamespec,
4284 simple_singleplayer_mode)) {
4289 } catch (SerializationError &e) {
4290 error_message = std::string("A serialization error occurred:\n")
4291 + e.what() + "\n\nThe server is probably "
4292 " running a different version of " PROJECT_NAME_C ".";
4293 errorstream << error_message << std::endl;
4294 } catch (ServerError &e) {
4295 error_message = e.what();
4296 errorstream << "ServerError: " << error_message << std::endl;
4297 } catch (ModError &e) {
4298 error_message = e.what() + strgettext("\nCheck debug.txt for details.");
4299 errorstream << "ModError: " << error_message << std::endl;