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 (*cur_formspec)->setFocus(L"btn_continue");
1152 (*cur_formspec)->doPause = true;
1155 /******************************************************************************/
1156 static void updateChat(Client &client, f32 dtime, bool show_debug,
1157 const v2u32 &screensize, bool show_chat, u32 show_profiler,
1158 ChatBackend &chat_backend, gui::IGUIStaticText *guitext_chat)
1160 // Add chat log output for errors to be shown in chat
1161 static LogOutputBuffer chat_log_error_buf(LMT_ERROR);
1163 // Get new messages from error log buffer
1164 while (!chat_log_error_buf.empty()) {
1165 chat_backend.addMessage(L"", narrow_to_wide(chat_log_error_buf.get()));
1168 // Get new messages from client
1169 std::wstring message;
1171 while (client.getChatMessage(message)) {
1172 chat_backend.addUnparsedMessage(message);
1175 // Remove old messages
1176 chat_backend.step(dtime);
1178 // Display all messages in a static text element
1179 unsigned int recent_chat_count = chat_backend.getRecentBuffer().getLineCount();
1180 std::wstring recent_chat = chat_backend.getRecentChat();
1181 unsigned int line_height = g_fontengine->getLineHeight();
1183 guitext_chat->setText(recent_chat.c_str());
1185 // Update gui element size and position
1186 s32 chat_y = 5 + line_height;
1189 chat_y += line_height;
1191 // first pass to calculate height of text to be set
1192 s32 width = std::min(g_fontengine->getTextWidth(recent_chat) + 10,
1193 porting::getWindowSize().X - 20);
1194 core::rect<s32> rect(10, chat_y, width, chat_y + porting::getWindowSize().Y);
1195 guitext_chat->setRelativePosition(rect);
1197 //now use real height of text and adjust rect according to this size
1198 rect = core::rect<s32>(10, chat_y, width,
1199 chat_y + guitext_chat->getTextHeight());
1202 guitext_chat->setRelativePosition(rect);
1203 // Don't show chat if disabled or empty or profiler is enabled
1204 guitext_chat->setVisible(
1205 show_chat && recent_chat_count != 0 && !show_profiler);
1209 /****************************************************************************
1210 Fast key cache for main game loop
1211 ****************************************************************************/
1213 /* This is faster than using getKeySetting with the tradeoff that functions
1214 * using it must make sure that it's initialised before using it and there is
1215 * no error handling (for example bounds checking). This is really intended for
1216 * use only in the main running loop of the client (the_game()) where the faster
1217 * (up to 10x faster) key lookup is an asset. Other parts of the codebase
1218 * (e.g. formspecs) should continue using getKeySetting().
1222 KeyCache() { populate(); }
1236 KEYMAP_ID_INVENTORY,
1243 KEYMAP_ID_CINEMATIC,
1244 KEYMAP_ID_SCREENSHOT,
1245 KEYMAP_ID_TOGGLE_HUD,
1246 KEYMAP_ID_TOGGLE_CHAT,
1247 KEYMAP_ID_TOGGLE_FORCE_FOG_OFF,
1248 KEYMAP_ID_TOGGLE_UPDATE_CAMERA,
1249 KEYMAP_ID_TOGGLE_DEBUG,
1250 KEYMAP_ID_TOGGLE_PROFILER,
1251 KEYMAP_ID_CAMERA_MODE,
1252 KEYMAP_ID_INCREASE_VIEWING_RANGE,
1253 KEYMAP_ID_DECREASE_VIEWING_RANGE,
1254 KEYMAP_ID_RANGESELECT,
1256 KEYMAP_ID_QUICKTUNE_NEXT,
1257 KEYMAP_ID_QUICKTUNE_PREV,
1258 KEYMAP_ID_QUICKTUNE_INC,
1259 KEYMAP_ID_QUICKTUNE_DEC,
1261 KEYMAP_ID_DEBUG_STACKS,
1263 // Fake keycode for array size and internal checks
1264 KEYMAP_INTERNAL_ENUM_COUNT
1271 KeyPress key[KEYMAP_INTERNAL_ENUM_COUNT];
1274 void KeyCache::populate()
1276 key[KEYMAP_ID_FORWARD] = getKeySetting("keymap_forward");
1277 key[KEYMAP_ID_BACKWARD] = getKeySetting("keymap_backward");
1278 key[KEYMAP_ID_LEFT] = getKeySetting("keymap_left");
1279 key[KEYMAP_ID_RIGHT] = getKeySetting("keymap_right");
1280 key[KEYMAP_ID_JUMP] = getKeySetting("keymap_jump");
1281 key[KEYMAP_ID_SPECIAL1] = getKeySetting("keymap_special1");
1282 key[KEYMAP_ID_SNEAK] = getKeySetting("keymap_sneak");
1284 key[KEYMAP_ID_DROP] = getKeySetting("keymap_drop");
1285 key[KEYMAP_ID_INVENTORY] = getKeySetting("keymap_inventory");
1286 key[KEYMAP_ID_CHAT] = getKeySetting("keymap_chat");
1287 key[KEYMAP_ID_CMD] = getKeySetting("keymap_cmd");
1288 key[KEYMAP_ID_CONSOLE] = getKeySetting("keymap_console");
1289 key[KEYMAP_ID_FREEMOVE] = getKeySetting("keymap_freemove");
1290 key[KEYMAP_ID_FASTMOVE] = getKeySetting("keymap_fastmove");
1291 key[KEYMAP_ID_NOCLIP] = getKeySetting("keymap_noclip");
1292 key[KEYMAP_ID_CINEMATIC] = getKeySetting("keymap_cinematic");
1293 key[KEYMAP_ID_SCREENSHOT] = getKeySetting("keymap_screenshot");
1294 key[KEYMAP_ID_TOGGLE_HUD] = getKeySetting("keymap_toggle_hud");
1295 key[KEYMAP_ID_TOGGLE_CHAT] = getKeySetting("keymap_toggle_chat");
1296 key[KEYMAP_ID_TOGGLE_FORCE_FOG_OFF]
1297 = getKeySetting("keymap_toggle_force_fog_off");
1298 key[KEYMAP_ID_TOGGLE_UPDATE_CAMERA]
1299 = getKeySetting("keymap_toggle_update_camera");
1300 key[KEYMAP_ID_TOGGLE_DEBUG]
1301 = getKeySetting("keymap_toggle_debug");
1302 key[KEYMAP_ID_TOGGLE_PROFILER]
1303 = getKeySetting("keymap_toggle_profiler");
1304 key[KEYMAP_ID_CAMERA_MODE]
1305 = getKeySetting("keymap_camera_mode");
1306 key[KEYMAP_ID_INCREASE_VIEWING_RANGE]
1307 = getKeySetting("keymap_increase_viewing_range_min");
1308 key[KEYMAP_ID_DECREASE_VIEWING_RANGE]
1309 = getKeySetting("keymap_decrease_viewing_range_min");
1310 key[KEYMAP_ID_RANGESELECT]
1311 = getKeySetting("keymap_rangeselect");
1313 key[KEYMAP_ID_QUICKTUNE_NEXT] = getKeySetting("keymap_quicktune_next");
1314 key[KEYMAP_ID_QUICKTUNE_PREV] = getKeySetting("keymap_quicktune_prev");
1315 key[KEYMAP_ID_QUICKTUNE_INC] = getKeySetting("keymap_quicktune_inc");
1316 key[KEYMAP_ID_QUICKTUNE_DEC] = getKeySetting("keymap_quicktune_dec");
1318 key[KEYMAP_ID_DEBUG_STACKS] = getKeySetting("keymap_print_debug_stacks");
1322 /****************************************************************************
1324 ****************************************************************************/
1326 const float object_hit_delay = 0.2;
1329 u32 last_time, busy_time, sleep_time;
1333 /* The reason the following structs are not anonymous structs within the
1334 * class is that they are not used by the majority of member functions and
1335 * many functions that do require objects of thse types do not modify them
1336 * (so they can be passed as a const qualified parameter)
1338 struct CameraOrientation {
1339 f32 camera_yaw; // "right/left"
1340 f32 camera_pitch; // "up/down"
1343 struct GameRunData {
1346 PointedThing pointed_old;
1350 bool update_wielded_item_trigger;
1351 bool reset_jump_timer;
1352 float nodig_delay_timer;
1354 float dig_time_complete;
1355 float repeat_rightclick_timer;
1356 float object_hit_delay_timer;
1357 float time_from_last_punch;
1358 ClientActiveObject *selected_object;
1362 float update_draw_list_timer;
1363 float statustext_time;
1367 v3f update_draw_list_last_cam_dir;
1369 u32 profiler_current_page;
1370 u32 profiler_max_page; // Number of pages
1373 float time_of_day_smooth;
1377 f32 max, min, avg, counter, max_sample, min_sample, max_fraction;
1385 Jitter dtime_jitter, busy_time_jitter;
1388 /* Flags that can, or may, change during main game loop
1390 struct VolatileRunFlags {
1396 bool show_profiler_graph;
1397 bool disable_camera_update;
1398 bool first_loop_after_window_activation;
1399 bool camera_offset_changed;
1403 /****************************************************************************
1405 ****************************************************************************/
1407 /* This is not intended to be a public class. If a public class becomes
1408 * desirable then it may be better to create another 'wrapper' class that
1409 * hides most of the stuff in this class (nothing in this class is required
1410 * by any other file) but exposes the public methods/data only.
1418 bool startup(bool *kill,
1420 InputHandler *input,
1421 IrrlichtDevice *device,
1422 const std::string &map_dir,
1423 const std::string &playername,
1424 const std::string &password,
1425 // If address is "", local server is used and address is updated
1426 std::string *address,
1428 std::string &error_message,
1429 ChatBackend *chat_backend,
1430 const SubgameSpec &gamespec, // Used for local game
1431 bool simple_singleplayer_mode);
1438 void extendedResourceCleanup();
1440 // Basic initialisation
1441 bool init(const std::string &map_dir, std::string *address,
1443 const SubgameSpec &gamespec);
1445 bool createSingleplayerServer(const std::string map_dir,
1446 const SubgameSpec &gamespec, u16 port, std::string *address);
1449 bool createClient(const std::string &playername,
1450 const std::string &password, std::string *address, u16 port);
1453 // Client connection
1454 bool connectToServer(const std::string &playername,
1455 const std::string &password, std::string *address, u16 port,
1456 bool *connect_ok, bool *aborted);
1457 bool getServerContent(bool *aborted);
1461 void updateInteractTimers(GameRunData *runData, f32 dtime);
1462 bool checkConnection();
1463 bool handleCallbacks();
1464 void processQueues();
1465 void updateProfilers(const GameRunData &runData, const RunStats &stats,
1466 const FpsControl &draw_times, f32 dtime);
1467 void addProfilerGraphs(const RunStats &stats, const FpsControl &draw_times,
1469 void updateStats(RunStats *stats, const FpsControl &draw_times, f32 dtime);
1471 void processUserInput(VolatileRunFlags *flags, GameRunData *runData,
1473 void processKeyboardInput(VolatileRunFlags *flags,
1474 float *statustext_time,
1476 bool *reset_jump_timer,
1477 u32 *profiler_current_page,
1478 u32 profiler_max_page);
1479 void processItemSelection(u16 *new_playeritem);
1481 void dropSelectedItem();
1482 void openInventory();
1484 void toggleFreeMove(float *statustext_time);
1485 void toggleFreeMoveAlt(float *statustext_time, float *jump_timer);
1486 void toggleFast(float *statustext_time);
1487 void toggleNoClip(float *statustext_time);
1488 void toggleCinematic(float *statustext_time);
1490 void toggleChat(float *statustext_time, bool *flag);
1491 void toggleHud(float *statustext_time, bool *flag);
1492 void toggleFog(float *statustext_time, bool *flag);
1493 void toggleDebug(float *statustext_time, bool *show_debug,
1494 bool *show_profiler_graph);
1495 void toggleUpdateCamera(float *statustext_time, bool *flag);
1496 void toggleProfiler(float *statustext_time, u32 *profiler_current_page,
1497 u32 profiler_max_page);
1499 void increaseViewRange(float *statustext_time);
1500 void decreaseViewRange(float *statustext_time);
1501 void toggleFullViewRange(float *statustext_time);
1503 void updateCameraDirection(CameraOrientation *cam, VolatileRunFlags *flags);
1504 void updateCameraOrientation(CameraOrientation *cam,
1505 const VolatileRunFlags &flags);
1506 void updatePlayerControl(const CameraOrientation &cam);
1507 void step(f32 *dtime);
1508 void processClientEvents(CameraOrientation *cam, float *damage_flash);
1509 void updateCamera(VolatileRunFlags *flags, u32 busy_time, f32 dtime,
1510 float time_from_last_punch);
1511 void updateSound(f32 dtime);
1512 void processPlayerInteraction(std::vector<aabb3f> &highlight_boxes,
1513 GameRunData *runData, f32 dtime, bool show_hud,
1515 void handlePointingAtNode(GameRunData *runData,
1516 const PointedThing &pointed, const ItemDefinition &playeritem_def,
1517 const ToolCapabilities &playeritem_toolcap, f32 dtime);
1518 void handlePointingAtObject(GameRunData *runData,
1519 const PointedThing &pointed, const ItemStack &playeritem,
1520 const v3f &player_position, bool show_debug);
1521 void handleDigging(GameRunData *runData, const PointedThing &pointed,
1522 const v3s16 &nodepos, const ToolCapabilities &playeritem_toolcap,
1524 void updateFrame(std::vector<aabb3f> &highlight_boxes, ProfilerGraph *graph,
1525 RunStats *stats, GameRunData *runData,
1526 f32 dtime, const VolatileRunFlags &flags, const CameraOrientation &cam);
1527 void updateGui(float *statustext_time, const RunStats &stats,
1528 const GameRunData& runData, f32 dtime, const VolatileRunFlags &flags,
1529 const CameraOrientation &cam);
1530 void updateProfilerGraphs(ProfilerGraph *graph);
1533 void limitFps(FpsControl *fps_timings, f32 *dtime);
1535 void showOverlayMessage(const wchar_t *msg, float dtime, int percent,
1536 bool draw_clouds = true);
1539 InputHandler *input;
1544 IWritableTextureSource *texture_src;
1545 IWritableShaderSource *shader_src;
1547 // When created, these will be filled with data received from the server
1548 IWritableItemDefManager *itemdef_manager;
1549 IWritableNodeDefManager *nodedef_manager;
1551 GameOnDemandSoundFetcher soundfetcher; // useful when testing
1552 ISoundManager *sound;
1553 bool sound_is_dummy;
1554 SoundMaker *soundmaker;
1556 ChatBackend *chat_backend;
1558 GUIFormSpecMenu *current_formspec;
1560 EventManager *eventmgr;
1561 QuicktuneShortcutter *quicktune;
1563 GUIChatConsole *gui_chat_console; // Free using ->Drop()
1564 MapDrawControl *draw_control;
1566 Clouds *clouds; // Free using ->Drop()
1567 Sky *sky; // Free using ->Drop()
1568 Inventory *local_inventory;
1572 This class does take ownership/responsibily for cleaning up etc of any of
1573 these items (e.g. device)
1575 IrrlichtDevice *device;
1576 video::IVideoDriver *driver;
1577 scene::ISceneManager *smgr;
1579 std::string *error_message;
1580 IGameDef *gamedef; // Convenience (same as *client)
1581 scene::ISceneNode *skybox;
1584 bool simple_singleplayer_mode;
1587 /* Pre-calculated values
1589 int crack_animation_length;
1593 gui::IGUIStaticText *guitext; // First line of debug text
1594 gui::IGUIStaticText *guitext2; // Second line of debug text
1595 gui::IGUIStaticText *guitext_info; // At the middle of the screen
1596 gui::IGUIStaticText *guitext_status;
1597 gui::IGUIStaticText *guitext_chat; // Chat text
1598 gui::IGUIStaticText *guitext_profiler; // Profiler text
1600 std::wstring infotext;
1601 std::wstring statustext;
1605 IntervalLimiter profiler_interval;
1607 /* TODO: Add a callback function so these can be updated when a setting
1608 * changes. At this point in time it doesn't matter (e.g. /set
1609 * is documented to change server settings only)
1611 * TODO: Local caching of settings is not optimal and should at some stage
1612 * be updated to use a global settings object for getting thse values
1613 * (as opposed to the this local caching). This can be addressed in
1616 bool m_cache_doubletap_jump;
1617 bool m_cache_enable_node_highlighting;
1618 bool m_cache_enable_clouds;
1619 bool m_cache_enable_particles;
1620 bool m_cache_enable_fog;
1621 f32 m_cache_mouse_sensitivity;
1622 f32 m_repeat_right_click_time;
1625 bool m_cache_hold_aux1;
1635 itemdef_manager(NULL),
1636 nodedef_manager(NULL),
1638 sound_is_dummy(false),
1641 current_formspec(NULL),
1644 gui_chat_console(NULL),
1649 local_inventory(NULL),
1652 m_cache_doubletap_jump = g_settings->getBool("doubletap_jump");
1653 m_cache_enable_node_highlighting = g_settings->getBool("enable_node_highlighting");
1654 m_cache_enable_clouds = g_settings->getBool("enable_clouds");
1655 m_cache_enable_particles = g_settings->getBool("enable_particles");
1656 m_cache_enable_fog = g_settings->getBool("enable_fog");
1657 m_cache_mouse_sensitivity = g_settings->getFloat("mouse_sensitivity");
1658 m_repeat_right_click_time = g_settings->getFloat("repeat_rightclick_time");
1660 m_cache_mouse_sensitivity = rangelim(m_cache_mouse_sensitivity, 0.001, 100.0);
1663 m_cache_hold_aux1 = false; // This is initialised properly later
1670 /****************************************************************************
1672 ****************************************************************************/
1678 if (!sound_is_dummy)
1681 delete server; // deleted first to stop all server threads
1684 delete local_inventory;
1690 delete nodedef_manager;
1691 delete itemdef_manager;
1692 delete draw_control;
1694 extendedResourceCleanup();
1697 bool Game::startup(bool *kill,
1699 InputHandler *input,
1700 IrrlichtDevice *device,
1701 const std::string &map_dir,
1702 const std::string &playername,
1703 const std::string &password,
1704 std::string *address, // can change if simple_singleplayer_mode
1706 std::string &error_message,
1707 ChatBackend *chat_backend,
1708 const SubgameSpec &gamespec,
1709 bool simple_singleplayer_mode)
1712 this->device = device;
1714 this->error_message = &error_message;
1715 this->random_input = random_input;
1716 this->input = input;
1717 this->chat_backend = chat_backend;
1718 this->simple_singleplayer_mode = simple_singleplayer_mode;
1720 driver = device->getVideoDriver();
1721 smgr = device->getSceneManager();
1723 smgr->getParameters()->setAttribute(scene::OBJ_LOADER_IGNORE_MATERIAL_FILES, true);
1725 if (!init(map_dir, address, port, gamespec))
1728 if (!createClient(playername, password, address, port))
1737 ProfilerGraph graph;
1738 RunStats stats = { 0 };
1739 CameraOrientation cam_view_target = { 0 };
1740 CameraOrientation cam_view = { 0 };
1741 GameRunData runData = { 0 };
1742 FpsControl draw_times = { 0 };
1743 VolatileRunFlags flags = { 0 };
1744 f32 dtime; // in seconds
1746 runData.time_from_last_punch = 10.0;
1747 runData.profiler_max_page = 3;
1748 runData.update_wielded_item_trigger = true;
1750 flags.show_chat = true;
1751 flags.show_hud = true;
1752 flags.show_debug = g_settings->getBool("show_debug");
1753 flags.invert_mouse = g_settings->getBool("invert_mouse");
1754 flags.first_loop_after_window_activation = true;
1756 /* Clear the profiler */
1757 Profiler::GraphValues dummyvalues;
1758 g_profiler->graphGet(dummyvalues);
1760 draw_times.last_time = device->getTimer()->getTime();
1762 shader_src->addGlobalConstantSetter(new GameGlobalShaderConstantSetter(
1764 &flags.force_fog_off,
1768 std::vector<aabb3f> highlight_boxes;
1770 set_light_table(g_settings->getFloat("display_gamma"));
1773 m_cache_hold_aux1 = g_settings->getBool("fast_move")
1774 && client->checkPrivilege("fast");
1777 while (device->run() && !(*kill || g_gamecallback->shutdown_requested)) {
1779 /* Must be called immediately after a device->run() call because it
1780 * uses device->getTimer()->getTime()
1782 limitFps(&draw_times, &dtime);
1784 updateStats(&stats, draw_times, dtime);
1785 updateInteractTimers(&runData, dtime);
1787 if (!checkConnection())
1789 if (!handleCallbacks())
1795 hud->resizeHotbar();
1797 updateProfilers(runData, stats, draw_times, dtime);
1798 processUserInput(&flags, &runData, dtime);
1799 // Update camera before player movement to avoid camera lag of one frame
1800 updateCameraDirection(&cam_view_target, &flags);
1801 float cam_smoothing = 0;
1802 if (g_settings->getBool("cinematic"))
1803 cam_smoothing = 1 - g_settings->getFloat("cinematic_camera_smoothing");
1805 cam_smoothing = 1 - g_settings->getFloat("camera_smoothing");
1806 cam_smoothing = rangelim(cam_smoothing, 0.01f, 1.0f);
1807 cam_view.camera_yaw += (cam_view_target.camera_yaw -
1808 cam_view.camera_yaw) * cam_smoothing;
1809 cam_view.camera_pitch += (cam_view_target.camera_pitch -
1810 cam_view.camera_pitch) * cam_smoothing;
1811 updatePlayerControl(cam_view);
1813 processClientEvents(&cam_view_target, &runData.damage_flash);
1814 updateCamera(&flags, draw_times.busy_time, dtime,
1815 runData.time_from_last_punch);
1817 processPlayerInteraction(highlight_boxes, &runData, dtime,
1818 flags.show_hud, flags.show_debug);
1819 updateFrame(highlight_boxes, &graph, &stats, &runData, dtime,
1821 updateProfilerGraphs(&graph);
1826 void Game::shutdown()
1828 showOverlayMessage(wgettext("Shutting down..."), 0, 0, false);
1833 if (gui_chat_console)
1834 gui_chat_console->drop();
1840 while (g_menumgr.menuCount() > 0) {
1841 g_menumgr.m_stack.front()->setVisible(false);
1842 g_menumgr.deletingMenu(g_menumgr.m_stack.front());
1845 if (current_formspec) {
1846 current_formspec->drop();
1847 current_formspec = NULL;
1850 chat_backend->addMessage(L"", L"# Disconnected.");
1851 chat_backend->addMessage(L"", L"");
1855 while (!client->isShutdown()) {
1856 assert(texture_src != NULL);
1857 assert(shader_src != NULL);
1858 texture_src->processQueue();
1859 shader_src->processQueue();
1866 /****************************************************************************/
1867 /****************************************************************************
1869 ****************************************************************************/
1870 /****************************************************************************/
1873 const std::string &map_dir,
1874 std::string *address,
1876 const SubgameSpec &gamespec)
1878 showOverlayMessage(wgettext("Loading..."), 0, 0);
1880 texture_src = createTextureSource(device);
1881 shader_src = createShaderSource(device);
1883 itemdef_manager = createItemDefManager();
1884 nodedef_manager = createNodeDefManager();
1886 eventmgr = new EventManager();
1887 quicktune = new QuicktuneShortcutter();
1889 if (!(texture_src && shader_src && itemdef_manager && nodedef_manager
1890 && eventmgr && quicktune))
1896 // Create a server if not connecting to an existing one
1897 if (*address == "") {
1898 if (!createSingleplayerServer(map_dir, gamespec, port, address))
1905 bool Game::initSound()
1908 if (g_settings->getBool("enable_sound")) {
1909 infostream << "Attempting to use OpenAL audio" << std::endl;
1910 sound = createOpenALSoundManager(&soundfetcher);
1912 infostream << "Failed to initialize OpenAL audio" << std::endl;
1914 infostream << "Sound disabled." << std::endl;
1918 infostream << "Using dummy audio." << std::endl;
1919 sound = &dummySoundManager;
1920 sound_is_dummy = true;
1923 soundmaker = new SoundMaker(sound, nodedef_manager);
1927 soundmaker->registerReceiver(eventmgr);
1932 bool Game::createSingleplayerServer(const std::string map_dir,
1933 const SubgameSpec &gamespec, u16 port, std::string *address)
1935 showOverlayMessage(wgettext("Creating server..."), 0, 5);
1937 std::string bind_str = g_settings->get("bind_address");
1938 Address bind_addr(0, 0, 0, 0, port);
1940 if (g_settings->getBool("ipv6_server")) {
1941 bind_addr.setAddress((IPv6AddressBytes *) NULL);
1945 bind_addr.Resolve(bind_str.c_str());
1946 } catch (ResolveError &e) {
1947 infostream << "Resolving bind address \"" << bind_str
1948 << "\" failed: " << e.what()
1949 << " -- Listening on all addresses." << std::endl;
1952 if (bind_addr.isIPv6() && !g_settings->getBool("enable_ipv6")) {
1953 *error_message = "Unable to listen on " +
1954 bind_addr.serializeString() +
1955 " because IPv6 is disabled";
1956 errorstream << *error_message << std::endl;
1960 server = new Server(map_dir, gamespec, simple_singleplayer_mode,
1961 bind_addr.isIPv6());
1963 server->start(bind_addr);
1968 bool Game::createClient(const std::string &playername,
1969 const std::string &password, std::string *address, u16 port)
1971 showOverlayMessage(wgettext("Creating client..."), 0, 10);
1973 draw_control = new MapDrawControl;
1977 bool could_connect, connect_aborted;
1979 if (!connectToServer(playername, password, address, port,
1980 &could_connect, &connect_aborted))
1983 if (!could_connect) {
1984 if (error_message->empty() && !connect_aborted) {
1985 // Should not happen if error messages are set properly
1986 *error_message = "Connection failed for unknown reason";
1987 errorstream << *error_message << std::endl;
1992 if (!getServerContent(&connect_aborted)) {
1993 if (error_message->empty() && !connect_aborted) {
1994 // Should not happen if error messages are set properly
1995 *error_message = "Connection failed for unknown reason";
1996 errorstream << *error_message << std::endl;
2001 // Update cached textures, meshes and materials
2002 client->afterContentReceived(device);
2006 camera = new Camera(smgr, *draw_control, gamedef);
2007 if (!camera || !camera->successfullyCreated(*error_message))
2012 if (m_cache_enable_clouds) {
2013 clouds = new Clouds(smgr->getRootSceneNode(), smgr, -1, time(0));
2015 *error_message = "Memory allocation error (clouds)";
2016 errorstream << *error_message << std::endl;
2023 sky = new Sky(smgr->getRootSceneNode(), smgr, -1, texture_src);
2024 skybox = NULL; // This is used/set later on in the main run loop
2026 local_inventory = new Inventory(itemdef_manager);
2028 if (!(sky && local_inventory)) {
2029 *error_message = "Memory allocation error (sky or local inventory)";
2030 errorstream << *error_message << std::endl;
2034 /* Pre-calculated values
2036 video::ITexture *t = texture_src->getTexture("crack_anylength.png");
2038 v2u32 size = t->getOriginalSize();
2039 crack_animation_length = size.Y / size.X;
2041 crack_animation_length = 5;
2047 /* Set window caption
2049 std::wstring str = narrow_to_wide(PROJECT_NAME_C);
2051 str += driver->getName();
2053 device->setWindowCaption(str.c_str());
2055 LocalPlayer *player = client->getEnv().getLocalPlayer();
2056 player->hurt_tilt_timer = 0;
2057 player->hurt_tilt_strength = 0;
2059 hud = new Hud(driver, smgr, guienv, gamedef, player, local_inventory);
2062 *error_message = "Memory error: could not create HUD";
2063 errorstream << *error_message << std::endl;
2070 bool Game::initGui()
2072 // First line of debug text
2073 guitext = guienv->addStaticText(
2074 narrow_to_wide(PROJECT_NAME_C).c_str(),
2075 core::rect<s32>(0, 0, 0, 0),
2076 false, false, guiroot);
2078 // Second line of debug text
2079 guitext2 = guienv->addStaticText(
2081 core::rect<s32>(0, 0, 0, 0),
2082 false, false, guiroot);
2084 // At the middle of the screen
2085 // Object infos are shown in this
2086 guitext_info = guienv->addStaticText(
2088 core::rect<s32>(0, 0, 400, g_fontengine->getTextHeight() * 5 + 5) + v2s32(100, 200),
2089 false, true, guiroot);
2091 // Status text (displays info when showing and hiding GUI stuff, etc.)
2092 guitext_status = guienv->addStaticText(
2094 core::rect<s32>(0, 0, 0, 0),
2095 false, false, guiroot);
2096 guitext_status->setVisible(false);
2099 guitext_chat = guienv->addStaticText(
2101 core::rect<s32>(0, 0, 0, 0),
2102 //false, false); // Disable word wrap as of now
2103 false, true, guiroot);
2104 // Remove stale "recent" chat messages from previous connections
2105 chat_backend->clearRecentChat();
2107 // Chat backend and console
2108 gui_chat_console = new GUIChatConsole(guienv, guienv->getRootGUIElement(),
2109 -1, chat_backend, client);
2110 if (!gui_chat_console) {
2111 *error_message = "Could not allocate memory for chat console";
2112 errorstream << *error_message << std::endl;
2116 // Profiler text (size is updated when text is updated)
2117 guitext_profiler = guienv->addStaticText(
2119 core::rect<s32>(0, 0, 0, 0),
2120 false, false, guiroot);
2121 guitext_profiler->setBackgroundColor(video::SColor(120, 0, 0, 0));
2122 guitext_profiler->setVisible(false);
2123 guitext_profiler->setWordWrap(true);
2125 #ifdef HAVE_TOUCHSCREENGUI
2127 if (g_touchscreengui)
2128 g_touchscreengui->init(texture_src, porting::getDisplayDensity());
2135 bool Game::connectToServer(const std::string &playername,
2136 const std::string &password, std::string *address, u16 port,
2137 bool *connect_ok, bool *aborted)
2139 *connect_ok = false; // Let's not be overly optimistic
2141 bool local_server_mode = false;
2143 showOverlayMessage(wgettext("Resolving address..."), 0, 15);
2145 Address connect_address(0, 0, 0, 0, port);
2148 connect_address.Resolve(address->c_str());
2150 if (connect_address.isZero()) { // i.e. INADDR_ANY, IN6ADDR_ANY
2151 //connect_address.Resolve("localhost");
2152 if (connect_address.isIPv6()) {
2153 IPv6AddressBytes addr_bytes;
2154 addr_bytes.bytes[15] = 1;
2155 connect_address.setAddress(&addr_bytes);
2157 connect_address.setAddress(127, 0, 0, 1);
2159 local_server_mode = true;
2161 } catch (ResolveError &e) {
2162 *error_message = std::string("Couldn't resolve address: ") + e.what();
2163 errorstream << *error_message << std::endl;
2167 if (connect_address.isIPv6() && !g_settings->getBool("enable_ipv6")) {
2168 *error_message = "Unable to connect to " +
2169 connect_address.serializeString() +
2170 " because IPv6 is disabled";
2171 errorstream << *error_message << std::endl;
2175 client = new Client(device,
2176 playername.c_str(), password,
2177 *draw_control, texture_src, shader_src,
2178 itemdef_manager, nodedef_manager, sound, eventmgr,
2179 connect_address.isIPv6());
2184 gamedef = client; // Client acts as our GameDef
2186 infostream << "Connecting to server at ";
2187 connect_address.print(&infostream);
2188 infostream << std::endl;
2190 client->connect(connect_address, *address,
2191 simple_singleplayer_mode || local_server_mode);
2194 Wait for server to accept connection
2200 FpsControl fps_control = { 0 };
2202 f32 wait_time = 0; // in seconds
2204 fps_control.last_time = device->getTimer()->getTime();
2206 while (device->run()) {
2208 limitFps(&fps_control, &dtime);
2210 // Update client and server
2211 client->step(dtime);
2214 server->step(dtime);
2217 if (client->getState() == LC_Init) {
2223 if (client->accessDenied()) {
2224 *error_message = "Access denied. Reason: "
2225 + client->accessDeniedReason();
2226 errorstream << *error_message << std::endl;
2230 if (input->wasKeyDown(EscapeKey) || input->wasKeyDown(CancelKey)) {
2232 infostream << "Connect aborted [Escape]" << std::endl;
2237 // Only time out if we aren't waiting for the server we started
2238 if ((*address != "") && (wait_time > 10)) {
2239 *error_message = "Connection timed out.";
2240 errorstream << *error_message << std::endl;
2245 showOverlayMessage(wgettext("Connecting to server..."), dtime, 20);
2247 } catch (con::PeerNotFoundException &e) {
2248 // TODO: Should something be done here? At least an info/error
2256 bool Game::getServerContent(bool *aborted)
2260 FpsControl fps_control = { 0 };
2261 f32 dtime; // in seconds
2263 fps_control.last_time = device->getTimer()->getTime();
2265 while (device->run()) {
2267 limitFps(&fps_control, &dtime);
2269 // Update client and server
2270 client->step(dtime);
2273 server->step(dtime);
2276 if (client->mediaReceived() && client->itemdefReceived() &&
2277 client->nodedefReceived()) {
2282 if (!checkConnection())
2285 if (client->getState() < LC_Init) {
2286 *error_message = "Client disconnected";
2287 errorstream << *error_message << std::endl;
2291 if (input->wasKeyDown(EscapeKey) || input->wasKeyDown(CancelKey)) {
2293 infostream << "Connect aborted [Escape]" << std::endl;
2300 if (!client->itemdefReceived()) {
2301 const wchar_t *text = wgettext("Item definitions...");
2303 draw_load_screen(text, device, guienv, dtime, progress);
2305 } else if (!client->nodedefReceived()) {
2306 const wchar_t *text = wgettext("Node definitions...");
2308 draw_load_screen(text, device, guienv, dtime, progress);
2311 std::stringstream message;
2312 message.precision(3);
2313 message << gettext("Media...");
2315 if ((USE_CURL == 0) ||
2316 (!g_settings->getBool("enable_remote_media_server"))) {
2317 float cur = client->getCurRate();
2318 std::string cur_unit = gettext("KiB/s");
2322 cur_unit = gettext("MiB/s");
2325 message << " (" << cur << ' ' << cur_unit << ")";
2328 progress = 30 + client->mediaReceiveProgress() * 35 + 0.5;
2329 draw_load_screen(narrow_to_wide(message.str()), device,
2330 guienv, dtime, progress);
2338 /****************************************************************************/
2339 /****************************************************************************
2341 ****************************************************************************/
2342 /****************************************************************************/
2344 inline void Game::updateInteractTimers(GameRunData *runData, f32 dtime)
2346 if (runData->nodig_delay_timer >= 0)
2347 runData->nodig_delay_timer -= dtime;
2349 if (runData->object_hit_delay_timer >= 0)
2350 runData->object_hit_delay_timer -= dtime;
2352 runData->time_from_last_punch += dtime;
2356 /* returns false if game should exit, otherwise true
2358 inline bool Game::checkConnection()
2360 if (client->accessDenied()) {
2361 *error_message = "Access denied. Reason: "
2362 + client->accessDeniedReason();
2363 errorstream << *error_message << std::endl;
2371 /* returns false if game should exit, otherwise true
2373 inline bool Game::handleCallbacks()
2375 if (g_gamecallback->disconnect_requested) {
2376 g_gamecallback->disconnect_requested = false;
2380 if (g_gamecallback->changepassword_requested) {
2381 (new GUIPasswordChange(guienv, guiroot, -1,
2382 &g_menumgr, client))->drop();
2383 g_gamecallback->changepassword_requested = false;
2386 if (g_gamecallback->changevolume_requested) {
2387 (new GUIVolumeChange(guienv, guiroot, -1,
2388 &g_menumgr, client))->drop();
2389 g_gamecallback->changevolume_requested = false;
2392 if (g_gamecallback->keyconfig_requested) {
2393 (new GUIKeyChangeMenu(guienv, guiroot, -1,
2394 &g_menumgr))->drop();
2395 g_gamecallback->keyconfig_requested = false;
2398 if (g_gamecallback->keyconfig_changed) {
2399 keycache.populate(); // update the cache with new settings
2400 g_gamecallback->keyconfig_changed = false;
2407 void Game::processQueues()
2409 texture_src->processQueue();
2410 itemdef_manager->processQueue(gamedef);
2411 shader_src->processQueue();
2415 void Game::updateProfilers(const GameRunData &runData, const RunStats &stats,
2416 const FpsControl &draw_times, f32 dtime)
2418 float profiler_print_interval =
2419 g_settings->getFloat("profiler_print_interval");
2420 bool print_to_log = true;
2422 if (profiler_print_interval == 0) {
2423 print_to_log = false;
2424 profiler_print_interval = 5;
2427 if (profiler_interval.step(dtime, profiler_print_interval)) {
2429 infostream << "Profiler:" << std::endl;
2430 g_profiler->print(infostream);
2433 update_profiler_gui(guitext_profiler, g_fontengine,
2434 runData.profiler_current_page, runData.profiler_max_page,
2435 driver->getScreenSize().Height);
2437 g_profiler->clear();
2440 addProfilerGraphs(stats, draw_times, dtime);
2444 void Game::addProfilerGraphs(const RunStats &stats,
2445 const FpsControl &draw_times, f32 dtime)
2447 g_profiler->graphAdd("mainloop_other",
2448 draw_times.busy_time / 1000.0f - stats.drawtime / 1000.0f);
2450 if (draw_times.sleep_time != 0)
2451 g_profiler->graphAdd("mainloop_sleep", draw_times.sleep_time / 1000.0f);
2452 g_profiler->graphAdd("mainloop_dtime", dtime);
2454 g_profiler->add("Elapsed time", dtime);
2455 g_profiler->avg("FPS", 1. / dtime);
2459 void Game::updateStats(RunStats *stats, const FpsControl &draw_times,
2466 /* Time average and jitter calculation
2468 jp = &stats->dtime_jitter;
2469 jp->avg = jp->avg * 0.96 + dtime * 0.04;
2471 jitter = dtime - jp->avg;
2473 if (jitter > jp->max)
2476 jp->counter += dtime;
2478 if (jp->counter > 0.0) {
2480 jp->max_sample = jp->max;
2481 jp->max_fraction = jp->max_sample / (jp->avg + 0.001);
2485 /* Busytime average and jitter calculation
2487 jp = &stats->busy_time_jitter;
2488 jp->avg = jp->avg + draw_times.busy_time * 0.02;
2490 jitter = draw_times.busy_time - jp->avg;
2492 if (jitter > jp->max)
2494 if (jitter < jp->min)
2497 jp->counter += dtime;
2499 if (jp->counter > 0.0) {
2501 jp->max_sample = jp->max;
2502 jp->min_sample = jp->min;
2510 /****************************************************************************
2512 ****************************************************************************/
2514 void Game::processUserInput(VolatileRunFlags *flags,
2515 GameRunData *runData, f32 dtime)
2517 // Reset input if window not active or some menu is active
2518 if (device->isWindowActive() == false
2519 || noMenuActive() == false
2520 || guienv->hasFocus(gui_chat_console)) {
2524 if (!guienv->hasFocus(gui_chat_console) && gui_chat_console->isOpen()) {
2525 gui_chat_console->closeConsoleAtOnce();
2528 // Input handler step() (used by the random input generator)
2531 #ifdef HAVE_TOUCHSCREENGUI
2533 if (g_touchscreengui) {
2534 g_touchscreengui->step(dtime);
2540 if (current_formspec != 0)
2541 current_formspec->getAndroidUIInput();
2545 // Increase timer for double tap of "keymap_jump"
2546 if (m_cache_doubletap_jump && runData->jump_timer <= 0.2)
2547 runData->jump_timer += dtime;
2549 processKeyboardInput(
2551 &runData->statustext_time,
2552 &runData->jump_timer,
2553 &runData->reset_jump_timer,
2554 &runData->profiler_current_page,
2555 runData->profiler_max_page);
2557 processItemSelection(&runData->new_playeritem);
2561 void Game::processKeyboardInput(VolatileRunFlags *flags,
2562 float *statustext_time,
2564 bool *reset_jump_timer,
2565 u32 *profiler_current_page,
2566 u32 profiler_max_page)
2569 //TimeTaker tt("process kybd input", NULL, PRECISION_NANO);
2571 if (input->wasKeyDown(keycache.key[KeyCache::KEYMAP_ID_DROP])) {
2573 } else if (input->wasKeyDown(keycache.key[KeyCache::KEYMAP_ID_INVENTORY])) {
2575 } else if (input->wasKeyDown(EscapeKey) || input->wasKeyDown(CancelKey)) {
2576 show_pause_menu(¤t_formspec, client, gamedef, texture_src, device,
2577 simple_singleplayer_mode);
2578 } else if (input->wasKeyDown(keycache.key[KeyCache::KEYMAP_ID_CHAT])) {
2579 show_chat_menu(¤t_formspec, client, gamedef, texture_src, device,
2581 } else if (input->wasKeyDown(keycache.key[KeyCache::KEYMAP_ID_CMD])) {
2582 show_chat_menu(¤t_formspec, client, gamedef, texture_src, device,
2584 } else if (input->wasKeyDown(keycache.key[KeyCache::KEYMAP_ID_CONSOLE])) {
2586 } else if (input->wasKeyDown(keycache.key[KeyCache::KEYMAP_ID_FREEMOVE])) {
2587 toggleFreeMove(statustext_time);
2588 } else if (input->wasKeyDown(keycache.key[KeyCache::KEYMAP_ID_JUMP])) {
2589 toggleFreeMoveAlt(statustext_time, jump_timer);
2590 *reset_jump_timer = true;
2591 } else if (input->wasKeyDown(keycache.key[KeyCache::KEYMAP_ID_FASTMOVE])) {
2592 toggleFast(statustext_time);
2593 } else if (input->wasKeyDown(keycache.key[KeyCache::KEYMAP_ID_NOCLIP])) {
2594 toggleNoClip(statustext_time);
2595 } else if (input->wasKeyDown(keycache.key[KeyCache::KEYMAP_ID_CINEMATIC])) {
2596 toggleCinematic(statustext_time);
2597 } else if (input->wasKeyDown(keycache.key[KeyCache::KEYMAP_ID_SCREENSHOT])) {
2598 client->makeScreenshot(device);
2599 } else if (input->wasKeyDown(keycache.key[KeyCache::KEYMAP_ID_TOGGLE_HUD])) {
2600 toggleHud(statustext_time, &flags->show_hud);
2601 } else if (input->wasKeyDown(keycache.key[KeyCache::KEYMAP_ID_TOGGLE_CHAT])) {
2602 toggleChat(statustext_time, &flags->show_chat);
2603 } else if (input->wasKeyDown(keycache.key[KeyCache::KEYMAP_ID_TOGGLE_FORCE_FOG_OFF])) {
2604 toggleFog(statustext_time, &flags->force_fog_off);
2605 } else if (input->wasKeyDown(keycache.key[KeyCache::KEYMAP_ID_TOGGLE_UPDATE_CAMERA])) {
2606 toggleUpdateCamera(statustext_time, &flags->disable_camera_update);
2607 } else if (input->wasKeyDown(keycache.key[KeyCache::KEYMAP_ID_TOGGLE_DEBUG])) {
2608 toggleDebug(statustext_time, &flags->show_debug, &flags->show_profiler_graph);
2609 } else if (input->wasKeyDown(keycache.key[KeyCache::KEYMAP_ID_TOGGLE_PROFILER])) {
2610 toggleProfiler(statustext_time, profiler_current_page, profiler_max_page);
2611 } else if (input->wasKeyDown(keycache.key[KeyCache::KEYMAP_ID_INCREASE_VIEWING_RANGE])) {
2612 increaseViewRange(statustext_time);
2613 } else if (input->wasKeyDown(keycache.key[KeyCache::KEYMAP_ID_DECREASE_VIEWING_RANGE])) {
2614 decreaseViewRange(statustext_time);
2615 } else if (input->wasKeyDown(keycache.key[KeyCache::KEYMAP_ID_RANGESELECT])) {
2616 toggleFullViewRange(statustext_time);
2617 } else if (input->wasKeyDown(keycache.key[KeyCache::KEYMAP_ID_QUICKTUNE_NEXT]))
2619 else if (input->wasKeyDown(keycache.key[KeyCache::KEYMAP_ID_QUICKTUNE_PREV]))
2621 else if (input->wasKeyDown(keycache.key[KeyCache::KEYMAP_ID_QUICKTUNE_INC]))
2623 else if (input->wasKeyDown(keycache.key[KeyCache::KEYMAP_ID_QUICKTUNE_DEC]))
2625 else if (input->wasKeyDown(keycache.key[KeyCache::KEYMAP_ID_DEBUG_STACKS])) {
2626 // Print debug stacks
2627 dstream << "-----------------------------------------"
2629 dstream << DTIME << "Printing debug stacks:" << std::endl;
2630 dstream << "-----------------------------------------"
2632 debug_stacks_print();
2635 if (!input->isKeyDown(getKeySetting("keymap_jump")) && *reset_jump_timer) {
2636 *reset_jump_timer = false;
2642 if (quicktune->hasMessage()) {
2643 std::string msg = quicktune->getMessage();
2644 statustext = narrow_to_wide(msg);
2645 *statustext_time = 0;
2650 void Game::processItemSelection(u16 *new_playeritem)
2652 LocalPlayer *player = client->getEnv().getLocalPlayer();
2654 /* Item selection using mouse wheel
2656 *new_playeritem = client->getPlayerItem();
2658 s32 wheel = input->getMouseWheel();
2659 u16 max_item = MYMIN(PLAYER_INVENTORY_SIZE - 1,
2660 player->hud_hotbar_itemcount - 1);
2663 *new_playeritem = *new_playeritem < max_item ? *new_playeritem + 1 : 0;
2665 *new_playeritem = *new_playeritem > 0 ? *new_playeritem - 1 : max_item;
2669 /* Item selection using keyboard
2671 for (u16 i = 0; i < 10; i++) {
2672 static const KeyPress *item_keys[10] = {
2673 NumberKey + 1, NumberKey + 2, NumberKey + 3, NumberKey + 4,
2674 NumberKey + 5, NumberKey + 6, NumberKey + 7, NumberKey + 8,
2675 NumberKey + 9, NumberKey + 0,
2678 if (input->wasKeyDown(*item_keys[i])) {
2679 if (i < PLAYER_INVENTORY_SIZE && i < player->hud_hotbar_itemcount) {
2680 *new_playeritem = i;
2681 infostream << "Selected item: " << new_playeritem << std::endl;
2689 void Game::dropSelectedItem()
2691 IDropAction *a = new IDropAction();
2693 a->from_inv.setCurrentPlayer();
2694 a->from_list = "main";
2695 a->from_i = client->getPlayerItem();
2696 client->inventoryAction(a);
2700 void Game::openInventory()
2703 * Don't permit to open inventory is CAO or player doesn't exists.
2704 * This prevent showing an empty inventory at player load
2707 LocalPlayer *player = client->getEnv().getLocalPlayer();
2708 if (player == NULL || player->getCAO() == NULL)
2711 infostream << "the_game: " << "Launching inventory" << std::endl;
2713 PlayerInventoryFormSource *fs_src = new PlayerInventoryFormSource(client);
2714 TextDest *txt_dst = new TextDestPlayerInventory(client);
2716 create_formspec_menu(¤t_formspec, client, gamedef, texture_src,
2717 device, fs_src, txt_dst, client);
2719 InventoryLocation inventoryloc;
2720 inventoryloc.setCurrentPlayer();
2721 current_formspec->setFormSpec(fs_src->getForm(), inventoryloc);
2725 void Game::openConsole()
2727 if (!gui_chat_console->isOpenInhibited()) {
2728 // Open up to over half of the screen
2729 gui_chat_console->openConsole(0.6);
2730 guienv->setFocus(gui_chat_console);
2735 void Game::toggleFreeMove(float *statustext_time)
2737 static const wchar_t *msg[] = { L"free_move disabled", L"free_move enabled" };
2739 bool free_move = !g_settings->getBool("free_move");
2740 g_settings->set("free_move", bool_to_cstr(free_move));
2742 *statustext_time = 0;
2743 statustext = msg[free_move];
2744 if (free_move && !client->checkPrivilege("fly"))
2745 statustext += L" (note: no 'fly' privilege)";
2749 void Game::toggleFreeMoveAlt(float *statustext_time, float *jump_timer)
2751 if (m_cache_doubletap_jump && *jump_timer < 0.2f)
2752 toggleFreeMove(statustext_time);
2756 void Game::toggleFast(float *statustext_time)
2758 static const wchar_t *msg[] = { L"fast_move disabled", L"fast_move enabled" };
2759 bool fast_move = !g_settings->getBool("fast_move");
2760 g_settings->set("fast_move", bool_to_cstr(fast_move));
2762 *statustext_time = 0;
2763 statustext = msg[fast_move];
2765 bool has_fast_privs = client->checkPrivilege("fast");
2767 if (fast_move && !has_fast_privs)
2768 statustext += L" (note: no 'fast' privilege)";
2771 m_cache_hold_aux1 = fast_move && has_fast_privs;
2776 void Game::toggleNoClip(float *statustext_time)
2778 static const wchar_t *msg[] = { L"noclip disabled", L"noclip enabled" };
2779 bool noclip = !g_settings->getBool("noclip");
2780 g_settings->set("noclip", bool_to_cstr(noclip));
2782 *statustext_time = 0;
2783 statustext = msg[noclip];
2785 if (noclip && !client->checkPrivilege("noclip"))
2786 statustext += L" (note: no 'noclip' privilege)";
2789 void Game::toggleCinematic(float *statustext_time)
2791 static const wchar_t *msg[] = { L"cinematic disabled", L"cinematic enabled" };
2792 bool cinematic = !g_settings->getBool("cinematic");
2793 g_settings->set("cinematic", bool_to_cstr(cinematic));
2795 *statustext_time = 0;
2796 statustext = msg[cinematic];
2800 void Game::toggleChat(float *statustext_time, bool *flag)
2802 static const wchar_t *msg[] = { L"Chat hidden", L"Chat shown" };
2805 *statustext_time = 0;
2806 statustext = msg[*flag];
2810 void Game::toggleHud(float *statustext_time, bool *flag)
2812 static const wchar_t *msg[] = { L"HUD hidden", L"HUD shown" };
2815 *statustext_time = 0;
2816 statustext = msg[*flag];
2817 if (g_settings->getBool("enable_node_highlighting"))
2818 client->setHighlighted(client->getHighlighted(), *flag);
2822 void Game::toggleFog(float *statustext_time, bool *flag)
2824 static const wchar_t *msg[] = { L"Fog enabled", L"Fog disabled" };
2827 *statustext_time = 0;
2828 statustext = msg[*flag];
2832 void Game::toggleDebug(float *statustext_time, bool *show_debug,
2833 bool *show_profiler_graph)
2835 // Initial / 3x toggle: Chat only
2836 // 1x toggle: Debug text with chat
2837 // 2x toggle: Debug text with profiler graph
2840 *show_profiler_graph = false;
2841 statustext = L"Debug info shown";
2842 } else if (*show_profiler_graph) {
2843 *show_debug = false;
2844 *show_profiler_graph = false;
2845 statustext = L"Debug info and profiler graph hidden";
2847 *show_profiler_graph = true;
2848 statustext = L"Profiler graph shown";
2850 *statustext_time = 0;
2854 void Game::toggleUpdateCamera(float *statustext_time, bool *flag)
2856 static const wchar_t *msg[] = {
2857 L"Camera update enabled",
2858 L"Camera update disabled"
2862 *statustext_time = 0;
2863 statustext = msg[*flag];
2867 void Game::toggleProfiler(float *statustext_time, u32 *profiler_current_page,
2868 u32 profiler_max_page)
2870 *profiler_current_page = (*profiler_current_page + 1) % (profiler_max_page + 1);
2872 // FIXME: This updates the profiler with incomplete values
2873 update_profiler_gui(guitext_profiler, g_fontengine, *profiler_current_page,
2874 profiler_max_page, driver->getScreenSize().Height);
2876 if (*profiler_current_page != 0) {
2877 std::wstringstream sstr;
2878 sstr << "Profiler shown (page " << *profiler_current_page
2879 << " of " << profiler_max_page << ")";
2880 statustext = sstr.str();
2882 statustext = L"Profiler hidden";
2884 *statustext_time = 0;
2888 void Game::increaseViewRange(float *statustext_time)
2890 s16 range = g_settings->getS16("viewing_range_nodes_min");
2891 s16 range_new = range + 10;
2892 g_settings->set("viewing_range_nodes_min", itos(range_new));
2893 statustext = narrow_to_wide("Minimum viewing range changed to "
2895 *statustext_time = 0;
2899 void Game::decreaseViewRange(float *statustext_time)
2901 s16 range = g_settings->getS16("viewing_range_nodes_min");
2902 s16 range_new = range - 10;
2907 g_settings->set("viewing_range_nodes_min", itos(range_new));
2908 statustext = narrow_to_wide("Minimum viewing range changed to "
2910 *statustext_time = 0;
2914 void Game::toggleFullViewRange(float *statustext_time)
2916 static const wchar_t *msg[] = {
2917 L"Disabled full viewing range",
2918 L"Enabled full viewing range"
2921 draw_control->range_all = !draw_control->range_all;
2922 infostream << msg[draw_control->range_all] << std::endl;
2923 statustext = msg[draw_control->range_all];
2924 *statustext_time = 0;
2928 void Game::updateCameraDirection(CameraOrientation *cam,
2929 VolatileRunFlags *flags)
2931 if ((device->isWindowActive() && noMenuActive()) || random_input) {
2934 if (!random_input) {
2935 // Mac OSX gets upset if this is set every frame
2936 if (device->getCursorControl()->isVisible())
2937 device->getCursorControl()->setVisible(false);
2941 if (flags->first_loop_after_window_activation)
2942 flags->first_loop_after_window_activation = false;
2944 updateCameraOrientation(cam, *flags);
2946 input->setMousePos((driver->getScreenSize().Width / 2),
2947 (driver->getScreenSize().Height / 2));
2951 // Mac OSX gets upset if this is set every frame
2952 if (device->getCursorControl()->isVisible() == false)
2953 device->getCursorControl()->setVisible(true);
2956 if (!flags->first_loop_after_window_activation)
2957 flags->first_loop_after_window_activation = true;
2963 void Game::updateCameraOrientation(CameraOrientation *cam,
2964 const VolatileRunFlags &flags)
2966 #ifdef HAVE_TOUCHSCREENGUI
2967 if (g_touchscreengui) {
2968 cam->camera_yaw = g_touchscreengui->getYaw();
2969 cam->camera_pitch = g_touchscreengui->getPitch();
2972 s32 dx = input->getMousePos().X - (driver->getScreenSize().Width / 2);
2973 s32 dy = input->getMousePos().Y - (driver->getScreenSize().Height / 2);
2975 if (flags.invert_mouse
2976 || camera->getCameraMode() == CAMERA_MODE_THIRD_FRONT) {
2980 cam->camera_yaw -= dx * m_cache_mouse_sensitivity;
2981 cam->camera_pitch += dy * m_cache_mouse_sensitivity;
2983 #ifdef HAVE_TOUCHSCREENGUI
2987 cam->camera_pitch = rangelim(cam->camera_pitch, -89.5, 89.5);
2991 void Game::updatePlayerControl(const CameraOrientation &cam)
2993 //TimeTaker tt("update player control", NULL, PRECISION_NANO);
2995 PlayerControl control(
2996 input->isKeyDown(keycache.key[KeyCache::KEYMAP_ID_FORWARD]),
2997 input->isKeyDown(keycache.key[KeyCache::KEYMAP_ID_BACKWARD]),
2998 input->isKeyDown(keycache.key[KeyCache::KEYMAP_ID_LEFT]),
2999 input->isKeyDown(keycache.key[KeyCache::KEYMAP_ID_RIGHT]),
3000 input->isKeyDown(keycache.key[KeyCache::KEYMAP_ID_JUMP]),
3001 input->isKeyDown(keycache.key[KeyCache::KEYMAP_ID_SPECIAL1]),
3002 input->isKeyDown(keycache.key[KeyCache::KEYMAP_ID_SNEAK]),
3003 input->getLeftState(),
3004 input->getRightState(),
3010 ( (u32)(input->isKeyDown(keycache.key[KeyCache::KEYMAP_ID_FORWARD]) & 0x1) << 0) |
3011 ( (u32)(input->isKeyDown(keycache.key[KeyCache::KEYMAP_ID_BACKWARD]) & 0x1) << 1) |
3012 ( (u32)(input->isKeyDown(keycache.key[KeyCache::KEYMAP_ID_LEFT]) & 0x1) << 2) |
3013 ( (u32)(input->isKeyDown(keycache.key[KeyCache::KEYMAP_ID_RIGHT]) & 0x1) << 3) |
3014 ( (u32)(input->isKeyDown(keycache.key[KeyCache::KEYMAP_ID_JUMP]) & 0x1) << 4) |
3015 ( (u32)(input->isKeyDown(keycache.key[KeyCache::KEYMAP_ID_SPECIAL1]) & 0x1) << 5) |
3016 ( (u32)(input->isKeyDown(keycache.key[KeyCache::KEYMAP_ID_SNEAK]) & 0x1) << 6) |
3017 ( (u32)(input->getLeftState() & 0x1) << 7) |
3018 ( (u32)(input->getRightState() & 0x1) << 8
3022 /* For Android, simulate holding down AUX1 (fast move) if the user has
3023 * the fast_move setting toggled on. If there is an aux1 key defined for
3024 * Android then its meaning is inverted (i.e. holding aux1 means walk and
3027 if (m_cache_hold_aux1) {
3028 control.aux1 = control.aux1 ^ true;
3029 keypress_bits ^= ((u32)(1U << 5));
3033 client->setPlayerControl(control);
3034 LocalPlayer *player = client->getEnv().getLocalPlayer();
3035 player->keyPressed = keypress_bits;
3041 inline void Game::step(f32 *dtime)
3043 bool can_be_and_is_paused =
3044 (simple_singleplayer_mode && g_menumgr.pausesGame());
3046 if (can_be_and_is_paused) { // This is for a singleplayer server
3047 *dtime = 0; // No time passes
3049 if (server != NULL) {
3050 //TimeTaker timer("server->step(dtime)");
3051 server->step(*dtime);
3054 //TimeTaker timer("client.step(dtime)");
3055 client->step(*dtime);
3060 void Game::processClientEvents(CameraOrientation *cam, float *damage_flash)
3062 ClientEvent event = client->getClientEvent();
3064 LocalPlayer *player = client->getEnv().getLocalPlayer();
3066 for ( ; event.type != CE_NONE; event = client->getClientEvent()) {
3068 if (event.type == CE_PLAYER_DAMAGE &&
3069 client->getHP() != 0) {
3070 //u16 damage = event.player_damage.amount;
3071 //infostream<<"Player damage: "<<damage<<std::endl;
3073 *damage_flash += 100.0;
3074 *damage_flash += 8.0 * event.player_damage.amount;
3076 player->hurt_tilt_timer = 1.5;
3077 player->hurt_tilt_strength = event.player_damage.amount / 4;
3078 player->hurt_tilt_strength = rangelim(player->hurt_tilt_strength, 1.0, 4.0);
3080 MtEvent *e = new SimpleTriggerEvent("PlayerDamage");
3081 gamedef->event()->put(e);
3082 } else if (event.type == CE_PLAYER_FORCE_MOVE) {
3083 cam->camera_yaw = event.player_force_move.yaw;
3084 cam->camera_pitch = event.player_force_move.pitch;
3085 } else if (event.type == CE_DEATHSCREEN) {
3086 show_deathscreen(¤t_formspec, client, gamedef, texture_src,
3089 chat_backend->addMessage(L"", L"You died.");
3091 /* Handle visualization */
3093 player->hurt_tilt_timer = 0;
3094 player->hurt_tilt_strength = 0;
3096 } else if (event.type == CE_SHOW_FORMSPEC) {
3097 FormspecFormSource *fs_src =
3098 new FormspecFormSource(*(event.show_formspec.formspec));
3099 TextDestPlayerInventory *txt_dst =
3100 new TextDestPlayerInventory(client, *(event.show_formspec.formname));
3102 create_formspec_menu(¤t_formspec, client, gamedef,
3103 texture_src, device, fs_src, txt_dst, client);
3105 delete(event.show_formspec.formspec);
3106 delete(event.show_formspec.formname);
3107 } else if ((event.type == CE_SPAWN_PARTICLE) ||
3108 (event.type == CE_ADD_PARTICLESPAWNER) ||
3109 (event.type == CE_DELETE_PARTICLESPAWNER)) {
3110 client->getParticleManager()->handleParticleEvent(&event, gamedef,
3112 } else if (event.type == CE_HUDADD) {
3113 u32 id = event.hudadd.id;
3115 LocalPlayer *player = client->getEnv().getLocalPlayer();
3116 HudElement *e = player->getHud(id);
3119 delete event.hudadd.pos;
3120 delete event.hudadd.name;
3121 delete event.hudadd.scale;
3122 delete event.hudadd.text;
3123 delete event.hudadd.align;
3124 delete event.hudadd.offset;
3125 delete event.hudadd.world_pos;
3126 delete event.hudadd.size;
3131 e->type = (HudElementType)event.hudadd.type;
3132 e->pos = *event.hudadd.pos;
3133 e->name = *event.hudadd.name;
3134 e->scale = *event.hudadd.scale;
3135 e->text = *event.hudadd.text;
3136 e->number = event.hudadd.number;
3137 e->item = event.hudadd.item;
3138 e->dir = event.hudadd.dir;
3139 e->align = *event.hudadd.align;
3140 e->offset = *event.hudadd.offset;
3141 e->world_pos = *event.hudadd.world_pos;
3142 e->size = *event.hudadd.size;
3144 u32 new_id = player->addHud(e);
3145 //if this isn't true our huds aren't consistent
3146 sanity_check(new_id == id);
3148 delete event.hudadd.pos;
3149 delete event.hudadd.name;
3150 delete event.hudadd.scale;
3151 delete event.hudadd.text;
3152 delete event.hudadd.align;
3153 delete event.hudadd.offset;
3154 delete event.hudadd.world_pos;
3155 delete event.hudadd.size;
3156 } else if (event.type == CE_HUDRM) {
3157 HudElement *e = player->removeHud(event.hudrm.id);
3161 } else if (event.type == CE_HUDCHANGE) {
3162 u32 id = event.hudchange.id;
3163 HudElement *e = player->getHud(id);
3166 delete event.hudchange.v3fdata;
3167 delete event.hudchange.v2fdata;
3168 delete event.hudchange.sdata;
3169 delete event.hudchange.v2s32data;
3173 switch (event.hudchange.stat) {
3175 e->pos = *event.hudchange.v2fdata;
3179 e->name = *event.hudchange.sdata;
3182 case HUD_STAT_SCALE:
3183 e->scale = *event.hudchange.v2fdata;
3187 e->text = *event.hudchange.sdata;
3190 case HUD_STAT_NUMBER:
3191 e->number = event.hudchange.data;
3195 e->item = event.hudchange.data;
3199 e->dir = event.hudchange.data;
3202 case HUD_STAT_ALIGN:
3203 e->align = *event.hudchange.v2fdata;
3206 case HUD_STAT_OFFSET:
3207 e->offset = *event.hudchange.v2fdata;
3210 case HUD_STAT_WORLD_POS:
3211 e->world_pos = *event.hudchange.v3fdata;
3215 e->size = *event.hudchange.v2s32data;
3219 delete event.hudchange.v3fdata;
3220 delete event.hudchange.v2fdata;
3221 delete event.hudchange.sdata;
3222 delete event.hudchange.v2s32data;
3223 } else if (event.type == CE_SET_SKY) {
3224 sky->setVisible(false);
3231 // Handle according to type
3232 if (*event.set_sky.type == "regular") {
3233 sky->setVisible(true);
3234 } else if (*event.set_sky.type == "skybox" &&
3235 event.set_sky.params->size() == 6) {
3236 sky->setFallbackBgColor(*event.set_sky.bgcolor);
3237 skybox = smgr->addSkyBoxSceneNode(
3238 texture_src->getTextureForMesh((*event.set_sky.params)[0]),
3239 texture_src->getTextureForMesh((*event.set_sky.params)[1]),
3240 texture_src->getTextureForMesh((*event.set_sky.params)[2]),
3241 texture_src->getTextureForMesh((*event.set_sky.params)[3]),
3242 texture_src->getTextureForMesh((*event.set_sky.params)[4]),
3243 texture_src->getTextureForMesh((*event.set_sky.params)[5]));
3245 // Handle everything else as plain color
3247 if (*event.set_sky.type != "plain")
3248 infostream << "Unknown sky type: "
3249 << (*event.set_sky.type) << std::endl;
3251 sky->setFallbackBgColor(*event.set_sky.bgcolor);
3254 delete event.set_sky.bgcolor;
3255 delete event.set_sky.type;
3256 delete event.set_sky.params;
3257 } else if (event.type == CE_OVERRIDE_DAY_NIGHT_RATIO) {
3258 bool enable = event.override_day_night_ratio.do_override;
3259 u32 value = event.override_day_night_ratio.ratio_f * 1000;
3260 client->getEnv().setDayNightRatioOverride(enable, value);
3266 void Game::updateCamera(VolatileRunFlags *flags, u32 busy_time,
3267 f32 dtime, float time_from_last_punch)
3269 LocalPlayer *player = client->getEnv().getLocalPlayer();
3272 For interaction purposes, get info about the held item
3274 - Is it a usable item?
3275 - Can it point to liquids?
3277 ItemStack playeritem;
3279 InventoryList *mlist = local_inventory->getList("main");
3281 if (mlist && client->getPlayerItem() < mlist->getSize())
3282 playeritem = mlist->getItem(client->getPlayerItem());
3285 ToolCapabilities playeritem_toolcap =
3286 playeritem.getToolCapabilities(itemdef_manager);
3288 v3s16 old_camera_offset = camera->getOffset();
3290 if (input->wasKeyDown(keycache.key[KeyCache::KEYMAP_ID_CAMERA_MODE])) {
3291 GenericCAO *playercao = player->getCAO();
3293 // If playercao not loaded, don't change camera
3294 if (playercao == NULL)
3297 camera->toggleCameraMode();
3299 playercao->setVisible(camera->getCameraMode() > CAMERA_MODE_FIRST);
3302 float full_punch_interval = playeritem_toolcap.full_punch_interval;
3303 float tool_reload_ratio = time_from_last_punch / full_punch_interval;
3305 tool_reload_ratio = MYMIN(tool_reload_ratio, 1.0);
3306 camera->update(player, dtime, busy_time / 1000.0f, tool_reload_ratio,
3308 camera->step(dtime);
3310 v3f camera_position = camera->getPosition();
3311 v3f camera_direction = camera->getDirection();
3312 f32 camera_fov = camera->getFovMax();
3313 v3s16 camera_offset = camera->getOffset();
3315 flags->camera_offset_changed = (camera_offset != old_camera_offset);
3317 if (!flags->disable_camera_update) {
3318 client->getEnv().getClientMap().updateCamera(camera_position,
3319 camera_direction, camera_fov, camera_offset);
3321 if (flags->camera_offset_changed) {
3322 client->updateCameraOffset(camera_offset);
3323 client->getEnv().updateCameraOffset(camera_offset);
3326 clouds->updateCameraOffset(camera_offset);
3332 void Game::updateSound(f32 dtime)
3334 // Update sound listener
3335 v3s16 camera_offset = camera->getOffset();
3336 sound->updateListener(camera->getCameraNode()->getPosition() + intToFloat(camera_offset, BS),
3337 v3f(0, 0, 0), // velocity
3338 camera->getDirection(),
3339 camera->getCameraNode()->getUpVector());
3340 sound->setListenerGain(g_settings->getFloat("sound_volume"));
3343 // Update sound maker
3344 soundmaker->step(dtime);
3346 LocalPlayer *player = client->getEnv().getLocalPlayer();
3348 ClientMap &map = client->getEnv().getClientMap();
3349 MapNode n = map.getNodeNoEx(player->getStandingNodePos());
3350 soundmaker->m_player_step_sound = nodedef_manager->get(n).sound_footstep;
3354 void Game::processPlayerInteraction(std::vector<aabb3f> &highlight_boxes,
3355 GameRunData *runData, f32 dtime, bool show_hud, bool show_debug)
3357 LocalPlayer *player = client->getEnv().getLocalPlayer();
3359 ItemStack playeritem;
3361 InventoryList *mlist = local_inventory->getList("main");
3363 if (mlist && client->getPlayerItem() < mlist->getSize())
3364 playeritem = mlist->getItem(client->getPlayerItem());
3367 const ItemDefinition &playeritem_def =
3368 playeritem.getDefinition(itemdef_manager);
3370 v3f player_position = player->getPosition();
3371 v3f camera_position = camera->getPosition();
3372 v3f camera_direction = camera->getDirection();
3373 v3s16 camera_offset = camera->getOffset();
3377 Calculate what block is the crosshair pointing to
3380 f32 d = playeritem_def.range; // max. distance
3381 f32 d_hand = itemdef_manager->get("").range;
3383 if (d < 0 && d_hand >= 0)
3388 core::line3d<f32> shootline;
3390 if (camera->getCameraMode() != CAMERA_MODE_THIRD_FRONT) {
3392 shootline = core::line3d<f32>(camera_position,
3393 camera_position + camera_direction * BS * (d + 1));
3396 // prevent player pointing anything in front-view
3397 if (camera->getCameraMode() == CAMERA_MODE_THIRD_FRONT)
3398 shootline = core::line3d<f32>(0, 0, 0, 0, 0, 0);
3401 #ifdef HAVE_TOUCHSCREENGUI
3403 if ((g_settings->getBool("touchtarget")) && (g_touchscreengui)) {
3404 shootline = g_touchscreengui->getShootline();
3405 shootline.start += intToFloat(camera_offset, BS);
3406 shootline.end += intToFloat(camera_offset, BS);
3411 PointedThing pointed = getPointedThing(
3413 client, player_position, camera_direction,
3414 camera_position, shootline, d,
3415 playeritem_def.liquids_pointable,
3416 !runData->ldown_for_dig,
3420 runData->selected_object);
3422 if (pointed != runData->pointed_old) {
3423 infostream << "Pointing at " << pointed.dump() << std::endl;
3425 if (m_cache_enable_node_highlighting) {
3426 if (pointed.type == POINTEDTHING_NODE) {
3427 client->setHighlighted(pointed.node_undersurface, show_hud);
3429 client->setHighlighted(pointed.node_undersurface, false);
3436 - releasing left mouse button
3437 - pointing away from node
3439 if (runData->digging) {
3440 if (input->getLeftReleased()) {
3441 infostream << "Left button released"
3442 << " (stopped digging)" << std::endl;
3443 runData->digging = false;
3444 } else if (pointed != runData->pointed_old) {
3445 if (pointed.type == POINTEDTHING_NODE
3446 && runData->pointed_old.type == POINTEDTHING_NODE
3447 && pointed.node_undersurface
3448 == runData->pointed_old.node_undersurface) {
3449 // Still pointing to the same node, but a different face.
3452 infostream << "Pointing away from node"
3453 << " (stopped digging)" << std::endl;
3454 runData->digging = false;
3458 if (!runData->digging) {
3459 client->interact(1, runData->pointed_old);
3460 client->setCrack(-1, v3s16(0, 0, 0));
3461 runData->dig_time = 0.0;
3465 if (!runData->digging && runData->ldown_for_dig && !input->getLeftState()) {
3466 runData->ldown_for_dig = false;
3469 runData->left_punch = false;
3471 soundmaker->m_player_leftpunch_sound.name = "";
3473 if (input->getRightState())
3474 runData->repeat_rightclick_timer += dtime;
3476 runData->repeat_rightclick_timer = 0;
3478 if (playeritem_def.usable && input->getLeftState()) {
3479 if (input->getLeftClicked())
3480 client->interact(4, pointed);
3481 } else if (pointed.type == POINTEDTHING_NODE) {
3482 ToolCapabilities playeritem_toolcap =
3483 playeritem.getToolCapabilities(itemdef_manager);
3484 handlePointingAtNode(runData, pointed, playeritem_def,
3485 playeritem_toolcap, dtime);
3486 } else if (pointed.type == POINTEDTHING_OBJECT) {
3487 handlePointingAtObject(runData, pointed, playeritem,
3488 player_position, show_debug);
3489 } else if (input->getLeftState()) {
3490 // When button is held down in air, show continuous animation
3491 runData->left_punch = true;
3494 runData->pointed_old = pointed;
3496 if (runData->left_punch || input->getLeftClicked())
3497 camera->setDigging(0); // left click animation
3499 input->resetLeftClicked();
3500 input->resetRightClicked();
3502 input->resetLeftReleased();
3503 input->resetRightReleased();
3507 void Game::handlePointingAtNode(GameRunData *runData,
3508 const PointedThing &pointed, const ItemDefinition &playeritem_def,
3509 const ToolCapabilities &playeritem_toolcap, f32 dtime)
3511 v3s16 nodepos = pointed.node_undersurface;
3512 v3s16 neighbourpos = pointed.node_abovesurface;
3515 Check information text of node
3518 ClientMap &map = client->getEnv().getClientMap();
3519 NodeMetadata *meta = map.getNodeMetadata(nodepos);
3522 infotext = narrow_to_wide(meta->getString("infotext"));
3524 MapNode n = map.getNodeNoEx(nodepos);
3526 if (nodedef_manager->get(n).tiledef[0].name == "unknown_node.png") {
3527 infotext = L"Unknown node: ";
3528 infotext += narrow_to_wide(nodedef_manager->get(n).name);
3532 if (runData->nodig_delay_timer <= 0.0 && input->getLeftState()
3533 && client->checkPrivilege("interact")) {
3534 handleDigging(runData, pointed, nodepos, playeritem_toolcap, dtime);
3537 if ((input->getRightClicked() ||
3538 runData->repeat_rightclick_timer >= m_repeat_right_click_time) &&
3539 client->checkPrivilege("interact")) {
3540 runData->repeat_rightclick_timer = 0;
3541 infostream << "Ground right-clicked" << std::endl;
3543 if (meta && meta->getString("formspec") != "" && !random_input
3544 && !input->isKeyDown(getKeySetting("keymap_sneak"))) {
3545 infostream << "Launching custom inventory view" << std::endl;
3547 InventoryLocation inventoryloc;
3548 inventoryloc.setNodeMeta(nodepos);
3550 NodeMetadataFormSource *fs_src = new NodeMetadataFormSource(
3551 &client->getEnv().getClientMap(), nodepos);
3552 TextDest *txt_dst = new TextDestNodeMetadata(nodepos, client);
3554 create_formspec_menu(¤t_formspec, client, gamedef,
3555 texture_src, device, fs_src, txt_dst, client);
3557 current_formspec->setFormSpec(meta->getString("formspec"), inventoryloc);
3559 // Report right click to server
3561 camera->setDigging(1); // right click animation (always shown for feedback)
3563 // If the wielded item has node placement prediction,
3565 bool placed = nodePlacementPrediction(*client,
3567 nodepos, neighbourpos);
3571 client->interact(3, pointed);
3573 soundmaker->m_player_rightpunch_sound =
3574 playeritem_def.sound_place;
3576 soundmaker->m_player_rightpunch_sound =
3580 if (playeritem_def.node_placement_prediction == "" ||
3581 nodedef_manager->get(map.getNodeNoEx(nodepos)).rightclickable)
3582 client->interact(3, pointed); // Report to server
3588 void Game::handlePointingAtObject(GameRunData *runData,
3589 const PointedThing &pointed,
3590 const ItemStack &playeritem,
3591 const v3f &player_position,
3594 infotext = narrow_to_wide(runData->selected_object->infoText());
3596 if (infotext == L"" && show_debug) {
3597 infotext = narrow_to_wide(runData->selected_object->debugInfoText());
3600 if (input->getLeftState()) {
3601 bool do_punch = false;
3602 bool do_punch_damage = false;
3604 if (runData->object_hit_delay_timer <= 0.0) {
3606 do_punch_damage = true;
3607 runData->object_hit_delay_timer = object_hit_delay;
3610 if (input->getLeftClicked())
3614 infostream << "Left-clicked object" << std::endl;
3615 runData->left_punch = true;
3618 if (do_punch_damage) {
3619 // Report direct punch
3620 v3f objpos = runData->selected_object->getPosition();
3621 v3f dir = (objpos - player_position).normalize();
3623 bool disable_send = runData->selected_object->directReportPunch(
3624 dir, &playeritem, runData->time_from_last_punch);
3625 runData->time_from_last_punch = 0;
3628 client->interact(0, pointed);
3630 } else if (input->getRightClicked()) {
3631 infostream << "Right-clicked object" << std::endl;
3632 client->interact(3, pointed); // place
3637 void Game::handleDigging(GameRunData *runData,
3638 const PointedThing &pointed, const v3s16 &nodepos,
3639 const ToolCapabilities &playeritem_toolcap, f32 dtime)
3641 if (!runData->digging) {
3642 infostream << "Started digging" << std::endl;
3643 client->interact(0, pointed);
3644 runData->digging = true;
3645 runData->ldown_for_dig = true;
3648 LocalPlayer *player = client->getEnv().getLocalPlayer();
3649 ClientMap &map = client->getEnv().getClientMap();
3650 MapNode n = client->getEnv().getClientMap().getNodeNoEx(nodepos);
3652 // NOTE: Similar piece of code exists on the server side for
3654 // Get digging parameters
3655 DigParams params = getDigParams(nodedef_manager->get(n).groups,
3656 &playeritem_toolcap);
3658 // If can't dig, try hand
3659 if (!params.diggable) {
3660 const ItemDefinition &hand = itemdef_manager->get("");
3661 const ToolCapabilities *tp = hand.tool_capabilities;
3664 params = getDigParams(nodedef_manager->get(n).groups, tp);
3667 if (params.diggable == false) {
3668 // I guess nobody will wait for this long
3669 runData->dig_time_complete = 10000000.0;
3671 runData->dig_time_complete = params.time;
3673 if (m_cache_enable_particles) {
3674 const ContentFeatures &features =
3675 client->getNodeDefManager()->get(n);
3676 client->getParticleManager()->addPunchingParticles(gamedef, smgr,
3677 player, nodepos, features.tiles);
3681 if (runData->dig_time_complete >= 0.001) {
3682 runData->dig_index = (float)crack_animation_length
3684 / runData->dig_time_complete;
3686 // This is for torches
3687 runData->dig_index = crack_animation_length;
3690 SimpleSoundSpec sound_dig = nodedef_manager->get(n).sound_dig;
3692 if (sound_dig.exists() && params.diggable) {
3693 if (sound_dig.name == "__group") {
3694 if (params.main_group != "") {
3695 soundmaker->m_player_leftpunch_sound.gain = 0.5;
3696 soundmaker->m_player_leftpunch_sound.name =
3697 std::string("default_dig_") +
3701 soundmaker->m_player_leftpunch_sound = sound_dig;
3705 // Don't show cracks if not diggable
3706 if (runData->dig_time_complete >= 100000.0) {
3707 } else if (runData->dig_index < crack_animation_length) {
3708 //TimeTaker timer("client.setTempMod");
3709 //infostream<<"dig_index="<<dig_index<<std::endl;
3710 client->setCrack(runData->dig_index, nodepos);
3712 infostream << "Digging completed" << std::endl;
3713 client->interact(2, pointed);
3714 client->setCrack(-1, v3s16(0, 0, 0));
3715 bool is_valid_position;
3716 MapNode wasnode = map.getNodeNoEx(nodepos, &is_valid_position);
3717 if (is_valid_position)
3718 client->removeNode(nodepos);
3720 if (m_cache_enable_particles) {
3721 const ContentFeatures &features =
3722 client->getNodeDefManager()->get(wasnode);
3723 client->getParticleManager()->addDiggingParticles(gamedef, smgr,
3724 player, nodepos, features.tiles);
3727 runData->dig_time = 0;
3728 runData->digging = false;
3730 runData->nodig_delay_timer =
3731 runData->dig_time_complete / (float)crack_animation_length;
3733 // We don't want a corresponding delay to
3734 // very time consuming nodes
3735 if (runData->nodig_delay_timer > 0.3)
3736 runData->nodig_delay_timer = 0.3;
3738 // We want a slight delay to very little
3739 // time consuming nodes
3740 const float mindelay = 0.15;
3742 if (runData->nodig_delay_timer < mindelay)
3743 runData->nodig_delay_timer = mindelay;
3745 // Send event to trigger sound
3746 MtEvent *e = new NodeDugEvent(nodepos, wasnode);
3747 gamedef->event()->put(e);
3750 if (runData->dig_time_complete < 100000.0) {
3751 runData->dig_time += dtime;
3753 runData->dig_time = 0;
3754 client->setCrack(-1, nodepos);
3757 camera->setDigging(0); // left click animation
3761 void Game::updateFrame(std::vector<aabb3f> &highlight_boxes,
3762 ProfilerGraph *graph, RunStats *stats, GameRunData *runData,
3763 f32 dtime, const VolatileRunFlags &flags, const CameraOrientation &cam)
3765 LocalPlayer *player = client->getEnv().getLocalPlayer();
3771 if (draw_control->range_all) {
3772 runData->fog_range = 100000 * BS;
3774 runData->fog_range = draw_control->wanted_range * BS
3775 + 0.0 * MAP_BLOCKSIZE * BS;
3776 runData->fog_range = MYMIN(
3778 (draw_control->farthest_drawn + 20) * BS);
3779 runData->fog_range *= 0.9;
3783 Calculate general brightness
3785 u32 daynight_ratio = client->getEnv().getDayNightRatio();
3786 float time_brightness = decode_light_f((float)daynight_ratio / 1000.0);
3787 float direct_brightness;
3790 if (g_settings->getBool("free_move")) {
3791 direct_brightness = time_brightness;
3792 sunlight_seen = true;
3794 ScopeProfiler sp(g_profiler, "Detecting background light", SPT_AVG);
3795 float old_brightness = sky->getBrightness();
3796 direct_brightness = client->getEnv().getClientMap()
3797 .getBackgroundBrightness(MYMIN(runData->fog_range * 1.2, 60 * BS),
3798 daynight_ratio, (int)(old_brightness * 255.5), &sunlight_seen)
3802 float time_of_day = runData->time_of_day;
3803 float time_of_day_smooth = runData->time_of_day_smooth;
3805 time_of_day = client->getEnv().getTimeOfDayF();
3807 const float maxsm = 0.05;
3808 const float todsm = 0.05;
3810 if (fabs(time_of_day - time_of_day_smooth) > maxsm &&
3811 fabs(time_of_day - time_of_day_smooth + 1.0) > maxsm &&
3812 fabs(time_of_day - time_of_day_smooth - 1.0) > maxsm)
3813 time_of_day_smooth = time_of_day;
3815 if (time_of_day_smooth > 0.8 && time_of_day < 0.2)
3816 time_of_day_smooth = time_of_day_smooth * (1.0 - todsm)
3817 + (time_of_day + 1.0) * todsm;
3819 time_of_day_smooth = time_of_day_smooth * (1.0 - todsm)
3820 + time_of_day * todsm;
3822 runData->time_of_day = time_of_day;
3823 runData->time_of_day_smooth = time_of_day_smooth;
3825 sky->update(time_of_day_smooth, time_brightness, direct_brightness,
3826 sunlight_seen, camera->getCameraMode(), player->getYaw(),
3827 player->getPitch());
3833 v3f player_position = player->getPosition();
3834 if (sky->getCloudsVisible()) {
3835 clouds->setVisible(true);
3836 clouds->step(dtime);
3837 clouds->update(v2f(player_position.X, player_position.Z),
3838 sky->getCloudColor());
3840 clouds->setVisible(false);
3847 client->getParticleManager()->step(dtime);
3853 if (m_cache_enable_fog && !flags.force_fog_off) {
3856 video::EFT_FOG_LINEAR,
3857 runData->fog_range * 0.4,
3858 runData->fog_range * 1.0,
3866 video::EFT_FOG_LINEAR,
3876 Get chat messages from client
3879 v2u32 screensize = driver->getScreenSize();
3881 updateChat(*client, dtime, flags.show_debug, screensize,
3882 flags.show_chat, runData->profiler_current_page,
3883 *chat_backend, guitext_chat);
3889 if (client->getPlayerItem() != runData->new_playeritem)
3890 client->selectPlayerItem(runData->new_playeritem);
3892 // Update local inventory if it has changed
3893 if (client->getLocalInventoryUpdated()) {
3894 //infostream<<"Updating local inventory"<<std::endl;
3895 client->getLocalInventory(*local_inventory);
3896 runData->update_wielded_item_trigger = true;
3899 if (runData->update_wielded_item_trigger) {
3900 // Update wielded tool
3901 InventoryList *mlist = local_inventory->getList("main");
3903 if (mlist && (client->getPlayerItem() < mlist->getSize())) {
3904 ItemStack item = mlist->getItem(client->getPlayerItem());
3905 camera->wield(item);
3907 runData->update_wielded_item_trigger = false;
3911 Update block draw list every 200ms or when camera direction has
3914 runData->update_draw_list_timer += dtime;
3916 v3f camera_direction = camera->getDirection();
3917 if (runData->update_draw_list_timer >= 0.2
3918 || runData->update_draw_list_last_cam_dir.getDistanceFrom(camera_direction) > 0.2
3919 || flags.camera_offset_changed) {
3920 runData->update_draw_list_timer = 0;
3921 client->getEnv().getClientMap().updateDrawList(driver);
3922 runData->update_draw_list_last_cam_dir = camera_direction;
3925 updateGui(&runData->statustext_time, *stats, *runData, dtime, flags, cam);
3928 make sure menu is on top
3929 1. Delete formspec menu reference if menu was removed
3930 2. Else, make sure formspec menu is on top
3932 if (current_formspec) {
3933 if (current_formspec->getReferenceCount() == 1) {
3934 current_formspec->drop();
3935 current_formspec = NULL;
3936 } else if (!noMenuActive()) {
3937 guiroot->bringToFront(current_formspec);
3945 video::SColor skycolor = sky->getSkyColor();
3947 TimeTaker tt_draw("mainloop: draw");
3949 TimeTaker timer("beginScene");
3950 driver->beginScene(true, true, skycolor);
3951 stats->beginscenetime = timer.stop(true);
3954 draw_scene(driver, smgr, *camera, *client, player, *hud, guienv,
3955 highlight_boxes, screensize, skycolor, flags.show_hud);
3960 if (flags.show_profiler_graph)
3961 graph->draw(10, screensize.Y - 10, driver, g_fontengine->getFont());
3966 if (runData->damage_flash > 0.0) {
3967 video::SColor color(std::min(runData->damage_flash, 180.0f),
3971 driver->draw2DRectangle(color,
3972 core::rect<s32>(0, 0, screensize.X, screensize.Y),
3975 runData->damage_flash -= 100.0 * dtime;
3981 if (player->hurt_tilt_timer > 0.0) {
3982 player->hurt_tilt_timer -= dtime * 5;
3984 if (player->hurt_tilt_timer < 0)
3985 player->hurt_tilt_strength = 0;
3992 TimeTaker timer("endScene");
3994 stats->endscenetime = timer.stop(true);
3997 stats->drawtime = tt_draw.stop(true);
3998 g_profiler->graphAdd("mainloop_draw", stats->drawtime / 1000.0f);
4002 inline static const char *yawToDirectionString(int yaw)
4004 // NOTE: TODO: This can be done mathematically without the else/else-if
4007 const char *player_direction;
4009 yaw = wrapDegrees_0_360(yaw);
4011 if (yaw >= 45 && yaw < 135)
4012 player_direction = "West [-X]";
4013 else if (yaw >= 135 && yaw < 225)
4014 player_direction = "South [-Z]";
4015 else if (yaw >= 225 && yaw < 315)
4016 player_direction = "East [+X]";
4018 player_direction = "North [+Z]";
4020 return player_direction;
4024 void Game::updateGui(float *statustext_time, const RunStats &stats,
4025 const GameRunData& runData, f32 dtime, const VolatileRunFlags &flags,
4026 const CameraOrientation &cam)
4028 v2u32 screensize = driver->getScreenSize();
4029 LocalPlayer *player = client->getEnv().getLocalPlayer();
4030 v3f player_position = player->getPosition();
4032 if (flags.show_debug) {
4033 static float drawtime_avg = 0;
4034 drawtime_avg = drawtime_avg * 0.95 + stats.drawtime * 0.05;
4036 u16 fps = 1.0 / stats.dtime_jitter.avg;
4037 //s32 fps = driver->getFPS();
4039 std::ostringstream os(std::ios_base::binary);
4041 << PROJECT_NAME_C " " << g_version_hash
4043 << " (R: range_all=" << draw_control->range_all << ")"
4044 << std::setprecision(0)
4045 << " drawtime = " << drawtime_avg
4046 << std::setprecision(1)
4047 << ", dtime_jitter = "
4048 << (stats.dtime_jitter.max_fraction * 100.0) << " %"
4049 << std::setprecision(1)
4050 << ", v_range = " << draw_control->wanted_range
4051 << std::setprecision(3)
4052 << ", RTT = " << client->getRTT();
4053 guitext->setText(narrow_to_wide(os.str()).c_str());
4054 guitext->setVisible(true);
4055 } else if (flags.show_hud || flags.show_chat) {
4056 std::ostringstream os(std::ios_base::binary);
4057 os << PROJECT_NAME_C " " << g_version_hash;
4058 guitext->setText(narrow_to_wide(os.str()).c_str());
4059 guitext->setVisible(true);
4061 guitext->setVisible(false);
4064 if (guitext->isVisible()) {
4065 core::rect<s32> rect(
4067 screensize.X, 5 + g_fontengine->getTextHeight()
4069 guitext->setRelativePosition(rect);
4072 if (flags.show_debug) {
4073 std::ostringstream os(std::ios_base::binary);
4074 os << std::setprecision(1) << std::fixed
4075 << "(" << (player_position.X / BS)
4076 << ", " << (player_position.Y / BS)
4077 << ", " << (player_position.Z / BS)
4078 << ") (yaw=" << (wrapDegrees_0_360(cam.camera_yaw))
4079 << " " << yawToDirectionString(cam.camera_yaw)
4080 << ") (seed = " << ((u64)client->getMapSeed())
4083 if (runData.pointed_old.type == POINTEDTHING_NODE) {
4084 ClientMap &map = client->getEnv().getClientMap();
4085 const INodeDefManager *nodedef = client->getNodeDefManager();
4086 MapNode n = map.getNodeNoEx(runData.pointed_old.node_undersurface);
4087 if (n.getContent() != CONTENT_IGNORE && nodedef->get(n).name != "unknown") {
4088 const ContentFeatures &features = nodedef->get(n);
4089 os << " (pointing_at = " << nodedef->get(n).name
4090 << " - " << features.tiledef[0].name.c_str()
4095 guitext2->setText(narrow_to_wide(os.str()).c_str());
4096 guitext2->setVisible(true);
4098 core::rect<s32> rect(
4099 5, 5 + g_fontengine->getTextHeight(),
4100 screensize.X, 5 + g_fontengine->getTextHeight() * 2
4102 guitext2->setRelativePosition(rect);
4104 guitext2->setVisible(false);
4107 guitext_info->setText(infotext.c_str());
4108 guitext_info->setVisible(flags.show_hud && g_menumgr.menuCount() == 0);
4110 float statustext_time_max = 1.5;
4112 if (!statustext.empty()) {
4113 *statustext_time += dtime;
4115 if (*statustext_time >= statustext_time_max) {
4117 *statustext_time = 0;
4121 guitext_status->setText(statustext.c_str());
4122 guitext_status->setVisible(!statustext.empty());
4124 if (!statustext.empty()) {
4125 s32 status_width = guitext_status->getTextWidth();
4126 s32 status_height = guitext_status->getTextHeight();
4127 s32 status_y = screensize.Y - 150;
4128 s32 status_x = (screensize.X - status_width) / 2;
4129 core::rect<s32> rect(
4130 status_x , status_y - status_height,
4131 status_x + status_width, status_y
4133 guitext_status->setRelativePosition(rect);
4136 video::SColor initial_color(255, 0, 0, 0);
4138 if (guienv->getSkin())
4139 initial_color = guienv->getSkin()->getColor(gui::EGDC_BUTTON_TEXT);
4141 video::SColor final_color = initial_color;
4142 final_color.setAlpha(0);
4143 video::SColor fade_color = initial_color.getInterpolated_quadratic(
4144 initial_color, final_color,
4145 pow(*statustext_time / statustext_time_max, 2.0f));
4146 guitext_status->setOverrideColor(fade_color);
4147 guitext_status->enableOverrideColor(true);
4152 /* Log times and stuff for visualization */
4153 inline void Game::updateProfilerGraphs(ProfilerGraph *graph)
4155 Profiler::GraphValues values;
4156 g_profiler->graphGet(values);
4162 /****************************************************************************
4164 ****************************************************************************/
4166 /* On some computers framerate doesn't seem to be automatically limited
4168 inline void Game::limitFps(FpsControl *fps_timings, f32 *dtime)
4170 // not using getRealTime is necessary for wine
4171 device->getTimer()->tick(); // Maker sure device time is up-to-date
4172 u32 time = device->getTimer()->getTime();
4173 u32 last_time = fps_timings->last_time;
4175 if (time > last_time) // Make sure time hasn't overflowed
4176 fps_timings->busy_time = time - last_time;
4178 fps_timings->busy_time = 0;
4180 u32 frametime_min = 1000 / (g_menumgr.pausesGame()
4181 ? g_settings->getFloat("pause_fps_max")
4182 : g_settings->getFloat("fps_max"));
4184 if (fps_timings->busy_time < frametime_min) {
4185 fps_timings->sleep_time = frametime_min - fps_timings->busy_time;
4186 device->sleep(fps_timings->sleep_time);
4188 fps_timings->sleep_time = 0;
4191 /* Get the new value of the device timer. Note that device->sleep() may
4192 * not sleep for the entire requested time as sleep may be interrupted and
4193 * therefore it is arguably more accurate to get the new time from the
4194 * device rather than calculating it by adding sleep_time to time.
4197 device->getTimer()->tick(); // Update device timer
4198 time = device->getTimer()->getTime();
4200 if (time > last_time) // Make sure last_time hasn't overflowed
4201 *dtime = (time - last_time) / 1000.0;
4205 fps_timings->last_time = time;
4208 // Note: This will free (using delete[])! \p msg. If you want to use it later,
4209 // pass a copy of it to this function
4210 // Note: \p msg must be allocated using new (not malloc())
4211 void Game::showOverlayMessage(const wchar_t *msg, float dtime,
4212 int percent, bool draw_clouds)
4214 draw_load_screen(msg, device, guienv, dtime, percent, draw_clouds);
4219 /****************************************************************************/
4220 /****************************************************************************
4222 ****************************************************************************/
4223 /****************************************************************************/
4225 void Game::extendedResourceCleanup()
4227 // Extended resource accounting
4228 infostream << "Irrlicht resources after cleanup:" << std::endl;
4229 infostream << "\tRemaining meshes : "
4230 << device->getSceneManager()->getMeshCache()->getMeshCount() << std::endl;
4231 infostream << "\tRemaining textures : "
4232 << driver->getTextureCount() << std::endl;
4234 for (unsigned int i = 0; i < driver->getTextureCount(); i++) {
4235 irr::video::ITexture *texture = driver->getTextureByIndex(i);
4236 infostream << "\t\t" << i << ":" << texture->getName().getPath().c_str()
4240 clearTextureNameCache();
4241 infostream << "\tRemaining materials: "
4242 << driver-> getMaterialRendererCount()
4243 << " (note: irrlicht doesn't support removing renderers)" << std::endl;
4247 /****************************************************************************/
4248 /****************************************************************************
4249 extern function for launching the game
4250 ****************************************************************************/
4251 /****************************************************************************/
4253 void the_game(bool *kill,
4255 InputHandler *input,
4256 IrrlichtDevice *device,
4258 const std::string &map_dir,
4259 const std::string &playername,
4260 const std::string &password,
4261 const std::string &address, // If empty local server is created
4264 std::string &error_message,
4265 ChatBackend &chat_backend,
4266 const SubgameSpec &gamespec, // Used for local game
4267 bool simple_singleplayer_mode)
4271 /* Make a copy of the server address because if a local singleplayer server
4272 * is created then this is updated and we don't want to change the value
4273 * passed to us by the calling function
4275 std::string server_address = address;
4279 if (game.startup(kill, random_input, input, device, map_dir,
4280 playername, password, &server_address, port,
4281 error_message, &chat_backend, gamespec,
4282 simple_singleplayer_mode)) {
4287 } catch (SerializationError &e) {
4288 error_message = std::string("A serialization error occurred:\n")
4289 + e.what() + "\n\nThe server is probably "
4290 " running a different version of " PROJECT_NAME_C ".";
4291 errorstream << error_message << std::endl;
4292 } catch (ServerError &e) {
4293 error_message = e.what();
4294 errorstream << "ServerError: " << error_message << std::endl;
4295 } catch (ModError &e) {
4296 error_message = e.what() + strgettext("\nCheck debug.txt for details.");
4297 errorstream << "ModError: " << error_message << std::endl;